blockchain.simple_blockchain¶
A simple blockchain implementation with Proof-of-Work (PoW).
This educational example demonstrates: - Block structure with index, timestamp, data, previous hash, nonce, and hash - Mining via Proof-of-Work - Chain integrity verification
Author: Letitia Gilbert
Classes¶
Represents a single block in a blockchain. |
|
Simple blockchain class maintaining a list of blocks. |
Module Contents¶
- class blockchain.simple_blockchain.Block(index: int, data: str, previous_hash: str, difficulty: int = 2)¶
Represents a single block in a blockchain.
- Attributes:
index (int): Position of the block in the chain. timestamp (float): Creation time of the block. data (str): Data stored in the block. previous_hash (str): Hash of the previous block. nonce (int): Number used for mining. hash (str): SHA256 hash of the block’s content.
- compute_hash(nonce: int) str¶
Compute SHA256 hash of the block with given nonce.
- Args:
nonce (int): Nonce to include in the hash.
- Returns:
str: Hexadecimal hash string.
>>> block = Block(0, "Genesis", "0", difficulty=2) >>> len(block.compute_hash(0)) == 64 True >>> isinstance(block.compute_hash(0), str) True
- mine_block(difficulty: int) tuple[int, str]¶
Simple Proof-of-Work mining algorithm.
- Args:
difficulty (int): Number of leading zeros required in the hash.
- Returns:
Tuple[int, str]: Valid nonce and resulting hash that satisfies difficulty.
>>> block = Block(0, "Genesis", "0", difficulty=2) >>> block.hash.startswith('00') True
- data¶
- index¶
- previous_hash¶
- timestamp¶
- class blockchain.simple_blockchain.Blockchain(difficulty: int = 2)¶
Simple blockchain class maintaining a list of blocks.
- Attributes:
chain (List[Block]): List of blocks forming the chain.
- add_block(data: str) Block¶
Add a new block to the blockchain with given data.
- Args:
data (str): Data to store in the block.
- Returns:
Block: Newly added block.
>>> bc = Blockchain() >>> new_block = bc.add_block("Test Data") >>> new_block.index 1 >>> new_block.previous_hash == bc.chain[0].hash True >>> new_block.hash.startswith('00') True >>> bc.is_valid() True
- create_genesis_block() Block¶
Create the first block in the blockchain.
- Returns:
Block: Genesis block.
>>> bc = Blockchain() >>> bc.chain[0].index 0 >>> bc.chain[0].hash.startswith('00') True
- is_valid() bool¶
Verify the integrity of the blockchain.
- Returns:
bool: True if chain is valid, False otherwise.
>>> bc = Blockchain() >>> new_block = bc.add_block("Test") >>> new_block.index 1 >>> new_block.previous_hash == bc.chain[0].hash True >>> new_block.hash.startswith('00') True >>> bc.is_valid() True >>> bc.chain[1].previous_hash = "tampered" >>> bc.is_valid() False
- difficulty = 2¶