Cryptography

Blockchain

An append-only, hash-linked chain of blocks — tamper-evident by design

A blockchain is a sequence of blocks where each one contains a hash of the previous block. Tampering with any past block changes its hash, breaking every subsequent block's link — making the entire history publicly verifiable. Combined with proof-of-work or proof-of-stake consensus, blockchains create distributed databases that no single party controls. Bitcoin, Ethereum, and most cryptocurrencies build on this primitive.

  • Block linkEach header includes hash of previous block
  • Tamper detectionChanging any block invalidates every later hash
  • Merkle rootPer-block summary of all transactions
  • Bitcoin block time (avg)10 minutes
  • Ethereum block time~12 seconds (post-merge, proof-of-stake)
  • Consensus mechanismsProof-of-work, proof-of-stake, BFT variants

Interactive visualization

Press play, or step through manually. The visualization is yours to drive — try it before reading on.

Open visualization fullscreen ↗

Watch the 60-second explainer

A condensed visual walkthrough — narrated, captioned, under a minute.

How a blockchain works

A blockchain is a linked list of "blocks," each containing:

  1. A header — version, timestamp, hash of the previous block, Merkle root of transactions, nonce.
  2. A list of transactions — typically thousands per block.
  3. Metadata — block size, miner reward, optional protocol fields.

The crucial field is the previous-block hash. Combined with the block's own contents, it gives every block a unique hash that depends on all prior history. Change any byte in any past block and every subsequent block's hash changes — instantly detectable by anyone with a copy of the chain.

The Merkle root inside each block (see Merkle tree) commits to all transactions without listing them in the header. Light clients can verify a single transaction's inclusion in O(log n) hashes without downloading the whole block.

Consensus — agreeing on the canonical chain

The hash chain alone doesn't prevent forks — multiple parties could each create a different "next block" simultaneously. Consensus mechanisms break the tie:

Proof of Work (PoW)Proof of Stake (PoS)BFT (PBFT, Tendermint)
How a block proposer is chosenFirst to find a valid hash winsRandom selection weighted by stakeRound-robin among validators
Energy costVery high — brute force hashingVery low — staked capitalLow — communication overhead
Block time10 min (BTC), 13 sec (LTC)12 sec (ETH), 1 sec (Solana)1-3 sec typical
FinalityProbabilistic (deeper = more confirmed)Often hybrid (probabilistic + finality)Immediate (within rounds)
PermissionedOpenOpenPermissioned (known validator set)
Resistance51% hash power33-50% stake33% Byzantine validators
Used byBitcoin, Litecoin, DogecoinEthereum (post-merge), Cardano, SolanaHyperledger Fabric, Cosmos

Bitcoin vs Ethereum

BitcoinEthereum
Primary purposeDigital cashProgrammable platform
State modelUTXO (unspent transaction outputs)Account-based (balances stored as state)
Block time10 minutes~12 seconds
Smart contractsLimited scriptTuring-complete EVM
ConsensusProof of Work (Nakamoto)Proof of Stake (since 2022 Merge)
Block reward (current)3.125 BTC + fees (halving every 4 years)~0.05 ETH + fees + MEV
Total supply21 million BTC (capped)No fixed cap, ~120M issued
Throughput~7 transactions per second~30 TPS base, 1000s+ on L2 rollups

Building a minimal hash-chained blockchain

const crypto = require('crypto');
const hash = (data) => crypto.createHash('sha256').update(data).digest('hex');

class Block {
  constructor(index, transactions, previousHash, nonce = 0) {
    this.index = index;
    this.timestamp = Date.now();
    this.transactions = transactions;
    this.previousHash = previousHash;
    this.nonce = nonce;
    this.hash = this.computeHash();
  }

  computeHash() {
    return hash(`${this.index}${this.timestamp}${JSON.stringify(this.transactions)}${this.previousHash}${this.nonce}`);
  }

  // Proof of work — find a hash with `difficulty` leading zeros
  mine(difficulty) {
    const target = '0'.repeat(difficulty);
    while (!this.hash.startsWith(target)) {
      this.nonce++;
      this.hash = this.computeHash();
    }
    return this;
  }
}

class Blockchain {
  constructor(difficulty = 4) {
    this.difficulty = difficulty;
    this.chain = [this.genesis()];
  }

  genesis() {
    return new Block(0, [], '0').mine(this.difficulty);
  }

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

  addBlock(transactions) {
    const block = new Block(
      this.chain.length,
      transactions,
      this.latestBlock.hash
    );
    block.mine(this.difficulty);
    this.chain.push(block);
    return block;
  }

  isValid() {
    for (let i = 1; i < this.chain.length; i++) {
      const block = this.chain[i];
      const prev = this.chain[i - 1];
      if (block.hash !== block.computeHash()) return false;
      if (block.previousHash !== prev.hash) return false;
      if (!block.hash.startsWith('0'.repeat(this.difficulty))) return false;
    }
    return true;
  }
}

const bc = new Blockchain(4);
bc.addBlock([{from: 'Alice', to: 'Bob', amount: 50}]);
bc.addBlock([{from: 'Bob', to: 'Charlie', amount: 25}]);
console.log('valid:', bc.isValid());

// Tampering test
bc.chain[1].transactions[0].amount = 1000;
console.log('valid after tamper:', bc.isValid());  // false — hashes don't match

This is missing many production essentials (UTXO model, signature verification, mempool, peer-to-peer networking, consensus among multiple nodes), but it captures the chain-link integrity property in ~50 lines.

When does a blockchain actually solve a problem?

  • Multiple parties, no trusted third party. The defining use case. If everyone trusts a single operator, a normal database is faster, cheaper, and simpler.
  • Audit trail with cryptographic proof. Notarization timestamps, certificate transparency logs, supply-chain provenance — the append-only Merkle-rooted structure provides irrefutable history.
  • Atomic multi-party value exchange. Smart contracts on Ethereum and similar platforms enforce conditional asset transfers without escrow agents. Decentralized exchanges, lending markets, and cross-chain bridges all build on this.
  • Censorship resistance. Public blockchains can't be selectively blocked at the protocol level. Used in geopolitically-sensitive remittances, dissident communications, and capital flight scenarios.

When a blockchain doesn't help — when there's a trusted operator, when transactions per second matter (a database does 100k+ TPS easily; Bitcoin does 7), when you need confidentiality (most blockchains are public), or when the regulatory framework requires central control. "Putting X on a blockchain" is rarely the right answer for X = healthcare records, voting (despite hype), or supply-chain unless you have the multi-party-no-trust precondition.

Layer 2 — scaling above the base chain

Base blockchains are slow by design — global consensus is expensive. Layer 2 scaling pushes most transactions off-chain while inheriting the base chain's security:

  • Optimistic rollups (Arbitrum, Optimism). Batch many transactions, post a state update to L1, allow a challenge window where anyone can prove fraud. ~7-day withdrawal delay.
  • Zero-knowledge rollups (zkSync, StarkNet, Polygon zkEVM). Batch many transactions, post a state update with a cryptographic proof of correctness. Faster finality (no challenge window) but proof generation is computationally expensive.
  • State channels (Lightning Network on Bitcoin). Two parties open a channel, exchange off-chain transactions, settle the final state on-chain. Useful for high-volume bilateral payment.
  • Sidechains (Polygon PoS). Independent chains pegged to a main chain via two-way bridge. Easier scaling but weaker security inheritance.

Common blockchain misconceptions

  • "Blockchain is encrypted and private." Bitcoin and Ethereum are PUBLIC — every transaction is visible to everyone forever. Pseudonymous (addresses don't directly identify people) but not private. For privacy, separate cryptographic primitives (zero-knowledge proofs, mixers, privacy coins like Monero) are needed.
  • "Smart contracts are bug-free because they're on a blockchain." Smart contract code can have bugs like any other code. Once deployed, bugs are often unfixable (immutable contracts). Audits, formal verification, and battle-tested libraries are critical.
  • "Decentralized = no admin can ever change anything." Most cryptocurrencies have core developers who decide protocol upgrades. "Hard forks" change the rules; nodes that don't update can't process new blocks. Decentralization is on a spectrum, not binary.
  • "51% attacks would steal everyone's coins." No. A 51% attack lets you double-spend YOUR own coins or rewrite recent transactions. It can't steal coins from other addresses — that requires breaking ECDSA signatures, which is cryptographically infeasible.
  • "Proof-of-work is essential for security." Empirically false since Ethereum's 2022 Merge. PoS achieves comparable security with ~99% less energy. The choice is now driven by other factors (decentralization properties, finality speed, ecosystem).
  • "This problem needs a blockchain." Usually no. The decision tree: do multiple distrusting parties need consistent state? If yes, do you also need censorship resistance? If no, a database (or a database with audit logs) works. Most "X on the blockchain" pitches don't pass step 1.

Frequently asked questions

What makes a blockchain different from a normal database?

Three properties together. (1) Append-only — past blocks aren't modified, only new ones added. (2) Hash-linked — every block contains the hash of the previous, making tampering with old blocks change every later hash. (3) Distributed consensus — many independent parties agree on which chain is canonical, eliminating any single point of trust. A normal database has none of these — it's mutable, centralized, and trusted by virtue of its operator.

Why does proof-of-work require so much energy?

Bitcoin miners compete to find a hash with N leading zeros — a brute-force search across nonces. The "work" is the wasted computation. The amount of energy is calibrated automatically — every 2016 blocks Bitcoin retargets the difficulty so the average block time stays at 10 minutes. As more miners join, difficulty rises, energy usage rises. Proof-of-stake (Ethereum since 2022) achieves the same security goal with ~99% less energy by requiring validators to stake capital instead of burning electricity.

What's a 51% attack?

An attack where someone controls more than half the network's hashing power (PoW) or stake (PoS). They can rewrite the recent chain history by mining a longer alternative chain than the rest of the network. With 51% you can double-spend (send a transaction, then reverse it) but you can't steal coins from other addresses (that requires breaking ECDSA, not consensus). Bitcoin's hashing power is large enough that a 51% attack would cost billions to mount.

How does Bitcoin prevent double-spending?

Every transaction references its inputs (previous unspent outputs). Miners check that each input hasn't been spent in any earlier confirmed block. Once a transaction is in a block buried under several confirmations, undoing it requires rewriting all subsequent blocks — extremely expensive. The "wait for 6 confirmations" rule comes from the math — 6 blocks deep is statistically very hard to revert.

How are blockchains used outside cryptocurrency?

Supply-chain tracking (IBM Food Trust), digital identity (Microsoft ION), notarization timestamps, voting (limited deployments), and cross-organization data sharing (Hyperledger Fabric, Quorum). Most non-crypto deployments use permissioned variants where only approved participants can validate blocks — sacrificing decentralization for performance.

What's the difference between a blockchain and a hash chain?

Hash chains are simpler — each item references the hash of the previous, that's it. Blockchains are hash chains organized into blocks (each containing many items, plus metadata) with consensus on which chain is canonical. A blockchain is a hash chain plus block structure plus consensus.

Are smart contracts secure?

Cryptographically yes — once deployed, a smart contract executes deterministically on every node. But the code itself can have bugs. The DAO hack (2016, $50M stolen), Parity wallet bug (2017, $300M frozen), and many others all came from contract bugs, not blockchain weaknesses. Auditing, formal verification, and battle-tested patterns (OpenZeppelin) are the practical defense.