import hashlib import json import time import uuid from create_keys import make_keys, get_keys, get_symmetric_key from lib.contract import Contract from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.fernet import Fernet import rsa class Transaction: def __init__(self): self.id = None self.data = None self.hash_value = None self.locked = False self.timestamp = 0 self.key = None def from_serialized(self, jsonobj: str): obj = json.loads(jsonobj) self.id = obj['id'] self.data = obj['data'] self.timestamp = obj['timestamp'] self.key = obj['key'] def set_serialized_contract(self, serialized): if not self.locked: self.id = str(uuid.uuid1()) self.data = serialized self.log('Serialized contract set') return True return False def set_contract(self, contract: dict): if not self.locked: self.id = str(uuid.uuid1()) # self.data = contract.serialize() self.data = contract self.timestamp = time.time() self.key = contract['id'] # self.log(f'Contract set: {contract.id} | {contract.title}')' self.log(f'Contract set: {contract["id"]}') return True return False def serialize(self, out_json=False): obj = { 'id': self.id, 'timestamp': self.timestamp, 'data': self.data, 'key': self.key, 'encrypted key': self.encrypted_key } self.log(f'Serialized') if out_json: return json.dumps(obj, sort_keys=True) return obj def lock_hash_finish(self): if not self.locked: self.timestamp = int(time.time()) self.locked = True self.hash() self.log('Locked') return True return False def hash(self, contract=None): string_object = json.dumps(self.data, sort_keys=True) block_string = string_object.encode() # open the public key file symmetric_key = get_symmetric_key(contract) pubkey = get_keys(contract) chiper = Fernet(symmetric_key) self.data = chiper.encrypt(block_string) self.encrypted_key = rsa.encrypt(symmetric_key,pubkey) # we need an extra field in the transaction # encrypted_data = pubkey.encrypt( # block_string, # padding.OAEP( # mgf=padding.MGF1(algorithm=hashes.SHA256()), # algorithm=hashes.SHA256(), # label=None # ) # ) self.log(f'Hashed: {self.hash_value}') def log(self, text): print(f'[ TRANS ] {text}')