def calculate_utxo(self, block, utxo_file_path=UTXO_FILE, del_old=0, save=1): self.create_utxo_if_not_exit(utxo_file_path) if del_old: utxo_file = open(utxo_file_path, "w+") else: utxo_file = open(utxo_file_path, "a+") utxos_dict = [] result_outputs_dict = "" for i in block.transactions: tx = Transaction(False, False) tx.set_signed_raw_tx(i) tx_outputs_dict = json.loads(tx.deserialize_raw_tx())['outputs'] out_id = 0 for j in tx_outputs_dict: j['address'] = base58.b58encode_check( bytes.fromhex('6f' + j['script'][6:46])).decode('utf-8') j['tx_id'] = hashlib.sha256( hashlib.sha256(bytes.fromhex(i)).digest()).hexdigest() j['output_id'] = out_id utxos_dict.append(j) result_outputs_dict += str(j) + "\n" out_id += 1 if save: utxo_file.write("%s" % result_outputs_dict) utxo_file.close() if len(utxos_dict) < 1: return False else: return utxos_dict
def find_tx(self, block, tx_id): for i in block.transactions: tx = Transaction(False, False) tx.set_signed_raw_tx(i) if flip_byte_order( hashlib.sha256(hashlib.sha256( bytes.fromhex(i)).digest()).hexdigest()) == tx_id: return tx.deserialize_raw_tx() return False
def verify_tx(self, raw_tx, utxo_flags): tx = Transaction(False, False) tx.set_signed_raw_tx(raw_tx) tx_dict = json.loads(tx.deserialize_raw_tx()) print(tx_dict) tx_inputs = [] for j in tx_dict['inputs']: output_tx_id = j['prev_tx_id'] output_id = j['out_index'] tx_inputs.append({ 'output_tx_id': output_tx_id, 'output_id': output_id }) inputs_amount = 0 for j in tx_inputs: input_found = 0 for utxo_flag in utxo_flags: if j['output_tx_id'] == utxo_flag[0]['tx_id'] and j[ 'output_id'] == utxo_flag[0]['output_id']: input_found = 1 if utxo_flag[1] == 1: print("[from: node]: BAD TX! INPUT ALREADY SPENT") return False utxo_flag[1] = 1 inputs_amount += float(utxo_flag[0]['value']) if not input_found: print("[from: node]: BAD TX! CANNOT FIND INPUT!") return False outputs_amount = 0.0 for i in tx_dict['outputs']: outputs_amount += float(i['value']) if outputs_amount > inputs_amount: print( "[from: node]: BAD TX! OUTPUTS VALUE SHOULD BE GREATER THAN INPUTS!" ) return False print("amount of inputs", inputs_amount, "amount of outputs", outputs_amount) if not self.execute_script(tx, "out"): return False return True