Tommi Versetti pfp
Tommi Versetti
@tommiversetti
import hashlib import json from time import time from uuid import uuid4 class Blockchain: def __init__(self): self.chain = [] self.current_transactions = [] # Create the genesis block self.new_block(previous_hash='1', proof=100) def new_block(self, proof, previous_hash=None): """ Create a new Block in the Blockchain :param proof: <int> The proof given by the Proof of Work algorithm :param previous_hash: (Optional) <str> Hash of previous Block :return: <dict> New Block """ block = { 'index': len(self.chain) + 1, 'timestamp': time(), 'transactions': self.current_transactions, 'proof': proof, 'previous_hash': previous_hash or self.hash(self.chain[-1]), } # Reset the current list of transactions self.current_transactions = [] self.chain.append(block) return block
0 reply
0 recast
4 reactions

Tommi Versetti pfp
Tommi Versetti
@tommiversetti
# Example usage: # Instantiate the Blockchain blockchain = Blockchain() # Example transactions blockchain.new_transaction('Alice', 'Bob', 1) blockchain.new_transaction('Bob', 'Alice', 5) # Mine a new block last_block = blockchain.last_block last_proof = last_block['proof'] proof = blockchain.proof_of_work(last_proof) # Add the block to the blockchain previous_hash = blockchain.hash(last_block) block = blockchain.new_block(proof, previous_hash) # Output the blockchain print(json.dumps(blockchain.chain, indent=2))
0 reply
0 recast
0 reaction