transaction.py 2.6 KB

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