block.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import hashlib
  2. import json
  3. import time
  4. from lib.transaction import Transaction
  5. CURRENT = None
  6. class Block:
  7. class Current:
  8. @staticmethod
  9. def set(block):
  10. global CURRENT
  11. CURRENT = block
  12. @staticmethod
  13. def get():
  14. global CURRENT
  15. return CURRENT
  16. def __init__(self, previous=None):
  17. self.proof = None
  18. self.previous_hash = previous.hash_value if previous is not None else None
  19. self.transactions = []
  20. self.hash_value = None
  21. self.locked = False
  22. self.timestamp = 0
  23. self.height = previous.height + 1 if previous is not None else 0
  24. def add_hashed_transaction(self, hashed: str):
  25. self.transactions.append(hashed)
  26. self.log(f'Transaction added: {hashed}')
  27. return True
  28. def add_transaction(self, trans: Transaction):
  29. if not self.locked:
  30. trans.lock_hash_finish()
  31. self.transactions.append(trans)
  32. self.log(f'Transaction added: {trans.id}')
  33. return True
  34. return False
  35. def lock_hash_finish(self):
  36. if not self.locked:
  37. self.timestamp = int(time.time())
  38. self.hash()
  39. self.locked = True
  40. self.log('Locked')
  41. return True
  42. return False
  43. def serialize(self):
  44. trans_serialize = []
  45. for transaction in self.transactions:
  46. trans_serialize.append(transaction.serialize())
  47. obj = {
  48. 'timestamp': self.timestamp,
  49. 'previous': self.previous_hash,
  50. 'transactions': trans_serialize
  51. }
  52. self.log(f'Serialized: {len(trans_serialize)} transactions')
  53. return obj
  54. def hash(self):
  55. string_object = json.dumps(self.serialize(), sort_keys=True)
  56. block_string = string_object.encode()
  57. raw_hash = hashlib.sha256(block_string)
  58. hex_hash = raw_hash.hexdigest()
  59. self.hash_value = hex_hash
  60. self.log(f'Hashed: {self.hash_value}')
  61. return hex_hash
  62. def log(self, text):
  63. print(f'[ BLOCK ] {text}')