blockchain in python

Using blockchain in Python typically involves creating a simple blockchain system with the ability to add blocks, validate the chain, and perform basic operations. Below is a simple example of a blockchain implemented in Python:

pythonCopy codeimport 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

def calculate_hash(index, previous_hash, timestamp, data
):
value = str(index) + str(previous_hash) + str(timestamp) + str(data)
return hashlib.sha256(value.encode('utf-8')).hexdigest()

def create_genesis_block():
return Block(0, '0', time.time(), 'Genesis Block', calculate_hash(0, '0', time.time(), 'Genesis Block'))

def create_new_block(previous_block, data):
index = previous_block.index + 1
timestamp = time.time()
hash = calculate_hash(index, previous_block.hash, timestamp, data)
return Block(index, previous_block.hash, timestamp, data, hash)

# Example usage
blockchain = [create_genesis_block()]
previous_block = blockchain[0]

# Add blocks to the blockchain
num_blocks_to_add = 5
for _ in range
(num_blocks_to_add):
new_data = f"Block #{len(blockchain)} data"
new_block = create_new_block(previous_block, new_data)
blockchain.append(new_block)
previous_block = new_block
print(f"Block #{new_block.index} has been added to the blockchain!")
print(f"Hash: {new_block.hash}\n")

This is a basic implementation that uses SHA-256 for hashing. Each block contains an index, a timestamp, some data, the hash of the previous block, and its own hash.