2
0

transaction.py 1.7 KB

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