Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. class MinimalChain():
  2. def __init__(self): # initialize when creating a chain
  3. self.blocks = [self.get_genesis_block()]
  4.  
  5. def get_genesis_block(self):
  6. return MinimalBlock(0,
  7. datetime.datetime.utcnow(),
  8. 'Genesis',
  9. 'arbitrary')
  10.  
  11. def add_block(self, data):
  12. self.blocks.append(MinimalBlock(len(self.blocks),
  13. datetime.datetime.utcnow(),
  14. data,
  15. self.blocks[len(self.blocks)-1].hash))
  16.  
  17. def get_chain_size(self): # exclude genesis block
  18. return len(self.blocks)-1
  19.  
  20. def verify(self, verbose=True):
  21. flag = True
  22. for i in range(1,len(self.blocks)):
  23. if self.blocks[i].index != i:
  24. flag = False
  25. if verbose:
  26. print(f'Wrong block index at block {i}.')
  27. if self.blocks[i-1].hash != self.blocks[i].previous_hash:
  28. flag = False
  29. if verbose:
  30. print(f'Wrong previous hash at block {i}.')
  31. if self.blocks[i].hash != self.blocks[i].hashing():
  32. flag = False
  33. if verbose:
  34. print(f'Wrong hash at block {i}.')
  35. if self.blocks[i-1].timestamp >= self.blocks[i].timestamp:
  36. flag = False
  37. if verbose:
  38. print(f'Backdating at block {i}.')
  39. return flag
  40.  
  41. def fork(self, head='latest'):
  42. if head in ['latest', 'whole', 'all']:
  43. return copy.deepcopy(self) # deepcopy since they are mutable
  44. else:
  45. c = copy.deepcopy(self)
  46. c.blocks = c.blocks[0:head+1]
  47. return c
  48.  
  49. def get_root(self, chain_2):
  50. min_chain_size = min(self.get_chain_size(), chain_2.get_chain_size())
  51. for i in range(1,min_chain_size+1):
  52. if self.blocks[i] != chain_2.blocks[i]:
  53. return self.fork(i-1)
  54. return self.fork(min_chain_size)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement