def blockHashCalc(self, genesis): if self.txValidator(self.transactions): root = merkle_root(self.transactions) # print('self.timestamp = ', type(self.timestamp), '\nself.nonce = ', self.nonce, # '\nself.previous_hash = ', type(self.previous_hash), '\nroot = ', type(root)) __preHash = str(self.timestamp) + str(self.nonce) + str(self.previous_hash) + str(root) # print('__prehash = ', __preHash) blockHash = hashlib.sha256(hashlib.sha256(__preHash.encode()).digest()).hexdigest() self.blockhash = blockHash self.block_root = root return blockHash, root elif genesis == 1: tx = Deserializer.deserialize(Deserializer, self.transactions[0]) tx.sender = '00000000000000000000000000000000' # print('txHash = ', tx.txHashCalc().encode('utf-8'), '\ntxpubkey = ', tx.pubkey, '\nsignature = ', tx.signature) if (Validator.addrVal(Validator, tx.recipient)) and Validator.signatureVal(Validator, tx.txHashCalc().encode('utf-8'), tx.pubkey, tx.signature): root = merkle_root(self.transactions) # print('root = ', root) __preHash = str(self.timestamp) + str(self.nonce) + str(self.previous_hash) + str(root) # print('pre hash = ', __preHash.encode()) blockHash = hashlib.sha256(hashlib.sha256(__preHash.encode()).digest()).hexdigest() # print('blockHash = ', blockHash) self.blockhash = blockHash self.block_root = root return blockHash, root else: return False else: print('one or more transactions are compromised') return False
def mine_block(self): txs = pending_pool.get_last_tx() for tx in txs: try: dec_tx = Deserializer.deserialize(tx) prev_outputs = [] for i in dec_tx.inputs: txid, vout, out = self.utxop.find_out(txid=i.txid, vout=i.vout) prev_outputs.append((txid, vout, out)) if not check_tx(dec_tx, prev_outputs): print("Non_valid input") raise Exception("Non valid input") except Exception as e: txs.remove(tx) print(f'Error: invalid tx {dec_tx.txid()[::-1].hex()}[{e}]') fee = 25 txs.insert(0, self.coinbase_tx(fee)) timestamp = time_ns() previus_block_hash = self.chain[-1].get_hash().hex() new_block = Block(timestamp=timestamp, previous_hash=previus_block_hash, transactions=txs) new_block.height = self.chain[-1].height + 1 new_block = self.find_nonce(new_block) return new_block
def validate_transactions(self): if self.transactions: for transaction in self.transactions: deserialized = Deserializer.deserialize(transaction) tsx = Transaction(deserialized['sender_addr'], deserialized['recepient_addr'], deserialized['num_of_coins']) tsx_hash = tsx.transaction_hash() transaction_validation(transaction, tsx_hash)
def add_transaction_to_pool(self, serialized_transaction): deserialized = Deserializer.deserialize(serialized_transaction) transaction = Transaction(deserialized['sender_addr'], deserialized['recepient_addr'], deserialized['num_of_coins']) transaction_hash = transaction.transaction_hash() is_valid = transaction_validation(deserialized, transaction_hash) if not is_valid: return is_valid self.transaction_pool.append(serialized_transaction) return True
def txValidator(self, transactions): for stx in transactions: tx = Deserializer.deserialize(Deserializer, stx) if stx[4:40] == '0' * 36 and not Validator.addrVal(Validator, tx.recipient): return True elif not Validator.addrVal(Validator, tx.sender) or not Validator.addrVal(Validator, tx.recipient) or not Validator.senderAddrVal(Validator, tx.pubkey, tx.sender): break elif not Validator.signatureVal(Validator, tx.txHashCalc().encode('utf-8'), tx.pubkey, tx.signature): break else: return True return False
def chain_balance(self, addr): bal = 0 senders = [] recipients = [] for block in self.blocks: for trans in block.transactions: x = Deserializer.deserialize(trans) if x.sender == addr: senders.append(x.amount) if x.recipient == addr: recipients.append(x.amount) for i in recipients: bal += i for i in senders: bal -= i return bal
def InitNewBlock(prev_hash, comp=2): block = Block(prev_hash) dec_txs = [] try: with open("address", 'r') as add: coinbase = tx.CoinBaseTransaction(add.readline()) # new_tx. coinbase.CalcHash() except IOError: print("Could not read 'address' file") return (0) dec_txs.append(coinbase) fresh_txs = pool.GetThreeTxFromFile("last") if (fresh_txs == None): return (None) for element in fresh_txs: dec_txs.append(deser.deserialize(element)) block.txs = dec_txs block.GetMerkleRoot() block.MineBlock(comp) return (block)
def update_pool(self, block: Block): for tx in block.transactions: tx_obj = Deserializer.deserialize(tx) txid = tx_obj.txid().hex() for tx_in in tx_obj.inputs: if tx_in.txid.hex() == 64 * '0': pass elif (tx_in.txid.hex() in self.pool) and (tx_in.vout in self.pool[tx_in.txid.hex()]): del self.pool[tx_in.txid.hex()][tx_in.vout] if len(self.pool[tx_in.txid.hex()]) == 0: del self.pool[tx_in.txid.hex()] else: pass # raise Exception("non valid input") i = 0 for tx_out in tx_obj.outputs: if txid in self.pool: self.pool[txid][i] = tx_out else: self.pool[txid] = {i: tx_out} i += 1
def add_trans(plain): x = Deserializer.deserialize(plain) save_to_mem(plain) if verification(x) else print( 'Error, serialization of transaction failed')
def add_tx(s): t = Deserializer.deserialize(s) tx_valiadtor.check_tx(t) with open((os.path.abspath(".") + "/mempool"), 'a+') as f: f.write(f"{s}\n") f.close()
def add_tx(s): t = Deserializer.deserialize(s) tx_valiadtor.check_tx(t) with open((_program_dir + "/mempool"), 'a+') as f: f.write(f"{s}\n") f.close()