Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def add_block(self, new_block):
if self.is_valid_new_block(new_block, self.get_latest_block()):
transactions = new_block.data if isinstance(new_block.data, list) else [new_block.data]
ret_val = process_transactions([transaction_object(transaction) for transaction in transactions], self.get_unspent_tx_outs(), new_block.index)
if ret_val is None:
print('block is not valid in terms of transactions')
return False
else:
self._blockchain.append(new_block)
self.set_unspent_tx_outs(ret_val)
update_transaction_pool(self.get_unspent_tx_outs())
return True
def is_valid_chain(self, blockchain_to_validate):
# if self.calculate_hash_for_block(Block(**blockchain_to_validate[0])) != self.get_genesis_block().hash:
# return False
previous_block = None
unspent_tx_outs = []
for current_block in blockchain_to_validate:
if previous_block and not self.is_valid_new_block(Block(**current_block), previous_block):
return False
current_block = (Block(**current_block))
transactions = current_block.data if isinstance(current_block.data, list) else [current_block.data]
unspent_tx_outs = process_transactions([transaction_object(transaction) for transaction in transactions], unspent_tx_outs, current_block.index)
previous_block = current_block
if not unspent_tx_outs:
return False
return unspent_tx_outs
def calculate_hash(self, index, previous_hash, timestamp, data, nonce=None):
# Calculating the transaction summary similar to a Merkle root
transactions = data if isinstance(data, list) else [data]
transactions_summary = [transaction_object(transaction).id for transaction in transactions]
if not nonce:
header = str(index) + previous_hash + str(timestamp) + str(transactions_summary) + str(self.difficulty_bits)
return self.proof_of_work(header)
else:
hash_object = SHA256.new(data=(str(index) + previous_hash + str(timestamp)
+ str(transactions_summary) + str(self.difficulty_bits) + str(nonce)).encode())
return hash_object.hexdigest()