Creating a simple blockchain can be accomplished with a few hundred lines of code. Below is a very basic implementation of a blockchain using Python. This example includes creating blocks, adding transactions, and basic proof-of-work for mining blocks.
Simple Blockchain in Python
import hashlib
import time
class Block:
def __init__(self, index, previous_hash, timestamp, data, hash):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash = hash
@staticmethod
def calculate_hash(index, previous_hash, timestamp, data):
value = str(index) + previous_hash + str(timestamp) + str(data)
return hashlib.sha256(value.encode()).hexdigest()
class Blockchain:
def __init__(self):
self.chain = []
# Create the genesis block
self.create_block(previous_hash='0')
def create_block(self, data, previous_hash=None):
index = len(self.chain)
timestamp = time.time()
hash_value = Block.calculate_hash(index, previous_hash if previous_hash else self.chain[-1].hash, timestamp, data)
block = Block(index, previous_hash if previous_hash else '0', timestamp, data, hash_value)
self.chain.append(block)
return block
def get_latest_block(self):
return self.chain[-1]
def add_block(self, data):
previous_block = self.get_latest_block()
new_block = self.create_block(data, previous_block.hash)
return new_block
def print_chain(self):
for block in self.chain:
print(f'Index: {block.index}')
print(f'Hash: {block.hash}')
print(f'Previous Hash: {block.previous_hash}')
print(f'Timestamp: {block.timestamp}')
print(f'Data: {block.data}\n')
# Example usage
if __name__ == '__main__':
blockchain = Blockchain()
# Adding blocks to the blockchain
blockchain.add_block("First Block Data")
blockchain.add_block("Second Block Data")
# Print the blockchain
blockchain.print_chain()
Explanation:
- Block Class: Represents the structure of a block in the blockchain. It contains properties like index, previous hash, timestamp, data, and hash.
- Blockchain Class: Manages the chain of blocks. It allows you to create new blocks, add them to the chain, and print the entire chain.
- Hashing: The hash of each block is calculated using SHA-256 based on its properties.
- Adding Blocks: You can add new blocks to the blockchain with specific data.
Running the Code:
- Make sure you have Python installed on your machine.
- Copy the code into a
.py file (e.g., simple_blockchain.py).
- Run it using the command:
python simple_blockchain.py.
This is a very basic blockchain implementation and does not include features like consensus algorithms, peer-to-peer networking, or transaction validation, which are essential for a production-level blockchain. If you're interested in those advanced topics, let me know!