Ejemplo n.º 1
0
    def handle_block(self, source,
                     message: qrllegacy_pb2.LegacyMessage):  # block received
        """
        Block
        This function processes any new block received.
        :return:
        """
        P2PBaseObserver._validate_message(message,
                                          qrllegacy_pb2.LegacyMessage.BK)
        try:
            block = Block(message.block)
        except Exception as e:
            logger.error(
                'block rejected - unable to decode serialised data %s',
                source.addr_remote)
            logger.exception(e)
            return

        logger.info('>>>Received block from %s %s %s', source.addr_remote,
                    block.block_number, bin2hstr(block.headerhash))

        if not source.factory.master_mr.isRequested(block.headerhash, source,
                                                    block):
            return

        source.factory.pow.pre_block_logic(
            block)  # FIXME: Ignores return value
        source.factory.master_mr.register(qrllegacy_pb2.LegacyMessage.BK,
                                          block.headerhash, message.block)
Ejemplo n.º 2
0
    def setUp(self):
        p2p_factory = Mock(spec=P2PFactory)
        p2p_factory.sync_state = SyncState()
        p2p_factory.num_connections = 23
        p2p_factory.pow = Mock()
        b = Block()
        self.chain_manager = Mock(spec=ChainManager)
        self.chain_manager.height = 0
        self.chain_manager.get_last_block = MagicMock(return_value=b)
        self.chain_manager.get_block_header_hash_by_number = MagicMock(
            return_value=b.headerhash)

        self.qrlnode = QRLNode(mining_address=b'')
        self.qrlnode.set_chain_manager(self.chain_manager)
        self.qrlnode._p2pfactory = p2p_factory
        self.qrlnode._pow = p2p_factory.pow

        self.block_header_params = {
            "dev_config": config.dev,
            "blocknumber": 10,
            "prev_headerhash": sha256(b'prevblock'),
            "prev_timestamp": 1234567890,
            "hashedtransactions": sha256(b'tx1'),
            "fee_reward": 1,
            "seed_height": 0,
            "seed_hash": None,
        }

        self.service = MiningAPIService(self.qrlnode)
Ejemplo n.º 3
0
    def test_GetBlockMiningCompatible(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.get_last_block = MagicMock(return_value=Block())

        qrlnode = QRLNode(mining_address=b'')
        qrlnode.set_chain_manager(chain_manager)
        qrlnode._p2pfactory = p2p_factory
        qrlnode._pow = p2p_factory.pow

        block_header = BlockHeader.create(blocknumber=10,
                                          prev_headerhash=sha256(b'prevblock'),
                                          prev_timestamp=1234567890,
                                          hashedtransactions=sha256(b'tx1'),
                                          fee_reward=1)

        qrlnode.get_blockheader_and_metadata = MagicMock(
            return_value=[block_header, BlockMetadata()])

        service = MiningAPIService(qrlnode)
        req = qrlmining_pb2.GetBlockMiningCompatibleReq(height=10)

        answer = service.GetBlockMiningCompatible(request=req, context=None)

        self.assertEqual(10, answer.blockheader.block_number)
        self.assertEqual(1, answer.blockheader.reward_fee)
Ejemplo n.º 4
0
    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()

        qrlnode = QRLNode(mining_address=b'')
        qrlnode.set_chain_manager(chain_manager)
        qrlnode._p2pfactory = p2p_factory
        qrlnode._pow = p2p_factory.pow
        qrlnode.peer_manager = Mock()
        qrlnode.peer_manager.known_peer_addresses = [
            '127.0.0.1', '192.168.1.1'
        ]

        service = PublicAPIService(qrlnode)
        response = service.GetKnownPeers(request=qrl_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)
Ejemplo n.º 5
0
 def test_delete(self):
     block = Block()
     Block.put_block(self.state, block, None)
     block1 = Block.get_block(self.state, block.headerhash)
     self.assertEqual(block.serialize(), block1.serialize())
     self.state._delete(block.headerhash, None)
     self.assertIsNone(Block.get_block(self.state, block.headerhash))
Ejemplo n.º 6
0
    def test_update_last_tx(self):
        alice_xmss = get_alice_xmss()
        # Test Case: When there is no last txns
        self.assertEqual(LastTransactions.get_last_txs(self.state), [])

        block = Block()
        tx1 = TransferTransaction.create(
            addrs_to=[get_some_address(1),
                      get_some_address(2)],
            amounts=[1, 2],
            message_data=None,
            fee=0,
            xmss_pk=alice_xmss.pk)
        block._data.transactions.extend([tx1.pbdata])
        LastTransactions._update_last_tx(self.state, block, None)
        last_txns = LastTransactions.get_last_txs(self.state)

        # Test Case: When there is only 1 last txns
        self.assertEqual(len(last_txns), 1)
        self.assertEqual(last_txns[0].to_json(), tx1.to_json())

        block = Block()
        tx2 = TransferTransaction.create(
            addrs_to=[get_some_address(2),
                      get_some_address(3)],
            amounts=[1, 2],
            message_data=None,
            fee=0,
            xmss_pk=alice_xmss.pk)

        tx3 = TransferTransaction.create(
            addrs_to=[get_some_address(4),
                      get_some_address(5)],
            amounts=[1, 2],
            message_data=None,
            fee=0,
            xmss_pk=alice_xmss.pk)
        block._data.transactions.extend([tx2.pbdata, tx3.pbdata])
        LastTransactions._update_last_tx(self.state, block, None)
        last_txns = LastTransactions.get_last_txs(self.state)

        # Test Case: When there are 3 last txns
        self.assertEqual(len(last_txns), 3)
        self.assertEqual(last_txns[0].to_json(), tx3.to_json())
        self.assertEqual(last_txns[1].to_json(), tx2.to_json())
        self.assertEqual(last_txns[2].to_json(), tx1.to_json())
Ejemplo n.º 7
0
 def block(headerhash):
     nth_block = Block()
     if headerhash == b'test_block_1':
         nth_block.blockheader._data.timestamp_seconds = 50000
     elif headerhash == b'test_block_2':
         nth_block.blockheader._data.timestamp_seconds = 80000
     elif headerhash == b'test_block_3':
         nth_block.blockheader._data.timestamp_seconds = 90000
     return nth_block
Ejemplo n.º 8
0
 def test_delete(self):
     with set_qrl_dir('no_data'):
         with State() as state:
             block = Block()
             state.put_block(block, None)
             block1 = state.get_block(block.headerhash)
             self.assertEqual(block.serialize(), block1.serialize())
             state._delete(block.headerhash, None)
             self.assertIsNone(state.get_block(block.headerhash))
Ejemplo n.º 9
0
    def test_peer_fetch_block_we_are_synced(self, m_reactor, m_logger):
        """
        If is_syncing_finished() is True, then let's not ask for more blocks.
        """
        self.factory._chain_manager._state.get_block.return_value = Block()
        self.factory.is_syncing_finished.return_value = True

        self.factory.peer_fetch_block()

        self.channel_1.send_fetch_block.assert_not_called()
Ejemplo n.º 10
0
    def test_peer_fetch_block_we_are_synced(self, m_reactor, m_logger):
        """
        If is_syncing_finished() is True, then let's not ask for more blocks.
        """
        with patch.object(Block, 'get_block', return_value=Block()):
            self.factory.is_syncing_finished.return_value = True

            self.factory.peer_fetch_block()

            self.channel_1.send_fetch_block.assert_not_called()
Ejemplo n.º 11
0
    def test_update_last_tx(self):
        with set_qrl_dir('no_data'):
            with State() as state:
                alice_xmss = get_alice_xmss()
                # Test Case: When there is no last txns
                self.assertEqual(state.get_last_txs(), [])

                block = Block()
                tx1 = TransferTransaction.create(addrs_to=[get_some_address(1), get_some_address(2)],
                                                 amounts=[1, 2],
                                                 fee=0,
                                                 xmss_pk=alice_xmss.pk)
                block._data.transactions.extend([tx1.pbdata])
                state._update_last_tx(block, None)
                last_txns = state.get_last_txs()

                # Test Case: When there is only 1 last txns
                self.assertEqual(len(last_txns), 1)
                self.assertEqual(last_txns[0].to_json(), tx1.to_json())

                block = Block()
                tx2 = TransferTransaction.create(addrs_to=[get_some_address(2), get_some_address(3)],
                                                 amounts=[1, 2],
                                                 fee=0,
                                                 xmss_pk=alice_xmss.pk)

                tx3 = TransferTransaction.create(addrs_to=[get_some_address(4), get_some_address(5)],
                                                 amounts=[1, 2],
                                                 fee=0,
                                                 xmss_pk=alice_xmss.pk)
                block._data.transactions.extend([tx2.pbdata, tx3.pbdata])
                state._update_last_tx(block, None)
                last_txns = state.get_last_txs()

                # Test Case: When there are 3 last txns
                self.assertEqual(len(last_txns), 3)
                self.assertEqual(last_txns[0].to_json(),
                                 tx3.to_json())
                self.assertEqual(last_txns[1].to_json(),
                                 tx2.to_json())
                self.assertEqual(last_txns[2].to_json(),
                                 tx1.to_json())
Ejemplo n.º 12
0
    def test_peer_fetch_block_we_already_have_the_block(self, m_reactor, m_logger):
        """
        If peer_fetch_block() finds a corresponding block in the node's chain, then it keeps asking the node's local
        chain for newer blocks until
        1. the node doesn't have any newer blocks OR
        2. we've reached the end of the peer's NodeHeaderHash.
        Then it will ask the peer for the next block after that.
        """
        self.factory._chain_manager._state.get_block.return_value = Block()

        self.factory.peer_fetch_block()

        self.assertEqual(self.factory._chain_manager._state.get_block.call_count, 3)
        self.channel_1.send_fetch_block.assert_called_once_with(3)
Ejemplo n.º 13
0
    def test_start_mining_works(self, m_getTime, m_logger):
        m_getTime.return_value = self.time

        # Do prepare_next_unmined_block_template()'s job
        self.miner._mining_block = Block()
        # From sample run of test_prepare_next_unmined_block_template_works()
        self.miner._measurement = 60
        self.miner._current_difficulty = StringToUInt256('0')
        self.miner._current_target = \
            StringToUInt256('115792089237316195423570985008687907853269984665640564039457584007913129639807')

        # start() is from Qryptominer, let's not actually mine in a test
        with patch('qrl.core.Miner.Miner.start', spec=True) as m_start:
            self.miner.start_mining(self.parent_block, self.parent_difficulty)
            m_start.assert_called_once()
Ejemplo n.º 14
0
    def test_get_last_txs(self):
        self.assertEqual(self.state.get_last_txs(), [])

        alice_xmss = get_alice_xmss()
        block = Block()
        tx1 = TransferTransaction.create(
            addrs_to=[get_some_address(0),
                      get_some_address(1)],
            amounts=[1, 2],
            fee=0,
            xmss_pk=alice_xmss.pk)
        block._data.transactions.extend([tx1.pbdata])
        self.state._update_last_tx(block, None)
        last_txns = self.state.get_last_txs()

        # Test Case: When there is only 1 last txns
        self.assertEqual(len(last_txns), 1)
        self.assertEqual(last_txns[0].to_json(), tx1.to_json())
Ejemplo n.º 15
0
    def test_get_last_txs(self):
        with set_qrl_dir('no_data'):
            with State() as state:
                self.assertEqual(state.get_last_txs(), [])

                alice_xmss = get_alice_xmss()
                block = Block()
                tx1 = TransferTransaction.create(addrs_to=[b'q1', b'q2'],
                                                 amounts=[1, 2],
                                                 fee=0,
                                                 xmss_pk=alice_xmss.pk)
                block._data.transactions.extend([tx1.pbdata])
                state.update_last_tx(block, None)
                last_txns = state.get_last_txs()

                # Test Case: When there is only 1 last txns
                self.assertEqual(len(last_txns), 1)
                self.assertEqual(last_txns[0].to_json(), tx1.to_json())
Ejemplo n.º 16
0
    def test_add_empty(self):
        with State() as state:
            with set_wallet_dir("test_wallet"):
                chain = Mock(spec=Chain)
                chain.height = 0
                chain.get_block = MagicMock(return_value=None)
                chain.wallet = Wallet()
                chain.pstate = state

                buffered_chain = BufferedChain(chain)

                b0 = buffered_chain.get_block(0)
                buffered_chain._chain.get_block.assert_called()
                self.assertIsNone(b0)

                tmp_block = Block()
                res = buffered_chain.add_block(block=tmp_block)
                self.assertFalse(res)
Ejemplo n.º 17
0
    def setUp(self):
        self.time = 1526830525
        self.m_mining_qaddress = alice.qaddress
        self.m_mining_address = parse_qaddress(self.m_mining_qaddress)

        self.chain_manager = Mock(spec=ChainManager)
        self.chain_manager.get_block_size_limit.return_value = 500
        self.chain_manager.get_config_by_block_number.return_value = config.dev
        self.parent_block = Block()
        self.parent_difficulty = StringToUInt256(
            '0')  # tuple (0,0,0,0,0...) length 32

        self.m_pre_block_logic = Mock(spec=POW.pre_block_logic, name='hello')
        mining_thread_count = 1

        self.miner = Miner(self.chain_manager, self.m_pre_block_logic,
                           self.m_mining_address, mining_thread_count)

        self.txpool = Mock(spec=TransactionPool)
        self.txpool.transactions = []
Ejemplo n.º 18
0
    def handle_push_block(self, source, message: qrllegacy_pb2.LegacyMessage):
        """
        Push Block
        This function processes requested blocks received while syncing.
        Block received under this function are directly added to the main
        chain i.e. chain.blockchain
        It is expected to receive only one block for a given blocknumber.
        :return:
        """
        # FIXME: Later rename
        P2PBaseObserver._validate_message(message, qrllegacy_pb2.LegacyMessage.PB)
        if message.pbData is None:
            return

        try:
            block = Block(message.pbData.block)
            source.factory.block_received(source, block)

        except Exception as e:
            logger.error('block rejected - unable to decode serialised data %s', source.peer_ip)
            logger.exception(e)
Ejemplo n.º 19
0
    def setUp(self):
        self.time = 1526830525
        self.m_mining_qaddress = alice.qaddress
        self.m_mining_address = parse_qaddress(self.m_mining_qaddress)

        self.chain_manager = Mock(spec=ChainManager)
        self.parent_block = Block()
        self.parent_difficulty = StringToUInt256('0')  # tuple (0,0,0,0,0...) length 32

        self.m_pre_block_logic = Mock(spec=POW.pre_block_logic, name='hello')
        m_add_unprocessed_txn_fn = create_autospec(P2PFactory.add_unprocessed_txn)
        mining_thread_count = 1

        self.miner = Miner(self.m_pre_block_logic,
                           self.m_mining_address,
                           self.chain_manager,
                           mining_thread_count,
                           m_add_unprocessed_txn_fn)

        self.txpool = Mock(spec=TransactionPool)
        self.txpool.transactions = []
Ejemplo n.º 20
0
    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()

        qrlnode = QRLNode(mining_address=b'')
        qrlnode.set_chain_manager(chain_manager)
        qrlnode._p2pfactory = p2p_factory
        qrlnode._pow = p2p_factory.pow

        service = PublicAPIService(qrlnode)
        node_state = service.GetNodeState(request=qrl_pb2.GetNodeStateReq, context=None)

        # self.assertEqual(__version__, node_state.info.version)  # FIXME
        self.assertEqual(qrl_pb2.NodeInfo.UNSYNCED, node_state.info.state)
        self.assertEqual(23, node_state.info.num_connections)
Ejemplo n.º 21
0
    def test_remove_last_tx(self):
        with set_qrl_dir('no_data'):
            with State() as state:
                # Test Case: When there is no last txns
                self.assertEqual(state.get_last_txs(), [])

                alice_xmss = get_alice_xmss()

                block = Block()
                tx1 = TransferTransaction.create(addrs_to=[get_some_address(1), get_some_address(2)],
                                                 amounts=[1, 2],
                                                 fee=0,
                                                 xmss_pk=alice_xmss.pk)
                block._data.transactions.extend([tx1.pbdata])
                state._update_last_tx(block, None)
                last_txns = state.get_last_txs()

                self.assertEqual(last_txns[0].to_json(), tx1.to_json())

                state._remove_last_tx(block, None)
                last_txns = state.get_last_txs()
                self.assertEqual(last_txns, [])
Ejemplo n.º 22
0
    def setUp(self):
        self.m_mining_qaddress = alice.qaddress
        self.m_mining_address = parse_qaddress(self.m_mining_qaddress)

        self.alice_address_state = Mock(
            autospec=OptimizedAddressState,
            name='mock alice OptimizedAddressState')

        self.chain_manager = Mock(spec=ChainManager)
        self.chain_manager.get_block_size_limit.return_value = 500
        self.chain_manager.get_address_state.return_value = self.alice_address_state
        self.chain_manager.get_config_by_block_number.return_value = config.dev

        self.parent_block = Block()
        self.parent_difficulty = StringToUInt256(
            '0')  # tuple (0,0,0,0,0...) length 32

        self.m_pre_block_logic = Mock(spec=POW.pre_block_logic, name='hello')
        mining_thread_count = 1

        self.miner = Miner(self.chain_manager, self.m_pre_block_logic,
                           self.m_mining_address, mining_thread_count)

        self.txpool = TransactionPool(None)

        def replacement_set_affected_address(addresses_set):
            return addresses_set.add(alice.address)

        self.m_tx_args = {
            "addr_from": alice.address,
            "addrs_to": [bob.address],
            "amounts": [10],
            "fee": 1,
            "PK": alice.pk,
            "master_addr": None,
            "size": 150,
            "validate_extended.return_value": True,
            "set_affected_address": replacement_set_affected_address
        }
Ejemplo n.º 23
0
    def test_remove_last_tx(self):
        # Test Case: When there is no last txns
        self.assertEqual(LastTransactions.get_last_txs(self.state), [])

        alice_xmss = get_alice_xmss()

        block = Block()
        tx1 = TransferTransaction.create(
            addrs_to=[get_some_address(1),
                      get_some_address(2)],
            amounts=[1, 2],
            message_data=None,
            fee=0,
            xmss_pk=alice_xmss.pk)
        block._data.transactions.extend([tx1.pbdata])
        LastTransactions._update_last_tx(self.state, block, None)
        last_txns = LastTransactions.get_last_txs(self.state)

        self.assertEqual(last_txns[0].to_json(), tx1.to_json())

        LastTransactions._remove_last_tx(self.state, block, None)
        last_txns = LastTransactions.get_last_txs(self.state)
        self.assertEqual(last_txns, [])
Ejemplo n.º 24
0
 def get_block_by_number(block_number):
     block = Block()
     block.blockheader._data.block_number = block_number
     return block
Ejemplo n.º 25
0
 def test_init(self):
     # TODO: Not much going on here..
     block = Block()
     self.assertIsNotNone(block)  # just to avoid warnings