Build a simple blockchain with proof of work. The mine_block function must find a nonce…
- User
Build a simple blockchain with proof of work. The mine_block function must find a nonce where the SHA-256 hash starts with 4 zeros. Verify chain integrity by recalculating hashes of all previous blocks.
- Assistant
Providing complete Python blockchain code
I'm providing a concise standalone Python implementation of a simple blockchain with proof of work (difficulty=4), including block mining and chain integrity verification as requested. Here's a minimal Python implementation of a blockchain with proof‑of‑work and an integrity check:
import hashlib import time class Block: def __init__(self, index, timestamp, data, previous_hash): self.index = index self.timestamp = timestamp self.data = data self.previous_hash = previous_hash self.nonce = 0 # will be adjusted during mining self.hash = self.compute_hash() def compute_hash(self) -> str: """ Compute the SHA-256 hash of the block's contents. """ block_string = f"{self.index}{self.timestamp}{self.data}{self.previous_hash}{self.nonce}" return hashlib.sha256(block_string.encode()).hexdigest() class Blockchain: def __init__(self, difficulty: int = 4): self.chain = [self.create_genesis_block()] self.difficulty = difficulty def create_genesis_block(self) -> Block: """ Manually create the first block in the chain. """ return Block(0, time.time(), "Genesis Block", "0") @property def last_block(self) -> Block: return self.chain[-1] def proof_of_work(self, block: Block) -> str: """ Increment the nonce until the block's hash starts with the required number of zeros. """ block.nonce = 0 computed_hash = block.compute_hash() while not computed_hash.startswith("0" * self.difficulty): block.nonce += 1 computed_hash = block.compute_hash() return computed_hash def add_block(self, block: Block, proof: str) -> bool: """ Validate and add the mined block to the chain. """ if block.previous_hash != self.last_block.hash: return False if not proof.startswith("0" * self.difficulty): return False if proof != block.compute_hash(): return False block.hash = proof self.chain.append(block) return True def mine_block(self, data) -> Block: """ Create a new block, find a valid nonce, and append it to the chain. """ new_block = Block(index=self.last_block.index + 1, timestamp=time.time(), data=data, previous_hash=self.last_block.hash) proof = self.proof_of_work(new_block) self.add_block(new_block, proof) return new_block def is_chain_valid(self) -> bool: """ Verify the integrity of the chain by recomputing hashes and checking linkage. """ for i in range(1, len(self.chain)): current = self.chain[i] previous = self.chain[i - 1] # Recompute the hash of the current block and compare if current.hash != current.compute_hash(): return False # Check that the current block points to the correct previous hash if current.previous_hash != previous.hash: return False # Check proof of work if not current.hash.startswith("0" * self.difficulty): return False return True if __name__ == "__main__": # Example usage bc = Blockchain(difficulty=4) bc.mine_block("Transaction 1") bc.mine_block("Transaction 2") bc.mine_block("Transaction 3") for b in bc.chain: print(f"Index: {b.index}, Hash: {b.hash}, Nonce: {b.nonce}") print("Chain valid?", bc.is_chain_valid())The
mine_blockmethod repeatedly increments the nonce untilcompute_hash()yields a digest starting with four zeros. Theis_chain_validmethod walks the chain, recomputes each block’s hash, checks that eachprevious_hashmatches, and ensures the proof‑of‑work criterion is still met.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.