Understanding Blockchain: A Developer's Guide to Blocks, Consensus, and Smart Contracts

Understanding Blockchain: A Developer's Guide to Blocks, Consensus, and Smart Contracts

Leader 1 4
calendar_today agoschedule9 min read

Blockchain for Developers: A Practical Introduction

If you have spent any time around tech Twitter, YouTube, or dev conferences in the last few years, you have heard the word "blockchain" thrown around a lot. Sometimes it is tied to cryptocurrency hype, sometimes to NFTs, and sometimes to serious enterprise systems. But if you strip away the noise, blockchain is actually a fairly simple idea once you understand the core mechanics. This article is meant to give developers a clear, no-nonsense introduction to what blockchain actually is, how it works under the hood, and where it might fit into your own projects.

What Is a Blockchain, Really?

At its core, a blockchain is a data structure. It is a list of records, called blocks, that are linked together in a chain using cryptographic hashes. Each block contains:

  • A set of data (transactions, in most cases)
  • A timestamp
  • A hash of the previous block
  • Its own hash, calculated from its contents

Because each block includes the hash of the one before it, the blocks form a chain where every entry depends on the one that came before. If someone tries to change the data in an old block, its hash changes, which breaks the link to the next block, which breaks the link to the one after that, and so on. This is what makes blockchains tamper evident.

Here is what that chain of dependency actually looks like:

graph LR
    A["Block 0 (Genesis)<br/>Hash: 0x1a2b...<br/>Prev: none"] --> B["Block 1<br/>Hash: 0x3c4d...<br/>Prev: 0x1a2b..."]
    B --> C["Block 2<br/>Hash: 0x5e6f...<br/>Prev: 0x3c4d..."]
    C --> D["Block 3<br/>Hash: 0x7g8h...<br/>Prev: 0x5e6f..."]
    D -.->|"tamper attempt breaks all following hashes"| E["Block 4 (invalid)"]

Notice how each block only stores the hash of the block before it, not its full content. That single link is enough to make the whole chain tamper evident, since recalculating one block's data changes its hash, which no longer matches what the next block expects.

You can actually build a very basic blockchain in about 40 lines of JavaScript or Python just to see this idea in action. Here is a simplified example in JavaScript:

const crypto = require('crypto');

class Block {
  constructor(index, data, previousHash = '') {
    this.index = index;
    this.timestamp = Date.now();
    this.data = data;
    this.previousHash = previousHash;
    this.hash = this.calculateHash();
  }

  calculateHash() {
    return crypto
      .createHash('sha256')
      .update(this.index + this.timestamp + JSON.stringify(this.data) + this.previousHash)
      .digest('hex');
  }
}

class Blockchain {
  constructor() {
    this.chain = [this.createGenesisBlock()];
  }

  createGenesisBlock() {
    return new Block(0, 'Genesis Block', '0');
  }

  getLatestBlock() {
    return this.chain[this.chain.length - 1];
  }

  addBlock(data) {
    const newBlock = new Block(this.chain.length, data, this.getLatestBlock().hash);
    this.chain.push(newBlock);
  }

  isChainValid() {
    for (let i = 1; i < this.chain.length; i++) {
      const current = this.chain[i];
      const previous = this.chain[i - 1];

      if (current.hash !== current.calculateHash()) return false;
      if (current.previousHash !== previous.hash) return false;
    }
    return true;
  }
}

This tiny example already demonstrates the core property of a blockchain: data integrity through linked hashes. Everything else, consensus algorithms, peer to peer networking, smart contracts, is built on top of this basic idea.

Why Decentralization Matters

A single chain of hashed blocks on your laptop is not very useful by itself. The real value of blockchain comes from decentralization: instead of one central server holding the "true" copy of the data, thousands of independent nodes each hold their own copy and agree on what the valid chain looks like.

This is where consensus mechanisms come in. The two most common are:

Proof of Work (PoW): Nodes, often called miners, compete to solve a computational puzzle. Whoever solves it first gets to add the next block and is rewarded for it. Bitcoin popularized this approach. It is secure but energy intensive.

Proof of Stake (PoS): Instead of competing with computing power, nodes called validators lock up, or "stake," some amount of cryptocurrency as collateral. Validators are chosen to propose blocks based on their stake, and they lose part of their stake if they act dishonestly. Ethereum switched to this model in 2022 to reduce energy consumption.

There are other consensus models too, like Proof of Authority or Delegated Proof of Stake, each with different tradeoffs between speed, decentralization, and security.

Here is roughly how a new block gets added to the network under either model:

flowchart TD
    A[New transactions broadcast to network] --> B{Consensus model}
    B -->|Proof of Work| C[Miners compete to solve puzzle]
    B -->|Proof of Stake| D[Validator selected based on stake]
    C --> E[Winning miner proposes block]
    D --> F[Selected validator proposes block]
    E --> G[Other nodes verify block]
    F --> G
    G -->|Valid| H[Block added to chain, reward given]
    G -->|Invalid| I[Block rejected]

And a quick side by side comparison of the two dominant models:

Factor Proof of Work Proof of Stake
Resource used Computing power Staked cryptocurrency
Energy usage Very high Low
Hardware needed Specialized mining rigs Standard servers
Example network Bitcoin Ethereum (post 2022)
Attack cost Requires majority of compute power Requires majority of staked value
Penalty for dishonesty Wasted computation Stake gets slashed

Smart Contracts: Where It Gets Interesting for Developers

For most developers, the more exciting part of blockchain is not the ledger itself but smart contracts. A smart contract is just code that lives on the blockchain and runs automatically when certain conditions are met. Think of it as a backend function that nobody can quietly modify or take down, because it exists across thousands of nodes instead of a single server you control.

Ethereum is the most common platform for this, and smart contracts there are usually written in Solidity. Here is a minimal example:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private storedValue;

    function set(uint256 value) public {
        storedValue = value;
    }

    function get() public view returns (uint256) {
        return storedValue;
    }
}

This looks almost like a plain class in any object oriented language. The difference is that once this contract is deployed, its logic cannot be silently changed by a company or admin. Anyone can read the contract's code and verify what it does, and every function call is recorded permanently on the chain.

This is roughly how a typical dapp talks to a deployed contract:

sequenceDiagram
    participant User
    participant Frontend as Frontend (React etc.)
    participant Wallet as Wallet (MetaMask)
    participant Contract as Smart Contract
    participant Chain as Blockchain

    User->>Frontend: Clicks "Set Value"
    Frontend->>Wallet: Request signature for transaction
    Wallet->>User: Prompt to approve
    User->>Wallet: Approves
    Wallet->>Contract: Sends signed transaction
    Contract->>Chain: Executes function, updates state
    Chain-->>Frontend: Emits confirmation/event
    Frontend-->>User: Shows updated value

This property opens the door to a lot of use cases beyond finance:

  • Supply chain tracking: recording the movement of goods so that every step is verifiable
  • Digital identity: giving people control over their own credentials without relying on a single company
  • Decentralized finance (DeFi): lending, borrowing, and trading without a traditional bank in the middle
  • Gaming and digital ownership: verifiable ownership of in-game items or digital collectibles

Should You Actually Use Blockchain?

This is the question most developers should ask before jumping in. Blockchain is not a replacement for a normal database in most situations. It is slower, more expensive to write to, and harder to update than a traditional system. It makes sense mainly when you specifically need:

  1. Trustless coordination between parties that do not fully trust each other
  2. Transparent, tamper resistant record keeping
  3. Removal of a single point of control or failure

If your app just needs a fast, private database for your own users, a blockchain is almost certainly the wrong tool. But if you are building something where multiple independent parties need to agree on shared state without a middleman, it might be worth exploring.

Getting Started as a Developer

If you want to actually build with blockchain technology, here is a reasonable path:

  1. Learn Solidity basics through interactive tools like Remix IDE, which lets you write and test contracts directly in the browser.
  2. Set up a local development environment using Hardhat or Foundry to compile, test, and deploy contracts.
  3. Use a testnet (like Sepolia for Ethereum) to deploy contracts without spending real money.
  4. Connect a frontend using a library like ethers.js or viem to interact with your deployed contracts from a normal web app.
  5. Study existing, audited contracts on platforms like OpenZeppelin to understand common patterns and security practices.

Security matters a lot more in this space than in typical web development, because a bug in a deployed smart contract can be permanent and costly. Reentrancy attacks, integer overflows, and access control mistakes have all led to real losses in production systems, so testing and audits are not optional extras here.

A Closer Look: Reentrancy Attacks

Reentrancy is one of the most well known smart contract vulnerabilities, largely because it caused the infamous DAO hack in 2016, which resulted in the loss of about 3.6 million ETH and eventually led to the Ethereum and Ethereum Classic split.

The bug happens when a contract sends funds to an external address before it updates its own internal state. If that external address is itself a malicious contract, it can call back into the original function before the first call finishes, and repeat the withdrawal multiple times before the balance is ever updated.

Here is a simplified vulnerable contract:

// VULNERABLE - do not use in production
contract VulnerableBank {
    mapping(address => uint256) public balances;

    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    function withdraw() public {
        uint256 amount = balances[msg.sender];
        require(amount > 0, "No balance");

        // External call happens BEFORE state is updated
        (bool sent, ) = msg.sender.call{value: amount}("");
        require(sent, "Transfer failed");

        balances[msg.sender] = 0; // too late, attacker already re-entered
    }
}

An attacking contract can exploit this by putting withdrawal logic inside its own receive() function, so that every time it receives funds, it immediately calls withdraw() again, since balances[msg.sender] has not been zeroed out yet.

The fix follows a pattern called "checks, effects, interactions": update your internal state before making any external call.

// FIXED - state updated before external call
contract SafeBank {
    mapping(address => uint256) public balances;

    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    function withdraw() public {
        uint256 amount = balances[msg.sender];
        require(amount > 0, "No balance");

        balances[msg.sender] = 0; // state updated first

        (bool sent, ) = msg.sender.call{value: amount}("");
        require(sent, "Transfer failed");
    }
}

Many teams also add OpenZeppelin's ReentrancyGuard modifier as a second layer of defense, which uses a simple lock to block any recursive call into a protected function while it is still executing:

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract SaferBank is ReentrancyGuard {
    mapping(address => uint256) public balances;

    function withdraw() public nonReentrant {
        uint256 amount = balances[msg.sender];
        require(amount > 0, "No balance");
        balances[msg.sender] = 0;

        (bool sent, ) = msg.sender.call{value: amount}("");
        require(sent, "Transfer failed");
    }
}

The core lesson here applies well beyond Solidity: never trust that an external call will return control to you in a clean, predictable state. Always finish updating your own data before handing control to code you do not own.

Final Thoughts

Blockchain is not magic, and it is not going to replace every database or backend system out there. But it solves a specific, real problem: how do you get a group of people or systems that do not trust each other to agree on a shared history of events, without needing a central authority to enforce it. For developers, that opens up an entirely different way of thinking about backend architecture, one where the "server" is not owned by anyone in particular but is instead maintained collectively by the network.

Whether or not you end up building on top of blockchain technology, understanding how it works is a useful addition to your toolkit as a developer, especially as more industries experiment with decentralized systems for identity, finance, and record keeping.

References

🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

ERC20 Edge Cases Every Smart Contract Engineer Should Know

BinnaDev - Jun 24

The Sovereign Vault — A Comprehensive Guide to Protocol-Driven AI

Ken W. Algerverified - Jun 4

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

The Death of Smart Contract Audits: Why NexusVeritas Hunts Web3 Scammers via Behavioral DNA

VeritasLab - Jun 12

Cavity on X-Ray: A Complete Guide to Detection and Diagnosis

Huifer - Feb 12
chevron_left
777 Points5 Badges
kolkata , Saltlake Sector ii , pin- 700091linkedin.com/in/soumabha-mahapatra
3Posts
1Comments
2Connections
Aspiring Data Analyst & Product Manager ⭐ B.Tech CSE | DSA • Python • Power BI • ETL • Front-End Development • Blockchain Research

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!