block.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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.previous_hash = previous.hash_value if previous is not None else None
  18. self.transactions = []
  19. self.hash_value = None
  20. self.locked = False
  21. self.timestamp = 0
  22. self.height = previous.height + 1 if previous is not None else 0
  23. self.nonce = self.height
  24. def add_hashed_transaction(self, hashed: str):
  25. trans = Transaction()
  26. trans.from_serialized(hashed)
  27. self.transactions.append(trans)
  28. self.log(f'Hashed transaction added: {hashed}')
  29. return True
  30. def add_transaction(self, trans: Transaction):
  31. if not self.locked:
  32. trans.lock_hash_finish()
  33. self.transactions.append(trans)
  34. self.log(f'Transaction added: {trans.id}')
  35. return True
  36. return False
  37. def lock_hash_finish(self):
  38. if not self.locked:
  39. self.timestamp = int(time.time())
  40. self.hash()
  41. self.locked = True
  42. self.log('Locked')
  43. return True
  44. return False
  45. def serialize(self):
  46. trans_serialize = []
  47. for transaction in self.transactions:
  48. trans_serialize.append(transaction.serialize())
  49. obj = {
  50. 'timestamp': self.timestamp,
  51. 'previous': self.previous_hash,
  52. 'transactions': trans_serialize
  53. }
  54. self.log(f'Serialized: {len(trans_serialize)} transactions')
  55. return obj
  56. def hash(self):
  57. string_object = json.dumps(self.serialize(), sort_keys=True)
  58. block_string = string_object.encode()
  59. raw_hash = hashlib.sha256(block_string)
  60. hex_hash = raw_hash.hexdigest()
  61. self.hash_value = hex_hash
  62. self.log(f'Hashed: {self.hash_value}')
  63. return hex_hash
  64. def log(self, text):
  65. print(f'[ BLOCK ] {text}')