Blockchain

If you do not mind, please read this article on Medium.

Blockchain is a distributed ledger technology that enables secure, transparent, and tamper-proof recording of transactions. It is the foundation of cryptocurrencies like Bitcoin. A blockchain consists of a series of blocks, where each block contains data, a timestamp, and a unique cryptographic hash. Each block also includes the hash of the previous block, creating a chain of interconnected blocks. This structure ensures that altering a single block invalidates the entire chain (even the slightest change causes the generated hash to be entirely different). If the hash of the first block changes because its value has been tampered with, the hash of the second block will also change because it was generated based on the block's value and the previous block's hash, and so on. This way, the blockchain's integrity can be easily verified.

A cryptographic hash function produces a fixed-length, unique output (hash) for any input, ensuring that even a minor change in the input results in a completely different hash.


import hashlib, 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.hash = self.calculate_hash()

    def calculate_hash(self):
        block_content = (str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash))
        return hashlib.sha256(block_content.encode()).hexdigest() # inverting a hash is infeasible

class Blockchain:
    def __init__(self):
        self.chain = [self.create_genesis_block()]

    def create_genesis_block(self):
        return Block(0, time.time(), "Genesis Block", "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.hash = new_block.calculate_hash()
        self.chain.append(new_block)

my_blockchain = Blockchain()
my_blockchain.add_block(Block(1, time.time(), "Block 1 data", "")) # changing one character of the string would completely change the hash
my_blockchain.add_block(Block(2, time.time(), "Block 2 data", ""))

for block in my_blockchain.chain:
    print("Index:", block.index)
    print("Timestamp:", block.timestamp)
    print("Data:", block.data)
    print("Hash:", block.hash)
    print("Previous hash:", block.previous_hash)
    print("----")