def test_getHeight(self): with set_xrd_dir('no_data'): db_state = State() alice_xmss = get_alice_xmss() optimized_address_state = OptimizedAddressState.create(address=alice_xmss.address, nonce=25, balance=10, ots_bitfield_used_page=0, transaction_hash_count=0, tokens_count=0, lattice_pk_count=0, slaves_count=0, multi_sig_address_count=0) addresses_state = {optimized_address_state.address: optimized_address_state} AddressState.put_addresses_state(db_state, addresses_state) p2p_factory = Mock(spec=P2PFactory) chain_manager = ChainManager(db_state) chain_manager._last_block = Mock() chain_manager._last_block.block_number = 100 xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) context = Mock(spec=ServicerContext) request = xrd_pb2.GetHeightReq() response = service.GetHeight(request=request, context=context) self.assertEqual(response.height, 100)
def test_getKnownPeers(self): p2p_factory = Mock(spec=P2PFactory) p2p_factory.sync_state = SyncState() p2p_factory.num_connections = 23 p2p_factory.pow = Mock() chain_manager = Mock(spec=ChainManager) chain_manager.height = 0 chain_manager.last_block = Block() xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow xrdnode.peer_manager = Mock() xrdnode.peer_manager.known_peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) response = service.GetKnownPeers(request=xrd_pb2.GetKnownPeersReq, context=None) self.assertEqual(2, len(response.known_peers)) self.assertEqual('127.0.0.1', response.known_peers[0].ip) self.assertEqual('192.168.1.1', response.known_peers[1].ip) logger.info(response)
def test_getBlock(self): with set_xrd_dir('no_data'): db_state = State() p2p_factory = Mock(spec=P2PFactory) p2p_factory.pow = Mock(spec=POW) chain_manager = ChainManager(db_state) xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) alice_xmss = get_alice_xmss() b = Block.create(dev_config=config.dev, block_number=1, prev_headerhash=sha256(b'reveal'), prev_timestamp=10, transactions=[], miner_address=alice_xmss.address, seed_height=0, seed_hash=None) Block.put_block(db_state, b, None) db_state.get_block = MagicMock(return_value=b) context = Mock(spec=ServicerContext) request = xrd_pb2.GetBlockReq(header_hash=b.headerhash) response = service.GetBlock(request=request, context=context) context.set_code.assert_not_called() self.assertEqual(1, response.block.header.block_number)
def test_getStats_timeseries(self): with MockedBlockchain.create(10) as mock_blockchain: service = PublicAPIService(mock_blockchain.xrdnode) request = xrd_pb2.GetStatsReq(include_timeseries=1) stats = service.GetStats(request=request, context=None) print(stats.block_timeseries) self.assertEqual(11, len(stats.block_timeseries)) self.assertEqual(61, stats.block_time_mean) self.assertEqual(1, stats.block_time_sd)
def test_transferCoins_push_unsigned(self): with set_xrd_dir('wallet_ver1'): with State() as db_state: p2p_factory = Mock(spec=P2PFactory) p2p_factory.pow = Mock(spec=POW) chain_manager = ChainManager(db_state) xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) context = Mock(spec=ServicerContext) alice = get_alice_xmss() bob = get_bob_xmss() request = xrd_pb2.TransferCoinsReq( addresses_to=[bob.address], amounts=[101], fee=12, xmss_pk=alice.pk ) response = service.TransferCoins(request=request, context=context) context.set_code.assert_not_called() context.set_details.assert_not_called() self.assertIsNotNone(response) self.assertIsNotNone(response.extended_transaction_unsigned) self.assertEqual('transfer', response.extended_transaction_unsigned.tx.WhichOneof('transactionType')) self.assertEqual(12, response.extended_transaction_unsigned.tx.fee) self.assertEqual(alice.pk, response.extended_transaction_unsigned.tx.public_key) self.assertEqual(0, response.extended_transaction_unsigned.tx.nonce) self.assertEqual(b'', response.extended_transaction_unsigned.tx.signature) self.assertEqual(b'', response.extended_transaction_unsigned.tx.transaction_hash) self.assertEqual(bob.address, response.extended_transaction_unsigned.tx.transfer.addrs_to[0]) self.assertEqual(101, response.extended_transaction_unsigned.tx.transfer.amounts[0]) req_push = xrd_pb2.PushTransactionReq(transaction_signed=response.extended_transaction_unsigned.tx) resp_push = service.PushTransaction(req_push, context=context) context.set_code.assert_not_called() context.set_details.assert_not_called() self.assertIsNotNone(resp_push) self.assertEqual(xrd_pb2.PushTransactionResp.VALIDATION_FAILED, resp_push.error_code)
def test_getTransaction(self): db_state = Mock(spec=State) db_state.get_tx_metadata = MagicMock(return_value=None) db_state.get_block = MagicMock(return_value=None) p2p_factory = Mock(spec=P2PFactory) p2p_factory.pow = Mock(spec=POW) chain_manager = ChainManager(db_state) xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) # Find an address bob_xmss = get_bob_xmss() # Find a transaction alice_xmss = get_alice_xmss() db_state.address_used = MagicMock(return_value=False) tx1 = TransferTransaction.create( addrs_to=[bob_xmss.address], amounts=[125], message_data=None, fee=19, xmss_pk=bob_xmss.pk, master_addr=alice_xmss.address) chain_manager.tx_pool.transaction_pool = [(0, TransactionInfo(tx1, 0))] context = Mock(spec=ServicerContext) request = xrd_pb2.GetTransactionReq() request.tx_hash = tx1.txhash response = service.GetTransaction(request=request, context=context) context.set_code.assert_not_called() self.assertIsNotNone(response.tx) self.assertEqual('transfer', response.tx.WhichOneof('transactionType')) self.assertEqual(alice_xmss.address, response.tx.master_addr) self.assertEqual(bob_xmss.pk, response.tx.public_key) self.assertEqual(tx1.txhash, response.tx.transaction_hash) self.assertEqual(b'', response.tx.signature) self.assertEqual(bob_xmss.address, response.tx.transfer.addrs_to[0]) self.assertEqual(125, response.tx.transfer.amounts[0]) self.assertEqual(19, response.tx.fee)
def test_getStats(self): number_blocks = 1 with MockedBlockchain.create(number_blocks) as mock_blockchain: with set_timeseries_size(10): service = PublicAPIService(mock_blockchain.xrdnode) for i in range(number_blocks + 1, 50): mock_blockchain.add_new_block() request = xrd_pb2.GetStatsReq() request.include_timeseries = True stats = service.GetStats(request=request, context=None) self.assertEqual(min(10, i + 1), len(stats.block_timeseries))
def test_getAddressState(self): with set_xrd_dir('no_data'): db_state = State() alice_xmss = get_alice_xmss() optimized_address_state = OptimizedAddressState.create(address=alice_xmss.address, nonce=25, balance=10, ots_bitfield_used_page=0, transaction_hash_count=0, tokens_count=0, lattice_pk_count=0, slaves_count=0, multi_sig_address_count=0) AddressState.put_address_state(db_state, optimized_address_state) p2p_factory = Mock(spec=P2PFactory) chain_manager = ChainManager(db_state) xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) context = Mock(spec=ServicerContext) request = xrd_pb2.GetAddressStateReq() service.GetAddressState(request=request, context=context) context.set_code.assert_called() context.set_details.assert_called() context = Mock(spec=ServicerContext) request = xrd_pb2.GetAddressStateReq() request.address = get_alice_xmss().address response = service.GetAddressState(request=request, context=context) context.set_code.assert_not_called() self.assertEqual(alice_xmss.address, response.state.address) self.assertEqual(25, response.state.nonce) self.assertEqual(10, response.state.balance) self.assertEqual([b'\x00'] * config.dev.ots_bitfield_size, response.state.ots_bitfield) self.assertEqual([], response.state.transaction_hashes)
def test_getOTS(self): with set_xrd_dir('no_data'): db_state = State() alice_xmss = get_alice_xmss() optimized_address_state = OptimizedAddressState.create(address=alice_xmss.address, nonce=25, balance=10, ots_bitfield_used_page=0, transaction_hash_count=0, tokens_count=0, lattice_pk_count=0, slaves_count=0, multi_sig_address_count=0) addresses_state = {optimized_address_state.address: optimized_address_state} AddressState.put_addresses_state(db_state, addresses_state) p2p_factory = Mock(spec=P2PFactory) chain_manager = ChainManager(db_state) xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) context = Mock(spec=ServicerContext) request = xrd_pb2.GetOTSReq(address=alice_xmss.address) response = service.GetOTS(request=request, context=context) context.set_code.assert_not_called() self.assertEqual(0, response.next_unused_ots_index) paginated_bitfield = PaginatedBitfield(True, db_state._db) paginated_bitfield.set_ots_key(addresses_state, optimized_address_state.address, 0) paginated_bitfield.put_addresses_bitfield(None) response = service.GetOTS(request=request, context=context) context.set_code.assert_not_called() self.assertEqual(1, response.next_unused_ots_index)
def test_getNodeState(self): p2p_factory = Mock(spec=P2PFactory) p2p_factory.sync_state = SyncState() p2p_factory.num_connections = 23 p2p_factory.pow = Mock() chain_manager = Mock(spec=ChainManager) chain_manager.height = 0 chain_manager.last_block = Block() xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow service = PublicAPIService(xrdnode) node_state = service.GetNodeState(request=xrd_pb2.GetNodeStateReq, context=None) # self.assertEqual(__version__, node_state.info.version) # FIXME self.assertEqual(xrd_pb2.NodeInfo.UNSYNCED, node_state.info.state) self.assertEqual(23, node_state.info.num_connections)
def test_GetTokenTxn_Error(self): p2p_factory = Mock(spec=P2PFactory) p2p_factory.sync_state = SyncState() p2p_factory.num_connections = 23 p2p_factory.pow = Mock() chain_manager = Mock(spec=ChainManager) chain_manager.height = 0 xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow service = PublicAPIService(xrdnode) request = xrd_pb2.TokenTxnReq() context = Mock(spec=ServicerContext) context.set_code = MagicMock() service.GetTokenTxn(request=request, context=context) context.set_code.assert_called_with(StatusCode.INVALID_ARGUMENT)
def test_getAddressFromPK(self): p2p_factory = Mock(spec=P2PFactory) p2p_factory.sync_state = SyncState() p2p_factory.num_connections = 23 p2p_factory.pow = Mock() chain_manager = Mock(spec=ChainManager) chain_manager.height = 0 xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow service = PublicAPIService(xrdnode) pk = hstr2bin('01060057ac9cb6085a8135631dcf018dff46d9c368a0b64d508f512e584199b6800' 'f8cfcb672b931398a023680fe0308ed4b6ec75877d684bc2ccf11703e8369f064e7') request = xrd_pb2.GetAddressFromPKReq(pk=bytes(pk)) response = service.GetAddressFromPK(request=request, context=None) self.assertEqual('010600b56d161c7de8aa741962e3e49b973b7e53456fa47f2443d69f17c632f29c8b1aab7d2491', bin2hstr(response.address))
def test_getStats(self): db_state = Mock(spec=State) db_state.total_coin_supply = 1000 db_state.get_measurement = MagicMock(return_value=60) db_state.get_block_by_number = MagicMock(return_value=None) p2p_factory = Mock(spec=P2PFactory) p2p_factory.sync_state = SyncState() p2p_factory.num_connections = 23 p2p_factory.pow = Mock() chain_manager = ChainManager(db_state) chain_manager._last_block = GenesisBlock() xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow service = PublicAPIService(xrdnode) request = xrd_pb2.GetStatsReq() stats = service.GetStats(request=request, context=None) # self.assertEqual(__version__, stats.node_info.version) # FIXME self.assertEqual(xrd_pb2.NodeInfo.UNSYNCED, stats.node_info.state) self.assertEqual(23, stats.node_info.num_connections) # self.assertEqual("testnet", stats.node_info.network_id) # FIXME self.assertEqual(0, stats.epoch) self.assertEqual(0, stats.uptime_network) self.assertEqual(65000000000000000, stats.block_last_reward) self.assertEqual(0, stats.block_time_mean) self.assertEqual(0, stats.block_time_sd) self.assertEqual(105000000, stats.coins_total_supply) self.assertEqual(1000, stats.coins_emitted) self.assertEqual(0, len(stats.block_timeseries))
def getStats_forking(self, timeseries_size): number_blocks = 10 with MockedBlockchain.create(number_blocks) as mock_blockchain: with set_timeseries_size(timeseries_size): service = PublicAPIService(mock_blockchain.xrdnode) request = xrd_pb2.GetStatsReq(include_timeseries=True) stats = service.GetStats(request=request, context=None) self.assertEqual(timeseries_size, len(stats.block_timeseries)) # Fork at node 9 with 2 blocks (b) block_9 = mock_blockchain.xrdnode.get_block_from_index(9) block_10 = mock_blockchain.xrdnode.get_block_last() block_10b = mock_blockchain.create_block(block_9.headerhash) mock_blockchain.add_block(block_10b) block_11b = mock_blockchain.create_block(block_10b.headerhash) mock_blockchain.add_block(block_11b) # Get time series request = xrd_pb2.GetStatsReq(include_timeseries=True) stats = service.GetStats(request=request, context=None) self.assertEqual(timeseries_size, len(stats.block_timeseries)) # check stats have moved to the correct branch self.assertEqual(block_11b.headerhash, stats.block_timeseries[-1].header_hash) # Add back to the original chain (a) block_11 = mock_blockchain.create_block(block_10.headerhash) mock_blockchain.add_block(block_11) block_12 = mock_blockchain.create_block(block_11.headerhash) mock_blockchain.add_block(block_12) # Get time series request = xrd_pb2.GetStatsReq(include_timeseries=True) stats = service.GetStats(request=request, context=None) self.assertEqual(timeseries_size, len(stats.block_timeseries)) # check stats have moved back to the correct branch self.assertEqual(block_12.headerhash, stats.block_timeseries[-1].header_hash)
def start_services(node: xrdNode): public_server = grpc.server(ThreadPoolExecutor(max_workers=config.user.public_api_threads), maximum_concurrent_rpcs=config.user.public_api_max_concurrent_rpc) add_BaseServicer_to_server(BaseService(node), public_server) add_PublicAPIServicer_to_server(PublicAPIService(node), public_server) if config.user.public_api_enabled: public_server.add_insecure_port("{0}:{1}".format(config.user.public_api_host, config.user.public_api_port)) public_server.start() logger.info("grpc public service - started !") admin_server = grpc.server(ThreadPoolExecutor(max_workers=config.user.admin_api_threads), maximum_concurrent_rpcs=config.user.admin_api_max_concurrent_rpc) add_AdminAPIServicer_to_server(AdminAPIService(node), admin_server) if config.user.admin_api_enabled: admin_server.add_insecure_port("{0}:{1}".format(config.user.admin_api_host, config.user.admin_api_port)) admin_server.start() logger.info("grpc admin service - started !") mining_server = grpc.server(ThreadPoolExecutor(max_workers=config.user.mining_api_threads), maximum_concurrent_rpcs=config.user.mining_api_max_concurrent_rpc) add_MiningAPIServicer_to_server(MiningAPIService(node), mining_server) if config.user.mining_api_enabled: mining_server.add_insecure_port("{0}:{1}".format(config.user.mining_api_host, config.user.mining_api_port)) mining_server.start() logger.info("grpc mining service - started !") debug_server = grpc.server(ThreadPoolExecutor(max_workers=config.user.debug_api_threads), maximum_concurrent_rpcs=config.user.debug_api_max_concurrent_rpc) add_DebugAPIServicer_to_server(DebugAPIService(node), debug_server) if config.user.debug_api_enabled: debug_server.add_insecure_port("{0}:{1}".format(config.user.debug_api_host, config.user.debug_api_port)) debug_server.start() logger.info("grpc debug service - started !") return admin_server, public_server, mining_server, debug_server
def test_transferCoins_sign(self): with set_xrd_dir('wallet_ver1'): with State() as db_state: p2p_factory = Mock(spec=P2PFactory) p2p_factory.pow = Mock(spec=POW) chain_manager = ChainManager(db_state) xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) context = Mock(spec=ServicerContext) alice = get_alice_xmss() bob = get_bob_xmss() request = xrd_pb2.TransferCoinsReq( addresses_to=[bob.address], amounts=[101], fee=12, xmss_pk=alice.pk ) response = service.TransferCoins(request=request, context=context) context.set_code.assert_not_called() context.set_details.assert_not_called() self.assertIsNotNone(response) self.assertIsNotNone(response.extended_transaction_unsigned.tx) self.assertEqual('transfer', response.extended_transaction_unsigned.tx.WhichOneof('transactionType')) self.assertEqual(12, response.extended_transaction_unsigned.tx.fee) self.assertEqual(alice.pk, response.extended_transaction_unsigned.tx.public_key) self.assertEqual(0, response.extended_transaction_unsigned.tx.nonce) self.assertEqual(b'', response.extended_transaction_unsigned.tx.signature) self.assertEqual(b'', response.extended_transaction_unsigned.tx.transaction_hash) self.assertEqual(bob.address, response.extended_transaction_unsigned.tx.transfer.addrs_to[0]) self.assertEqual(101, response.extended_transaction_unsigned.tx.transfer.amounts[0]) tmp_hash_pre = bytes(xrdHelper.getAddress(response.extended_transaction_unsigned.tx.public_key)) tmp_hash_pre += str(response.extended_transaction_unsigned.tx.fee).encode() tmp_hash_pre += response.extended_transaction_unsigned.tx.transfer.addrs_to[0] tmp_hash_pre += str(response.extended_transaction_unsigned.tx.transfer.amounts[0]).encode() self.assertEqual('010300a1da274e68c88b0ccf448e0b1916fa789b01eb2ed4e9ad565ce264c939078' '2a9c61ac02f31320103001d65d7e59aed5efbeae64246e0f3184d7c42411421eb38' '5ba30f2c1c005a85ebc4419cfd313031', bin2hstr(tmp_hash_pre)) tmp_hash = sha256(tmp_hash_pre) self.assertEqual('3645f2819aba65479f9a7fad3f5d7a41a9357410a595fa02fb947bfe3ed96e0f', bin2hstr(tmp_hash)) signed_transaction = response.extended_transaction_unsigned.tx signed_transaction.signature = alice.sign(tmp_hash) req_push = xrd_pb2.PushTransactionReq(transaction_signed=signed_transaction) resp_push = service.PushTransaction(req_push, context=context) context.set_code.assert_not_called() context.set_details.assert_not_called() self.assertIsNotNone(resp_push) self.assertEqual(xrd_pb2.PushTransactionResp.SUBMITTED, resp_push.error_code) self.assertEqual('30955fdc5e2d9dbe5fb9bf812f2e1b6c4b409a8a7c7a75f1c3e9ba1ffdd8e60e', bin2hstr(resp_push.tx_hash))
def test_messageTxn_sign(self): with set_xrd_dir('wallet_ver1'): with State() as db_state: p2p_factory = Mock(spec=P2PFactory) p2p_factory.pow = Mock(spec=POW) chain_manager = ChainManager(db_state) xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) context = Mock(spec=ServicerContext) alice = get_alice_xmss() my_message = b'Hello xrd!' request = xrd_pb2.MessageTxnReq( message=my_message, fee=12, xmss_pk=alice.pk ) response = service.GetMessageTxn(request=request, context=context) context.set_code.assert_not_called() context.set_details.assert_not_called() self.assertIsNotNone(response) self.assertIsNotNone(response.extended_transaction_unsigned.tx) self.assertEqual('message', response.extended_transaction_unsigned.tx.WhichOneof('transactionType')) self.assertEqual(12, response.extended_transaction_unsigned.tx.fee) self.assertEqual(alice.pk, response.extended_transaction_unsigned.tx.public_key) self.assertEqual(0, response.extended_transaction_unsigned.tx.nonce) self.assertEqual(b'', response.extended_transaction_unsigned.tx.signature) self.assertEqual(b'', response.extended_transaction_unsigned.tx.transaction_hash) self.assertEqual(my_message, response.extended_transaction_unsigned.tx.message.message_hash) tmp_hash_pre = response.extended_transaction_unsigned.tx.master_addr tmp_hash_pre += response.extended_transaction_unsigned.tx.fee.to_bytes(8, byteorder='big', signed=False) tmp_hash_pre += response.extended_transaction_unsigned.tx.message.message_hash tmp_hash = sha256(tmp_hash_pre) hash_found = bin2hstr(Transaction.from_pbdata(response.extended_transaction_unsigned.tx). get_data_hash()) self.assertEqual(hash_found, bin2hstr(tmp_hash)) signed_transaction = response.extended_transaction_unsigned.tx signed_transaction.signature = alice.sign(tmp_hash) req_push = xrd_pb2.PushTransactionReq(transaction_signed=signed_transaction) resp_push = service.PushTransaction(req_push, context=context) context.set_code.assert_not_called() context.set_details.assert_not_called() self.assertIsNotNone(resp_push) self.assertEqual(xrd_pb2.PushTransactionResp.SUBMITTED, resp_push.error_code) self.assertEqual('b7ee814a548a6bbb8d97b2d3a0eb9e1f8b6ceee49b764e3c7b23d104aca6abeb', bin2hstr(resp_push.tx_hash))
def test_getTotalBalance(self): with set_xrd_dir('no_data'): db_state = State() xmss1 = get_alice_xmss() xmss2 = get_alice_xmss(4) xmss3 = get_bob_xmss(4) address_state1 = OptimizedAddressState.create(address=xmss1.address, nonce=25, balance=1000, ots_bitfield_used_page=0, transaction_hash_count=0, tokens_count=0, lattice_pk_count=0, slaves_count=0, multi_sig_address_count=0) address_state2 = OptimizedAddressState.create(address=xmss2.address, nonce=25, balance=2000, ots_bitfield_used_page=0, transaction_hash_count=0, tokens_count=0, lattice_pk_count=0, slaves_count=0, multi_sig_address_count=0) address_state3 = OptimizedAddressState.create(address=xmss3.address, nonce=25, balance=3000, ots_bitfield_used_page=0, transaction_hash_count=0, tokens_count=0, lattice_pk_count=0, slaves_count=0, multi_sig_address_count=0) AddressState.put_address_state(db_state, address_state1) AddressState.put_address_state(db_state, address_state2) AddressState.put_address_state(db_state, address_state3) p2p_factory = Mock(spec=P2PFactory) chain_manager = ChainManager(db_state) xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) context = Mock(spec=ServicerContext) request = xrd_pb2.GetAddressStateReq() service.GetAddressState(request=request, context=context) context.set_code.assert_called() context.set_details.assert_called() context = Mock(spec=ServicerContext) request = xrd_pb2.GetTotalBalanceReq() request.addresses.extend([xmss1.address, xmss2.address, xmss3.address]) response = service.GetTotalBalance(request=request, context=context) context.set_code.assert_not_called() self.assertEqual(6000, response.balance)
def test_getObject(self): SOME_ODD_HASH = sha256(b'this should not be found') with set_xrd_dir('no_data'): db_state = State() p2p_factory = Mock(spec=P2PFactory) p2p_factory.pow = Mock(spec=POW) chain_manager = ChainManager(db_state) xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) # First try an empty request context = Mock(spec=ServicerContext) request = xrd_pb2.GetObjectReq() response = service.GetObject(request=request, context=context) context.set_code.assert_not_called() context.set_details.assert_not_called() self.assertFalse(response.found) # Some odd address context = Mock(spec=ServicerContext) request = xrd_pb2.GetObjectReq() request.query = SOME_ODD_HASH response = service.GetObject(request=request, context=context) context.set_code.assert_not_called() self.assertFalse(response.found) # Find an address bob_xmss = get_bob_xmss() addr1_state = OptimizedAddressState.create(address=bob_xmss.address, nonce=25, balance=10, ots_bitfield_used_page=0, transaction_hash_count=0, tokens_count=0, lattice_pk_count=0, slaves_count=0, multi_sig_address_count=0) AddressState.put_address_state(db_state, addr1_state, None) context = Mock(spec=ServicerContext) request = xrd_pb2.GetObjectReq() request.query = bob_xmss.address response = service.GetObject(request=request, context=context) context.set_code.assert_not_called() self.assertTrue(response.found) self.assertIsNotNone(response.address_state) self.assertEqual(bob_xmss.address, response.address_state.address) self.assertEqual(25, response.address_state.nonce) self.assertEqual(10, response.address_state.balance) # Find a transaction alice_xmss = get_alice_xmss() db_state.address_used = MagicMock(return_value=False) tx1 = TransferTransaction.create( addrs_to=[bob_xmss.address], amounts=[125], message_data=None, fee=19, xmss_pk=bob_xmss.pk, master_addr=alice_xmss.address) chain_manager.tx_pool.transaction_pool = [(0, TransactionInfo(tx1, 0))] context = Mock(spec=ServicerContext) request = xrd_pb2.GetObjectReq() request.query = tx1.txhash response = service.GetObject(request=request, context=context) context.set_code.assert_not_called() self.assertTrue(response.found) self.assertIsNotNone(response.transaction) self.assertEqual('transfer', response.transaction.tx.WhichOneof('transactionType')) self.assertEqual(alice_xmss.address, response.transaction.tx.master_addr) self.assertEqual(bob_xmss.pk, response.transaction.tx.public_key) self.assertEqual(tx1.txhash, response.transaction.tx.transaction_hash) self.assertEqual(b'', response.transaction.tx.signature) self.assertEqual(bob_xmss.address, response.transaction.tx.transfer.addrs_to[0]) self.assertEqual(125, response.transaction.tx.transfer.amounts[0]) self.assertEqual(19, response.transaction.tx.fee) alice_xmss = get_alice_xmss() # Find a block block = Block.create(dev_config=config.dev, block_number=1, prev_headerhash=sha256(b'reveal'), prev_timestamp=10, transactions=[], miner_address=alice_xmss.address, seed_height=0, seed_hash=None) Block.put_block(db_state, block, None) Block.put_block_number_mapping(db_state, block.block_number, xrd_pb2.BlockNumberMapping(headerhash=block.headerhash), None) context = Mock(spec=ServicerContext) request = xrd_pb2.GetObjectReq() request.query = bytes(str2bin('1')) response = service.GetObject(request=request, context=context) context.set_code.assert_not_called() self.assertTrue(response.found) self.assertIsNotNone(response.block_extended) self.assertEqual(1, response.block_extended.header.block_number)
def test_getLatestData(self): with set_xrd_dir('no_data'): db_state = State() chain_manager = ChainManager(db_state) blocks = [] txs = [] alice_xmss = get_alice_xmss() bob_xmss = get_bob_xmss() for i in range(0, 4): for j in range(1, 3): txs.append(TransferTransaction.create(addrs_to=[bob_xmss.address], amounts=[i * 100 + j], message_data=None, fee=j, xmss_pk=alice_xmss.pk)) blocks.append(Block.create(dev_config=config.dev, block_number=i, prev_headerhash=sha256(b'reveal'), prev_timestamp=10, transactions=txs, miner_address=alice_xmss.address, seed_height=10, seed_hash=None)) block = blocks[i] Block.put_block(db_state, block, None) Block.put_block_number_mapping(db_state, block.block_number, xrd_pb2.BlockNumberMapping(headerhash=block.headerhash), None) TransactionMetadata.update_tx_metadata(db_state, block, None) chain_manager._last_block = blocks[-1] txpool = [] txs = [] for j in range(10, 15): tx = TransferTransaction.create(addrs_to=[bob_xmss.address], amounts=[1000 + j], message_data=None, fee=j, xmss_pk=get_alice_xmss().pk) txpool.append((tx.fee, TransactionInfo(tx, 0))) txs.append(tx) p2p_factory = Mock(spec=P2PFactory) p2p_factory.pow = Mock(spec=POW) chain_manager.tx_pool = Mock() chain_manager.tx_pool.transactions = heapq.nlargest(len(txpool), txpool) chain_manager.tx_pool.transaction_pool = txpool xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode.get_block_from_index = MagicMock(return_value=None) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow service = PublicAPIService(xrdnode) context = Mock(spec=ServicerContext) request = xrd_pb2.GetLatestDataReq(filter=xrd_pb2.GetLatestDataReq.ALL, offset=0, quantity=3) response = service.GetLatestData(request=request, context=context) context.set_code.assert_not_called() context.set_details.assert_not_called() # Verify blockheaders self.assertEqual(3, len(response.blockheaders)) self.assertEqual(1, response.blockheaders[0].header.block_number) self.assertEqual(2, response.blockheaders[1].header.block_number) self.assertEqual(3, response.blockheaders[2].header.block_number) # Verify transactions_unconfirmed self.assertEqual(3, len(response.transactions_unconfirmed)) # TODO: Verify expected order self.assertEqual(1014, response.transactions_unconfirmed[0].tx.transfer.amounts[0]) self.assertEqual(1013, response.transactions_unconfirmed[1].tx.transfer.amounts[0]) self.assertEqual(1012, response.transactions_unconfirmed[2].tx.transfer.amounts[0]) # Verify transactions self.assertEqual(3, len(response.transactions)) self.assertEqual(2, response.transactions[0].tx.fee) self.assertEqual(1, response.transactions[1].tx.fee) self.assertEqual(2, response.transactions[2].tx.fee) self.assertEqual(302, response.transactions[0].tx.transfer.amounts[0]) self.assertEqual(301, response.transactions[1].tx.transfer.amounts[0]) self.assertEqual(202, response.transactions[2].tx.transfer.amounts[0])
def test_getMiniTransactionsByAddress(self, mock_dev_config): mock_dev_config.data_per_page = 5 with set_xrd_dir('no_data'): db_state = State() p2p_factory = Mock(spec=P2PFactory) p2p_factory.pow = Mock(spec=POW) chain_manager = ChainManager(db_state) xrdnode = xrdNode(mining_address=b'') xrdnode.set_chain_manager(chain_manager) xrdnode._p2pfactory = p2p_factory xrdnode._pow = p2p_factory.pow xrdnode._peer_addresses = ['127.0.0.1', '192.168.1.1'] service = PublicAPIService(xrdnode) # Find a transaction alice_xmss = get_alice_xmss(8) context = Mock(spec=ServicerContext) bob_xmss = get_bob_xmss(4) txs = [] for i in range(0, 100): tx = TransferTransaction.create(addrs_to=[bob_xmss.address], amounts=[10], message_data=None, fee=0, xmss_pk=alice_xmss.pk) tx.sign(alice_xmss) txs.append(tx) addresses_set = {bob_xmss.address, alice_xmss.address} block = Block.create(config.dev, 10, b'', 100000000, txs, alice_xmss.address, seed_height=0, seed_hash=None) state_container = chain_manager.new_state_container(addresses_set, 5, True, None) for tx in txs: chain_manager.update_state_container(tx, state_container) address_state = state_container.addresses_state[tx.addr_from] state_container.paginated_tx_hash.insert(address_state, tx.txhash) address_state = state_container.addresses_state[tx.addrs_to[0]] state_container.paginated_tx_hash.insert(address_state, tx.txhash) state_container.paginated_tx_hash.put_paginated_data(None) OptimizedAddressState.put_optimized_addresses_state(db_state, state_container.addresses_state) TransactionMetadata.update_tx_metadata(db_state, block, None) request = xrd_pb2.GetMiniTransactionsByAddressReq(address=alice_xmss.address, item_per_page=10, page_number=1) response = service.GetMiniTransactionsByAddress(request=request, context=context) context.set_code.assert_not_called() self.assertEqual(len(response.mini_transactions), 10) for i in range(0, 10): self.assertEqual(bin2hstr(txs[len(txs) - i - 1].txhash), response.mini_transactions[i].transaction_hash) self.assertEqual(response.balance, 0) TransactionMetadata.update_tx_metadata(db_state, block, None) request = xrd_pb2.GetMiniTransactionsByAddressReq(address=alice_xmss.address, item_per_page=8, page_number=3) response = service.GetMiniTransactionsByAddress(request=request, context=context) context.set_code.assert_not_called() self.assertEqual(len(response.mini_transactions), 8) for i in range(0, 8): self.assertEqual(bin2hstr(txs[len(txs) - i - 17].txhash), response.mini_transactions[i].transaction_hash) self.assertEqual(response.balance, 0)