def start_neo(): # Use TestNet settings.setup_testnet() # Setup the blockchain blockchain = LevelDBBlockchain(settings.chain_leveldb_path) Blockchain.RegisterBlockchain(blockchain) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) NodeLeader.Instance().Start() wallet = UserWallet.Open(path, to_aes_key(password)) # wallet.Rebuild() _walletdb_loop = task.LoopingCall(wallet.ProcessBlocks()) _walletdb_loop.start(.1) print("Opened wallet at %s" % path) # Start a thread with custom code d = threading.Thread(target=custom_background_code) d.setDaemon( True ) # daemonizing the thread will kill it when the main thread is quit d.start() # Run all the things (blocking call) reactor.run() logger.info("Shutting down.")
def runRawTransaction(operation, args): invocation_tx = InvocationTransaction() smartcontract_scripthash = UInt160.ParseString(CONTRACT_HASH) sb = ScriptBuilder() sb.EmitAppCallWithOperationAndArgs( smartcontract_scripthash, operation, args) invocation_tx.Script = binascii.unhexlify(sb.ToArray()) wallet = UserWallet.Create( 'neo-privnet.wallet', to_aes_key('coz'), generate_default_key=False) private_key = KeyPair.PrivateKeyFromWIF( "KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr") wallet.CreateKey(private_key) context = ContractParametersContext(invocation_tx) wallet.Sign(context) invocation_tx.scripts = context.GetScripts() raw_tx = invocation_tx.ToArray() payload = {"jsonrpc": "2.0", "id": 1, "method": "sendrawtransaction", "params": [raw_tx.decode("ascii")]} res = requests.post( "http://neo-nodes:30333/testNeoConnection", json=payload) print("received POST result") print(res.status_code) result = res.text print(result) return result
def __init__(self, contract_hash, wallet_path, wallet_pass): super(SurTokenContract, self).__init__() self.daemon = True self.contract_hash = contract_hash self.wallet_path = wallet_path self.wallet_pass = to_aes_key(wallet_pass) self.smart_contract = SmartContract(contract_hash) self.invoke_queue = Queue() self.tx_in_progress = None self.wallet = None settings.set_log_smart_contract_events(False) @self.smart_contract.on_notify def sc_notify(event): logger.info("SmartContract Runtime.Notify event: %s", event) # Make sure that the event payload list has at least one element. if not len(event.event_payload): return # The event payload list has at least one element. As developer of the smart contract # you should know what data-type is in the bytes, and how to decode it. In this example, # it's just a string, so we decode it with utf-8: logger.info("- payload part 1: %s", event.event_payload[0].decode("utf-8"))
def reset_password(new_path, new_password): db = PWDatabase(new_path).DB if LoadStoredData('MigrationState') == '1': print("This wallet was already secured") return False else: print("The wallet is vulnerable, will proceed with the operation.") # Decrypt Master Key - Without using a password master_enc = LoadStoredData('MasterKey') passwordHash = LoadStoredData('PasswordHash') iv = LoadStoredData('IV') aes_dec = AES.new(passwordHash, AES.MODE_CBC, iv) master_key = aes_dec.decrypt(master_enc) # Encrypt again with the new password new_key = to_aes_key(new_password) new_hash = hashlib.sha256(new_key).digest() aes_enc = AES.new(new_key, AES.MODE_CBC, iv) mk = aes_enc.encrypt(master_key) SaveStoredData('PasswordHash', new_hash) SaveStoredData('MasterKey', mk) SaveStoredData('MigrationState', '1') db.close() return True
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() while Blockchain.Default().Height < 2: print("Waiting for chain to sync...") time.sleep(1) # Claim initial NEO address = "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y" self.claim_initial_neo(address) # Open wallet again print("Opening wallet %s" % self.wallet_fn) self.wallet = UserWallet.Open(self.wallet_fn, to_aes_key("coz")) self.wallet.ProcessBlocks() self._walletdb_loop = task.LoopingCall(self.wallet.ProcessBlocks) self._walletdb_loop.start(1) # self.wallet.Rebuild() # print("\nOpened wallet. Rebuilding...") # time.sleep(10) print("\nWait %s min before claiming GAS." % self.min_wait) time.sleep(60 * self.min_wait) print("\nSending NEO to own wallet...") with patch('neo.Prompt.Commands.Send.prompt', side_effect=["coz"]): framework = construct_send_basic(self.wallet, ["neo", address, "100000000"]) tx = process_transaction(self.wallet, contract_tx=framework[0], scripthash_from=framework[1], fee=framework[2], owners=framework[3], user_tx_attributes=framework[4]) if not tx: print("Something went wrong, no tx.") return # Wait until transaction is on blockchain self.wait_for_tx(tx) print("Claiming the GAS...") claim_tx, relayed = ClaimGas(self.wallet, require_password=False) self.wait_for_tx(claim_tx) # Finally, need to rebuild the wallet self.wallet.Rebuild() print("\nAll done!") print("- Wallet file: %s" % self.wallet_fn) print("- Wallet pwd: %s" % self.wallet_pwd) if self.wif_fn: with open(self.wif_fn, "w") as f: f.write("KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr") self.quit()
def openWallet(self): """ open a Wallet. Needed for invoking contract methods """ if not os.path.exists(self.walletpath): logger.info("Wallet file not found") return else: assert self.Wallet is None aespasswd = to_aes_key(self.walletpw) self.Wallet = UserWallet.Open(self.walletpath, aespasswd) print("Opened wallet at: ", self.walletpath) self.wallet_sh = self.Wallet.GetStandardAddress() self.wallet_addr = Crypto.ToAddress(self.wallet_sh) print('Wallet Sh', self.wallet_sh) print('Wallet Addr', self.wallet_addr) self.Wallet.Rebuild() print("Wallet is syncing...") while self.Wallet.IsSynced is False: self._walletdb_loop = task.LoopingCall( self.Wallet.ProcessBlocks) self._walletdb_loop.start(1) print(self.Wallet._current_height, "/", Blockchain.Default().Height) return len(self.Wallet.GetTransactions())
def GetWallet1(cls, recreate=False): if cls._wallet1 is None or recreate: shutil.copyfile(cls.wallet_1_path(), cls.wallet_1_dest()) cls._wallet1 = UserWallet.Open( UserWalletTestCase.wallet_1_dest(), to_aes_key(UserWalletTestCase.wallet_1_pass())) return cls._wallet1
def execute(self, arguments): if PromptData.Wallet: PromptData.close_wallet() path = PromptUtils.get_arg(arguments, 0) if not path: print("Please specify the required parameter") return if not os.path.exists(path): print("Wallet file not found") return passwd = prompt("[password]> ", is_password=True) password_key = to_aes_key(passwd) try: PromptData.Wallet = UserWallet.Open(path, password_key) PromptData.Prompt.start_wallet_loop() print("Opened wallet at %s" % path) return PromptData.Wallet except Exception as e: print("Could not open wallet: %s" % e)
def do_open(self, arguments): if self.Wallet: self.do_close_wallet() item = get_arg(arguments) if item and item == 'wallet': path = get_arg(arguments, 1) if path: if not os.path.exists(path): print("Wallet file not found") return passwd = prompt("[password]> ", is_password=True) password_key = to_aes_key(passwd) try: self.Wallet = UserWallet.Open(path, password_key) self.start_wallet_loop() print("Opened wallet at %s" % path) except Exception as e: print("Could not open wallet: %s" % e) else: print("Please specify a path") else: print("Please specify something to open")
def main(): settings.setup_coznet() # Setup the blockchain blockchain = LevelDBBlockchain(settings.LEVELDB_PATH) Blockchain.RegisterBlockchain(blockchain) dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) NodeLeader.Instance().Start() #Disable smart contract events for external smart contracts settings.set_log_smart_contract_events(False) global Wallet Wallet = UserWallet.Open(path="infinite", password=to_aes_key("0123456789")) logger.info("Created the Wallet") logger.info(Wallet.AddressVersion) walletdb_loop = task.LoopingCall(Wallet.ProcessBlocks) walletdb_loop.start(1) # Start a thread with custom code d = threading.Thread(target=custom_background_code) d.setDaemon(True) # daemonizing the thread will kill it when the main thread is quit d.start() # Run all the things (blocking call) logger.info("Everything setup and running. Waiting for events...") reactor.run() logger.info("Shutting down.")
def execute(self, arguments): if PromptData.Wallet: PromptData.close_wallet() path = PromptUtils.get_arg(arguments, 0) if not path: print("Please specify the required parameter") return if not os.path.exists(path): print("Wallet file not found") return try: passwd = prompt("[password]> ", is_password=True) except KeyboardInterrupt: print("Wallet opening cancelled") return password_key = to_aes_key(passwd) try: PromptData.Wallet = UserWallet.Open(path, password_key) print("Opened wallet at %s" % path) asyncio.create_task( PromptData.Wallet.sync_wallet( start_block=PromptData.Wallet._current_height)) return PromptData.Wallet except Exception as e: print("Could not open wallet: %s" % e)
def do_open(self, arguments): if self.Wallet: self.do_close_wallet() item = get_arg(arguments) if item and item == 'wallet': path = get_arg(arguments, 1) if path: if not os.path.exists(path): print("Wallet file not found") return passwd = prompt("[password]> ", is_password=True) password_key = to_aes_key(passwd) try: self.Wallet = UserWallet.Open(path, password_key) self._walletdb_loop = task.LoopingCall( self.Wallet.ProcessBlocks) self._walletdb_loop.start(1) print("Opened wallet at %s" % path) except Exception as e: print("Could not open wallet: %s" % e) else: print("Please specify a path") else: print("Please specify something to open")
def do_create(self, arguments): item = get_arg(arguments) if item and item == 'wallet': path = get_arg(arguments, 1) if path: if os.path.exists(path): print("File already exists") return #passwd1 = prompt("[password]> ", is_password=True) #passwd2 = prompt("[password again]> ", is_password=True) #if passwd1 != passwd2 or len(passwd1) < 10: # print("Please provide matching passwords that are at least 10 characters long") # return password_key = to_aes_key(to_aes_key("coz")) try: self.Wallet = UserWallet.Create(path=path, password=password_key) contract = self.Wallet.GetDefaultContract() key = self.Wallet.GetKey(contract.PublicKeyHash) print("Wallet %s" % json.dumps(self.Wallet.ToJson(), indent=4)) print("Pubkey %s" % key.PublicKey.encode_point(True)) except Exception as e: print("Exception creating wallet: %s" % e) self.Wallet = None if os.path.isfile(path): try: os.remove(path) except Exception as e: print("Could not remove {}: {}".format(path, e)) return if self.Wallet: self._walletdb_loop = task.LoopingCall( self.Wallet.ProcessBlocks) self._walletdb_loop.start(1) else: print("Please specify a path")
def create_raw_sc_method_call_tx( source_address, source_address_wif, smartcontract_scripthash, smartcontract_method, smartcontract_method_args, ): source_script_hash = address_to_scripthash(source_address) # start by creating a base InvocationTransaction # the inputs, outputs and Type do not have to be set anymore. invocation_tx = InvocationTransaction() # often times smart contract developers use the function ``CheckWitness`` to determine if the transaction is signed by somebody eligible of calling a certain method # in order to pass that check you want to add the corresponding script_hash as a transaction attribute (this is generally the script_hash of the public key you use for signing) # Note that for public functions like the NEP-5 'getBalance' and alike this would not be needed, but it doesn't hurt either invocation_tx.Attributes.append( TransactionAttribute(usage=TransactionAttributeUsage.Script, data=source_script_hash)) smartcontract_scripthash = UInt160.ParseString(smartcontract_scripthash) # next we need to build a 'script' that gets executed against the smart contract. # this is basically the script that calls the entry point of the contract with the necessary parameters sb = ScriptBuilder() # call the method on the contract (assumes contract address is a NEP-5 token) sb.EmitAppCallWithOperationAndArgs( smartcontract_scripthash, smartcontract_method, smartcontract_method_args, ) invocation_tx.Script = binascii.unhexlify(sb.ToArray()) # at this point we've build our unsigned transaction and it's time to sign it before we get the raw output that we can send to the network via RPC # we need to create a Wallet instance for helping us with signing wallet = UserWallet.Create('path', to_aes_key('mypassword'), generate_default_key=False) # if you have a WIF use the following # this WIF comes from the `neo-test1-w.wallet` fixture wallet private_key = KeyPair.PrivateKeyFromWIF(source_address_wif) # if you have a NEP2 encrypted key use the following instead # private_key = KeyPair.PrivateKeyFromNEP2("NEP2 key string", "password string") # we add the key to our wallet wallet.CreateKey(private_key) # and now we're ready to sign context = ContractParametersContext(invocation_tx) wallet.Sign(context) invocation_tx.scripts = context.GetScripts() raw_tx = invocation_tx.ToArray() print(raw_tx) return raw_tx.decode()
def GetWallet1(cls, recreate=False): if cls._wallet1 is None or recreate: shutil.copyfile(cls.wallet_1_path(), cls.wallet_1_dest()) cls._wallet1 = UserWallet.Open(UserWalletTestCase.wallet_1_dest(), to_aes_key(UserWalletTestCase.wallet_1_pass())) return cls._wallet1
def GetWallet3(cls, recreate=False): if cls._wallet3 is None or recreate: shutil.copyfile(cls.wallet_3_path(), cls.wallet_3_dest()) cls._wallet3 = UserWallet.Open(cls.wallet_3_dest(), to_aes_key(cls.wallet_3_pass())) return cls._wallet3
def setup_wallet(self, wallet_path): if not os.path.exists(wallet_path): raise ValueError("Wallet file not found") self.wallet_path = wallet_path wallet_passwd = prompt("[password]> ", is_password=True) self.wallet_passwd_key = to_aes_key(wallet_passwd) self.setup_network()
def test_getwalletheight(self): self.app.wallet = UserWallet.Open( os.path.join(ROOT_INSTALL_PATH, "neo/data/neo-privnet.sample.wallet"), to_aes_key("coz")) req = self._gen_rpc_req("getwalletheight", params=[]) mock_req = mock_request(json.dumps(req).encode("utf-8")) res = json.loads(self.app.home(mock_req)) self.assertEqual(1, res.get('result'))
def ValidatePassword(self, password): """ Validates if the provided password matches with the stored password. Args: password (string): a password. Returns: bool: the provided password matches with the stored password. """ password = to_aes_key(password) return hashlib.sha256(password).digest() == self.LoadStoredData('PasswordHash')
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() while Blockchain.Default().Height < 2: print("Waiting for chain to sync...") time.sleep(1) # Claim initial MFF address = "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y" self.claim_initial_neo(address) # Open wallet again print("Opening wallet %s" % self.wallet_fn) self.wallet = UserWallet.Open(self.wallet_fn, to_aes_key("coz")) self.wallet.ProcessBlocks() self._walletdb_loop = task.LoopingCall(self.wallet.ProcessBlocks) self._walletdb_loop.start(1) # self.wallet.Rebuild() # print("\nOpened wallet. Rebuilding...") # time.sleep(10) print("\nWait %s min before claiming GAS." % self.min_wait) time.sleep(60 * self.min_wait) print("\nSending MFF to own wallet...") tx = construct_and_send(None, self.wallet, ["neo", address, "100000000"], prompt_password=False) if not tx: print("Something went wrong, no tx.") return # Wait until transaction is on blockchain self.wait_for_tx(tx) print("Claiming the GAS...") claim_tx, relayed = ClaimGas(self.wallet, require_password=False) self.wait_for_tx(claim_tx) # Finally, need to rebuild the wallet self.wallet.Rebuild() print("\nAll done!") print("- Wallet file: %s" % self.wallet_fn) print("- Wallet pwd: %s" % self.wallet_pwd) if self.wif_fn: with open(self.wif_fn, "w") as f: f.write("KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr") self.quit()
def example2(): source_address = "AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3" source_script_hash = address_to_scripthash(source_address) # start by creating a base InvocationTransaction # the inputs, outputs and Type do not have to be set anymore. invocation_tx = InvocationTransaction() # Since we are building a raw transaction, we will add the raw_tx flag invocation_tx.raw_tx = True # often times smart contract developers use the function ``CheckWitness`` to determine if the transaction is signed by somebody eligible of calling a certain method # in order to pass that check you want to add the corresponding script_hash as a transaction attribute (this is generally the script_hash of the public key you use for signing) # Note that for public functions like the NEP-5 'getBalance' and alike this would not be needed, but it doesn't hurt either invocation_tx.Attributes.append( TransactionAttribute(usage=TransactionAttributeUsage.Script, data=source_script_hash)) # next we need to build a 'script' that gets executed against the smart contract. # this is basically the script that calls the entry point of the contract with the necessary parameters smartcontract_scripthash = UInt160.ParseString( "31730cc9a1844891a3bafd1aa929a4142860d8d3") sb = ScriptBuilder() # call the NEP-5 `name` method on the contract (assumes contract address is a NEP-5 token) sb.EmitAppCallWithOperation(smartcontract_scripthash, 'name') invocation_tx.Script = binascii.unhexlify(sb.ToArray()) # at this point we've build our unsigned transaction and it's time to sign it before we get the raw output that we can send to the network via RPC # we need to create a Wallet instance for helping us with signing wallet = UserWallet.Create('path', to_aes_key('mypassword'), generate_default_key=False) # if you have a WIF use the following # this WIF comes from the `neo-test1-w.wallet` fixture wallet private_key = KeyPair.PrivateKeyFromWIF( "Ky94Rq8rb1z8UzTthYmy1ApbZa9xsKTvQCiuGUZJZbaDJZdkvLRV") # if you have a NEP2 encrypted key use the following instead # private_key = KeyPair.PrivateKeyFromNEP2("NEP2 key string", "password string") # we add the key to our wallet wallet.CreateKey(private_key) # and now we're ready to sign context = ContractParametersContext(invocation_tx) wallet.Sign(context) invocation_tx.scripts = context.GetScripts() raw_tx = invocation_tx.ToArray() return raw_tx
def execute(self, arguments): path = PromptUtils.get_arg(arguments, 0) if not path: print("Please specify a path") return if os.path.exists(path): print("File already exists") return if PromptData.Wallet: PromptData.close_wallet() try: passwd1 = prompt("[password]> ", is_password=True) passwd2 = prompt("[password again]> ", is_password=True) except KeyboardInterrupt: print("Wallet creation cancelled") return if passwd1 != passwd2 or len(passwd1) < 10: print( "Please provide matching passwords that are at least 10 characters long" ) return password_key = to_aes_key(passwd1) try: PromptData.Wallet = UserWallet.Create(path=path, password=password_key) contract = PromptData.Wallet.GetDefaultContract() key = PromptData.Wallet.GetKey(contract.PublicKeyHash) print("Wallet %s" % json.dumps(PromptData.Wallet.ToJson(), indent=4)) print("Pubkey %s" % key.PublicKey.encode_point(True)) except Exception as e: print("Exception creating wallet: %s" % e) PromptData.Wallet = None if os.path.isfile(path): try: os.remove(path) except Exception as e: print("Could not remove {}: {}".format(path, e)) return if PromptData.Wallet: asyncio.create_task( PromptData.Wallet.sync_wallet( start_block=PromptData.Wallet._current_height)) return PromptData.Wallet
def claim_initial_neo(self, target_address): wallets = [] i = 0 tx_json = None dbloops = [] print("Signing new transaction with 3 of 4 node keys...") for pkey, wif in nodekeys.items(): walletpath = "wallet{}.db3".format(i + 1) if os.path.exists(walletpath): os.remove(walletpath) wallet = UserWallet.Create(path=walletpath, password=to_aes_key(self.wallet_pwd)) wallets.append(wallet) print("Importing node private key to to {}".format(walletpath)) prikey = KeyPair.PrivateKeyFromWIF(wif) wallet.CreateKey(prikey) print("Importing multi-sig contract to {}".format(walletpath)) keys = list(nodekeys.keys()) pubkey_script_hash = Crypto.ToScriptHash(pkey, unhex=True) verification_contract = Contract.CreateMultiSigContract( pubkey_script_hash, 3, keys) wallet.AddContract(verification_contract) print("Added multi-sig contract address %s to wallet" % verification_contract.Address) dbloop = task.LoopingCall(wallet.ProcessBlocks) dbloop.start(1) dbloops.append(dbloop) # print("Wallet %s " % json.dumps(wallet.ToJson(), indent=4)) if i == 0: print( "Creating spend transaction to {}".format(target_address)) tx_json = self.send_neo(wallet, multisig_addr, target_address, '100000000') if tx_json is None: break else: tx_json = self.sign_and_finish(wallet, tx_json) if tx_json == 'success': print( "Finished, {} should now own all the NEO on the private network." .format(target_address)) break i += 1
def Sign(self, NEP2orPrivateKey, NEP2password=None, multisig_args=[]): """ Sign the raw transaction Args: NEP2orPrivateKey: (str) the NEP2 or PrivateKey string from the address you are sending from. NOTE: Assumes WIF if NEP2password is None. NEP2password: (str, optional) the NEP2 password associated with the NEP2 key string. Defaults to None. multisig_args: (list, optional) the arguments for importing a multsig address (e.g. [<owner pubkey>, <num required sigs>, [<signing pubkey>, ...]]) """ temp_path = "temp_wallet.wallet" temp_password = "******" wallet = UserWallet.Create(temp_path, to_aes_key(temp_password), generate_default_key=False) if NEP2password: private_key = KeyPair.PrivateKeyFromNEP2(NEP2orWIF, NEP2password) else: private_key = binascii.unhexlify(NEP2orPrivateKey) wallet.CreateKey(private_key) if multisig_args: # import a multisig address verification_contract = Contract.CreateMultiSigContract( Crypto.ToScriptHash(multisig_args[0], unhex=True), multisig_args[1], multisig_args[2]) wallet.AddContract(verification_contract) if self.Type == b'\xd1' and not self.SOURCE_SCRIPTHASH: # in case of an invocation with no funds transfer context = ContractParametersContext(self) elif not self._context: # used during transactions involving a funds transfer signer_contract = wallet.GetContract(self.SOURCE_SCRIPTHASH) context = ContractParametersContext( self, isMultiSig=signer_contract.IsMultiSigContract) else: context = self._context # used for a follow-on signature for a multi-sig transaction wallet.Sign(context) if context.Completed: self.scripts = context.GetScripts() self.Validate() # ensure the tx is ready to be relayed elif context.ContextItems: self._context = context print( "Transaction initiated, but the signature is incomplete. Sign again with another valid multi-sig keypair." ) else: raise SignatureError("Unable to sign transaction.") wallet.Close() wallet = None os.remove(temp_path)
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() while Blockchain.Default().Height < 2: print("Waiting for chain to sync...") time.sleep(1) # Open wallet again print("Opening wallet %s" % self.wallet_fn) self.wallet = UserWallet.Open(self.wallet_fn, to_aes_key("coz")) self.wallet.ProcessBlocks() self._walletdb_loop = task.LoopingCall(self.wallet.ProcessBlocks) self._walletdb_loop.start(1) print("\nWait %s min before claiming GAS." % self.min_wait) time.sleep(60 * self.min_wait) self.wallet.Rebuild() print("\nRebuilding wallet...") time.sleep(20) print("\nSending NEO to own wallet...") address = "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y" with patch('neo.Prompt.Commands.Send.prompt', side_effect=["coz"]): framework = construct_send_basic(self.wallet, ["neo", address, "100000000"]) tx = process_transaction(self.wallet, contract_tx=framework[0], scripthash_from=framework[1], fee=framework[2], owners=framework[3], user_tx_attributes=framework[4]) if not tx: print("Something went wrong, no tx.") return # Wait until transaction is on blockchain self.wait_for_tx(tx) print("Claiming the GAS...") claim_tx, relayed = ClaimGas(self.wallet, require_password=False) self.wait_for_tx(claim_tx) # Finally, need to rebuild the wallet # self.wallet.Rebuild() self.quit()
def test_listaddress_with_wallet(self): test_wallet_path = os.path.join(mkdtemp(), "listaddress.db3") self.app.wallet = UserWallet.Create(test_wallet_path, to_aes_key('awesomepassword')) req = self._gen_rpc_req("listaddress", params=[]) mock_req = mock_request(json.dumps(req).encode("utf-8")) res = json.loads(self.app.home(mock_req)) results = res.get('result', []) self.assertGreater(len(results), 0) self.assertIn(results[0].get('address', None), self.app.wallet.Addresses) self.app.wallet.Close() self.app.wallet = None os.remove(test_wallet_path)
def setup_wallet(self, wallet_path): if not os.path.exists(wallet_path): raise ValueError("Wallet file not found") self.wallet_path = wallet_path self.syncd_wallet_path = wallet_path + ".syncd" #always create a new synced wallet that will be used self.logger.info("Creating syncd copy of wallet file...") copyfile(self.wallet_path, self.syncd_wallet_path) wallet_passwd = prompt("[password]> ", is_password=True) self.wallet_passwd_key = to_aes_key(wallet_passwd) self.setup_network()
def setup_wallet(self, wallet_path): if not os.path.exists(wallet_path): raise ValueError("Wallet file not found") self.wallet_path = wallet_path self.syncd_wallet_path = wallet_path + ".syncd" if not os.path.exists(self.syncd_wallet_path): self.logger.info("Creating syncd copy of wallet file...") copyfile(self.wallet_path, self.syncd_wallet_path) wallet_passwd = getpass.getpass() self.wallet_passwd_key = to_aes_key(wallet_passwd) self.setup_network()
def test_getbalance_invalid_params(self): test_wallet_path = os.path.join(mkdtemp(), "getbalance.db3") self.app.wallet = UserWallet.Create( test_wallet_path, to_aes_key('awesomepassword') ) # max param length should be one, we provide 2 req = self._gen_rpc_req("getbalance", params=[1, 2]) mock_req = mock_request(json.dumps(req).encode("utf-8")) res = json.loads(self.app.home(mock_req)) error = res.get('error', {}) self.assertEqual(error.get('code', None), -400) self.assertEqual(error.get('message', None), "Params should contain 1 id.")
def __init__(self, contract_hash, wallet_file_path, wallet_password): logger.info("Initializes a BContract Instance") self.contract_hash = contract_hash self.wallet_file_path = wallet_file_path self.wallet_password = wallet_password if not os.path.exists(self.wallet_file_path): logger.error("Wallet file not found.") raise RuntimeError('Wallet File Not found') password_key = to_aes_key(self.wallet_password) try: self.Wallet = UserWallet.Open(self.wallet_file_path, password_key) logger.info("Opened wallet at %s" % self.wallet_file_path) except Exception as e: logger.error("Could not open wallet: %s" % e) raise RuntimeError("Could not open wallet: %s" % e)
def test_getbalance_token_with_wallet(self): test_wallet_path = os.path.join(mkdtemp(), "getbalance.db3") self.app.wallet = UserWallet.Create(test_wallet_path, to_aes_key('awesomepassword')) fake_token_id = "fd941304d9cf36f31cd141c7c7029d81b1efa4f3" req = self._gen_rpc_req("getbalance", params=[fake_token_id]) mock_req = mock_request(json.dumps(req).encode("utf-8")) res = json.loads(self.app.home(mock_req)) self.assertIn('Balance', res.get('result').keys()) self.assertNotIn('Confirmed', res.get('result').keys()) self.app.wallet.Close() self.app.wallet = None os.remove(test_wallet_path)
def test_getbalance_neo_with_wallet(self): test_wallet_path = os.path.join(mkdtemp(), "getbalance.db3") self.app.wallet = UserWallet.Create(test_wallet_path, to_aes_key('awesomepassword')) neo_id = "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b" req = self._gen_rpc_req("getbalance", params=[neo_id]) mock_req = mock_request(json.dumps(req).encode("utf-8")) res = json.loads(self.app.home(mock_req)) self.assertIn('Balance', res.get('result').keys()) self.assertIn('Confirmed', res.get('result').keys()) self.app.wallet.Close() self.app.wallet = None os.remove(test_wallet_path)
def do_create(self, arguments): item = get_arg(arguments) if item and item == 'wallet': path = get_arg(arguments, 1) if path: if os.path.exists(path): print("File already exists") return passwd1 = prompt("[password]> ", is_password=True) passwd2 = prompt("[password again]> ", is_password=True) if passwd1 != passwd2 or len(passwd1) < 10: print("Please provide matching passwords that are at least 10 characters long") return password_key = to_aes_key(passwd1) try: self.Wallet = UserWallet.Create(path=path, password=password_key) contract = self.Wallet.GetDefaultContract() key = self.Wallet.GetKey(contract.PublicKeyHash) print("Wallet %s" % json.dumps(self.Wallet.ToJson(), indent=4)) print("Pubkey %s" % key.PublicKey.encode_point(True)) except Exception as e: print("Exception creating wallet: %s" % e) self.Wallet = None if os.path.isfile(path): try: os.remove(path) except Exception as e: print("Could not remove {}: {}".format(path, e)) return if self.Wallet: self.start_wallet_loop() else: print("Please specify a path")
def GetWallet2(cls, recreate=False): if cls._wallet2 is None or recreate: cls._wallet2 = UserWallet.Open(WithdrawWalletTestCase.wallet_2_dest(), to_aes_key(WithdrawWalletTestCase.wallet_2_pass())) return cls._wallet2
def test_get_contains_key_should_be_found(self): wallet = Wallet("fakepath", to_aes_key("123"), True) wallet.CreateKey() keypair = wallet.GetKeys()[0] self.assertTrue(wallet.ContainsKey(keypair.PublicKey))
def test_get_contains_key_should_not_be_found(self): wallet = Wallet("fakepath", to_aes_key("123"), True) wallet.CreateKey() keypair = KeyPair(priv_key=self.pk) self.assertFalse(wallet.ContainsKey(keypair.PublicKey))
def test_privnet_wallet(self): """ Simple test if we can open the privnet wallet """ wallet = UserWallet.Open(os.path.join(ROOT_INSTALL_PATH, "neo/data/neo-privnet.sample.wallet"), to_aes_key("coz"))
def GetWallet1(cls, recreate=False): if cls._wallet1 is None or recreate: cls._wallet1 = UserWallet.Open(WalletFixtureTestCase.wallet_1_dest(), to_aes_key(WalletFixtureTestCase.wallet_1_pass())) return cls._wallet1
def test_0_bad_password(self): self.assertRaises(Exception, UserWallet.Open, UserWalletTestCase.wallet_1_dest(), to_aes_key('blah'))
def GetWallet1(cls, recreate=False): if cls._wallet1 is None or recreate: cls._wallet1 = UserWallet.Create(UserWalletTestCase.new_wallet_dest(), to_aes_key('awesomepassword')) return cls._wallet1