epoch.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from ouroboros.utils import state_hash
  2. class Epoch(object):
  3. '''
  4. epoch spans R slots,
  5. maximum number of block in Epoch is R
  6. epoch must start with gensis block B0
  7. '''
  8. def __init__(self, gensis_block, R, epoch_idx):
  9. self.gensis_block=gensis_block
  10. self.blocks = []
  11. self.R = R #maximum epoch legnth, and it's a fixed property of the system
  12. self.e = epoch_idx
  13. self.index=0
  14. @property
  15. def slot(self):
  16. return self.gensis_block.sl
  17. @property
  18. def length(self):
  19. return len(self.blocks)
  20. @property
  21. def index(self):
  22. return self.e
  23. @property
  24. def genesis(self):
  25. if self.length==0:
  26. return None
  27. return self.blocks[0]
  28. def add_block(self, block):
  29. if len(self.blocks)>0 and not block.state==state_hash(self.block[-1]):
  30. #TODO we dealing with corrupt stakeholder,
  31. # action to be taken
  32. # the caller of the add_block should execute (corrupt,U)
  33. pass
  34. if self.length==self.R:
  35. raise f"can't exceed Epoch's length: {self.length}"
  36. self.blocks.append(block)
  37. def __iter__(self):
  38. return self
  39. def __next__(self):
  40. for i in range(self.length):
  41. try:
  42. res=self.blocks[self.index]
  43. except IndexError:
  44. raise StopIteration
  45. self.index+=1
  46. return res