block.py 2.2 KB

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