Unit 4: Ethereum blockchain and Distributed applications

CSC307 — Blockchain Architecture And Design-I 8 min read

I. Orientation: Ethereum as a Programmable Blockchain

Ethereum (proposed by Vitalik Buterin in 2013, launched July 2015) extends Bitcoin's idea of a decentralised ledger into a general-purpose computing platform. Where Bitcoin records value transfers, Ethereum records state transitions driven by arbitrary code, making it a "world computer" on which decentralised applications run.

  • Account-based model: Unlike Bitcoin's UTXO model, Ethereum tracks balances and storage per account, giving each account a persistent, mutable state.
  • Turing-complete execution: Smart contracts written in high-level languages (Solidity, Vyper) compile to bytecode run by the Ethereum Virtual Machine (EVM).
  • Gas metering: Every operation costs gas; execution halts when gas runs out, preventing infinite loops and denial-of-service.
  • Native currency: Ether (ETH) pays for computation and secures the network via staking (post-Merge, 2022) or formerly mining.
  • Global shared state: Every full node holds a copy of the state trie; consensus keeps copies identical.

II. Ethereum as a Blockchain Platform

A. Core architecture

Ethereum is a replicated state machine where blocks apply transactions to transform a global state.

  • State transition function: σ' = Υ(σ, T) — applying transaction T to state σ yields new state σ'.
  • World state: A mapping of 20-byte addresses to account objects, stored in a modified Merkle Patricia Trie whose root hash is committed in each block header.
  • Account types:
    • Externally Owned Accounts (EOA): controlled by a private key, no code.
    • Contract accounts: controlled by their code, triggered by messages.
  • Block header fields: parent hash, state root, transaction root, receipts root, timestamp, and gas limit anchor the chain's integrity.

B. Ethereum network

The network is the peer-to-peer layer of nodes that propagate transactions and blocks.

  • Node roles: full nodes validate and store state; archive nodes keep all historical states; light clients verify headers only.
  • Networks: Mainnet (production, real ETH) versus testnets (Sepolia, Holesky) using valueless ETH for development.
  • Consensus (post-Merge): Proof of Stake via validators who deposit 32 ETH; proposers build blocks and committees attest, finalising through the Casper FFG mechanism.
  • Peer discovery: nodes use the devp2p protocol and a Kademlia-style DHT to find peers.

C. Ethereum ecosystem

The ecosystem is the stack of tools, standards, and services built around the protocol.

  • Clients: Geth (Go), Nethermind, Besu implement the protocol; a consensus client (e.g., Prysm, Lighthouse) pairs with each execution client.
  • Development tools: Truffle, Hardhat, and Foundry compile, test, and deploy; web3.js and ethers.js connect applications to nodes.
  • Standards (ERCs): ERC-20 for fungible tokens, ERC-721 for non-fungible tokens, ERC-1155 for multi-token contracts.
  • Infrastructure: wallets (MetaMask), node providers (Infura, Alchemy), and decentralised storage (IPFS, Swarm) for off-chain data.

III. Keys, Addresses, Transactions, Messages, and Ether

A. Keys

Keys establish ownership and authorise actions using elliptic curve cryptography (secp256k1).

  • Private key: a random 256-bit number k, kept secret; it signs transactions.
  • Public key: K = k · G, where G is the curve generator point; a 512-bit value derived one-way from k.
  • Signatures: ECDSA produces (v, r, s) so anyone can verify authorship without seeing k.

B. Addresses

An address is the public identifier of an account, derived from the public key.

  • Derivation: address = last 20 bytes of Keccak-256(public key).
  • Format: 40 hexadecimal characters prefixed 0x; EIP-55 mixed-case checksums guard against typos.
  • Contract addresses: computed deterministically from the creator's address and nonce, so the address is known before deployment.

C. Transaction

A transaction is a signed instruction from an EOA that triggers a state change.

  • Fields: nonce (sequence counter preventing replay), gasPrice/maxFeePerGas, gasLimit, to, value (wei), data, and signature (v, r, s).
  • Types:
    • Value transfer: to is an EOA, data empty.
    • Contract call: to is a contract, data encodes the function selector and arguments.
    • Contract creation: to is empty, data holds init bytecode.
  • Fees (EIP-1559): fee = gasUsed × (baseFee + priorityFee); the base fee is burned, the tip rewards the proposer.

D. Message

A message is an internal call passed between accounts during execution; it is never serialised to the chain.

  • Origin: produced by the EVM when a contract calls another contract (CALL, DELEGATECALL).
  • Contents: sender, recipient, value, data, and remaining gas, mirroring a transaction but existing only in the virtual machine.
  • Significance: messages let contracts compose, enabling libraries and inter-contract workflows without a new transaction.

E. Ether

Ether is the native asset fuelling computation and securing consensus.

  • Denominations: 1 ether = 10⁹ gwei = 10¹⁸ wei; gas prices are quoted in gwei.
  • Roles: paying gas, staking collateral for validators, and serving as the base unit of value transfer.
  • Issuance: post-Merge, new ETH is issued as staking rewards while EIP-1559 burns base fees, making net supply variable.

IV. Ethereum Virtual Machine

A. Purpose and principle

The EVM is the sandboxed runtime that executes contract bytecode deterministically across all nodes.

  • Stack machine: a 256-bit word stack up to 1024 items deep; opcodes like ADD, MSTORE, SSTORE, CALL operate on it.
  • Memory model:
    • Stack: transient operands.
    • Memory: byte-addressable, volatile, cleared after the call.
    • Storage: persistent key-value map saved in the account's state trie.
  • Gas accounting: each opcode has a fixed cost (e.g., SSTORE ≈ 20,000 gas for a new slot); exceeding gasLimit throws out-of-gas and reverts state.
  • Determinism: no access to clocks, randomness, or network, so every node reproduces identical results.
SOLIDITY
// Minimal contract compiled to EVM bytecode
contract Counter {
    uint public count;              // stored in persistent storage
    function increment() public {   // callable via a transaction
        count += 1;                 // SLOAD, ADD, SSTORE opcodes
    }
}

V. Implementing Distributed Applications (DApps)

A. Anatomy of a DApp

A DApp couples on-chain smart contracts with an off-chain user interface.

  • Smart contract layer: backend logic and state on Ethereum; immutable once deployed.
  • Front-end layer: a web/mobile client using ethers.js to read state and submit signed transactions via a wallet.
  • Off-chain storage: large files kept on IPFS, with only their content hash stored on-chain to save gas.
  • Lifecycle: write contract → compile to bytecode → deploy (creation transaction) → interact via function calls and events.

B. Event registration

Events are logged outputs that let off-chain applications observe contract activity cheaply.

  • Declaration: event Registered(address indexed user, uint id); — indexed fields become filterable topics.
  • Emission: emit Registered(msg.sender, newId); writes to the transaction receipt's log, cheaper than storage.
  • Use case: a registration DApp records each sign-up as an event; the UI subscribes with contract.on("Registered", ...) to update in real time.
  • Limitation: logs are not readable from within contracts; they serve external listeners only.

C. Document verification

Document verification uses the chain as a tamper-proof timestamping notary.

  • Principle: store the Keccak-256 hash of a document, not the document itself, preserving privacy and minimising cost.
  • Workflow:
    1. Hash the file off-chain; submit storeHash(bytes32 h) which records hashes[h] = block.timestamp.
    2. To verify, re-hash the file and call verify(h); a matching stored timestamp proves existence and integrity.
  • Property: any alteration changes the hash, so forged documents fail verification.

D. Call option

A call option contract encodes a financial right to buy an asset at a fixed strike price.

  • Terms on-chain: strike price, expiry block/timestamp, underlying reference, and premium paid by the buyer.
  • Mechanics:
    1. Writer locks collateral and sets strike K and expiry T.
    2. Holder pays premium; before T, calling exercise() triggers settlement if the market price exceeds K.
  • Automation: the contract enforces payout without a broker, using an oracle to supply the settlement price.

E. Interest rate swap

An interest rate swap contract exchanges fixed-rate for floating-rate cash flows between two parties.

  • Parties: one pays a fixed rate, the other a floating rate indexed to an oracle-fed benchmark, on a shared notional.
  • Settlement: at each period the contract computes netPayment = notional × (floatingRate − fixedRate) × periodFraction and transfers only the difference.
  • Benefit: collateral and payment logic are enforced automatically, removing counterparty default risk through on-chain escrow.

F. Industrial IoT

Industrial IoT applications bind physical devices to Ethereum for trusted machine-to-machine coordination.

  • Device identity: each sensor or machine holds a key pair; its address signs readings, proving provenance.
  • On-chain automation:
    • Data anchoring: devices emit hashed telemetry as events for auditability.
    • Autonomous payments: machines settle usage micro-payments in ETH or tokens on verified conditions.
  • Example: a supply-chain sensor records temperature breaches on-chain, automatically releasing or withholding escrowed payment via a smart contract.
  • Limitation: on-chain latency and gas cost push high-frequency data to off-chain layers, with only summaries or disputes settled on Ethereum.