Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
    def setUp(self):
        self.db_state = Mock(autospec=State, name='mocked State')
        # self.db_state = State()

        self.xrdnode = xrdNode(mining_address=b'')

        # As the xrdNode is instantiated and torn down for each test, the minuscule or negative diff between present
        # time and start_time can cause problems.
        self.xrdnode.start_time -= 10

        self.xrdnode._pow = Mock(autospec=POW)
        self.xrdnode._pow.miner.lock.__enter__ = Mock()
        self.xrdnode._pow.miner.lock.__exit__ = Mock()

        self.xrdnode.peer_manager = Mock(autospec=P2PPeerManager,
                                         name='mock P2PPeerManager',
                                         known_peer_addresses=set())
        self.xrdnode.p2pchain_manager = Mock(autospec=P2PChainManager,
                                             name='mock P2PChainManager')

        self.chain_manager = ChainManager(self.db_state)
        self.chain_manager.tx_pool = Mock(autospec=TransactionPool)
        mock_last_block = Mock(autospec=Block,
                               name='mock last Block',
                               block_number=2,
                               headerhash=b'deadbeef')
        self.chain_manager._last_block = mock_last_block
        self.chain_manager.get_unconfirmed_transaction = Mock()

        self.xrdnode.set_chain_manager(self.chain_manager)
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
 def setUp(self):
     # You have to set_xrd_dir to an empty one, otherwise State will have some Transactions from disk
     with set_xrd_dir('no_data'):
         self.db_state = State()
         self.chainmanager = ChainManager(self.db_state)
         self.xrdnode = xrdNode(mining_address=b'')
         self.xrdnode.set_chain_manager(self.chainmanager)
Ejemplo n.º 5
0
    def setUp(self):
        state = Mock()
        self.m_chain_manager = ChainManager(state=state)
        self.m_chain_manager._last_block = None
        self.m_chain_manager._state.get_block_by_number.return_value = None

        self.m_peer_manager = Mock(name='mock P2PPeerManager')

        self.xrdnode = xrdNode(mining_address=b'')
        self.xrdnode.set_chain_manager(self.m_chain_manager)
        self.xrdnode.peer_manager = self.m_peer_manager
    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)
Ejemplo n.º 7
0
    def setUp(self):
        with set_xrd_dir('no_data'):
            self.state = State()
        self.chain_manager = ChainManager(self.state)
        self.alice = get_alice_xmss()
        self.bob = get_bob_xmss()
        self.slave = get_slave_xmss()

        self.tx1 = TransferTransaction.create(addrs_to=[self.bob.address],
                                              amounts=[10],
                                              message_data=None,
                                              fee=1,
                                              xmss_pk=self.alice.pk)
        self.tx2 = TransferTransaction.create(addrs_to=[self.bob.address],
                                              amounts=[10],
                                              message_data=None,
                                              fee=1,
                                              xmss_pk=self.slave.pk,
                                              master_addr=self.alice.address)
        self.tx1._data.nonce = 3
        self.tx2._data.nonce = 6
        self.tx1.sign(self.alice)
        self.tx2.sign(self.slave)

        self.block_attrs = {
            "dev_config": config.dev,
            "block_number": 5,
            "prev_headerhash": bytes(sha2_256(b'test')),
            "prev_timestamp": 10,
            "transactions": [self.tx1, self.tx2],
            "miner_address": self.alice.address,
            "seed_height": 0,
            "seed_hash": None,
        }
        self.coinbase_addrstate_attrs = OptimizedAddressState.get_default(
            config.dev.coinbase_address)
        self.coinbase_addrstate_attrs.update_balance(
            None,
            int(config.dev.coin_remaining_at_genesis *
                config.dev.shor_per_quanta))
        self.bob_addrstate_attrs = OptimizedAddressState.get_default(
            self.bob.address)
        self.bob_addrstate_attrs.update_balance(None, 20)
        self.alice_addrstate_attrs = OptimizedAddressState.get_default(
            self.alice.address)
        self.alice_addrstate_attrs.update_balance(None, 100)
        self.alice_addrstate_attrs.pbdata.nonce = 2
        self.slave_addrstate_attrs = OptimizedAddressState.get_default(
            self.slave.address)
        self.slave_addrstate_attrs.pbdata.nonce = 5
Ejemplo n.º 8
0
    def test_measurement_1(self, mock_get_block):
        with set_xrd_dir('no_data'):
            with State() as state:
                self.assertIsNotNone(state)  # to avoid warning (unused variable)
                chain_manager = ChainManager(state)
                mock_get_block.side_effect = TestStateMeasurement.get_block_example1
                parent_metadata = Mock()
                parent_metadata.last_N_headerhashes = [b'0']

                measurement = chain_manager.get_measurement(config.dev, 210, b'1', parent_metadata)
                self.assertEqual(55, measurement)

                measurement = chain_manager.get_measurement(config.dev, 250, b'1', parent_metadata)
                self.assertEqual(75, measurement)
Ejemplo n.º 9
0
    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)
Ejemplo n.º 10
0
    def test_measurement_4(self, mock_get_block):
        db_name = config.dev.db_name
        with mock.patch('xrd.core.config.dev') as devconfig:
            devconfig.N_measurement = 3
            devconfig.db_name = db_name
            with set_xrd_dir('no_data'):
                with State() as state:
                    self.assertIsNotNone(state)  # to avoid warning (unused variable)
                    chain_manager = ChainManager(state)
                    mock_get_block.side_effect = TestStateMeasurement.get_block_example1
                    parent_metadata = Mock()
                    parent_metadata.last_N_headerhashes = [b'0', b'1', b'2']

                    measurement = chain_manager.get_measurement(config.dev, 350, b'3', parent_metadata)
                    self.assertEqual(63, measurement)

                    measurement = chain_manager.get_measurement(config.dev, 370, b'3', parent_metadata)
                    self.assertEqual(70, measurement)
Ejemplo n.º 11
0
    def test_check_stale_txn(self, m_is_full_transaction_pool, m_config):
        """
        Stale Transactions are Transactions that were supposed to go into block 5, but for some reason didn't make it.
        They languish in TransactionPool until check_stale_txn() checks the Pool and updates the tx_info to make them
        go into a higher block.
        For each stale transaction, P2PFactory.broadcast_tx() will be called.
        """

        # Redefine at what point should txs be considered stale
        m_config.user.stale_transaction_threshold = 2
        bob_xmss = get_bob_xmss(4)
        alice_xmss = get_alice_xmss(4)

        tx1 = TransferTransaction.create(addrs_to=[bob_xmss.address], amounts=[1000000],
                                         message_data=None, fee=1, xmss_pk=alice_xmss.pk)
        tx1.sign(alice_xmss)
        tx2 = TransferTransaction.create(addrs_to=[bob_xmss.address], amounts=[10000],
                                         message_data=None, fee=1, xmss_pk=alice_xmss.pk)
        tx2.sign(alice_xmss)
        m_broadcast_tx = Mock(name='Mock Broadcast TX function (in P2PFactory)')
        self.txpool.add_tx_to_pool(tx1, 5)
        self.txpool.add_tx_to_pool(tx2, 5)
        self.txpool.set_broadcast_tx(m_broadcast_tx)

        with set_xrd_dir('no_data'):
            state = State()
            chain_manager = ChainManager(state)
            self.txpool.check_stale_txn(chain_manager.new_state_container, chain_manager.update_state_container, 8)

            self.assertEqual(m_broadcast_tx.call_count, 0)

            m = MockFunction()
            bob_address_state = OptimizedAddressState.get_default(bob_xmss.address)
            bob_address_state.pbdata.balance = 1000000000000
            m.put(bob_xmss.address, bob_address_state)
            chain_manager.get_optimized_address_state = m.get
            tx3 = TransferTransaction.create(addrs_to=[alice_xmss.address], amounts=[10000],
                                             message_data=None, fee=1, xmss_pk=bob_xmss.pk)
            tx3.sign(bob_xmss)
            self.txpool.add_tx_to_pool(tx3, 5)
            self.txpool.check_stale_txn(chain_manager.new_state_container, chain_manager.update_state_container, 8)

            self.assertEqual(m_broadcast_tx.call_count, 1)
Ejemplo n.º 12
0
    def test_check_mock_get(self, mock_get_block):
        with set_xrd_dir('no_data'):
            with State() as state:
                self.assertIsNotNone(state)  # to avoid warning (unused variable)

                chain_manager = ChainManager(state)
                mock_get_block.side_effect = TestStateMeasurement.get_block_example1

                block = chain_manager.get_block(b'1')
                self.assertEqual(1, block.block_number)
                self.assertEqual(160, block.timestamp)

                block = chain_manager.get_block(b'3')
                self.assertEqual(3, block.block_number)
                self.assertEqual(310, block.timestamp)

                block = chain_manager.get_block(b'0')
                self.assertEqual(0, block.block_number)
                self.assertEqual(10, block.timestamp)
Ejemplo n.º 13
0
    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)
Ejemplo n.º 14
0
    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)
Ejemplo n.º 15
0
    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))
Ejemplo n.º 16
0
    def setUp(self):
        self.m_xrdnode = Mock(autospec=xrdNode, name='Fake xrdNode')
        self.m_xrdnode.peer_manager = Mock(autospec=P2PPeerManager, name='Fake PeerManager')
        self.m_xrdnode.peer_manager.is_banned.return_value = False
        self.m_xrdnode.peer_manager.load_known_peers.return_value = ['8.8.8.8', '9.9.9.9']

        self.channel_1 = Mock(autospec=P2PProtocol,
                              name='mock Channel 1',
                              peer=IPMetadata('1.1.1.1', config.user.p2p_public_port))
        self.channel_2 = Mock(autospec=P2PProtocol,
                              name='mock Channel 2',
                              peer=IPMetadata('2.2.2.2', config.user.p2p_public_port))
        self.channel_3 = Mock(autospec=P2PProtocol,
                              name='mock Channel 3',
                              peer=IPMetadata('3.3.3.3', config.user.p2p_public_port))

        self.factory = P2PFactory(chain_manager=ChainManager(state=Mock(autospec=State)), sync_state=None, xrd_node=self.m_xrdnode)
        self.factory.pow = Mock(autospec=POW)

        self.factory.add_connection(self.channel_1)
        self.factory.add_connection(self.channel_2)
        self.factory.add_connection(self.channel_3)
Ejemplo n.º 17
0
    def create(num_blocks, mining_address=None):
        tmp_gen = GenesisBlock()
        start_time = tmp_gen.timestamp + config.dev.block_timing_in_seconds
        with mock.patch('xrd.core.misc.ntp.getTime') as ntp_mock, \
                set_xrd_dir('no_data'), \
                State() as state, \
                mock.patch('time.time') as time_mock:  # noqa
            time_mock.return_value = start_time
            ntp_mock.return_value = start_time

            state.get_measurement = MagicMock(return_value=10000000)

            genesis_difficulty = config.user.genesis_difficulty
            try:
                config.user.genesis_difficulty = 10
                genesis_block = GenesisBlock()
                chain_manager = ChainManager(state)
                chain_manager.load(genesis_block)

                chain_manager._difficulty_tracker = Mock()
                dt = DifficultyTracker()
                tmp_difficulty = StringToUInt256('2')
                tmp_target = dt.get_target(tmp_difficulty, config.dev)

                chain_manager._difficulty_tracker.get = MagicMock(
                    return_value=(tmp_difficulty, tmp_target))

                xrdnode = xrdNode(mining_address=b'')
                xrdnode.set_chain_manager(chain_manager)

                mock_blockchain = MockedBlockchain(xrdnode, time_mock,
                                                   ntp_mock)
                for block_idx in range(1, num_blocks + 1):
                    mock_blockchain.add_new_block(mining_address)

                yield mock_blockchain
            finally:
                config.user.genesis_difficulty = genesis_difficulty
Ejemplo n.º 18
0
    def setUp(self):
        port = '9000'
        self.m_xrdnode = Mock(autospec=xrdNode, name='Fake xrdNode')
        self.channel_1 = Mock(autospec=P2PProtocol, name='mock Channel 1', peer_ip='1.1.1.1', peer_port=port)
        self.channel_2 = Mock(autospec=P2PProtocol, name='mock Channel 2', peer_ip='2.2.2.2', peer_port=port)
        self.channel_3 = Mock(autospec=P2PProtocol, name='mock Channel 3', peer_ip='3.3.3.3', peer_port=port)

        self.factory = P2PFactory(chain_manager=ChainManager(state=Mock(autospec=State)), sync_state=None,
                                  xrd_node=self.m_xrdnode)
        self.factory.pow = Mock(autospec=POW)

        self.m_xrdnode.is_banned.return_value = False
        self.factory.add_connection(self.channel_1)
        self.factory.add_connection(self.channel_2)
        self.factory.add_connection(self.channel_3)

        self.factory._target_channel = self.channel_1
        self.factory.is_syncing_finished = Mock(return_value=False, autospec=P2PFactory.is_syncing_finished)
        self.factory._target_node_header_hash = xrd_pb2.NodeHeaderHash(
            block_number=1,
            headerhashes=[bhstr2bin('123456'), bhstr2bin('deadbeef'), bhstr2bin('abcdef')]
        )
        self.factory._last_requested_block_number = 1
Ejemplo n.º 19
0
    def setUp(self):
        def replacement_get_block_by_number(i):
            return self.blocks[i - 1]

        port = '9000'
        self.m_xrdnode = Mock(autospec=xrdNode, name='Fake xrdNode')
        self.factory = P2PFactory(chain_manager=ChainManager(state=Mock(autospec=State)), sync_state=None,
                                  xrd_node=self.m_xrdnode)

        self.factory.peer_fetch_block = Mock(autospec=P2PFactory.peer_fetch_block)
        self.factory._chain_manager.get_block_by_number = replacement_get_block_by_number

        self.channel_1 = Mock(autospec=P2PProtocol, name='mock Channel 1', peer_ip='1.1.1.1', peer_port=port)
        self.factory.add_connection(self.channel_1)

        self.blocks = [
            Mock(autospec=Block, name='0th Block', block_number=1, headerhash=bhstr2bin('123456')),
            Mock(autospec=Block, name='1st Block', block_number=2, headerhash=bhstr2bin('7890ab')),
            Mock(autospec=Block, name='2nd Block', block_number=3, headerhash=bhstr2bin('deadbeef'))
        ]
        self.node_header_hash = xrd_pb2.NodeHeaderHash(
            block_number=1,
            headerhashes=[bhstr2bin('123456'), bhstr2bin('7890ab'), bhstr2bin('deadbeef')]
        )
Ejemplo n.º 20
0
def main():
    persistent_state = State()
    chain_manager = ChainManager(state=persistent_state)
    chain_manager.load(GenesisBlock())

    ph = PoWHelper()
    difficulty = StringToUInt256('5000')

    filename = os.path.expanduser(
        "~/crypto/qryptonight/modeling/blockdata.csv")

    with open(filename, 'w') as f:
        f.write("i,timestamp,prev_timestamp,delta,difficulty,target\n")
        prev_timestamp = None
        for i in range(chain_manager.height):
            block = chain_manager.get_block_by_number(i)

            if i == 0:
                prev_timestamp = block.blockheader.timestamp
                continue

            target = ph.getTarget(difficulty)
            delta = block.blockheader.timestamp - prev_timestamp

            outs = "{},{},{},{},{},{}\n".format(i, block.blockheader.timestamp,
                                                prev_timestamp, delta,
                                                UInt256ToString(difficulty),
                                                UInt256ToString(target))

            f.write(outs)

            difficulty = ph.getDifficulty(block.blockheader.timestamp,
                                          prev_timestamp, difficulty)
            difficulty = StringToUInt256(
                str(max(2, int(UInt256ToString(difficulty)))))
            prev_timestamp = block.blockheader.timestamp
Ejemplo n.º 21
0
    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)
Ejemplo n.º 22
0
def gen_blocks(block_count, state, miner_address):
    blocks = []
    block = None
    with mock.patch('xrd.core.misc.ntp.getTime') as time_mock:
        time_mock.return_value = 1615270948
        addresses_state = dict()
        for i in range(0, block_count):
            if i == 0:
                block = GenesisBlock()
                for genesis_balance in GenesisBlock().genesis_balance:
                    bytes_addr = genesis_balance.address
                    addresses_state[
                        bytes_addr] = OptimizedAddressState.get_default(
                            bytes_addr)
                    addresses_state[
                        bytes_addr]._data.balance = genesis_balance.balance
            else:
                block = Block.create(dev_config=config.dev,
                                     block_number=i,
                                     prev_headerhash=block.headerhash,
                                     prev_timestamp=block.timestamp,
                                     transactions=[],
                                     miner_address=miner_address,
                                     seed_height=None,
                                     seed_hash=None)
                addresses_set = ChainManager.set_affected_address(block)
                coin_base_tx = Transaction.from_pbdata(block.transactions[0])
                coin_base_tx.set_affected_address(addresses_set)

                chain_manager = ChainManager(state)
                state_container = chain_manager.new_state_container(
                    addresses_set, block.block_number, False, None)
                coin_base_tx.apply(state, state_container)

                for tx_idx in range(1, len(block.transactions)):
                    tx = Transaction.from_pbdata(block.transactions[tx_idx])
                    if not chain_manager.update_state_container(
                            tx, state_container):
                        return False
                    tx.apply(state, state_container)

                block.set_nonces(dev_config=config.dev,
                                 mining_nonce=10,
                                 extra_nonce=0)
            blocks.append(block)

            metadata = BlockMetadata()
            metadata.set_block_difficulty(StringToUInt256('256'))
            BlockMetadata.put_block_metadata(state, block.headerhash, metadata,
                                             None)

            Block.put_block(state, block, None)
            bm = xrd_pb2.BlockNumberMapping(
                headerhash=block.headerhash,
                prev_headerhash=block.prev_headerhash)

            Block.put_block_number_mapping(state, block.block_number, bm, None)
            state.update_mainchain_height(block.block_number, None)
            OptimizedAddressState.put_optimized_addresses_state(
                state, addresses_state)

    return blocks
Ejemplo n.º 23
0
def main():
    args = parse_arguments()

    xrd_dir_post_fix = ''
    copy_files = []
    if args.network_type == 'testnet':
        config.dev.hard_fork_heights[0] = config.dev.testnet_hard_fork_heights[0]  # Hard Fork Block Height For Testnet
        xrd_dir_post_fix = '-testnet'
        package_directory = os.path.dirname(os.path.abspath(__file__))
        copy_files.append(os.path.join(package_directory, 'network/testnet/genesis.yml'))
        copy_files.append(os.path.join(package_directory, 'network/testnet/config.yml'))

    logger.debug("=====================================================================================")
    logger.info("xrd Path: %s", args.xrd_dir)
    config.user.xrd_dir = os.path.expanduser(os.path.normpath(args.xrd_dir) + xrd_dir_post_fix)
    config.create_path(config.user.xrd_dir, copy_files)
    config.user.load_yaml(config.user.config_path)

    if args.mining_thread_count is None:
        args.mining_thread_count = config.user.mining_thread_count
    logger.debug("=====================================================================================")

    config.create_path(config.user.wallet_dir)
    mining_address = None
    ntp.setDrift()

    logger.info('Initializing chain..')
    persistent_state = State()

    if args.mocknet:
        args.debug = True
        config.user.mining_enabled = True
        config.user.mining_thread_count = 1
        config.user.mining_pause = 500
        config.dev.pbdata.block.block_timing_in_seconds = 1
        config.user.genesis_difficulty = 2

        # Mocknet mining address
        # Q01050058bb3f8cb66fd90d0347478e5bdf3a475e82cfc5fe5dc276500ca21531e6edaf3d2d0f7e
        # Mocknet mining hexseed
        # 010500dd70f898c2cb4c11ce7fd85aa04554e41dcc46569871d189a3f48d84e2fbedbe176695e291e9b81e619b3625c624cde6
        args.mining_address = 'Q01050058bb3f8cb66fd90d0347478e5bdf3a475e82cfc5fe5dc276500ca21531e6edaf3d2d0f7e'

    if args.debug:
        logger.warning("FAULT HANDLER ENABLED")
        faulthandler.enable()

    if config.user.mining_enabled:
        mining_address = get_mining_address(args.mining_address)

        if not mining_address:
            logger.warning('Invalid Mining Credit Wallet Address')
            logger.warning('%s', args.mining_address)
            return False

    chain_manager = ChainManager(state=persistent_state)
    if args.measurement > -1:
        chain_manager.get_measurement = MagicMock(return_value=args.measurement)

    chain_manager.load(Block.deserialize(GenesisBlock().serialize()))

    xrdnode = xrdNode(mining_address=mining_address)
    xrdnode.set_chain_manager(chain_manager)

    set_logger.set_logger(args, xrdnode.sync_state)

    #######
    # NOTE: Keep assigned to a variable or might get collected
    admin_service, grpc_service, mining_service, debug_service = start_services(xrdnode)

    xrdnode.start_listening()

    xrdnode.start_pow(args.mining_thread_count)

    logger.info('xrd blockchain ledger %s', config.dev.version)
    if config.user.mining_enabled:
        logger.info('Mining/staking address %s using %s threads (0 = auto)', 'Q' + bin2hstr(mining_address), args.mining_thread_count)

    elif args.mining_address or args.mining_thread_count:
        logger.warning('Mining is not enabled but you sent some "mining related" param via CLI')

    reactor.run()
    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))
Ejemplo n.º 26
0
    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)
Ejemplo n.º 27
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)
Ejemplo n.º 28
0
 def test_create_factory(self, m_reactor, m_logger):
     factory = P2PFactory(chain_manager=ChainManager(None), sync_state=None, xrd_node=None)
     self.assertEqual(P2PProtocol, factory.protocol,
                      "Factory has not been assigned the expected protocol")
Ejemplo n.º 29
0
    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])