Created
May 18, 2020 19:22
-
-
Save bajcmartinez/f69267afab29f888547036a75e1f5532 to your computer and use it in GitHub Desktop.
From Zero to Blockchain in Python - Part 1 - Replace Blockchain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def validate_chain(self, chain_to_validate): | |
""" | |
Verifies if a given chain is valid | |
:param chain_to_validate: <[Block]> | |
:return: <bool> True if the chain is valid | |
""" | |
# First validate both genesis blocks | |
if chain_to_validate[0].hash_block() != self.__chain[0].hash_block(): | |
return False | |
# Then we compare each block with its previous one | |
for x in range(1, len(chain_to_validate)): | |
if not self.validate_block(chain_to_validate[x], chain_to_validate[x - 1]): | |
return False | |
return True | |
def replace_chain(self, new_chain): | |
""" | |
Attempts to replace the chain for a new one | |
:param new_chain: | |
:return: <bool> True if the chain was replace, False if not. | |
""" | |
# We only replace if the new chain is bigger than the current one | |
if len(new_chain) <= len(self.__chain): | |
return False | |
# Validate the new chain | |
if not self.validate_chain(new_chain): | |
return False | |
new_blocks = new_chain[len(self.__chain):] | |
for block in new_blocks: | |
self.add_block(block) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment