blockchain.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. class Blockchain:
  2. ''' This class represents a sequence of blocks starting with the genesis block. '''
  3. def __init__(self, intial_block):
  4. self.blocks = [intial_block]
  5. def __repr__(self):
  6. return "Blockchain=[blocks={0}]".format(self.blocks)
  7. def __eq__(self, other):
  8. return self.blocks == other.blocks
  9. def __len__(self):
  10. return len(self.blocks)
  11. def __getitem__(self, index):
  12. return self.blocks[index]
  13. ''' A block is considered valid when its parent hash is equal to the hash of the
  14. previous block and their epochs are incremental, exluding genesis.
  15. Aadditional validity rules can be applied. '''
  16. def check_block_validity(self, block, previous_block):
  17. assert(block.h != '⊥') # genesis block check
  18. assert(block.h == hash(previous_block))
  19. assert(block.e > previous_block.e)
  20. ''' A blockchain is considered valid, when every block is valid, based on check_block_validity method. '''
  21. def check_chain_validity(self):
  22. for index, block in enumerate(self.blocks[1:]):
  23. self.check_block_validity(block, self.blocks[index])
  24. ''' Insertion of a valid block. '''
  25. def add_block(self, block):
  26. self.check_block_validity(block, self.blocks[-1])
  27. self.blocks.append(block)