Skip to content

Instantly share code, notes, and snippets.

@bajcmartinez
Created May 18, 2020 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bajcmartinez/f69267afab29f888547036a75e1f5532 to your computer and use it in GitHub Desktop.
Save bajcmartinez/f69267afab29f888547036a75e1f5532 to your computer and use it in GitHub Desktop.
From Zero to Blockchain in Python - Part 1 - Replace Blockchain
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