Lecture 7 - Ethereum and Smart Contract

Updated 21 Oct 2026

History of Ethereum

  • Founder: Vitalik Buterin
    • Russian-Canadian programmer
    • Co-founded Ethereum when he was 19 years old

Timeline

  • Oct 2013 — Idea (Bitcoin logo shown as the "origin point")
  • Jul 2014 — Crowdfunding
  • Sep 2014 — Ethereum Foundation founded
  • Jun 2015 — First release
  • Mar 2016 — Official release

Think of it like a startup timeline: idea → seed funding (crowdsale) → founding a "company" (the Foundation) → beta launch → v1.0 public launch.


Important Concepts (Roadmap of this chapter)

  • Cryptography (similar to Bitcoin)
  • Blockchain
    • Accounts (two types) and Wallets
    • Transactions
  • Smart Contracts
    • Solidity — language used for smart contract development

The Merge

  • Ethereum initially used Proof of Work (PoW) as its consensus mechanism.
  • It has since transitioned to Proof of Stake (PoS) with the upgrade known as "The Merge" (completed Sept 15, 2022).

Cryptography

  • Hash functions
  • Symmetric Cryptography
  • Asymmetric Cryptography
  • Signatures

Hash Functions

  • BTC uses SHA-256
  • Ethereum uses Keccak-256
    • Similar to SHA-3 (a variant of it)
    • Won a security contest in 2007
    • Used for all hashing in Ethereum
    • Derived differently than standard block-cipher-based hashes or previous SHA functions

Digital Signatures (Digital Proof)

  • Same use-case/cryptographic method (ECDSA) as Bitcoin
  • Signer uses a private key to generate a signed message
  • The signed message can be verified using the signer's public key
  • In Ethereum, hashes are signed, not the raw data itself

Blockchain

  • A fully distributed database, like BTC

Advantages:

  • Highly Secure
  • Transparent
  • Immutable

Disadvantages:

  • Scaling
  • Performance

Ethereum Block Structure (Post-Merge, PoS)

+---------------------------------------------------------+
| Block Header                                             |
|  - Parent Hash                                           |
|  - State Root                                            |
|  - Transactions Root                                     |
|  - Receipts Root                                         |
|  - Logs Bloom                                             |
|  - Block Number, Timestamp, Gas Info                      |
|  - Proposer Index, Randomness, Extra Data                 |
+---------------------------------------------------------+
| Block Body                                                |
|  - Transactions [Tx1, Tx2, ...]                           |
|  - Withdrawals                                             |
|  - Attestations (votes)                                    |
|  - Slashings                                                |
|  - Deposits                                                  |
|  - Other consensus data                                      |
+---------------------------------------------------------+
| Block Hash = H(Header + Body)                              |
+---------------------------------------------------------+

Think of the header as the "cover page/summary" of the block (fingerprints of everything inside), and the body as the actual "contents" of the block.


Reward Structure

A common simplification of Ethereum staking rewards:

APR(S)=kS\boxed{\text{APR}(S) = \frac{k}{\sqrt{S}}}

  • SS = total ETH staked on the network
  • kk = a constant (set by protocol economics)
  • Result: as SS grows, APR falls (the "diminishing returns" effect)

We calibrate kk so that when S=30,000,000S = 30{,}000{,}000 ETH, APR =3.5%= 3.5\%:

k=0.035⋅30,000,000\boxed{k = 0.035 \cdot \sqrt{30{,}000{,}000}}

From this:

  • If S=10M→S = 10\text{M} \rightarrow APR ≈6.06%\approx 6.06\%
  • If S=30M→S = 30\text{M} \rightarrow APR =3.50%= 3.50\%
  • If S=60M→S = 60\text{M} \rightarrow APR ≈2.475%\approx 2.475\% (because 3.5%/23.5\%/\sqrt{2})

The relationship is like splitting a fixed-size pizza among more and more people — the more validators (people) stake, the smaller each individual's slice (APR) becomes, but by the square root rate, not linearly.

Worked Example

  • Alice stakes sA=32s_A = 32 ETH (solo validator)
  • Bob stakes sB=320,000s_B = 320{,}000 ETH (a whale/custodian)

At S=30S = 30M (APR = 3.5%):

  • Alice yearly reward: 32×0.035=1.1232 \times 0.035 = \boxed{1.12} ETH/yr (≈0.0933\approx 0.0933 ETH/month, 0.003070.00307 ETH/day)
  • Bob yearly reward: 320,000×0.035=11,200320{,}000 \times 0.035 = \boxed{11{,}200} ETH/yr

At S=60S = 60M (APR ≈2.475\approx 2.475%):

  • Alice yearly reward: 32×0.02475≈0.79232 \times 0.02475 \approx \boxed{0.792} ETH/yr (≈0.0660\approx 0.0660 ETH/month, 0.002170.00217 ETH/day)

  • Bob yearly reward: 320,000×0.02475≈7,920320{,}000 \times 0.02475 \approx \boxed{7{,}920} ETH/yr

  • When total stake doubled from 30M → 60M: the APR dropped for everyone (3.5% → ~2.475%)

  • That's the diminishing returns effect driven by 1/S1/\sqrt{S}

Per-ETH Reward and "Diminishing Returns"

  • At a fixed SS, rewards are proportional to your stake (double your stake → double your ETH earned)
  • But as the network SS rises (often because large stakers enter), APR falls for everyone, so the per-ETH reward shrinks
  • Therefore, for very large stakers (who help push SS up), each extra ETH they add earns a slightly lower marginal rate than before

More ETH Staked→More Validators/Security→Lower Reward Rate per Unit of Stake\boxed{\text{More ETH Staked} \rightarrow \text{More Validators/Security} \rightarrow \text{Lower Reward Rate per Unit of Stake}}


Ethereum Blockchain (General)

  • All blocks are visible, like BTC
  • However, blocks have a different structure than BTC
  • Explorer: etherscan.io

The Transactions Root is stored in the block header, committing to all transactions in that block (like a tamper-proof seal over the whole batch).


Why Ethereum?

  • While Bitcoin was primarily designed to serve as a digital currency and store of value, the Ethereum network was created to support complex smart contracts and decentralized applications (dApps), enabling programmable blockchain-based functionality beyond simple transactions.

Proof of Stake (PoS)

What is Staking?

  • Staking = locking up (committing) a certain amount of cryptocurrency to become eligible to validate transactions and propose new blocks on a PoS blockchain. Validators receive rewards for participating in securing the network.
  • Block Proposal and Validation: validators are randomly chosen to propose new blocks based on their staked amount — the higher the stake, the higher the chance of being selected. Other validators then verify the block; if valid, it's added to the chain.

PoS Mechanism (After The Merge, Sept 15 2022)

  • Mechanism: validators are chosen to propose new blocks and validate transactions based on how much ETH they hold and are willing to "stake" as collateral. Validators are randomly selected based on stake size, rather than computational work.
  • Energy Efficiency: PoS is far more energy-efficient than PoW — no computational puzzles; validators just verify blocks instead of competing in computational races.
  • Validator Rewards: validators earn rewards for validating blocks and securing the network. Malicious or negligent validators can lose part of their staked ETH ("slashing").
  • Staking Requirements: minimum of 32 ETH to become a solo validator. Smaller holders can join via staking pools.

How Staking Works — Step by Step

  1. Owner stakes their native tokens in staking pools
  2. Algorithm pseudo-randomly selects the next validator
  3. The selected validator proposes a block of transactions
  4. Other validators verify and approve the transaction
  5. The block is added to the existing blockchain
  6. The validator earns a transaction fee

Like a lottery where your number of tickets (stake) determines your odds of being picked to "run" the round — but if you cheat, you lose your tickets.


Key Algorithms in Ethereum's PoS Block Validation

  • Casper FFG (Friendly Finality Gadget)
  • LMD-GHOST (Latest Message Driven — Greediest Heaviest Observed SubTree)

PoS Process (Detailed)

1. System Initialization

  • Let V=v1,v2,…,vn\mathcal{V} = {v_1, v_2, \dots, v_n} denote the set of validators
  • Each validator deposits a minimum of 3232 ETH into the staking contract
  • Each validator viv_i is assigned an index and a balance sis_i
  • The total stake is S=∑i=1nsiS = \sum_{i=1}^{n} s_i

2. Time Division

  • Time is divided into slots (≈12s\approx 12s)
  • 32 slots form an epoch (≈6.4\approx 6.4 minutes)
  • At each slot, exactly one validator is designated to propose a block; a committee of validators is designated to attest

3. Block Proposal

  • For slot tt, the block proposer is selected pseudorandomly using:

pt=H(randao_seed∥t)mod  n\boxed{p_t = H(\text{randao\_seed} \parallel t) \mod n}

  • Validator vptv_{p_t} constructs a block BtB_t consisting of:
    • transactions
    • attestations
    • withdrawals, deposits, and slashings
    • consensus metadata
  • BtB_t references the parent block hash, ensuring chain continuity

4. Attestation (Voting)

  • A committee Ct⊆V\mathcal{C}_t \subseteq \mathcal{V} of validators is assigned to attest
  • Each attestation includes:
    • LMD-GHOST vote: attesting to the head of the chain
    • FFG vote: linking the current epoch to a checkpoint
  • Each vote is weighted by stake:

wi=siS,vi∈Ctw_i = \frac{s_i}{S}, \quad v_i \in \mathcal{C}_t

  • A block is justified if at least 23\frac{2}{3} of total stake votes for it

5. Finality (Casper FFG)

  • Checkpoint: the first block of each epoch
  • A checkpoint CkC_k is justified if ≥23\geq \frac{2}{3} of stake attests to it
  • A justified checkpoint becomes finalized once a later checkpoint is justified on top of it:

Cj finalized  ⟺  ∃,Ck,(Cj→Ck∧Justified(Ck))C_j \text{ finalized} \iff \exists, C_k , (C_j \rightarrow C_k \wedge \text{Justified}(C_k))

  • Finality = irreversible guarantee (rollback requires slashing of ≥1/3\geq 1/3 stake)

Justification is like getting "provisional approval" from 2/3 of the voting body; finalization is like that approval being locked in permanently once the next round also gets provisional approval on top of it.


Casper FFG (Friendly Finality Gadget)

  • Finality means that once a block is finalized, it is immutable and cannot be altered or reverted.

  • Diagram: "Casper FFG Checkpoint Verification" — shows a tree of candidate blocks where a justified chain (root → b1 → b2 → b3 → b4) is validated by consent of two-thirds of validators, marking b3 as a "Verified Checkpoint" (slide 24, source: Vitalik Buterin / Xangle).
    • หรือว่าเรียกว่า Cannanical chain

LMD-GHOST

  • Latest Message Driven – Greediest Heaviest Observed SubTree
  • It is the fork-choice rule used in Ethereum's PoS consensus
  • Purpose: provides the fork-choice rule (i.e., what's the "head" of the chain between finalized checkpoints)

Process:

  1. Start at the last justified checkpoint
    • receives 2/3 supermajority??
  2. Look at its children blocks
  3. Select the child with the highest sum of validator weights (based on their latest messages)
  4. Repeat until you reach the "heaviest" leaf — this is the head of the chain

  • Diagram: "GHOST: The longest chain (A) is chosen" — shows chain A (4 connected blocks, highlighted) being selected over competing forks B and C, because chain A has more accumulated validator support (slide 26).

  • That (winning) path is highlighted — this becomes the canonical chain head.

  • Competing blocks (C, D, G, H in the fuller example) are ignored because their subtrees have less validator support.

Casper Checkpoints + LMD-GHOST Combined Example

  • Left (Initially): Path A → B → E → F → I is chosen as the canonical chain (I is heavier)
  • Right (Later): More validators vote for H, so its path A → B → E → F → H becomes heavier. LMD-GHOST switches the head to H.
  • But notice the finalized checkpoint (E):
    • Any fork that diverges before E can never be chosen, even if it gets more weight
    • So the switch between I and H is allowed (since both descend from E), but a fork like C or D is forever excluded

  • Weight คือจำนวน of voter who vote that block?? (CHECK PLS)
  • High degree of vliadator support

Casper FFG + LMD-GHOST (Summary)

  • Casper FFG handles finality (safety: prevents reorgs beyond finalized points)
  • LMD-GHOST handles fork-choice (liveness: decides which chain to extend before finality)
  • Together, this hybrid design is sometimes just called the "Casper consensus protocol," but technically it's Casper FFG + LMD-GHOST
    \boxed{\text{LMD-GHOST} = \text{"Which block do we build on next?"}} $$$$ \boxed{\text{Casper} = \text{"Which past blocks can we never go back and change?"}}

LMD-GHOST is like choosing which trail to keep hiking based on which one has the most footprints (recent votes); Casper FFG is like planting a flag at a certain point on the trail that says "we will never backtrack past here."


Merkle Tree

  • Ethereum uses regular Merkle trees for some block-level data structures:
    • Transactions Root → Merkle tree of all transactions in a block
    • Receipts Root → Merkle tree of all transaction receipts
  • This is similar to Bitcoin's transaction Merkle tree
  • Each transaction/receipt is hashed → paired → hashed again → up to the Merkle Root, which is stored in the block header

[Image]

  • Diagram: "Ethereum Transactions → Merkle Tree → Transactions Root" — shows 4 transactions (Tx1–Tx4) each hashed individually (H(Tx1)...H(Tx4)), paired and hashed together (H(H1||H2), H(H3||H4)), and finally combined into the single Transactions Root (Merkle Root), which is stored in the block header, committing to all transactions (slide 16).

Merkle Patricia Trie (MPT) — "Merkle Practicia"

  • Ethereum's world state (all accounts, balances, contract storage) is too complex for a simple binary Merkle tree.
  • Instead, Ethereum uses a Merkle Patricia Trie (MPT):
    • A trie (prefix tree) organizes key–value pairs efficiently
    • The Patricia (Practical Algorithm To Retrieve Information Coded In Alphanumeric) modification compresses paths to reduce storage
    • The Merkle part means each node is hashed, so any change in state propagates up to the root
  • The result is the State Root, stored in the block header, which commits to the entire Ethereum state

Motivation for MPT

Ethereum needs a way to:

  • Store a huge state (all accounts, balances, contract storage)
  • Allow efficient lookup, insertion, and deletion
  • Provide a cryptographic commitment to the entire state (so one hash in the block header proves the whole world state)
  • A simple Merkle tree isn't enough because state is a key–value database, not just a list. That's why Ethereum uses an MPT.

MPT Concept

1. Trie (prefix tree)

  • A tree where each path from root to leaf corresponds to a key
  • Example: storing accounts {"alice", "bob", "carol"} → each character extends the path
  • Tries allow fast lookup: O(k)O(k), where kk = length of key
  • A trie stores keys by breaking them into symbols (in Ethereum: hex nibbles 0–f)
  • Each character/nibble extends the path from the root → branch → leaf
    • alice goes down path a → l → i → c → e
    • bob goes b → o → b
    • carol goes c → a → r → o → l

2. Patricia compression

  • Instead of creating many "single-child" steps, Ethereum compresses consecutive nodes
  • So carol might just be stored as "carol" in one extension node, instead of 5 hops

3. Merkle hashing

  • Every node (branch, extension, leaf) is hashed
  • Parent nodes store hashes of their children
  • This makes the structure a Merkle tree → if you change one account balance, the hash changes all the way up to the State Root

State commitment

  • The root hash of the MPT = State Root, stored in the Ethereum block header
  • This commits to all account balances, contract code, and storage
  • Light clients can verify account data with a Merkle proof without downloading the full state

MPT=Trie (efficient lookup)+Patricia (path compression)+Merkle (integrity verification)\boxed{\text{MPT} = \text{Trie (efficient lookup)} + \text{Patricia (path compression)} + \text{Merkle (integrity verification)}}

Think of a trie like a filing cabinet organized by the letters of a name; Patricia compression is like collapsing empty drawers that only ever lead to one folder; Merkle hashing is like sealing every drawer with a tamper-evident sticker that changes if anything inside changes.

Node Types in MPT

  • Branch node → 16-way branching (for each hex nibble), plus an optional value
  • Extension node → compresses a path with only one child
  • Leaf node → holds the actual value (e.g., account object)

What is a Hex Nibble?

  • A nibble is the basic unit used to follow hexadecimal key paths in an Ethereum MPT
  • 1 nibble = 4 bits = 1 hexadecimal digit (0–F)
  • Why 16 values? 44 bits → 24=162^4 = 16 combinations (binary 0000→1111, decimal 0→15, hex 0→F)
  • Example: 0xA3 → A = decimal 10 = 1010 (1 nibble), 3 = decimal 3 = 0011 (1 nibble) → 2 nibbles = 1 byte
  • Example key: A → 3 → F → 7 — each hex digit selects one of 16 possible branch positions

1 hex digit=1 nibble=4 bits→16 possible values (0–F)→MPT Branch node has 16 child slots\boxed{1 \text{ hex digit} = 1 \text{ nibble} = 4 \text{ bits} \rightarrow 16 \text{ possible values (0–F)} \rightarrow \text{MPT Branch node has 16 child slots}}

Node Roles Recap

  • Extension Node — compresses a shared path with no branching. Stores: shared path + pointer to next node.
    • Example: two keys share the prefix "a7" → a7b2 → Value A, a7f4 → Value B
    • Structure: Root → Extension(path="a7") → Branch → {b → Leaf("2") → Value A, f → Leaf("4") → Value B}
  • Branch Node — used where key paths split. Stores: 16 child slots (0–f) + optional value.
  • Leaf Node — marks the end of a key and stores its value. Stores: remaining path + value.

Extension=compressed path→Branch=path splits→Leaf=key ends and value is stored\boxed{\text{Extension} = \text{compressed path} \rightarrow \text{Branch} = \text{path splits} \rightarrow \text{Leaf} = \text{key ends and value is stored}}

Why Ethereum Uses Nibbles in the MPT

  • The MPT branches at the nibble level (16-way branching: 0–f)
  • Each step in the trie consumes one hex digit from the key
  • Example: an account address (20 bytes = 40 hex chars) → trie path = 40 steps (one per nibble)

Patricia Trie (Recap)

  • A tree-like data structure used to store (key, value) pairs
  • The compression technique reduces the storage requirement in the blockchain
  • In Ethereum, each node of the tree is referenced by its hash value, like a Merkle tree

Merkle Patricia Trie — Worked Example


Data (key → value):
  1111    → ahoj
  11110AA → hi
  11112FF → thus
  1111FBB → ciao
Extension node
  Prefix: -        Shared nibble: 1111        key: (points to Branch)
       |
       v
Branch node
  v0 ... v15   (branches at "0", "2", "F")     value: ahoj
       |               |                |
     (0)              (2)              (F)
       v                v                v
  Leaf node         Leaf node         Leaf node
  Prefix: 10        Prefix: 10        Prefix: 10
  Key suffix: AA    Key suffix: FF    Key suffix: BB
  Value: hi         Value: thus       Value: ciao
  • The Extension node stores the shared prefix 1111 common to all four keys, and its value ahojcorresponds to the exact key 1111
  • The Branch node splits on the next nibble (0, 2, or F) toward each of the three remaining keys
  • Each Leaf node stores the remaining key suffix and its value
  • Ethereum's Merkle Patricia Trie (Prefix tree) is essentially a key-value mapping
  • Trie (also called digital tree, prefix trie, or radix trie)
  • A nibble is basically just a single hex character
  • An extension node is an optimized node (a compressed branch node that has only one child) of the branch node
  • See more: Merkle Patricia Trie Explained

RLP Serialization (used to encode trie paths)

  • In RLP(HP(Prefix, path)), the Hex-Prefix (HP) encoded path is serialized using RLP
  • This allows the path to be efficiently stored and hashed within the trie
  • The Recursive-Length Prefix (RLP) serialization protocol is an encoding scheme to represent and store structured data
  • RLP is the primary data structure encoding method utilized within the Ethereum network for encoding its various components, such as transactions, account status, and smart contract data

RLP Encoding Rules #FYI

The key concept in RLP: it encodes data structures (such as lists or byte arrays) using length prefixes, which tell how long the data is, followed by the actual data.

1. Basic Types in RLP

  • Strings (byte arrays): raw binary data
  • Lists: nested structures that contain other RLP-encoded elements

2. Encoding Strings

  • If the string is 0–55 bytes long, RLP encodes it with a single byte prefix followed by the string itself
    • The prefix byte is calculated as 0x80 + length_of_string
  • If the string is longer than 55 bytes, RLP uses a multi-byte prefix that encodes the length of the string

3. Encoding Lists

  • If a list of items has a total encoded length of 0–55 bytes, RLP uses a prefix byte 0xC0 + length_of_list
  • If the list's length is greater than 55 bytes, the prefix is encoded with more bytes that specify the length of the list

Detailed Process

For Strings:

  • For a string of 0 to 55 bytes:

RLP(string)=(0x80+lengthof,string)+string\boxed{RLP(string) = (0x80 + length_{of,string}) + string}

  • Example: the string "dog" (3 bytes) is encoded as 0x83 followed by the UTF-8 encoding of "dog"

  • For a string longer than 55 bytes, the encoding includes the length of the length of the string:

RLP(string)=(0xB7+lengthof,lengthof,string)+lengthof,string+string\boxed{RLP(string) = (0xB7 + length_{of,length_{of,string}}) + length_{of,string} + string}

For Lists:

  • For a list where the total encoded length is 0 to 55 bytes:

RLP(list)=(0xC0+lengthof,encoded,list)+concatenated,encoded,elements\boxed{RLP(list) = (0xC0 + length_{of,encoded,list}) + concatenated,encoded,elements}

  • Example: the list ["cat", "dog"] is encoded by encoding each element as a string, then concatenating them with the appropriate length prefix

  • For a list longer than 55 bytes:

RLP(list)=(0xF7+lengthof,lengthof,list)+lengthof,list+concatenated,encoded,elements\boxed{RLP(list) = (0xF7 + length_{of,length_{of,list}}) + length_{of,list} + concatenated,encoded,elements}

RLP prefixes work like a shipping label that first tells you how big the box is before you open it — short boxes get a one-byte label, long boxes get a bigger "label about the label."


Ethereum Data Structures

  • Diagram: overview of how a Block (Header + Ommers + Body) links out to three tries — World State Trie, Receipt Trie, and Transaction Trie — plus an Account Storage Trie per account, all ultimately stored as hash(RLP(node)) → RLP(node) pairs in a flat key-value store (slide 46).

Ethereum's Trie Data Structures Ethereum utilizes its "Modified Merkle Patricia Trie" for each of its 4 trie data structures:

  • Receipt Tree
  • State Tree
  • Storage Tree
  • Transaction Tree

Transaction Trie

  • As mentioned above, the transaction root exists within the block header, and its purpose is to record transactions.
  • Since the ordering of the data is mostly decided upon by the miner, we do not know what the data looks like until it is mined.
  • We do know what parameters are used to compose the transaction trie:
    • Account nonce
    • Gas price
    • Gas limit
    • Recipient
    • Transfer value
    • Transaction signature values
    • Account initialization (if transaction is of contract-creation type), or transaction data (if transaction is a message call)

Receipt Trie

  • Every time a transaction executes, Ethereum produces a receipt, which contains:
    • status (success/failure)
    • cumulativeGasUsed
    • logsBloom (for filtering events)
    • logs (contract-generated events)
  • All receipts for a block are inserted into a Merkle Patricia Trie → the root of that trie is stored in the block header as Receipts Root

What type of treee used to support audiability, answer Receipt Trie

Why design it this way?

  • Auditability: the Receipts Root in the header allows anyone to verify transaction outcomes without replaying the whole block

  • Immutability: once a block is finalized, its receipts cannot change, so the trie is never updated

  • Efficiency: since receipts are only needed for logs/events, Ethereum doesn't waste effort updating them in future blocks

  • Again, the receipt root lives within the block header and its purpose is to record the outcome of a transaction.

  • According to the yellow paper, the receipt trie can also be useful for zero-knowledge proofs or searches.

  • Parameters that make up the receipt trie:

    • Post-transaction state
    • Cumulative gas used
    • Logs
    • Bloom filter created from the information of the above logs
  • This trie never updates.

State Trie

  • The one and only one global state trie.
  • It contains a key-value pair for every Ethereum account on the network, where the key is an Ethereum address and the value is the RLP-encoded Ethereum account.
  • An Ethereum account and the state trie is comprised of the following fields:
    • Nonce
    • Balance
    • Storage Root
    • Codehash
  • Unlike the transaction and receipt tries, the state trie updates over time... constantly.

Storage Trie

  • The storage trie is where all the contract data lives, and there is a separate storage trie for each account.
  • Reference: Ethereum block architecture

Bloom Filter #FYI

  • A Bloom filter is used within the Receipt Trie to efficiently and probabilistically check whether a particular event or log entry is part of a block's transaction receipts, without requiring a full scan of all logs.
  • Bloom filters provide a space-efficient way of representing large sets of data and allow for fast lookups with some level of false positives but no false negatives.
  • In a Bloom filter, the position of a bit is specified by applying hash functions to the data you want to store or check (e.g., a log entry, event, or piece of data).
  • The hash functions produce integers, which are then mapped to specific positions in the bit array. The bits at these positions are set to 1.

Purpose of the Bloom Filter in Ethereum

  • Ethereum logs events when smart contracts are executed, and these events are stored in the receipt of each transaction.
  • To make it more efficient for nodes/users to check if a certain event (or log) occurred within a block, Ethereum uses Bloom filters to encode the logs associated with each transaction in the Receipt Trie.
  • By using a Bloom filter, one can quickly test if a log/event might be in the block's receipts, without needing to download and verify all logs and receipts.

Hashing Used in Bloom Filters

  • Bloom Filters don't mandate one specific hash function.
  • In practice, MurmurHash3 (non-crypto) is the most widely used, unless cryptographic strength is required → then use SHA-256.

position=hi(x) mod m\boxed{\text{position} = h_i(x) \bmod m}

Structure of the Bloom Filter in Ethereum

  • Size: Ethereum uses a 2048-bit Bloom filter for each transaction and block.
  • Hash Functions: multiple (typically three) hash functions are applied to the data (contract addresses and topics).
  • Bits Set: each hash function sets certain bits in the Bloom filter, indicating that a specific log event might be associated with the transaction or block.

Bloom Filter Example: Let's say we want to know if a particular log (e.g., a Transfer event from an ERC-20 token contract) is part of a block's transaction receipts:

  1. Event: a smart contract emits a "Transfer" event from an address
  2. Hashing: the contract address and event topics (like the Transfer event signature) are hashed
  3. Bloom Filter: the resulting hashes are used to set certain bits in the block's Bloom filter
  4. Checking Presence: to see if this "Transfer" event might exist in the block, you check the Bloom filter by computing the same hashes and seeing if the corresponding bits are set

Worked Example — Building Up a Bloom Filter

Example 1: Log Event A — sets bits in positions 7, 15, and 24

  • Hash function 1 sets bit 7
  • Hash function 2 sets bit 15
  • Hash function 3 sets bit 24
Bit Array: 0000000100000001000000100000000
(1s at positions 7, 15, and 24)

Example 2: Log Event B — sets bits in positions 4, 15, and 29

  • Hash function 1 sets bit 4
  • Hash function 2 sets bit 15 (already set by Log A)
  • Hash function 3 sets bit 29
Bit Array: 0001000110000001000000010010000
(1s at positions 4, 7, 15, 24, and 29)

Example 3: Log Event C — sets bits at positions 2, 7, and 18

  • Hash function 1 sets bit 2
  • Hash function 2 sets bit 7 (already set by Log A)
  • Hash function 3 sets bit 18
Bit Array: 0011000110000001010000010010000
(1s at positions 2, 4, 7, 15, 18, 24, and 29)

  • Bar chart visualization showing the bit array building up across three panels ("After Log A", "After Log B", "After Log C"), with bit positions 0–31 on the x-axis and bars appearing at the positions listed above as each log event is added (slide 62).

Summary: the Bloom filter evolves as different log events (Log A, Log B, Log C) set bits at various positions in the bit array. As more log events are processed, the Bloom filter accumulates set bits, allowing quick checks of whether a particular event may have occurred in the logs. Multiple events might set the same bits, which is why Bloom filters can result in false positives but never false negatives.

Testing the Presence of Logs

  • When you want to check if a particular log (or event) exists in a block, you can query the Bloom filter by hashing the event's address and topics. These hashes are used to test the corresponding bits in the block's Bloom filter.
  • If all the relevant bits are set, the log might be in the block, and you would need to perform a deeper scan of the transaction receipts to confirm.
  • If any of the relevant bits are not set, you know for certain that the log is not present in the block.

Bloom Filter Creation:

  • For each log entry, the address and topics are hashed using multiple hash functions.
  • Each hash is used to set certain bits in the Bloom filter (a 2048-bit bitmask for Ethereum).
  • The result is a Bloom filter that summarizes all the logs associated with the transaction receipt.

Block-Level Bloom Filter:

  • Ethereum also creates a block-level Bloom filter, which aggregates the Bloom filters of all transaction receipts within that block. This allows fast searching for events across an entire block.
  • This block-level Bloom filter is stored in the block header, making it accessible to any node that wants to check if certain logs/events are present in the block.

A Bloom filter is like a bouncer with a checklist of "maybe on the list" — it can instantly say "definitely not here" but can only say "possibly here, go check the guest book" for a match.


Ethereum Nodes

  • Validate all transactions and new blocks
  • Operate in a P2P fashion
  • Each contains a copy of the entire Blockchain
  • Light clients — store only block headers
    • Provide easy verification through tree data structure
    • Don't execute transactions; used primarily for balance validation
  • Implemented in a variety of languages (Go, Rust, etc.)

Accounts and Wallets

Accounts:

  • Two kinds:
    • External Owned Accounts (EOA) — the most common account type
    • Contract Accounts
  • Consist of a public/private keypair
  • Allow for interaction with the blockchain

Wallets:

  • A set of one or more external accounts
  • Used to store/transfer ether

External Account (EOA, Valid Ethereum Address)

  • Has an associated nonce (number of transactions sent from the account) and a balance
  • codeHash — hash of associated account code, i.e. a computer program for a smart contract (hash of an empty string for EOAs)
  • Storage Root is the root hash of the Merkle-Patricia trie of associated account data

Contract Account

  • Ethereum accounts can store and execute code
    • Has an associated nonce and balance
    • codeHash — hash of associated account code; storageRoot contains a Merkle tree of associated storage data

Example Account

  • Private Key: 0x2dcef1bfb03d6a950f91c573616cdd778d9581690db1cc43141f7cca06fd08ee
    • Ethereum private keys are 66-character strings (with 0x appended). Case is irrelevant. Same derivation through ECDSA as BTC.
  • Address: 0xA6fA5e50da698F6E4128994a4c1ED345E98Df50
    • Ethereum private keys map to addresses directly — simply the last 40 characters of the Keccak-256 hash of the public key. Address is 42 characters total (append 0x to front).

Transactions

  • A request to modify the state of the blockchain
    • Can run code (contracts) which change global state (contrasts with only balance updates in BTC)
  • Signed by the originating account
  • Types:
    • Send value from one account to another account
    • Create smart contract
    • Execute smart contract code

Ether Denominations

  • Wei — lowest denomination
    • Named after Wei Dai — author of the b-money paper (1998), many core concepts used in the BTC implementation (b-money paper)
    • 1/1,000,000,000,000,000,0001/1{,}000{,}000{,}000{,}000{,}000{,}000 (quintillion) of an ETH
  • Szabo — next denomination
    • Named after Nick Szabo — author of Bit-Gold
  • Finney — 2nd highest denomination
    • Named after Hal Finney — received the first Tx from Nakamoto

Smart Contracts

  • Executable code
  • Turing Complete
  • Function like an external account:
    • Hold funds
    • Can interact with other accounts and smart contracts
    • Contain code
  • Can be called through transactions

Code Execution

  • Every node contains a virtual machine (similar to Java)
    • Called the Ethereum Virtual Machine (EVM)
    • Compiles code from a high-level language to bytecode
    • Executes smart contract code and broadcasts state
  • Every full node on the blockchain processes every transaction and stores the entire state

EVM

  • The Ethereum blockchain network is a group of EVMs (nodes) connected to every other node in a peer-to-peer mechanism.
  • Each node consists of a copy of the entire blockchain data store and competes with other nodes to mine/validate the next block.
  • If a new block is added, the blockchain gets updated and propagated to the entire network so every node stays in sync.

Gas

  • Halting problem (infinite loop) — the reason for Gas
    • Problem: cannot tell whether a program will run infinitely just from compiled code
    • Solution: charge a fee per computational step to limit infinite loops and stop flawed code from executing
  • Every transaction needs to specify an estimate of the amount of gas it will spend
  • Essentially a measure of how much one is willing to spend on a transaction

Gas Cost

  • Gas Price: current market price of a unit of Gas (in Wei) — check here: ethgasstation.info; always set before a transaction by the user
  • Gas Limit: maximum amount of Gas the user is willing to spend — helps regulate load on the network
  • Gas Cost (used when sending transactions) is calculated as:

Gas Cost=gasLimit×gasPrice\boxed{\text{Gas Cost} = \text{gasLimit} \times \text{gasPrice}}

  • All blocks have a Gas Limit (maximum Gas each block can use)

Gas is like a "meter running" on a taxi ride: the gas price is the rate per unit distance, the gas limit is the most you're willing to let the meter run before you get out, and the total fare is price × distance traveled.


PoW vs. PoS

Ethereum in the process of moving to Proof of Stake:

  • This approach does not require large expenditures on computing and energy

  • Miners are now "validators" and post a deposit in an escrow account

  • The more escrow you post, the higher the probability you will be chosen to nominate the next block

  • If you nominate a block with invalid transactions, you lose your escrow

  • One issue with this approach: those with the most Ethereum will be able to get even more

  • This leads to centralization eventually

  • On the other hand, it reduces the chance of a 51% attack and allows for near-instant transaction approvals

  • The protocol is called Casper, and this was a hard fork

    • Casper is the implementation that eventually converted Ethereum into a Proof of Stake blockchain (also known as Ethereum 2.0) — reference

Other Approaches to Consensus

There are many other types of consensus:

  • (PoW) Proof of Work (Bitcoin, Ethereum, …)
  • (PoS) Proof of Stake (Ethereum)
  • (PoI) Proof of Importance (used in NEM)
  • (PBFT) Practical Byzantine Fault Tolerance (Hyperledger Fabric)
  • (FBFT) Federated Byzantine Fault Tolerance (Ripple, Stellar)
  • (DPoS) Delegated Proof of Stake
  • (PoET) Proof of Elapsed Time (Hyperledger Sawtooth)

Reference: Consensus in Blockchain Systems, in Short


Appendix materials

A. Ethereum Blockchain Header

  • Hash of included ommers stored in the block header
  • State root is the hash of a Merkle trie that holds all account information
  • Similar storage structure for transactions and receipts

A. Ethereum Blockchain State

StateRoot, TransactionRoot, and ReceiptsRoot

  • Stored in a data structure known as a Merkle-Patricia trie
  • Similar to the Merkle trie used in BTC, but with three leaves per node
  • Trie is cryptographically secure — any alteration of a leaf or intermediary node results in a different root hash

[Image]

  • Small diagram showing State Root / Transaction Root / Receipt Root each branching into a Merkle-Patricia trie structure at the block level (slide 86).

StateRoot

  • Each node in the stateRoot trie represents an Ethereum address
  • Each address has 4 components:
    • Nonce — list/count of number of Tx's from the address
    • CodeHash — hash of associated code
    • StorageRoot — Merkle-Patricia tree root of account storage contents
    • Balance — balance of the account

A. Ethereum Blockchain — "Difficulty Bomb"

  • A spike (increase) in mining difficulty
  • Introduced to attempt to reduce the number of miners
    • Aimed to pre-date the shift of algorithm from PoW to Proof-of-Stake (PoS)

B. Smart Contract Programming

  • Solidity (JavaScript-based), the most popular
    • Not yet as functional as other, more mature programming languages
  • Serpent (Python-based)
  • LLL (Lisp-based)

Solidity

Solidity is a language similar to JavaScript which allows you to develop contracts and compile to EVM bytecode. It is currently the flagship language of Ethereum and the most popular.

  • Solidity Documentation — the flagship Ethereum high-level language used to write contracts
  • Solidity online realtime compiler

Serpent

Serpent is a language similar to Python which can be used to develop contracts and compile to EVM bytecode. It is intended to be maximally clean and simple, combining many of the efficiency benefits of a low-level language with ease-of-use in programming style, while adding special domain-specific features for contract programming. Serpent is compiled using LLL.

  • Serpent on the Ethereum wiki
  • Serpent EVM compiler

Editor Tooling

  • Atom Ethereum interface — plugin for the Atom editor featuring syntax highlighting, compilation, and a runtime environment (requires a backend node)
  • Atom Solidity Linter — plugin for the Atom editor providing Solidity linting
  • Vim Solidity — plugin for the Vim editor providing syntax highlighting
  • Vim Syntastic — plugin for the Vim editor providing compile checking

Solidity Example Code

contract Example {
 
    uint value;
 
    function setValue(uint pValue) {
       value = pValue;
    }
 
    function getValue() returns (uint) {
       return value;
    }
 
}
var logIncrement =
   OtherExample.LogIncrement({sender: userAddress,
uint value});
 
logIncrement.watch(function(err, result) {
  // do something with result
})

C. Development Workflow

Testing Cycle:

\boxed{\text{Create Account} \rightarrow \text{Fund Account} \rightarrow \text{Develop} \rightarrow \text{Compile} \rightarrow \text{Sign & Deploy} \rightarrow \text{Interact & Test}}

  • Onboard additional users
  • Create new accounts
  • Develop new applications

1. Create Account

  • Programmatically: Go, Python, C++, JavaScript, Haskell
  • Tools:
    • MyEtherWallet.com
    • MetaMask
    • TestRPC
    • Many other websites

2. Fund Account

  • From friends
  • Faucet
  • Exchanges (for public blockchain)

3. Develop

Ethereum Application Components:

  • Base application — can be developed in any language
  • Smart contract — developed in Solidity or one of the other contract-compatible languages
  • Connector library — facilitates communication between base application and smart contracts (e.g., Metamask)

4. Sign and Deploy

Transaction --sign--> Signed tx --deploy--> Live Smart Contract
Bytecodes -----------------------> Connector* (facilitates communication with Blockchain)

*Library that facilitates communication and connection with the blockchain; connects your code to a running node.

5. TestRPC

TestRPC/TestChain

  • Local development or Test Blockchain

  • ethereumjs/testrpc

  • Ethereum TestRPC is a fast and customizable blockchain emulator. It allows making calls to the blockchain without the overhead of running an actual Ethereum node. Accounts can be recycled, reset, and instantiated with a fixed amount of Ether (no need for faucets or mining).

  • EthereumJS TestRPC is suited for development and testing

  • It's a complete blockchain-in-memory that runs only on your development machine

  • It processes transactions instantly instead of waiting for the default block time — so you can test that your code works quickly — and it tells you immediately when your smart contracts run into errors

  • It also makes a great client for automated testing

  • Truffle knows how to use its special features to speed up test runtime by almost 90%


END OF CHAPTER