Here’s a simple implementation of a blockchain in Python3. This implementation will allow us to create new blocks, add transactions to blocks, and mine the blocks to secure the network.
pythonCopy codeimport hashlib
import json
import time
class Block:
def __init__(self, index, transactions, timestamp, previous_hash):
self.index = index
self.transactions = transactions
self.timestamp = timestamp
self.previous_hash = previous_hash
self.nonce = 0
self.hash = self.calculate_hash()
def calculate_hash(self):
block_string = json.dumps(self.__dict__, sort_keys=True)
return hashlib.sha256(block_string.encode()).hexdigest()
def mine_block(self, difficulty):
while self.hash[:difficulty] != "0" * difficulty:
self.nonce += 1
self.hash = self.calculate_hash()
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
self.difficulty = 2
def create_genesis_block(self):
return Block(0, [], time.time(), "0")
def get_latest_block(self):
return self.chain[-1]
def add_block(self, new_block):
new_block.previous_hash = self.get_latest_block().hash
new_block.mine_block(self.difficulty)
self.chain.append(new_block)
def is_valid_chain(self):
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i-1]
if current_block.hash != current_block.calculate_hash():
return False
if current_block.previous_hash != previous_block.hash:
return False
return True
Here’s how to use this code to create a simple blockchain:
pythonCopy code# Create a new blockchain
blockchain = Blockchain()
# Add some transactions to the blockchain
blockchain.add_block(Block(1, [{"from": "Alice", "to": "Bob", "amount": 10}], time.time(), ""))
blockchain.add_block(Block(2, [{"from": "Bob", "to": "Charlie", "amount": 5}], time.time(), ""))
# Print out the current state of the blockchain
for block in blockchain.chain:
print(vars(block))
This will output the following:
cssCopy code{'index': 0, 'transactions': [], 'timestamp': 1648355049.8712897, 'previous_hash': '0', 'nonce': 0, 'hash': '203b3d2571167f407e136a9c7e18c2a92d7cc23c78cf05b7a452f346aee3847d'}
{'index': 1, 'transactions': [{'from': 'Alice', 'to': 'Bob', 'amount': 10}], 'timestamp': 1648355049.873434, 'previous_hash': '203b3d2571167f407e136a9c7e18c2a92d7cc23c78cf05b7a452f346aee3847d', 'nonce': 7, 'hash': '00a45632ee9c9a276bdf23ce143772c296e83a70f07e656bfb0f29e34f4418a9'}
{'index': 2, 'transactions': [{'from': 'Bob', 'to': 'Charlie', 'amount': 5}], 'timestamp': 1648355049.875718, 'previous_hash': '00a45632ee9c9a276bdf23ce143772c296e83a70f07e