def check_privatenet(self): """ Check if privatenet is running, and if container is same as the current Chains/privnet database. Raises: PrivnetConnectionError: if the private net couldn't be reached or the nonce does not match """ rpc_settings.setup(self.RPC_LIST) client = RPCClient() version = client.get_version() if not version: raise PrivnetConnectionError("Error: private network container doesn't seem to be running, or RPC is not enabled.") print("Privatenet useragent '%s', nonce: %s" % (version["useragent"], version["nonce"])) # Now check if nonce is the same as in the chain path nonce_container = str(version["nonce"]) neopy_chain_meta_filename = os.path.join(self.chain_leveldb_path, ".privnet-nonce") if os.path.isfile(neopy_chain_meta_filename): nonce_chain = open(neopy_chain_meta_filename, "r").read() if nonce_chain != nonce_container: raise PrivnetConnectionError( "Chain database in Chains/privnet is for a different private network than the current container. " "Consider deleting the Chain directory with 'rm -rf %s*'." % self.chain_leveldb_path ) else: # When the Chains/privnet folder is removed, we need to create the directory if not os.path.isdir(self.chain_leveldb_path): os.mkdir(self.chain_leveldb_path) # Write the nonce to the meta file with open(neopy_chain_meta_filename, "w") as f: f.write(nonce_container)
def test_tx_json(self): client = RPCClient() hash = '58c634f81fbd4ae2733d7e3930a9849021840fc19dc6af064d6f2812a333f91d' tx = client.get_transaction(hash) self.assertEqual(tx['blocktime'], 1510283768) self.assertEqual(tx['txid'][2:], hash)
def test_call_endpoint_status_moved(self): # , mocked_post): client = RPCClient() responses.add(responses.POST, 'https://test5.cityofzion.io:443/', json={'Found': 'Moved'}, status=302) response = client.get_height() self.assertTrue('Found' in response)
def test_call_endpoint_exception(self): settings = SettingsHolder() settings.setup_privnet() client = RPCClient(config=settings) # Assumes no privnet is running (which always holds true on Travis-CI) with self.assertRaises(NEORPCException) as context: client.get_height() self.assertTrue("Could not call method" in str(context.exception))
def check_privatenet(self): """ Check if privatenet is running, and if container is same as the current Chains/privnet database. Raises: PrivnetConnectionError: if the private net couldn't be reached or the nonce does not match """ rpc_settings.setup(self.RPC_LIST) client = RPCClient() print("-----------check_privatenet----------") print("------------MOVIDA MEORED------------giorgi----------") print( "------------MOVIDA MEORED------------giorgi-----meore----------") print( "------------MOVIDA MEORED------------giorgi-----mesame----------") print( "------------MOVIDA MEORED------------giorgi-----mesamsadasdasde----------" ) print( "------------MOVIDA MEORED------------giorgi-----mesamsadasdasdesssss----------" ) print( "------------MOVIDA MEORED------------giorgi-----sasasasasasasasasasasasasassasss----------" ) try: version = client.get_version() except NEORPCException: raise PrivnetConnectionError( "Error: private network container doesn't seem to be running, or RPC is not enabled." ) print("Privatenet useragent '%s', nonce: %s" % (version["useragent"], version["nonce"])) # Now check if nonce is the same as in the chain path nonce_container = str(version["nonce"]) neopy_chain_meta_filename = os.path.join(self.chain_leveldb_path, ".privnet-nonce") if os.path.isfile(neopy_chain_meta_filename): nonce_chain = open(neopy_chain_meta_filename, "r").read() if nonce_chain != nonce_container: raise PrivnetConnectionError( "Chain database in Chains/privnet is for a different private network than the current container. " "Consider deleting the Chain directory with 'rm -rf %s*'." % self.chain_leveldb_path) else: # When the Chains/privnet folder is removed, we need to create the directory if not os.path.isdir(self.chain_leveldb_path): os.mkdir(self.chain_leveldb_path) # Write the nonce to the meta file with open(neopy_chain_meta_filename, "w") as f: f.write(nonce_container)
def test_asset_state(self): client = RPCClient() asset = client.get_asset(self.sample_asset) self.assertEqual(asset['type'], 'GoverningToken') self.assertEqual(int(asset['available']), 100000000) self.assertEqual(int(asset['precision']), 0)
def test_getblockhash(self): client = RPCClient() height = 12344 hash = client.get_block_hash(height) self.assertEqual( hash[2:], '1e67372c158a4cfbb17b9ad3aaae77001a4247a00318e354c62e53b56af4006f')
def test_contract_state(self): client = RPCClient() contract_hash = 'f8d448b227991cf07cb96a6f9c0322437f1599b9' contract = client.get_contract_state(contract_hash) hash = contract['hash'][2:] self.assertEqual(hash, contract_hash)
def test_send_raw_tx(self): client = RPCClient() raw_tx = '80000120d8edd2df8d6907caacd4af8872a596cb75c5829d015ce72895ce376d12def9a780ba502ae28ad7a4b7fbcf6baa4856edb537417d2a0000029b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc500a3e11100000000d8edd2df8d6907caacd4af8872a596cb75c5829d9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc500bbeea000000000d8edd2df8d6907caacd4af8872a596cb75c5829d01414044dfd2b360e548607ece3d453173079233040c2484a99671a7346a8ca16969245b946bfa4c13125f4c931b0cbab216e0d241d908f37ad96abb776890832a3a4b2321025de86902ed42aca7246207a70869b22253aeb7cc84a4cb5eee3773fd78b3f339ac' # this will result in a false, since this tx has already been made # but, if it were badly formmated, it would be an error # so we are testing if we get back a false result = client.send_raw_tx(raw_tx) self.assertEqual(result, False)
def test_getblockheader(self): client = RPCClient() hash = '1e67372c158a4cfbb17b9ad3aaae77001a4247a00318e354c62e53b56af4006f' header = client.get_block_header(hash) self.assertEqual( header['hash'][2:], '1e67372c158a4cfbb17b9ad3aaae77001a4247a00318e354c62e53b56af4006f') self.assertEqual(header['index'], 12344) self.assertNotIn('tx', header)
def test_tx_out(self): client = RPCClient() tx_hash = '58c634f81fbd4ae2733d7e3930a9849021840fc19dc6af064d6f2812a333f91d' index = 0 txout = client.get_tx_out(tx_hash, index) # this tests fails since this tx out has been spent on the blockchain? # self.assertEqual(txout['asset'][2:], '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7') # self.assertEqual(txout['n'], index) # self.assertEqual(txout['address'], self.sample_addr) self.assertIsNone(txout)
def test_settings(self): settings = SettingsHolder() settings.setup_mainnet() client = RPCClient(config=settings) self.assertIsNotNone(client.endpoints) settings.setup_testnet() client = RPCClient(config=settings) self.assertIsNotNone(client.endpoints) settings.setup_privnet() client = RPCClient(config=settings) self.assertIsNotNone(client.endpoints)
def test_validate_addr(self): client = RPCClient() result = client.validate_addr(self.sample_addr) self.assertEqual(result['isvalid'], True) self.assertEqual(result['address'], self.sample_addr) bad_addr = 'BXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK' result = client.validate_addr(bad_addr) self.assertEqual(result['isvalid'], False)
def test_get_storage(self): client = RPCClient() contract_hash = 'd7678dd97c000be3f33e9362e673101bac4ca654' key = 'totalSupply' storage = client.get_storage(contract_hash, key) self.assertIsInstance(storage, bytearray) intval = int.from_bytes(storage, 'little') self.assertEqual(intval, 196900000000000)
def test_account_state(self): client = RPCClient() account = client.get_account(self.sample_addr) script_hash = bytearray(binascii.unhexlify(account['script_hash'][2:])) script_hash.reverse() self.assertEqual(len(script_hash), 20) balances = account['balances'] self.assertIsNotNone(balances) self.assertGreater(len(balances), 0)
def __init__(self, use_privnet=True): settings = SettingsHolder() if use_privnet: addr_list = ["http://private_net:20332"] settings.setup(addr_list) else: settings.setup_mainnet() self.neo_rpc_client = RPCClient(settings) self.rds = Redis(host='redis', port=6379, db=0) self.nm_auth_token = os.environ.get('NM_AUTH_TOKEN', None)
def test_get_block_json(self): client = RPCClient() height = 12344 blockjson1 = client.get_block(height) blockhash = blockjson1['hash'][2:] self.assertEqual(blockhash, '1e67372c158a4cfbb17b9ad3aaae77001a4247a00318e354c62e53b56af4006f') blockjson2 = client.get_block(blockhash) # self.assertEqual(blockjson1, blockjson2) self.assertEqual(height, blockjson1['index'])
def test_invoke(self): client = RPCClient() contract_hash = 'd7678dd97c000be3f33e9362e673101bac4ca654' params = [{'type': 7, 'value': 'symbol'}, {'type': 16, 'value': []}] result = client.invoke_contract(contract_hash, params) self.assertEqual(result['state'], 'HALT, BREAK') invoke_result = result['stack'] self.assertEqual(len(invoke_result), 1) stack_item = invoke_result[0] self.assertEqual(stack_item['type'], 'ByteArray') self.assertEqual(binascii.hexlify('LWTF'.encode('utf-8')).decode('utf-8'), stack_item['value'])
def test_client(self): client = RPCClient() self.assertIsNotNone(client.endpoints) self.assertGreater(len(client.endpoints), 0) self.assertIsInstance(client.default_endpoint, RPCEndpoint) self.assertEqual(client.default_endpoint.height, None)
def test_get_storage(self): client = RPCClient() contract_hash = 'd7678dd97c000be3f33e9362e673101bac4ca654' key = 'totalSupply' storage = client.get_storage(contract_hash, key) self.assertIsInstance(storage, bytearray) intval = int.from_bytes(storage, 'little') self.assertEqual(intval, 227000000000000) # now also test for failure key = 'invalidkey' with self.assertRaises(NEORPCException) as context: storage = client.get_storage(contract_hash, key) self.assertTrue("could not decode result" in str(context.exception))
def test_client_setup(self): client = RPCClient(setup=True) self.assertIsNotNone(client.endpoints) self.assertGreater(len(client.endpoints), 0) self.assertIsInstance(client.default_endpoint, RPCEndpoint) self.assertIsNotNone(client.default_endpoint.height) self.assertEqual(client.default_endpoint.status, 200)
def test_invoke_script(self): client = RPCClient() script = '00c10b746f74616c537570706c796754a64cac1b1073e662933ef3e30b007cd98d67d7' result = client.invoke_script(script) self.assertEqual(result['state'], 'HALT, BREAK') invoke_result = result['stack'] self.assertEqual(len(invoke_result), 1) invoke_result = result['stack'] self.assertEqual(len(invoke_result), 1) stack_item = invoke_result[0] self.assertEqual(stack_item['type'], 'ByteArray') val = int.from_bytes(binascii.unhexlify(stack_item['value'].encode('utf-8')), 'little') self.assertEqual(val, 227000000000000)
def test_invoke_fn(self): client = RPCClient() contract_hash = 'd7678dd97c000be3f33e9362e673101bac4ca654' result = client.invoke_contract_fn(contract_hash, 'name') self.assertEqual(result['state'], 'HALT, BREAK') invoke_result = result['stack'] self.assertEqual(len(invoke_result), 1) invoke_result = result['stack'] self.assertEqual(len(invoke_result), 1) stack_item = invoke_result[0] self.assertEqual(stack_item['type'], 'ByteArray') val = binascii.unhexlify(stack_item['value'].encode('utf-8')).decode('utf-8') self.assertEqual(val, 'LOCALTOKEN')
class NEOInterface(): def __init__(self, use_privnet=True): settings = SettingsHolder() if use_privnet: addr_list = ["http://private_net:20332"] settings.setup(addr_list) else: settings.setup_mainnet() self.neo_rpc_client = RPCClient(settings) self.rds = Redis(host='redis', port=6379, db=0) self.nm_auth_token = os.environ.get('NM_AUTH_TOKEN', None) def check_funds(self, address, amount, asset): account = None while not account: account = self.neo_rpc_client.get_account(address) balances = account['balances'] for i in balances: if i['asset'] == asset: if int(i['value']) >= amount: return True return False def check_transaction(self, sender, receiver, amount, asset, min_conf): height = None while not height: height = self.neo_rpc_client.get_height() time.sleep(1) block = None while not block: block = self.neo_rpc_client.get_block(height) if 'error' in block: if 'message' in block['error']: if block['error']['message'] == 'Unknown block': block = None confirmations = int(block['confirmations']) for i in block['tx']: if i['type'] == 'ContractTransaction': txid = i['txid'] transaction = self.neo_rpc_client.get_transaction(txid) if transaction['vout'][0]['address'] == 'receiver': if transaction['vout'][1]['address'] == 'sender': if int(transaction['vout'][0]['value']) == int(amount): if transaction['vout'][0] == asset: if confirmations >= int(min_conf): return True return False def validate_addr(self, address): result = None while not result: result = self.neo_rpc_client.validate_addr(address) return result def address_to_hash(self, address): account = self.neo_rpc_client.get_account(address) script_hash = account['script_hash'] return script_hash def add_milestone(self, dapp_script_hash, milestone_key, agreement, neo_address_customer, neo_address_assignee, platform, timestamp, utc_offset, neo_address_oracle, pay_out, asset, threshold): params = {} params['milestone_key'] = milestone_key params['agreement'] = agreement customer_hash = self.address_to_hash(neo_address_customer) params['customer'] = customer_hash assignee_hash = self.address_to_hash(neo_address_assignee) params['assignee'] = assignee_hash params['platform'] = platform params['timestamp'] = timestamp params['utc_offset'] = utc_offset oracle_hash = self.address_to_hash(neo_address_oracle) params['oracle'] = oracle_hash params['pay_out'] = pay_out params['asset'] = asset params['threshold'] = threshold cmd_id = uuid.uuid4() operation = 'milestone' data = { 'auth_token': self.nm_auth_token, 'cmd_id': cmd_id, 'operation': operation, 'params': params } data = json.dumps(data) self.rds.publish('neo-cmd', data) def review_milestone(self, dapp_script_hash, milestone_key, score): params = {} params['milestone_key'] = milestone_key params['score'] = score cmd_id = uuid.uuid4() operation = 'review' data = { 'auth_token': self.nm_auth_token, 'cmd_id': cmd_id, 'operation': operation, 'params': params } data = json.dumps(data) self.rds.publish('neo-cmd', data)
def test_get_version(self): client = RPCClient() version = client.get_version() self.assertIn("port", version) self.assertIn("nonce", version) self.assertIn("useragent", version)
from neorpc.Client import RPCClient client = RPCClient() blockchain_height = client.get_height() print(blockchain_height) balance = client.get_balance( "602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7") print(balance)
from neorpc.Client import RPCClient import binascii import base64 import json client = RPCClient() CONTRACT_ID = '0xe9bf8617ee1e4a3ff9177eb6ebe2d9e790fc590a' def get_hash_of_block(block_id=1): return client.get_block_hash(block_id) def invoke_contract(assets_id): return client.invoke_contract_fn(CONTRACT_ID, "query", [{ 'type': 7, 'value': assets_id }]) def invoke_contract_query_asset(owner): return client.invoke_contract_fn(CONTRACT_ID, "query_asset_list", [{ 'type': 7, 'value': owner }]) def get_owner_data(assets_id='asd'): data = dict(invoke_contract(assets_id)) value = data['stack'][0]['value']
print(string_value) return string_value print("No value!") except Exception as e: print("Error: {}".format(e)) from neorpc.Client import RPCClient, RPCEndpoint from neorpc.Settings import SettingsHolder from binascii import hexlify, unhexlify settings = SettingsHolder() settings.setup_privnet() client = RPCClient(config=settings) endpoint = "http://neo-privnet.what.digital:30333" WALLETS = { "main_wallet": { 'address': "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y", 'wif': "KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr", }, "wallet_chris": { 'address': "ALA1eYePMiNVfiHvQGVnupDFmjoPFwSoUc", 'wif': "L3QGJ5FMg7LQWYkVekkwRDyYL3HXTw3ntYrTupjp3EViru7kTGN7", }, "wallet_mario": { 'address': "AeT1nT8AM9jvDBiYWVKHj3NC6eACnmnpdU", 'wif': "L3cm5QTxQncntWBVGZxFNSS2C7GEoL4Q3Mk8iKVXVvMTBrpjAyPM", }