- Foundations of Blockchain
- Koshik Raj
- 208字
- 2021-07-02 14:17:23
Block and blockchain interface
The Block and Blockchain class methods are similar to those used in the previous chapter to build a simple blockchain, with the only enhancement being the validation methods used to validate the received blocks.
The following method is invoked to verify that every block is linked to its previous block:
def is_valid_new_block(self, new_block, previous_block):
The following condition validates the index of the new block:
if previous_block.index + 1 != new_block.index: logger.warning('invalid index') return False
This condition performs hash validation by comparing the hash values of the blocks:
if previous_block.hash != new_block.previous_hash: logger.warning('invalid previous hash') return False
This condition checks the integrity of the newly added block by calculating its digest:
if self.calculate_hash_for_block(new_block) != new_block.hash: logger.info(type(new_block.hash) + ' ' + type(self.calculate_hash_for_block(new_block))) logger.warning('invalid hash: ' + self.calculate_hash_for_block(new_block) + ' ' + new_block.hash) return False return True
The following method is used to validate the entire blockchain when the node wants to replace the local blockchain with the one retrieved from its peer:
def is_valid_chain(self, blockchain_to_validate): if self.calculate_hash_for_block(Block(**blockchain_to_validate[0])) != self.get_genesis_block().hash: return False
This condition validates the hardcoded genesis block:
temp_blocks = [Block(**blockchain_to_validate[0])] for currentBlock in blockchain_to_validate[1:]: if self.is_valid_new_block(Block(**currentBlock), temp_blocks[-1]): temp_blocks.append(Block(**currentBlock)) else: return False return True
Every block of the received blockchain is validated iteratively by invoking is_valid_new_block.