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 try: self.Wallet = UserWallet.Create(path=path, password=passwd1) 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 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=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)) multisig_args = [pkey, '3'] multisig_args.extend(list(nodekeys.keys())) ImportMultiSigContractAddr(wallet, multisig_args) 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 test_send_to_address_wrong_arguments(self): test_wallet_path = os.path.join(mkdtemp(), "sendtoaddress.db3") self.app.wallet = UserWallet.Create(test_wallet_path, to_aes_key('awesomepassword')) req = self._gen_rpc_req("sendtoaddress", params=["arg"]) 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), -32602) self.assertEqual(error.get('message', None), "Invalid params") self.app.wallet.Close() self.app.wallet = None os.remove(test_wallet_path)
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() 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: 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: PromptData.Prompt.start_wallet_loop() return PromptData.Wallet
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 test_getnewaddress_with_wallet(self): test_wallet_path = os.path.join(mkdtemp(), "getnewaddress.db3") self.app.wallet = UserWallet.Create(test_wallet_path, to_aes_key('awesomepassword')) old_addrs = self.app.wallet.Addresses req = self._gen_rpc_req("getnewaddress", params=[]) mock_req = mock_request(json.dumps(req).encode("utf-8")) res = json.loads(self.app.home(mock_req)) result = res.get('result') self.assertNotIn(result, old_addrs) self.assertIn(result, self.app.wallet.Addresses) self.app.wallet.Close() self.app.wallet = None os.remove(test_wallet_path)
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 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 testNeoClient(): invocation_tx = InvocationTransaction() smartcontract_scripthash = UInt160.ParseString(CONTRACT_HASH) sb = ScriptBuilder() sb.EmitAppCallWithOperationAndArgs( smartcontract_scripthash, 'onboard', [b'Munich', b'*****@*****.**', b'xxx']) 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 json.dumps({ "raw_tx": raw_tx.decode("ascii"), "result": result, "payload": payload, })
def create_wallet(self, path, password): try: self.Wallet = UserWallet.Create(path, password) 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)
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() while Blockchain.Default().Height < 2: print("Waiting for wallet to sync...") time.sleep(1) print("Creating Wallet...") self.wallet = UserWallet.Create(path=self.wallet_fn, password=self.wallet_pwd) self.wallet.ProcessBlocks() # Extract infos from wallet contract = self.wallet.GetDefaultContract() key = self.wallet.GetKey(contract.PublicKeyHash) address = key.GetAddress() wif = key.Export() print("- Address:", address) print("- WIF key:", wif) self.wallet = None # Claim initial NEO self.claim_initial_neo(address) # Open wallet again self.wallet = UserWallet.Open(self.wallet_fn, self.wallet_pwd) 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) print("\nSending NEO 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("- WIF key: %s" % wif) 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(wif) self.quit()
def GetWallet1(cls, recreate=False): if cls._wallet1 is None or recreate: cls._wallet1 = UserWallet.Create( UserWalletTestCase.new_wallet_dest(), 'awesomepassword') return cls._wallet1
def example1(): neo_asset_id = Blockchain.GetSystemShare().Hash gas_asset_id = Blockchain.GetSystemCoin().Hash source_address = "AJQ6FoaSXDFzA6wLnyZ1nFN7SGSN2oNTc3" source_script_hash = address_to_scripthash(source_address) destination_address = "Ad9A1xPbuA5YBFr1XPznDwBwQzdckAjCev" destination_script_hash = address_to_scripthash(destination_address) # Let's start with building a ContractTransaction # The constructor already sets the correct `Type` and `Version` fields, so we do not have to worry about that contract_tx = ContractTransaction() # the ContractTransaction type has no special data, so we do not have to do anything there # Next we can add Attributes if we want. Again the various types are described in point 4. of the main link above # We will add a simple "description" contract_tx.Attributes.append( TransactionAttribute(usage=TransactionAttributeUsage.Description, data="My raw contract transaction description")) # The next field we will set are the inputs. The inputs neo-python expects are of the type ``CoinReference`` # To create these inputs we will need the usual `PrevHash` and `PrevIndex` values. # You can get the required data by using e.g. the neoscan.io API: https://api.neoscan.io/docs/index.html#api-v1-get-3 # The `PrevHash` field equals to neoscan's `balance.unspent[index].txid` key, and `PrevIndex` comes from `balance.unspent[index].n` # It is up to the transaction creator to make sure that the sum of all input ``value`` fields is equal to or bigger than the amount that's intended to be send # The below values are taken from data out of the `neo-test1-w.wallet` fixture wallet (a wallet neo-python uses for internal testing) input1 = CoinReference(prev_hash=UInt256(data=binascii.unhexlify( '949354ea0a8b57dfee1e257a1aedd1e0eea2e5837de145e8da9c0f101bfccc8e')), prev_index=1) contract_tx.inputs = [input1] # Next we will create the outputs. # The above input has a value of 50. We will create 2 outputs. # 1 output for sending 3 NEO to a specific destination address send_to_destination_output = TransactionOutput( AssetId=neo_asset_id, Value=Fixed8.FromDecimal(3), script_hash=destination_script_hash) # and a second output for sending the change back to ourselves return_change_output = TransactionOutput(AssetId=neo_asset_id, Value=Fixed8.FromDecimal(47), script_hash=source_script_hash) contract_tx.outputs = [send_to_destination_output, return_change_output] # 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(contract_tx) wallet.Sign(context) contract_tx.scripts = context.GetScripts() print(contract_tx.Hash.ToString()) raw_tx = contract_tx.ToArray()
def registerUser(username,password): settings.setup_privnet() UserWallet.Create(username+".json",to_aes_key(password)) return UserWallet.Addresses