transaction.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import hashlib
  2. import json
  3. import time
  4. from lib.contract import Contract
  5. class Transaction:
  6. def __init__(self):
  7. self.id = None
  8. self.data = None
  9. self.hash_value = None
  10. self.locked = False
  11. self.timestamp = 0
  12. def set_contract(self, contract: Contract):
  13. if not self.locked:
  14. self.data = contract.serialize()
  15. self.log(f'Contract set: {contract.id} | {contract.title}')
  16. return True
  17. return False
  18. def serialize(self):
  19. obj = {
  20. 'id': self.id,
  21. 'timestamp': self.timestamp,
  22. 'data': self.data
  23. }
  24. self.log(f'Serialized')
  25. return obj
  26. def lock_hash_finish(self):
  27. if not self.locked:
  28. self.timestamp = int(time.time())
  29. self.locked = True
  30. self.hash()
  31. self.log('Locked')
  32. return True
  33. return False
  34. def hash(self):
  35. string_object = json.dumps(self.data, sort_keys=True)
  36. block_string = string_object.encode()
  37. raw_hash = hashlib.sha256(block_string)
  38. hex_hash = raw_hash.hexdigest()
  39. self.hash_value = hex_hash
  40. self.log(f'Hashed: {self.hash_value}')
  41. return hex_hash
  42. def log(self, text):
  43. print(f'[ TRANS ] {text}')