How Blocks are Linked in a Blockchain

how blocks are linked in a blockchain

In this blog we are going to discuss, how blocks are linked in a blockchain using Python! Let’s get started!

💎 Block Structure and the Power of Chaining 💎

In a blockchain, each block’s header contains a list of transactions. The header of the block, holds essential components such as the previous block’s hash, a timestamp, a proof-of-work value (nonce), and, of course, the block’s unique hash!

The secret to linking these blocks is the previous block’s hash! Each block carries the digital fingerprint of its predecessor, creating an unbreakable bond within the blockchain. It’s like chain that keeps all the blocks connected ! 🔗

🔐 Hashing 🔐

When a new block enters the scene, The data in the header of this block, combined with the previous block’s hash, undergoes cryptographic transformation, generating a new hash for the current block. This unique hash becomes the part of the header of next blocks’ header!

🔍 Detecting Tempting 🔍

Trying to change anything inside a blockchain block can cause a lot of trouble. Even a tiny change anywhere in the blockchain would make the block’s hash value completely different. This would also affect all the blocks that come after it. This happens because each block is connected to the one before by using previous block’s hash in header. If you change one block, it’s like pulling a thread that affects the whole chain. So, changing something small can mess up the entire order of blocks in the blockchain.

🤝 Consensus Mechanism 🤝

Consensus mechanism refers to the protocol or set of rules that enables a network of distributed nodes to achieve synchronization and agreement on the validity and order of transactions or data updates. Given the decentralized nature of blockchains, where multiple participants maintain copies of the same ledger, a consensus mechanism plays a pivotal role in maintaining data integrity, preventing double-spending, and ensuring the consistency of the shared ledger.

Consensus mechanisms tackle the Byzantine Generals’ Problem, a theoretical dilemma where participants in a distributed network need to cooperate to make a unified decision, despite the presence of potential malicious actors or unreliable communication channels.

To address this challenge, various consensus mechanisms have emerged, each with distinct technical implementations:

  1. Proof of Work (PoW): In PoW, participants (miners) compete to solve a complex mathematical puzzle. The first one to solve it gets the right to add the next block to the blockchain. This process requires a significant amount of computational power, creating a secure and decentralized network. Bitcoin, the first cryptocurrency, uses PoW.
  2. Proof of Stake (PoS): In PoS, participants (validators) are chosen to create new blocks based on the amount of cryptocurrency they hold and are willing to “stake” as collateral. Validators are incentivized to act honestly to avoid losing their staked assets. Ethereum is transitioning from PoW to PoS.
  3. Delegated Proof of Stake (DPoS): DPoS introduces a reputation-based voting system. Token holders elect a limited number of delegates who are responsible for validating transactions and producing blocks. This mechanism enhances scalability and energy efficiency.

These mechanisms, among others, enable blockchain networks to achieve consensus and validate transactions without relying on a central authority. They represent the intricate technical underpinnings that enable distributed networks to function securely and transparently, solving the challenges posed by the distributed nature of blockchain systems.

🏆 The Longest Chain Rule 🏆

The longest chain rule, also known as the longest valid chain rule, is a fundamental principle in blockchain technology that determines the canonical (official) version of the blockchain in a decentralized network. It states that the valid blockchain with the most accumulated proof of work (or another consensus mechanism’s equivalent) is considered the true and accepted version of the blockchain.

In simpler terms, the longest chain rule establishes that the version of the blockchain with the most computational effort invested in it is recognized as the valid one. This helps in preventing malicious actors from manipulating the blockchain’s history, as changing a past transaction or block would require redoing the work for all subsequent blocks, which becomes increasingly difficult as more blocks are added to the chain.

The longest chain rule is particularly associated with proof of work (PoW) consensus mechanisms, such as those used in Bitcoin. Miners in a PoW network compete to solve complex mathematical puzzles to validate transactions and create new blocks. The chain with the most “proof of work” behind it is considered the valid chain, as it represents the most honest and resource-intensive effort.

This rule plays a crucial role in maintaining the security and immutability of blockchain networks by ensuring that the majority of participants follow the same rules and validate transactions according to the protocol. It incentivizes participants to contribute their computational power honestly, as deviating from the rules would risk creating a less valid chain, leading to a lack of consensus and a potential disregard for the dishonest chain.

🔢 Let’s Code Our Own Blockchain using Python! 🔢

Enough talk, time for hands-on magic! Let’s see how blocks link together in a simple blockchain built using Python. Don’t worry; we’ll keep it simple and skip the nonce part, just to make it more beginner-friendly!

import hashlib
import time

class Block:
    def __init__(self, index, previous_block_hash, timestamp, transaction_data, hash):
        self.index = index
        self.previous_block_hash = previous_block_hash
        self.timestamp = timestamp
        self.transaction_data = transaction_data
        self.hash = hash

def calculate_hash(index, previous_block_hash, timestamp, transaction_data):
    return hashlib.sha256(f"{index}{previous_block_hash}{timestamp}{transaction_data}".encode()).hexdigest()

def create_genesis_block():
    # Let's start this amazing blockchain journey with a bang!
    return Block(0, "0", time.time(), "Genesis Block", calculate_hash(0, "0", time.time(), "Genesis Block"))

def create_new_block(previous_block, transaction_data):
    # Ready to forge a new block and add it to the chain!
    index = previous_block.index + 1
    timestamp = time.time()
    hash = calculate_hash(index, previous_block.hash, timestamp, transaction_data)
    return Block(index, previous_block.hash, timestamp, transaction_data, hash)

# Blockchain creation and adding blocks!
blockchain = [create_genesis_block()]
previous_block = blockchain[0]

# The number of blocks we'll be adding to the chain
num_blocks_to_add = 5

for i in range(num_blocks_to_add):
    new_block_transaction_data = f"Block #{i+1}: Transactions data"
    new_block = create_new_block(previous_block, new_block_transaction_data)
    blockchain.append(new_block)
    previous_block = new_block
    print(f"🔗 Block #{new_block.index} added to blockchain!")
    print(f"🔒 Hash: {new_block.hash}\n")

print("🎉 Congratulations! We've built our first blockchain!\n")
print("📜 Blockchain details:")
for block in blockchain:
    print(f"Index: {block.index}")
    print(f"Previous Hash: {block.previous_block_hash}")
    print(f"Timestamp: {block.timestamp}")
    print(f"Transaction_data: {block.transaction_data}")
    print(f"Hash: {block.hash}\n")

We get the following output:

🔗 Block #1 added to blockchain!
🔒 Hash: a0d0f8afdcd286dc59abc3cf8bd9d37eec830d17cb4c16672227e8280bccccc2

🔗 Block #2 added to blockchain!
🔒 Hash: 227906f93efddb9e38960ca54c8456646afc497555aeb1a12a4a0f8aeabc1fba

🔗 Block #3 added to blockchain!
🔒 Hash: 776ab7f1ececfe26c002a38d2da95a53228ea1a90b0426031638fd4083d47e31

🔗 Block #4 added to blockchain!
🔒 Hash: b373c4e86dd4d8a162d6e884543ce2dc5e15563b88956f34887c432f5e6c25bf

🔗 Block #5 added to blockchain!
🔒 Hash: 97d026a8e8d5141e98a54535bd940d1b44b4cfcde5996e268752f166aa41a62b

🎉 Congratulations! We've built our first blockchain!

📜 Blockchain details:
Index: 0
Previous Hash: 0
Timestamp: 1691145309.9377732
Transaction_data: Genesis Block
Hash: 84a2a07a809b7ddbdb4d36249d7959f5075e3003b7c22008707eb67d13d3ddb2

Index: 1
Previous Hash: 84a2a07a809b7ddbdb4d36249d7959f5075e3003b7c22008707eb67d13d3ddb2
Timestamp: 1691145309.9377732
Transaction_data: Block #1: Transactions data
Hash: a0d0f8afdcd286dc59abc3cf8bd9d37eec830d17cb4c16672227e8280bccccc2

Index: 2
Previous Hash: a0d0f8afdcd286dc59abc3cf8bd9d37eec830d17cb4c16672227e8280bccccc2
Timestamp: 1691145309.9377732
Transaction_data: Block #2: Transactions data
Hash: 227906f93efddb9e38960ca54c8456646afc497555aeb1a12a4a0f8aeabc1fba

Index: 3
Previous Hash: 227906f93efddb9e38960ca54c8456646afc497555aeb1a12a4a0f8aeabc1fba
Timestamp: 1691145309.9377732
Transaction_data: Block #3: Transactions data
Hash: 776ab7f1ececfe26c002a38d2da95a53228ea1a90b0426031638fd4083d47e31

Index: 4
Previous Hash: 776ab7f1ececfe26c002a38d2da95a53228ea1a90b0426031638fd4083d47e31
Timestamp: 1691145309.9377732
Transaction_data: Block #4: Transactions data
Hash: b373c4e86dd4d8a162d6e884543ce2dc5e15563b88956f34887c432f5e6c25bf

Index: 5
Previous Hash: b373c4e86dd4d8a162d6e884543ce2dc5e15563b88956f34887c432f5e6c25bf
Timestamp: 1691145309.9377732
Transaction_data: Block #5: Transactions data
Hash: 97d026a8e8d5141e98a54535bd940d1b44b4cfcde5996e268752f166aa41a62b

Try to analyze the pattern in the output of the above code. You will see each block’s previous hash value is equal to hash value of the previous block.

When we calculate the hash of a block, we use the previous block’s hash, the timestamp, the transaction data, and the block’s index. This unique combination creates an unbreakable bond between every block with its’ previous block, hence creating a chain.

Now, imagine stirring things up by tweaking the data of a single block. You see, each block holds the hash of its predecessor, so any change to a block’s hash sets off a cascade that flows to the next block, and the next, and so forth through the entire blockchain, leaving no block untouched.

The very foundation of the entire blockchain relies on the sanctity of each block’s data and its connection to the past. Even the tiniest alteration sets forth a chain reaction, rippling through the entire chain, imprinting its mark on every future block.

🕵️‍♂️ Detecting Tampering 🕵️‍♂️

Let’s see how any change in the data of a block will break the chain and make it invalid. We’ll tamper with the data in Block #3 and change it from “Block #3” to “Block #3 (modified).” Watch how it affects the blockchain’s integrity!

# ... (Previous code remains the same) add previous code here ...
# Tamper with the data in Block #3 (index 3)
blockchain[3].transaction_data = "Block #3 (modified)"

# Check if the blockchain is still valid
def is_blockchain_valid(chain):
    for i in range(1, len(chain)):
        current_block = chain[i]
        previous_block = chain[i - 1]

        # Check if the hash of the previous block matches the 'previous_block_hash' field of the current block
        if current_block.previous_block_hash != calculate_hash(previous_block.index, previous_block.previous_block_hash,
 previous_block.timestamp, previous_block.transaction_data):
            return False

        # Check if the hash of the current block is valid (meets certain criteria)
        if current_block.hash != calculate_hash(current_block.index, current_block.previous_block_hash,
                                                current_block.timestamp, current_block.transaction_data):
            return False

    return True

# Check if the blockchain is valid
print("Is the blockchain valid?", is_blockchain_valid(blockchain))

Output:

Is the blockchain valid? False

As we suspected, the blockchain is no longer valid after the tampering. The harmony of the blockchain has been disrupted, and the chain’s integrity shattered. Yet, our Python code detected the deception instantly! The blockchain’s power to resist tampering prevails!

Blockchains offer endless possibilities, from revolutionizing finance to enhancing security across industries! Now, let the adventure begin! Happy coding!

Don't Miss Out! Subscribe to Read Our Latest Blogs.

Subscription form (#5)

If you found this blog helpful, share it on social media.

Leave a Comment

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Scroll to Top