🌱 Beginner ⏱️ 20 min

What is a Blockchain?

Before diving into smart contract security, you need a solid mental model of what a blockchain actually is. The best analogy: think of it as a shared spreadsheet that the entire world can read, but that no single person can secretly edit. Unlike a normal database controlled by one company, a blockchain is maintained by thousands of computers simultaneously — and they all agree on what the data says.

📖 Database Analogy

A traditional database (like MySQL or PostgreSQL) is controlled by one organization. They can change records, delete rows, or go offline. A blockchain replaces that central authority with cryptographic math and a global network — no single party can alter history unilaterally.

Blockchain vs Traditional Database

FeatureTraditional Database (SQL)Blockchain
Who controls it?One company / adminAll nodes collectively
Can data be changed?Yes, easilyPractically impossible once confirmed
Who can read it?Whoever has permissionAnyone (public chains)
SpeedThousands of writes/sec10-30 transactions/sec (Ethereum)
Cost to writeNear zeroGas fee (real money)
DowntimePossible (server crashes)Never (globally distributed)
Trust modelTrust the companyTrust the math and code
PrivacyData can be privateAll data is public by default

Block Anatomy — What's Inside a Block?

Every block in the chain is a data structure containing several key fields. Here is what a simplified block looks like in JSON format:

📋 Block Data Structure
// Simplified Ethereum block structure { "blockNumber": 19500000, "hash": "0x4a3b...f9e2", // SHA-256 fingerprint of THIS block "parentHash": "0x7c1d...a4b8", // Hash of the PREVIOUS block "timestamp": 1710000000, // Unix timestamp "miner": "0xd3cd...8f12", // Validator who proposed this block "nonce": "0x0000000000000000", // Used in Proof of Work (now 0 in PoS) "gasLimit": 30000000, // Max gas this block can consume "gasUsed": 14532891, // Actual gas used "transactions": [ // List of all txs in this block "0xabc...001", "0xabc...002", // ... up to ~200 transactions ], "stateRoot": "0x9f2a...c3e1", // Merkle root of ALL account states "transactionsRoot": "0x5b7f...d2a9", // Merkle root of transactions "receiptsRoot": "0x3e8c...f1b4" // Merkle root of tx receipts }

Key Fields Explained

  • hash: A cryptographic fingerprint (SHA-3/Keccak256) of all block contents. Change anything in the block and the hash changes completely.
  • parentHash: This is what creates the "chain". Every block references the block before it. This linkage makes history tamper-evident.
  • stateRoot: A Merkle root that captures the entire state of all accounts (balances, contract storage) after this block's transactions executed.
  • gasUsed / gasLimit: Ethereum limits computation per block. These fields track how much was used versus the maximum allowed.

How the Chain Is Formed — The Linked Hash Diagram

The critical insight of blockchain design is that each block contains the hash of the previous block. This creates a chain where any tampering is immediately detectable:

🔗 Chain Linkage (ASCII Diagram)
┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐ │ Block #100 │ │ Block #101 │ │ Block #102 │ │─────────────────────│ │─────────────────────│ │─────────────────────│ │ hash: 0x7c1d... │◄───│ parentHash: 0x7c1d │ │ parentHash: 0x4a3b │ │ parentHash: 0x3f2a │ │ hash: 0x4a3b... │◄───│ hash: 0x8e5c... │ │ transactions: [...] │ │ transactions: [...] │ │ transactions: [...] │ │ timestamp: 12000000 │ │ timestamp: 12000012 │ │ timestamp: 12000024 │ └─────────────────────┘ └─────────────────────┘ └─────────────────────┘ If you change ANY data in Block #100: → Its hash changes to 0xXXXX → Block #101's parentHash now DOESN'T MATCH → Block #102's parentHash doesn't match either → The ENTIRE chain from that point forward is invalidated → All honest nodes REJECT your modified version

To successfully rewrite history, an attacker would need to redo the cryptographic work for the altered block AND every block that came after it — while the rest of the network is adding new blocks. On Ethereum with thousands of validators, this is computationally infeasible.

Consensus Mechanisms: How Nodes Agree

A blockchain is useless without a way for thousands of independent nodes to agree on which version of history is correct. This is called a consensus mechanism.

FeatureProof of Work (PoW)Proof of Stake (PoS)
How you earn right to add a blockSolve a hard math puzzle (hashing)Lock up (stake) ETH as collateral
Who does it?Miners with GPUs/ASICsValidators with 32 ETH staked
Energy usageMassive (as much as a country)~99.95% less than PoW
Attack costBuy 51% of mining hardwareBuy 33%+ of staked ETH ($20B+)
Used byBitcoin, LitecoinEthereum (since The Merge, Sep 2022)
SlashingNo (just wasted electricity)Yes — bad validators lose staked ETH
FinalityProbabilistic (6 confirmations)Economic finality (~2 epochs / 13 min)

Why Proof of Stake Matters for Security Auditors

Under PoS, validators are pseudorandom — you cannot predict exactly which validator will propose the next block. However, the validator does know they will propose a block a few slots in advance. This is relevant for MEV (Maximal Extractable Value) and sandwich attack vulnerabilities that auditors encounter in DeFi protocols.

Decentralization — Why No Single Point of Failure

Ethereum has over 8,000 nodes worldwide. Each node holds a complete copy of the blockchain. Here is what that network looks like:

🌐 Node Network (Simplified)
[Node - Tokyo] | [Node - NYC]--[Node - Frankfurt]--[Node - London] | | [Node - Sydney] [Node - Seoul] | [Node - Singapore] Every node has: ✓ Full copy of all blocks since genesis ✓ Current state of every account ✓ Independent ability to verify all transactions ✓ Ability to reject invalid blocks If Frankfurt goes offline → rest of network continues If 1000 nodes are hacked → 7000+ honest nodes dominate If one country bans Ethereum → nodes in other countries continue

Immutability — Why Bugs Are Permanent

When data is written to the blockchain and confirmed in a finalized block, it cannot be changed. This is Ethereum's greatest security property — and its greatest operational risk.

🔒 What Immutability Means in Practice
Traditional web app: 1. Discover SQL injection vulnerability 2. Push patch to server 3. Database records corrected 4. Users unaffected Time to fix: hours Ethereum smart contract: 1. Discover reentrancy vulnerability 2. Contract address is PERMANENT — cannot be updated 3. All ETH locked in contract is accessible to attacker 4. Options: emergency pause (if coded in), upgrade proxy (if designed for it), convince users to migrate, or accept the loss Time to fix: N/A — the bug is in immutable code Real examples: - The DAO hack (2016): $60M stolen, required a hard fork to reverse - Parity multisig (2017): $150M frozen PERMANENTLY (not stolen, just frozen) - Ronin Bridge (2022): $625M stolen, no recovery from on-chain code

The Ethereum Virtual Machine (EVM)

Ethereum is not just a ledger of transactions. It is a world computer — a globally distributed virtual machine that executes code. The EVM is what makes smart contracts possible.

🖥️ EVM Execution Model
When you call a smart contract function: 1. Your transaction carries: - Target contract address - Function selector (4 bytes) - Encoded arguments - ETH value (optional) - Gas limit 2. Every Ethereum node runs the EVM: - Loads contract bytecode from state - Executes opcodes one by one - Each opcode costs gas - State changes are tracked 3. All nodes reach IDENTICAL results: - Same bytecode + same inputs = same output (deterministic) - This is how global consensus on state is maintained 4. If gas runs out mid-execution: - Transaction REVERTS (all state changes undone) - But you STILL PAY for the gas consumed

Common Misconceptions

⚠️ Misconception: "Blockchain is Private"

Public blockchains like Ethereum are completely transparent. Every transaction, every contract call, every storage write is visible to anyone. There is no privacy by default. Auditors can see every historical exploit transaction on Etherscan. If you write sensitive data (passwords, private keys, personal info) to a smart contract — even in a "private" variable — it is readable by anyone who queries the node's state.

⚠️ Misconception: "Decentralized = Anonymous"

Addresses are pseudonymous, not anonymous. Every transaction from an address is permanently public. Chain analysis firms (Chainalysis, TRM Labs) can often de-anonymize wallets by correlating on-chain patterns with off-chain data (exchanges with KYC, IP addresses, etc.). Most hackers who stole crypto have eventually been identified.

⚠️ Misconception: "Smart Contracts Are Smart"

Smart contracts are dumb programs that execute exactly what they are coded to do — including their bugs. There is no AI, no judgment, no error recovery. If you coded transfer(attacker, balance) to be reachable by anyone, the contract will happily do it.

Why Auditors Must Understand This

🚨 Security Implication: Immutable = Permanent Bugs

When you audit a smart contract, you are the last line of defense. Once deployed, a vulnerable contract cannot be patched like a web app. The bug lives on the blockchain forever. The total value locked (TVL) in DeFi protocols routinely exceeds $50 billion. A single critical vulnerability can result in a loss that cannot be undone. This is why smart contract auditing pays extremely well — and why precision matters.

Step-by-Step: What Happens When You Send ETH

💸 Transaction Lifecycle
You: "Send 1 ETH to Alice" Step 1 — Sign the transaction Your wallet signs the tx with your private key Nobody can forge this signature without your key Step 2 — Broadcast to the network Transaction enters the mempool (waiting room) All nodes see it immediately It is NOT yet confirmed Step 3 — Validator picks it up A validator building the next block selects your tx Higher gas price = higher chance of being included sooner This is the basis of MEV (miners/validators reordering txs for profit) Step 4 — Block is proposed and validated Other validators check: Is the signature valid? Enough gas? No double-spend? If valid: block is accepted, your tx is now CONFIRMED Step 5 — Finalization After 2 epochs (~13 minutes), the block is economically finalized Reversing it would require destroying billions of dollars of staked ETH

Security Implications Box

🚨 This Is Why Bugs Cost Millions

In traditional software, a bug costs time and reputation to fix. In blockchain:

  • Code is public — anyone can read and probe it
  • Exploits are instant — no delay between discovery and attack
  • Transactions are irreversible — no chargebacks, no reversals
  • Bugs are permanent — cannot patch deployed bytecode
  • Value is on-chain — the code directly controls real money

The Euler Finance hack (2023) drained $197M in a single transaction. The Wormhole bridge hack (2022) lost $320M due to a signature verification bug. These are not hypotheticals — they are the consequences of shipping vulnerable code to an immutable, public, value-holding system.

Summary / Key Takeaways

ConceptKey FactWhy It Matters for Security
BlockchainAppend-only distributed ledgerBugs cannot be deleted
Block HashCryptographic fingerprint of block dataAny tamper breaks the chain
ConsensusPoW (compute) or PoS (stake)Attack cost is extremely high
Decentralization8,000+ independent nodesNo single point of failure/control
ImmutabilityFinalized blocks cannot be changedDeployed code with bugs is permanent
EVMDeterministic world computerSame code = same result on all nodes
Public stateAll data visible on-chainAttackers can read your contract too