def create_account_console(logger: Logger, network: str): """Creates an Ethereum account and echoes the details to console.""" acc = Account.create() private_key = to_hex(acc.privateKey) if private_key.startswith("0x"): # Looks like this behaves differently in different versions, # we assume no 0x prefix for private key to distinguish it from addresses # and hashes private_key = private_key[2:] logger.info("Account address: %s", acc.address) logger.info("Account private key: %s", private_key) config = CONFIG_FILE_TEMPLATE.format(private_key=private_key, network=network, address=acc.address) config_file_name = "myconfig.ini" print() print("Create a file {}{}{} and paste in the following content: {}{}{}". format(colorama.Fore.LIGHTBLUE_EX, config_file_name, colorama.Fore.RESET, colorama.Fore.LIGHTBLACK_EX, config, colorama.Fore.RESET)) print() print("After this you can run {}sto --config-file={} diagnose{}".format( colorama.Fore.LIGHTBLUE_EX, config_file_name, colorama.Fore.RESET))
def register(self, username, password): ac = Account.create(password) kf = Account.encrypt(ac.privateKey, password) keyfile = "{}/{}.keystore".format(client_config.account_keyfile_path, username) # file is exist, account is registed if os.access(keyfile, os.F_OK): return -1 try: with open(keyfile, "w") as dump_f: json.dump(kf, dump_f) dump_f.close() with open(keyfile, "r") as dump_f: keytext = json.load(dump_f) privkey = Account.decrypt(keytext, password) client_account = Account.from_key(privkey) ps = PermissionService("./pythonsdk/contracts/precompile") ps.grant("t_rep1", client_account.address) ps.grant("t_company", client_account.address) del ps # write file failed except Exception as e: return -2 return 0
def mock_accounts(): accounts = dict() for i in range(NUMBER_OF_MOCK_KEYSTORE_ACCOUNTS): account = Account.create() filename = KEYFILE_NAME_TEMPLATE.format(month=i+1, address=account.address) accounts[filename] = account return accounts
def create_account(name, password=""): ac = Account.create(password) kf = Account.encrypt(ac.privateKey, password) keyfile = "{}/{}.keystore".format(client_config.account_keyfile_path, name) # if os.access(keyfile, os.F_OK): # common.backup_file(keyfile) with open(keyfile, "w") as dump_f: json.dump(kf, dump_f) dump_f.close() return signin_account(name, password)
def init(ctx_obj, verbose): if not ctx_obj['settings']['PRIVATEKEY']: # click.echo('Choosing EthVigil Alpha instance https://alpha.ethvigil.com/api ...') invite_code = click.prompt('Enter your invite code') new_account = Account.create('RANDOM ENTROPY WILL SUCK YOUR SOUL') signup_status = ev_signup(ctx_obj['settings']['INTERNAL_API_ENDPOINT'], invite_code, new_account.key.hex()) if not signup_status: click.echo('Signup failed') return else: ctx_obj['settings']['PRIVATEKEY'] = new_account.key.hex() ctx_obj['settings']['ETHVIGIL_USER_ADDRESS'] = new_account.address with open( pwd.getpwuid(os.getuid()).pw_dir + '/.ethvigil/settings.json', 'w') as f: json.dump(ctx_obj['settings'], f) click.echo('Sign up succeeded...') click.echo('Logging in with your credentials...') login_data = ev_login(ctx_obj['settings']['INTERNAL_API_ENDPOINT'], new_account.key.hex(), verbose) if login_data: ctx_obj['settings']['ETHVIGIL_API_KEY'] = login_data['key'] ctx_obj['settings']['REST_API_ENDPOINT'] = login_data[ 'api_prefix'] with open( pwd.getpwuid(os.getuid()).pw_dir + '/.ethvigil/settings.json', 'w') as f: json.dump(ctx_obj['settings'], f) click.echo( 'You have signed up and logged in successfully to EthVigil Alpha' ) click.echo( '---YOU MIGHT WANT TO COPY THESE DETAILS TO A SEPARATE FILE---' ) click.echo( '===Private key (that signs messages to interact with EthVigil APIs===' ) click.echo(ctx_obj['settings']['PRIVATEKEY']) click.echo( '===ETHEREUM hexadecimal address corresponding to above private key===' ) click.echo(ctx_obj['settings']['ETHVIGIL_USER_ADDRESS']) else: click.echo( 'Login failed with credentials. Run `ev-cli reset`.') else: click.echo( "A registered private key exists for this ev-cli installation. Run ev-cli reset if you wish" " to do a fresh install")
def create_account_console(logger: Logger, network: str): """Creates an Ethereum account and echoes the details to console.""" acc = Account.create() private_key = to_hex(acc.privateKey) logger.info("Account address: %s", acc.address) logger.info("Account private key: %s", private_key) config = CONFIG_FILE_TEMPLATE.format(private_key=private_key, network=network) config_file_name = "myconfig.ini" print("Create a file {} and paste in the following content:".format( config_file_name)) print() print(config)
def generateAccount(name, password): try: ac = Account.create(password) stat = StatTool.begin() kf = Account.encrypt(ac.privateKey, password) stat.done() keyfile = "{}/{}.keystore".format(client_config.account_keyfile_path, name) if os.access(keyfile, os.F_OK): print("error") return with open(keyfile, "w") as dump_f: json.dump(kf, dump_f) dump_f.close() print("success") except: print("error")
def create_ecdsa_account(name, password, forcewrite): ac = Account.create(password) print("new address :\t", ac.address) print("new privkey :\t", encode_hex(ac.key)) print("new pubkey :\t", ac.publickey) stat = StatTool.begin() kf = Account.encrypt(ac.privateKey, password) stat.done() print("encrypt use time : %.3f s" % (stat.time_used)) keyfile = "{}/{}.keystore".format( client_config.account_keyfile_path, name) print("save to file : [{}]".format(keyfile)) forcewrite = False if not os.access(keyfile, os.F_OK): # 默认的账号文件不存在,就强行存一个 forcewrite = True else: # old file exist,move to backup file first if len(inputparams) == 3 and inputparams[2] == "save": forcewrite = True else: forcewrite = common.backup_file( keyfile) # 如果备份文件不成功,就不要覆盖写了 if forcewrite: with open(keyfile, "w") as dump_f: json.dump(kf, dump_f) dump_f.close() print(">>-------------------------------------------------------") print( "INFO >> read [{}] again after new account,address & keys in file:" .format(keyfile)) with open(keyfile, "r") as dump_f: keytext = json.load(dump_f) stat = StatTool.begin() privkey = Account.decrypt(keytext, password) stat.done() print("decrypt use time : %.3f s" % (stat.time_used)) ac2 = Account.from_key(privkey) print("address:\t", ac2.address) print("privkey:\t", encode_hex(ac2.key)) print("pubkey :\t", ac2.publickey) print("\naccount store in file: [{}]".format(keyfile)) print("\n**** please remember your password !!! *****") dump_f.close()
def press_register(self): name, password, balance = self.line_name.text(), self.line_pwd.text( ), self.line_balance.text() # balabce代表启动资金 balance = int(balance) if len(name) > 256: QMessageBox.warning(self, 'Error', '名称过长。') sys.exit(1) print("starting : {} {} ".format(name, password)) ac = Account.create(password) print("new address :\t", ac.address) print("new privkey :\t", encode_hex(ac.key)) print("new pubkey :\t", ac.publickey) kf = Account.encrypt(ac.privateKey, password) keyfile = "{}/{}.keystore".format(client_config.account_keyfile_path, name) print("save to file : [{}]".format(keyfile)) with open(keyfile, "w") as dump_f: json.dump(kf, dump_f) dump_f.close() print( "INFO >> Read [{}] again after new account,address & keys in file:" .format(keyfile)) with open(keyfile, "r") as dump_f: keytext = json.load(dump_f) privkey = Account.decrypt(keytext, password) ac2 = Account.from_key(privkey) print("address:\t", ac2.address) print("privkey:\t", encode_hex(ac2.key)) print("pubkey :\t", ac2.publickey) print("\naccount store in file: [{}]".format(keyfile)) dump_f.close() global client, contract_abi, to_address args = [name, ac.address, 'Company', balance] # 调用智能合约中的register函数 receipt = client.sendRawTransactionGetReceipt(to_address, contract_abi, "register", args) print("receipt:", receipt['output']) QMessageBox.information(self, 'Prompt', '注册成功。', QMessageBox.Ok)
def test_keystore(): ac1 = Account.create('123456') print(ac1.address) print(encode_hex(ac1.key)) print(ac1.publickey) print() kf = Account.encrypt(ac1.privateKey, "123456") print(kf) keyfile = "d:/blockchain/accounts/pyaccount.keystore" with open(keyfile, "w") as dump_f: json.dump(kf, dump_f) with open(keyfile, "r") as dump_f: keytext = json.load(dump_f) privkey = Account.decrypt(keytext, "123456") ac2 = Account.from_key(privkey) print("read from file:", ac2.address) print(encode_hex(ac2.key)) print(ac2.publickey)
def create_account_console(logger: Logger, network: str): """Creates an Ethereum account and echoes the details to console.""" acc = Account.create() private_key = to_hex(acc.privateKey) logger.info("Account address: %s", acc.address) logger.info("Account private key: %s", private_key) config = CONFIG_FILE_TEMPLATE.format(private_key=private_key, network=network, address=acc.address) config_file_name = "myconfig.ini" print() print("Create a file {}{}{} and paste in the following content: {}{}{}". format(colorama.Fore.LIGHTBLUE_EX, config_file_name, colorama.Fore.RESET, colorama.Fore.LIGHTBLACK_EX, config, colorama.Fore.RESET)) print() print("After this you can run {}sto --config-file={} diagnose{}".format( colorama.Fore.LIGHTBLUE_EX, config_file_name, colorama.Fore.RESET))
def init(ctx_obj, verbose): """ Launches a signup process if no MaticVigil credentials are found. """ if not ctx_obj['settings']['PRIVATEKEY']: if "MATICVIGIL_CLI_TESTMODE" not in os.environ: click.secho('Redirecting to the signup page...', fg='green') time.sleep(2) webbrowser.open('https://mainnet.maticvigil.com/?clisignup=true') invite_code = click.prompt('Enter your invite code') new_account = Account.create('RANDOM ENTROPY WILL SUCK YOUR SOUL') signup_status = ev_signup(ctx_obj['settings']['INTERNAL_API_ENDPOINT'], invite_code, new_account.key.hex(), verbose) if not signup_status: click.echo('Signup failed') return else: ctx_obj['settings']['PRIVATEKEY'] = new_account.key.hex() ctx_obj['settings'][ 'MATICVIGIL_USER_ADDRESS'] = new_account.address with open(settings_json_loc, 'w') as f: json.dump(ctx_obj['settings'], f) click.echo('Sign up succeeded...') click.echo('Logging in with your credentials...') login_data = ev_login(ctx_obj['settings']['INTERNAL_API_ENDPOINT'], new_account.key.hex(), verbose) if len(login_data.keys()) > 0: ctx_obj['settings']['MATICVIGIL_API_KEY'] = login_data['key'] ctx_obj['settings']['READ_API_KEY'] = login_data['readKey'] ctx_obj['settings']['REST_API_ENDPOINT'] = login_data[ 'api_prefix'] click.echo( 'You have signed up and logged in successfully to MaticVigil' ) if verbose: click.echo( '---YOU MIGHT WANT TO COPY THESE DETAILS TO A SEPARATE FILE---' ) click.echo( '===Private key (that signs messages to interact with MaticVigil APIs===' ) click.echo(ctx_obj['settings']['PRIVATEKEY']) click.echo( '===ETHEREUM hexadecimal address corresponding to above private key===' ) click.echo(ctx_obj['settings']['MATICVIGIL_USER_ADDRESS']) with open(settings_json_loc, 'w') as f: json.dump(ctx_obj['settings'], f) if verbose: click.echo('Wrote context object to settings location') click.echo(settings_json_loc) click.echo('Context object') click.echo(ctx_obj) sys.exit(0) else: click.echo( 'Login failed with credentials. Run `mv-cli reset`.') sys.exit(2) else: click.secho( "A registered private key exists for this mv-cli installation. Run mv-cli reset if you wish" " to do a fresh install", fg='yellow') sys.exit(1)
print("\n**** please remember your password !!! *****") validcmds.append("newaccount") usagemsg.append('''newaccount [name] [password] [save] 创建一个新帐户,参数为帐户名(如alice,bob)和密码 结果加密保存在配置文件指定的帐户目录 *如同目录下已经有同名帐户文件,旧文件会复制一个备份 如输入了"save"参数在最后,则不做询问直接备份和写入 create a new account ,save to :[{}] (default) , the path in client_config.py:[account_keyfile_path] if account file has exist ,then old file will save to a backup if "save" arg follows,then backup file and write new without ask'''.format( client_config.account_keyfile_path)) if cmd == 'newaccount': name = inputparams[0] password = inputparams[1] print("starting : {} {} ".format(name, password)) ac = Account.create(password) print("new address :\t", ac.address) print("new privkey :\t", encode_hex(ac.key)) print("new pubkey :\t", ac.publickey) stat = StatTool.begin() kf = Account.encrypt(ac.privateKey, password) stat.done() print("encrypt use time : %.3f s" % (stat.time_used)) import json keyfile = "{}/{}.keystore".format(client_config.account_keyfile_path, name) print("save to file : [{}]".format(keyfile)) forcewrite = False if not os.access(keyfile, os.F_OK): forcewrite = True
def main(argv): try: usagemsg = usage(client_config) cmd, inputparams = parse_commands(argv) precompile = Precompile(cmd, inputparams, contracts_dir + "/precompile") # check cmd valid = check_cmd(cmd, validcmds) if valid is False: printusage(usagemsg, precompile) return # try to callback cns precompile precompile.call_cns() # try to callback consensus precompile precompile.call_consensus() # try to callback config precompile precompile.call_sysconfig_precompile() # try to callback permission precompile precompile.call_permission_precompile() # try to callback crud precompile precompile.call_crud_precompile() # try to callback rpc functions rpcConsole = RPCConsole(cmd, inputparams, contracts_dir) rpcConsole.executeRpcCommand() if cmd == 'showaccount': # must be 2 params common.check_param_num(inputparams, 2, True) name = inputparams[0] password = inputparams[1] keyfile = "{}/{}.keystore".format( client_config.account_keyfile_path, name) # the account doesn't exists if os.path.exists(keyfile) is False: raise BcosException("account {} doesn't exists".format(name)) print("show account : {}, keyfile:{} ,password {} ".format( name, keyfile, password)) try: with open(keyfile, "r") as dump_f: keytext = json.load(dump_f) stat = StatTool.begin() privkey = Account.decrypt(keytext, password) stat.done() print("decrypt use time : %.3f s" % (stat.time_used)) ac2 = Account.from_key(privkey) print("address:\t", ac2.address) print("privkey:\t", encode_hex(ac2.key)) print("pubkey :\t", ac2.publickey) print("\naccount store in file: [{}]".format(keyfile)) print("\n**** please remember your password !!! *****") except Exception as e: raise BcosException(("load account info for [{}] failed," " error info: {}!").format(name, e)) if cmd == 'newaccount': common.check_param_num(inputparams, 2, True) name = inputparams[0] max_account_len = 240 if len(name) > max_account_len: common.print_info( "WARNING", "account name should no more than {}".format( max_account_len)) sys.exit(1) password = inputparams[1] print("starting : {} {} ".format(name, password)) ac = Account.create(password) print("new address :\t", ac.address) print("new privkey :\t", encode_hex(ac.key)) print("new pubkey :\t", ac.publickey) stat = StatTool.begin() kf = Account.encrypt(ac.privateKey, password) stat.done() print("encrypt use time : %.3f s" % (stat.time_used)) keyfile = "{}/{}.keystore".format( client_config.account_keyfile_path, name) print("save to file : [{}]".format(keyfile)) forcewrite = False if not os.access(keyfile, os.F_OK): forcewrite = True else: # old file exist,move to backup file first if (len(inputparams) == 3 and inputparams[2] == "save"): forcewrite = True else: forcewrite = common.backup_file(keyfile) if forcewrite: with open(keyfile, "w") as dump_f: json.dump(kf, dump_f) dump_f.close() print(">>-------------------------------------------------------") print( "INFO >> read [{}] again after new account,address & keys in file:" .format(keyfile)) with open(keyfile, "r") as dump_f: keytext = json.load(dump_f) stat = StatTool.begin() privkey = Account.decrypt(keytext, password) stat.done() print("decrypt use time : %.3f s" % (stat.time_used)) ac2 = Account.from_key(privkey) print("address:\t", ac2.address) print("privkey:\t", encode_hex(ac2.key)) print("pubkey :\t", ac2.publickey) print("\naccount store in file: [{}]".format(keyfile)) print("\n**** please remember your password !!! *****") dump_f.close() # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "deploy": '''deploy abi bin file''' # must be at least 2 params common.check_param_num(inputparams, 1) contractname = inputparams[0].strip() gasPrice = 30000000 # need save address whether or not needSaveAddress = False args_len = len(inputparams) if inputparams[-1] == "save": needSaveAddress = True args_len = len(inputparams) - 1 # get the args fn_args = inputparams[1:args_len] trans_client = transaction_common.TransactionCommon( "", contracts_dir, contractname) result = trans_client.send_transaction_getReceipt( None, fn_args, gasPrice, True)[0] print("deploy result for [{}] is:\n {}".format( contractname, json.dumps(result, indent=4))) name = contractname address = result['contractAddress'] blocknum = int(result["blockNumber"], 16) ContractNote.save_contract_address(name, address) print("on block : {},address: {} ".format(blocknum, address)) if needSaveAddress is True: ContractNote.save_address(name, address, blocknum) print("address save to file: ", client_config.contract_info_file) else: print('''\nNOTE : if want to save new address as last address for (call/sendtx)\nadd 'save' to cmdline and run again''' ) # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "call" or cmd == "sendtx": common.check_param_num(inputparams, 3) paramsname = ["contractname", "address", "func"] params = fill_params(inputparams, paramsname) contractname = params["contractname"] address = params["address"] if address == "last": address = ContractNote.get_last(contractname) if address is None: sys.exit("can not get last address for [{}],break;".format( contractname)) tx_client = transaction_common.TransactionCommon( address, contracts_dir, contractname) fn_name = params["func"] fn_args = inputparams[3:] print("INFO >> {} {} , address: {}, func: {}, args:{}".format( cmd, contractname, address, fn_name, fn_args)) if cmd == "call": result = tx_client.call_and_decode(fn_name, fn_args) print("INFO >> {} result: {}".format(cmd, result)) if cmd == "sendtx": receipt = tx_client.send_transaction_getReceipt( fn_name, fn_args)[0] data_parser = DatatypeParser(default_abi_file(contractname)) # 解析receipt里的log 和 相关的tx ,output print_receipt_logs_and_txoutput(tx_client, receipt, "", data_parser) # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "list": RPCConsole.print_rpc_usage() print( "--------------------------------------------------------------------" ) # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "txinput": contractname = inputparams[0] inputdata = inputparams[1] abi_path = default_abi_file(contractname) if os.path.isfile(abi_path) is False: raise BcosException( "execute {} failed for {} doesn't exist".format( cmd, abi_path)) try: dataParser = DatatypeParser(abi_path) # print(dataParser.func_abi_map_by_selector) result = dataParser.parse_transaction_input(inputdata) print("\nabifile : ", default_abi_file(contractname)) print("parse result: {}".format(result)) except Exception as e: raise BcosException("execute {} failed for reason: {}".format( cmd, e)) # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "checkaddr": address = inputparams[0] result = to_checksum_address(address) print("{} -->\n{}".format(address, result)) # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "usage": printusage(usagemsg, precompile) except TransactionException as e: common.print_error_msg(cmd, e) except PrecompileError as e: common.print_error_msg(cmd, e) except BcosError as e: common.print_error_msg(cmd, e) except CompileError as e: common.print_error_msg(cmd, e) except ArgumentsError as e: common.print_error_msg(cmd, e) except BcosException as e: common.print_error_msg(cmd, e)
def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character
''' @author: kentzhang @date: 2019-06 ''' from eth_account.account import (Account) from eth_utils.hexadecimal import encode_hex ac1 = Account.create('123456') print(ac1.address) print(encode_hex(ac1.key)) print(ac1.publickey) print() kf = Account.encrypt(ac1.privateKey, "123456") print(kf) import json keyfile = "d:/blockchain/accounts/pyaccount.keystore" with open(keyfile, "w") as dump_f: json.dump(kf, dump_f) with open(keyfile, "r") as dump_f: keytext = json.load(dump_f) privkey = Account.decrypt(keytext, "123456") ac2 = Account.from_key(privkey) print("read from file:", ac2.address) print(encode_hex(ac2.key)) print(ac2.publickey)
from eth_account.account import Account from web3 import Web3, HTTPProvider from web3._utils.transactions import wait_for_transaction_receipt from web3.method import Method from web3.middleware import construct_sign_and_send_raw_middleware from web3.types import Wei from web3_flashbots import flashbot # test miner account faucet = Account.privateKeyToAccount( "0x133be114715e5fe528a1b8adf36792160601a2d63ab59d1fd454275b31328791") dummy_receiver = "0x1111111111111111111111111112144211111112" user = Account.create("test") if __name__ == '__main__': # instantiate Web3 as usual w3 = Web3(HTTPProvider("http://localhost:8545")) w3.middleware_onion.add(construct_sign_and_send_raw_middleware(faucet)) # inject the new data flashbot(w3, flashbots_key_id="5", flashbots_secret="2", flashbots_url="http://localhost:8545") # faucet funds the user assert w3.eth.getBalance(user.address) == 0 tx = w3.eth.sendTransaction({ "from": faucet.address, "to": user.address, "value": w3.toWei("1.1", "ether"),