def test_show_validate_false(self): # Values Dumped nonce_false = 4 hash_false = "03422354358392586569542654697954676849367548926706893" # Consensus instance with Mock consensus = Consensus() consensus.crypto_helper.hash = MagicMock(return_value=hash_false) # Block Instance block = Block(1, None, None, None, [], 0, datetime.now()) block.nonce = nonce_false self.assertFalse(consensus.validate(block, datetime(2007, 12, 6, 15, 29, 52), datetime(2007, 12, 6, 15, 29, 43), 1))
def test_request_blocks_by_hash_range(self): """Test case #13.""" # given self.available_blocks[2] = Block( 2, 'test_merkle_hash', 'test_pred_block_hash', 'test_creator', [ Transaction('test_sender', 'test_receiver', 'test_payload', 'test_signature') ], nonce=5, timestamp=1337.0) # when json_rpc_request = { "jsonrpc": "2.0", "method": "requestBlocksByHashRange", "params": [], "id": 1 } response = self.make_request(json.dumps(json_rpc_request)) # then self.assert_json_equal( response, '{ "jsonrpc": "2.0", "result": [{"nr": 2, "timestamp": 1337.0, ' '"merkleHash" : "test_merkle_hash", ' '"difficulty" : -1,' '"predecessorBlock" : "test_pred_block_hash", "nonce" : 5, ' '"creator" : "test_creator", "transactions" : ' '[{"sender": "test_sender", "receiver": "test_receiver", ' '"payload": "test_payload", "signature": "test_signature"}]}], "id":1}' )
def get_blockchain_from_db(self): """Fetch all blocks with their transactions from database Returns ------- List of all blocks """ self.open_connection(self.db_file) get_block = "SELECT * from {}".format(self.blockchain_table) get_transactions = "SELECT * FROM {} WHERE block_hash = ?".format(self.transaction_table) self.cursor.execute(get_block) blocks = [] blocks_db = self.cursor.fetchall() if len(blocks_db) == 0: return None for block_db in blocks_db: self.cursor.execute(get_transactions, (block_db[0],)) txns = [] txns_db = self.cursor.fetchall() if len(txns_db) != 0: for txn_db in txns_db: txn = Transaction(txn_db[0], txn_db[1], txn_db[2], txn_db[3]) txn.transaction_hash = txn_db[4] txns.append(txn) #txns=[] block = Block(block_id=block_db[1], merkle_tree_root=block_db[2], predecessor_hash=block_db[3], block_creator_id=block_db[4], transactions=txns, nonce=block_db[5], timestamp=float(block_db[6]), difficulty=int(block_db[7])) blocks.append(block) self.conn.close() return blocks
def requestBlockByHash(self, block_hash): """Request a single block by its hash value.""" responses = self._bulk_send('requestBlockByHash', [block_hash], return_on_first_success=True) if responses: if responses[0]: return Block.from_dict(responses[0]) else: raise BlockDoesNotExistException() else: raise NoPeersException( 'No nodes available to request the block from')
def test_request_block_from_nonempty_blockchain(self): """ Test case: #10 Tested requirement: #210 """ # given transactions = [] for i in range(5): transactions.append( Transaction("test_sender", "test_receiver", "payload_data")) block0 = Block(0, "merkle_tree_hash_qthq4thi4q4t", 'pred_hash_1', "creator_hash", transactions, 123) block1 = Block( 1, "merkle_tree_hash_qthq5thi4q1t", 'pred_hash_2', "creator_hash", transactions, 456, ) self.add_block(block0) self.add_block(block1) # when self.queue_input('3') self.queue_input('1') self.queue_input('1') self.queue_input('') # press enter self.queue_input('3') self.queue_input('5') self.client.main() # then self.assert_string_in_output('1') # block number self.assert_string_in_output( 'merkle_tree_hash_qthq5thi4q1t') # merkle tree root self.assert_string_in_output('pred_hash_2') # predecessor hash self.assert_string_in_output('456') # nonce self.assert_string_in_output('creator_hash') # block creator
def test_show_mine_true(self): # Values Dumped nonce_true = 4 hash_true = "00054358392586569542654697954676849367548926706893" hash_false = "03422354358392586569542654697954676849367548926706893" hash_list_for_nonce_4 = [hash_false, hash_false, hash_false, hash_false, hash_true] # Consensus instance with Mock consensus = Consensus() consensus.crypto_helper.hash = MagicMock(side_effect=hash_list_for_nonce_4) # Block Instance block = Block(1, None, None, None, [], 0, datetime.now()) consensus.mine(block, datetime(2007, 12, 6, 15, 29, 52), datetime(2007, 12, 6, 15, 29, 43), 1) self.assertEqual(nonce_true, block.nonce)
def __handle_send_block(self, block_data): block = Block.from_dict(block_data) block_initially_in_chain = block in self.get_block_callback( block.block_id) self.on_block_received_callback(block) if block not in self.get_block_callback(block.block_id): # if still not in chain, the bock must be invalid self.__add_block_to_cache(block) if not block_initially_in_chain and not self.__block_in_cache(block): logger.debug('Broadcasting block: {}'.format(str(block))) self._call_threaded(self.__send_block_safe, [block]) else: logger.debug( 'Block already present. Skipping propagation: {}'.format( block))
def requestBlock(self, block_id): """Request a single block by block ID. Returns a list, because multiple blocks might have the same ID. """ responses = self._bulk_send('requestBlock', [block_id], return_on_first_success=True) if responses: if responses[0]: return [ Block.from_dict(block_data) for block_data in responses[0] ] else: raise BlockDoesNotExistException() else: raise NoPeersException( 'No nodes available to request the block from')
def requestBlocksByHashRange(self, block_start_hash=None, block_end_hash=None): """Request a single block by its hash value.""" responses = self._bulk_send('requestBlocksByHashRange', [block_start_hash, block_end_hash], return_on_first_success=True) res = [] if responses: if len(responses) > 0: for block in responses[0]: res.append(Block.from_dict(block)) else: raise NoBlockExistsInRange() else: raise NoPeersException( 'No nodes available to request the block from') return res
def test_send_block_client_valid(self): """Test Case #8""" # Given self.add_peer('192.168.100.4', 6666) now = time.time() test_block = Block(2, 'merkle_hash123', 'pre_hash123', 'test_creator', [ Transaction('test_sender', 'test_receiver', 'test_payload', 'test_signature') ], 6969, now) # when self.json_rpc_client.queue_response({ 'jsonrpc': '2.0', 'result': None, 'id': 1 }) self.network_interface.sendBlock(test_block) # then last_request_method, last_request_params = self.get_last_request( '192.168.100.4', 6666) self.assertEqual(last_request_method, 'sendBlock') self.assert_json_equal(last_request_params, [{ 'nr': 2, 'timestamp': now, 'merkleHash': 'merkle_hash123', 'predecessorBlock': 'pre_hash123', 'nonce': 6969, 'creator': 'test_creator', 'difficulty': -1, 'transactions': [{ 'sender': 'test_sender', 'receiver': 'test_receiver', 'payload': 'test_payload', 'signature': 'test_signature' }] }])
def on_get_block_by_hash(self, hash): """callback method for get block""" block_data = self.blockchain_obj.get_block_by_hash(hash) if block_data: return Block.from_json(block_data) return None
from labchain.network.networking import ServerNetworkInterface, JsonRpcClient, BlockDoesNotExistException project_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) if project_dir not in sys.path: sys.path.append(project_dir) # change to DEBUG to see more output LOG_LEVEL = logging.INFO # change the polling interval POLL_INTERVAL = 10 BLOCKS = { 1: Block(1, 'some_root', 'pred_hash', 'creator_id', [ Transaction('some sender', 'some_receiver', 'some_payload', 'some_signature') ], 1234) } def get_block(block_id): if int(block_id) in BLOCKS: return [BLOCKS[block_id]] return [] def empty_function(): """Empty function for unneeded functionality.""" pass