transaction.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import hashlib
  2. import json
  3. import time
  4. import uuid
  5. from gui.encyption import encrypt_data
  6. from create_keys import make_keys, get_keys, get_symmetric_key
  7. from lib.contract import Contract
  8. class Transaction:
  9. def __init__(self):
  10. self.id = None
  11. self.data = None
  12. self.hash_value = None
  13. self.locked = False
  14. self.timestamp = 0
  15. self.key = None
  16. self.encrypted_key = None
  17. def from_serialized(self, jsonobj: str):
  18. print('FROM SERIALIZED: \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n')
  19. obj = json.loads(jsonobj)
  20. self.id = obj['id']
  21. self.data = obj['data']
  22. self.timestamp = obj['timestamp']
  23. self.key = obj['key']
  24. self.encrypted_key = obj['encrypted key']
  25. def set_serialized_contract(self, serialized):
  26. if not self.locked:
  27. self.id = str(uuid.uuid1())
  28. self.data = serialized
  29. self.log('Serialized contract set')
  30. return True
  31. return False
  32. def set_contract(self, contract: dict):
  33. if not self.locked:
  34. self.id = str(uuid.uuid1())
  35. # self.data = contract.serialize()
  36. self.data = contract
  37. self.timestamp = time.time()
  38. self.key = contract['id']
  39. # self.log(f'Contract set: {contract.id} | {contract.title}')'
  40. self.log(f'Contract set: {contract["id"]}')
  41. return True
  42. return False
  43. def serialize(self, out_json=False):
  44. obj = {
  45. 'id': self.id,
  46. 'timestamp': self.timestamp,
  47. 'data': self.data,
  48. 'key': self.key,
  49. 'encrypted key': self.encrypted_key
  50. }
  51. self.log(f'Serialized')
  52. if out_json:
  53. return json.dumps(obj, sort_keys=True)
  54. return obj
  55. def lock_hash_finish(self):
  56. if not self.locked:
  57. self.timestamp = int(time.time())
  58. self.locked = True
  59. self.hash()
  60. self.log('Locked')
  61. return True
  62. return False
  63. def hash(self, contract=None):
  64. string_object = json.dumps(self.data, sort_keys=True)
  65. block_string = string_object.encode()
  66. self.data, self.encrypted_key = encrypt_data(contract, block_string)
  67. # open the public key file
  68. # we need an extra field in the transaction
  69. # encrypted_data = pubkey.encrypt(
  70. # block_string,
  71. # padding.OAEP(
  72. # mgf=padding.MGF1(algorithm=hashes.SHA256()),
  73. # algorithm=hashes.SHA256(),
  74. # label=None
  75. # )
  76. # )
  77. self.log(f'Hashed: {self.hash_value}')
  78. def log(self, text):
  79. print(f'[ TRANS ] {text}')