SlideShare a Scribd company logo
Ethereum: mechanics
CS251 Fall 2022
(cs251.stanford.edu)
Dan Boneh
Note: HW#2 posted tonight. Due Oct. 24.
New topic: limitations of Bitcoin
Recall: UTXO contains (hash of) ScriptPK
• simple script: indicates conditions when UTXO can be spent
Limitations:
• Difficult to maintain state in multi-stage contracts
• Difficult to enforce global rules on assets
A simple example: rate limiting. My wallet manages 100 UTXOs.
• Desired policy: can only transfer 2BTC per day out of my wallet
An example: DNS
Domain name system on the blockchain: [google.com IP addr]
⇾
Need support for three operations:
• Name.new(OwnerAddr, DomainName): intent to register
• Name.update(DomainName, newVal, newOwner, OwnerSig)
• Name.lookup(DomainName)
Note: also need to ensure no front-running on Name.new()
A broken implementation
Name.new() and Name.upate() create a UTXO with ScriptPK:
DUP HASH256 <OwnerAddr> EQVERIFY CHECKSIG VERIFY
<DNS> <DomainName> <IPaddr> <1>
only owner can “spend” this UTXO to update domain data
Contract: (should be enforced by miners)
if domain google.com is registered,
no one else can register that domain
Problem: this contract cannot be enforced using Bitcoin script
verify
sig is valid
ensure top
of stack is 1
What to do?
NameCoin: a fork of Bitcoin that implements this contract
(see also the Ethereum Name Service -- ENS)
Can we build a blockchain that natively supports generic
contracts like this?
⇒ Ethereum
Ethereum: enables a world of
applications
stateofthedapps.com, dapp.review
A world of Ethereum Decentralized apps (DAPPs)
• New coins: ERC-20 standard interface
• DeFi: exchanges, lending, stablecoins, derivatives, etc.
• Insurance
• DAOs: decentralized organizations
• NFTs: Managing asset ownership (ERC-721 interface)
Bitcoin as a state transition system
UTXO1
UTXO2
⋮
world state
…
UTXO1
UTXO3
⋮
updated world state
…
input
Tx: UTXO2 UTXO
⇾ 3
Fbitcoin : S × I S
⇾
S: set of all possible world states, s0 S genesis state
∈
I: set of all possible inputs
Bitcoin rules:
Ethereum as a state transition system
Much richer state transition functions
⇒ one transition executes an entire program
Ethereum
world state
…
updated Ethereum
world state
…
input
Tx
Running a program on a blockchain (DAPP)
consensus layer (beacon chain)
compute layer (execution chain): The EVM
state0
program
code
… blockchain …
state1
Tx1 Tx2 state2
create a DAPP
…
The Ethereum system
Proof-of-Stake consensus
One block every 12 seconds.
about 150 Tx per block.
Block proposer receives
Tx fees for block
(along with other rewards)
A bit about the beacon chain (Eth2 consensus
layer)
To become a validator: stake (lock up) 32 ETH … or use Lido.
Validators: - sign blocks to express correctness (finalized once enough sigs)
- occasionally act as block proposer (chosen at random)
- correct behavior issued
⇒ new ETH every epoch (32 blocks)
- incorrect behavior slashed
⇒
Staked ETH
(27M)
# Validators
(843K)
(lots of details)
The economics of staking
Validator locks up 32 ETH. Oct 2023: 27M ETH staked (total)
Annual validator income (an example):
• Issuance: 1.0 ETH
• Tx fees: 0.4 ETH
• MEV: 0.4 ETH
• Total: 1.8 ETH (5.6% return on 32 ETH staked)
Can be adjusted
(BASE_REWARD_FACTOR)
A function of
congestion
In practice: staking provider (e.g., Lido) takes a cut of the returns
The Ethereum system
consensus layer (beacon chain)
compute layer (execution chain)
notify_new_payload(payload) [Engine API]
sends transactions to compute layer
32 blocks
in an epoch
update
world state
The Ethereum Compute Layer:
The EVM
Ethereum compute layer: the EVM
World state: set of accounts identified by 32-byte address.
Two types of accounts:
(1) externally owned accounts (EOA):
controlled by ECDSA signing key pair (pk,sk).
sk: signing key known only to account owner
(2) contracts: controlled by code.
code set at account creation time, does not change
Data associated with an account
Account data Owned (EOA) Contracts
address (computed): H(pk) H(CreatorAddr, CreatorNonce)
code: ⊥ CodeHash
storage root (state): ⊥ StorageRoot
balance (in Wei): balance balance (1 Wei = 10−18
ETH)
nonce: nonce nonce
(#Tx sent) + (#accounts created): anti-replay mechanism
Account state: persistent storage
Every contract has an associated storage array S[]:
S[0], S[1], … , S[2256
-1]: each cell holds 32 bytes, init to 0.
Account storage root: Merkle Patricia Tree hash of S[]
• Cannot compute full Merkle tree hash: 2256
leaves
S[000] = a
S[010] = b
S[011] = c
S[110] = d
root
10, d
0
1
0, a
0
1
⊥, b
⊥, c
0
1
time to compute
root hash:
≤ 2×|S|
|S| = # non-zero cells
State transitions: Tx and messages
Transactions: signed data by initiator
• To: 32-byte address of target (0 create new account)
⇾
• From, [Signature]: initiator address and signature on Tx (if owned)
• Value: # Wei being sent with Tx (1 Wei = 10-18
ETH)
• Tx fees (EIP 1559): gasLimit, maxFee, maxPriorityFee (later)
• if To = 0: create new contract code = (init, body)
• if To ≠ 0: data (what function to call & arguments)
• nonce: must match current nonce of sender (prevents Tx replay)
State transitions: Tx and messages
Transaction types:
owned owned: transfer ETH between users
⇾
owned contract: call contract with ETH &
⇾
data
Example (block #10993504)
From To msg.value Tx fee (ETH)
Messages: virtual Tx initiated by a
contract
Same as Tx, but no signature (contract has no signing key)
contract owned: contract sends funds to user
⇾
contract contract: one program calls another
⇾ (and sends funds)
One Tx from user: can lead to many Tx processed. Composability!
Tx from owned addr contract another contract
⇾ ⇾
another contract different owned
⇾
Example Tx
world state (four accounts) updated world state
An Ethereum Block
Block proposer creates a block of n Tx: (from Txs submitted by users)
• To produce a block do:
• for i=1,…,n: execute state change of Txi sequentially
(can change state of >n accounts)
• record updated world state in block
Other validators re-execute all Tx to verify block ⇒
sign block if valid enough sigs, epoch is finalized.
⇒
Block header data (simplified)
(1) consensus data: proposer ID, parent hash, votes, etc.
(2) address of gas beneficiary: where Tx fees will go
(3) world state root: updated world state
Merkle Patricia Tree hash of all accounts in the system
(4) Tx root: Merkle hash of all Tx processed in block
(5) Tx receipt root: Merkle hash of log messages generated in block
(5) Gas used: used to adjust gas price (target 15M gas per block)
The Ethereum blockchain: abstractly
…
prev hash
updated
world
state
Tx log
messages
accts.
prev hash
updated
world
state
Tx log
messages
accts.
…
Amount of memory to run a node
ETH total blockchain size (archival): 16 TB (Oct. 2023)
≈1.3 TB
An example contract: NameCoin
contract nameCoin { // Solidity code (next lecture)
struct nameEntry {
address owner; // address of domain owner
bytes32 value; // IP address
}
// array of all registered domains
mapping (bytes32 => nameEntry) data;
An example contract: NameCoin
function nameNew(bytes32 name) {
// registration costs is 100 Wei
if (data[name] == 0 && msg.value >= 100) {
data[name].owner = msg.sender // record domain owner
emit Register(msg.sender, name) // log event
}}
Code ensures that no one can take over a registered name
Serious bug in this code! Front running. Solved using commitments.
An example contract: NameCoin
nction nameUpdate(
bytes32 name, bytes32 newValue, address newOwner)
// check if message is from domain owner,
// and update cost of 10 Wei is paid
if (data[name].owner == msg.sender && msg.value >= 10) {
data[name].value = newValue; // record new valu
data[name].owner = newOwner; // record new ow
}}
An example contract: NameCoin
function nameLookup(bytes32 name) {
return data[name];
}
} // end of contract
Used by other contracts
Humans do not need this
(use etherscan.io)
EVM mechanics: execution environment
Write code in Solidity (or another front-end language)
⇒ compile to EVM bytecode
(some projects use WASM or BPF
bytecode)
⇒ validators use the EVM to execute contract bytecode
in response to a Tx
The EVM
Stack machine (like Bitcoin) but with JUMP
• max stack depth = 1024
• program aborts if stack size exceeded; block proposer keeps gas
• contract can create or call another contract
In addition: two types of zero initialized memory
• Persistent storage (on blockchain): SLOAD, SSTORE (expensive)
• Volatile memory (for single Tx): MLOAD, MSTORE (cheap)
• LOG0(data): write data to log
see https://www.evm.codes
Every instruction costs gas, examples:
SSTORE addr (32 bytes), value (32 bytes)
• zero non-zero:
⇾ 20,000 gas
• non-zero non-zero:
⇾ 5,000 gas (for a cold slot)
• non-zero zero:
⇾ 15,000 gas refund (example)
CREATE : 32,000 + 200×(code size) gas; CALL gas, addr, value, args
SELFDESTRUCT addr: kill current contract (5000 gas)
Refund is given for reducing size of blockchain state
Gas calculation
Why charge gas?
• Tx fees (gas) prevents submitting Tx that runs for many steps.
• During high load: block proposer chooses Tx from mempool
that maximize its income.
Old EVM: (prior to EIP1559, live on 8/2021)
• Every Tx contains a gasPrice ``bid’’ (gas Wei conversion price)
⇾
• Producer chooses Tx with highest gasPrice (max sum(gasPrice×gasLimit))
⟹ not an efficient auction mechanism (first price auction)
Gas prices spike during congestion
GasPrice in Gwei:
86 Gwei = 86×10-9
ETH
Average Tx fee in USD congestion
Gas calculation: EIP1559 (since 8/2021)
EIP1559 goals (informal):
• users incentivized to bid their true utility for posting Tx,
• block proposer incentivized to not create fake Tx, and
• disincentivize off chain agreements.
[ Transaction Fee Mechanism Design, by T. Roughgarden, 2021 ]
Gas calculation: EIP1559
Every block has a “baseFee”:
the minimum gasPrice for all Tx in the block
baseFee is computed from total gas in earlier blocks:
• earlier blocks at gas limit (30M gas) base fee goes up 12.5%
⟹
• earlier blocks empty base fee decreases by 12.5%
⟹
If earlier blocks at “target size” (15M gas) base fee does not change
⟹
interpolate
in between
Computed gasPrice bid:
gasPrice min(
⇽ maxFee, baseFee +
maxPriorityFee)
Gas calculation
EIP1559 Tx specifies three parameters:
• gasLimit: max total gas allowed for Tx
• maxFee: maximum allowed gas price (max gas Wei conversion)
⇾
• maxPriorityFee: additional “tip” to be paid to block proposer
Max Tx fee: gasLimit × gasPrice
Gas calculation (informal)
gasUsed gas used by Tx
⇽
Send gasUsed×(gasPrice – baseFee) to block proposer
BURN gasUsed× baseFee
⇒ total supply of ETH can decrease
Gas calculation
(1) if gasPrice < baseFee: abort
(2) If gasLimit×gasPrice < msg.sender.balance: abort
(3) deduct gasLimit×gasPrice from msg.sender.balance
(4) set Gas ⇽ gasLimit
(5) execute Tx: deduct gas from Gas for each instruction
if at end (Gas < 0): abort, Tx is invalid (proposer keeps gasLimit×gasPrice)
(6) Refund Gas×gasPrice to msg.sender.balance
(7) gasUsed ⇽ gasLimit – Gas
(7a) BURN gasUsed× baseFee
(7b) Send gasUsed×(gasPrice – baseFee) to block producer
Example baseFee and effect of burn
block # gasUsed baseFee (Gwei) ETH burned
15763570 21,486,058 16.92 0.363
15763569 14,609,185 16.97 0.248
15763568 25,239,720 15.64 0.394
15763567 29,976,215 13.90 0.416
15763566 14,926,172 13.91 0.207
15763565 1,985,580 15.60 0.031
≈ gasUsed×baseFee
baseFee < 16Gwei new issuance > burn ETH inflates
⇒ ⇒
baseFee > 16Gwei new issuance < burn ETH deflates
⇒ ⇒
(<15M)
↓
(<15M)
↓
(<15M)
↓
beacon chain
Why burn ETH ???
Recall: EIP1559 goals (informal)
• users incentivized to bid their true utility for posting Tx,
• block proposer incentivized to not create fake Tx, and
• disincentivize off chain agreements.
Suppose no burn (i.e., baseFee given to block producer):
⟹ in periods of low Tx volume proposer would try to increase
volume by offering to refund the baseFee off chain to users.
Note: transactions are becoming more complex
Gas usage is increasing each Tx takes more instructions to execute
⇒
Next lecture: writing Solidity contracts
END OF LECTURE

More Related Content

Similar to lecture7 blockchain ethereum mechanics 101 (20)

PPTX
EthereumBlockchainMarch3 (1).pptx
WijdenBenothmen1
 
PDF
Blockchain Autopsies - Analyzing Ethereum Smart Contract Deaths
Priyanka Aash
 
DOCX
How does ethereum work, anyway?
philrussell001
 
PDF
Encode Club: Nethermind Workshop EVM Bootcamp
lara348812
 
PDF
Ethereum A to Z
Dongsam Byun
 
PDF
Blockchain
Rishabh Sharma
 
PDF
Ethereum-Cryptocurrency (All about Ethereum)
عطاءالمنعم اثیل شیخ
 
PDF
solutions.hamburg | web3 // smart contracts // ethereum
Maximilian Reichel
 
PDF
"Programming Smart Contracts on Ethereum" by Anatoly Ressin from AssistUnion ...
Dace Barone
 
PDF
Grokking TechTalk #17: Introduction to blockchain
Grokking VN
 
PDF
Smart contracts in Solidity
Felix Crisan
 
PDF
BlockchainDay "Ethereum Dapp - Asset Exchange YOSEMITE alpha" Session
병완 임
 
PPTX
Blockchain for Developers
Shimi Bandiel
 
PPTX
Blockchain, Ethereum and Business Applications
Matthias Zimmermann
 
PDF
Blockchain Chapter #4.pdf
ssuser79c46d1
 
PDF
“Create your own cryptocurrency in an hour” - Sandip Pandey
EIT Digital Alumni
 
PPTX
Ethereum Block Chain
SanatPandoh
 
PDF
Hands on Ethereum - Getting Started
CodeOps Technologies LLP
 
PPTX
Explain Ethereum smart contract hacking like i am a five
Zoltan Balazs
 
PPTX
Zoltán Balázs - Ethereum Smart Contract Hacking Explained like I’m Five
hacktivity
 
EthereumBlockchainMarch3 (1).pptx
WijdenBenothmen1
 
Blockchain Autopsies - Analyzing Ethereum Smart Contract Deaths
Priyanka Aash
 
How does ethereum work, anyway?
philrussell001
 
Encode Club: Nethermind Workshop EVM Bootcamp
lara348812
 
Ethereum A to Z
Dongsam Byun
 
Blockchain
Rishabh Sharma
 
Ethereum-Cryptocurrency (All about Ethereum)
عطاءالمنعم اثیل شیخ
 
solutions.hamburg | web3 // smart contracts // ethereum
Maximilian Reichel
 
"Programming Smart Contracts on Ethereum" by Anatoly Ressin from AssistUnion ...
Dace Barone
 
Grokking TechTalk #17: Introduction to blockchain
Grokking VN
 
Smart contracts in Solidity
Felix Crisan
 
BlockchainDay "Ethereum Dapp - Asset Exchange YOSEMITE alpha" Session
병완 임
 
Blockchain for Developers
Shimi Bandiel
 
Blockchain, Ethereum and Business Applications
Matthias Zimmermann
 
Blockchain Chapter #4.pdf
ssuser79c46d1
 
“Create your own cryptocurrency in an hour” - Sandip Pandey
EIT Digital Alumni
 
Ethereum Block Chain
SanatPandoh
 
Hands on Ethereum - Getting Started
CodeOps Technologies LLP
 
Explain Ethereum smart contract hacking like i am a five
Zoltan Balazs
 
Zoltán Balázs - Ethereum Smart Contract Hacking Explained like I’m Five
hacktivity
 

More from HariPurnama5 (6)

PDF
IDS Kuliah Keamanan Informasi Pak Budi Rahardjo
HariPurnama5
 
PDF
Firewall Kuliah Keamanan Informasi Pak Budi
HariPurnama5
 
PDF
AI in Teaching - bebras Bu Ayu Purwarianti
HariPurnama5
 
PDF
Decentralized Auction App, task for DEMO
HariPurnama5
 
PDF
Blockchain and Money courses from MIT 4 oct 2018
HariPurnama5
 
PDF
Blockchain & Money MIT from MIT courses.
HariPurnama5
 
IDS Kuliah Keamanan Informasi Pak Budi Rahardjo
HariPurnama5
 
Firewall Kuliah Keamanan Informasi Pak Budi
HariPurnama5
 
AI in Teaching - bebras Bu Ayu Purwarianti
HariPurnama5
 
Decentralized Auction App, task for DEMO
HariPurnama5
 
Blockchain and Money courses from MIT 4 oct 2018
HariPurnama5
 
Blockchain & Money MIT from MIT courses.
HariPurnama5
 
Ad

Recently uploaded (20)

PDF
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
PDF
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PPTX
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
PDF
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PDF
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
Ad

lecture7 blockchain ethereum mechanics 101

  • 1. Ethereum: mechanics CS251 Fall 2022 (cs251.stanford.edu) Dan Boneh Note: HW#2 posted tonight. Due Oct. 24.
  • 2. New topic: limitations of Bitcoin Recall: UTXO contains (hash of) ScriptPK • simple script: indicates conditions when UTXO can be spent Limitations: • Difficult to maintain state in multi-stage contracts • Difficult to enforce global rules on assets A simple example: rate limiting. My wallet manages 100 UTXOs. • Desired policy: can only transfer 2BTC per day out of my wallet
  • 3. An example: DNS Domain name system on the blockchain: [google.com IP addr] ⇾ Need support for three operations: • Name.new(OwnerAddr, DomainName): intent to register • Name.update(DomainName, newVal, newOwner, OwnerSig) • Name.lookup(DomainName) Note: also need to ensure no front-running on Name.new()
  • 4. A broken implementation Name.new() and Name.upate() create a UTXO with ScriptPK: DUP HASH256 <OwnerAddr> EQVERIFY CHECKSIG VERIFY <DNS> <DomainName> <IPaddr> <1> only owner can “spend” this UTXO to update domain data Contract: (should be enforced by miners) if domain google.com is registered, no one else can register that domain Problem: this contract cannot be enforced using Bitcoin script verify sig is valid ensure top of stack is 1
  • 5. What to do? NameCoin: a fork of Bitcoin that implements this contract (see also the Ethereum Name Service -- ENS) Can we build a blockchain that natively supports generic contracts like this? ⇒ Ethereum
  • 6. Ethereum: enables a world of applications stateofthedapps.com, dapp.review A world of Ethereum Decentralized apps (DAPPs) • New coins: ERC-20 standard interface • DeFi: exchanges, lending, stablecoins, derivatives, etc. • Insurance • DAOs: decentralized organizations • NFTs: Managing asset ownership (ERC-721 interface)
  • 7. Bitcoin as a state transition system UTXO1 UTXO2 ⋮ world state … UTXO1 UTXO3 ⋮ updated world state … input Tx: UTXO2 UTXO ⇾ 3 Fbitcoin : S × I S ⇾ S: set of all possible world states, s0 S genesis state ∈ I: set of all possible inputs Bitcoin rules:
  • 8. Ethereum as a state transition system Much richer state transition functions ⇒ one transition executes an entire program Ethereum world state … updated Ethereum world state … input Tx
  • 9. Running a program on a blockchain (DAPP) consensus layer (beacon chain) compute layer (execution chain): The EVM state0 program code … blockchain … state1 Tx1 Tx2 state2 create a DAPP …
  • 10. The Ethereum system Proof-of-Stake consensus One block every 12 seconds. about 150 Tx per block. Block proposer receives Tx fees for block (along with other rewards)
  • 11. A bit about the beacon chain (Eth2 consensus layer) To become a validator: stake (lock up) 32 ETH … or use Lido. Validators: - sign blocks to express correctness (finalized once enough sigs) - occasionally act as block proposer (chosen at random) - correct behavior issued ⇒ new ETH every epoch (32 blocks) - incorrect behavior slashed ⇒ Staked ETH (27M) # Validators (843K) (lots of details)
  • 12. The economics of staking Validator locks up 32 ETH. Oct 2023: 27M ETH staked (total) Annual validator income (an example): • Issuance: 1.0 ETH • Tx fees: 0.4 ETH • MEV: 0.4 ETH • Total: 1.8 ETH (5.6% return on 32 ETH staked) Can be adjusted (BASE_REWARD_FACTOR) A function of congestion In practice: staking provider (e.g., Lido) takes a cut of the returns
  • 13. The Ethereum system consensus layer (beacon chain) compute layer (execution chain) notify_new_payload(payload) [Engine API] sends transactions to compute layer 32 blocks in an epoch update world state
  • 14. The Ethereum Compute Layer: The EVM
  • 15. Ethereum compute layer: the EVM World state: set of accounts identified by 32-byte address. Two types of accounts: (1) externally owned accounts (EOA): controlled by ECDSA signing key pair (pk,sk). sk: signing key known only to account owner (2) contracts: controlled by code. code set at account creation time, does not change
  • 16. Data associated with an account Account data Owned (EOA) Contracts address (computed): H(pk) H(CreatorAddr, CreatorNonce) code: ⊥ CodeHash storage root (state): ⊥ StorageRoot balance (in Wei): balance balance (1 Wei = 10−18 ETH) nonce: nonce nonce (#Tx sent) + (#accounts created): anti-replay mechanism
  • 17. Account state: persistent storage Every contract has an associated storage array S[]: S[0], S[1], … , S[2256 -1]: each cell holds 32 bytes, init to 0. Account storage root: Merkle Patricia Tree hash of S[] • Cannot compute full Merkle tree hash: 2256 leaves S[000] = a S[010] = b S[011] = c S[110] = d root 10, d 0 1 0, a 0 1 ⊥, b ⊥, c 0 1 time to compute root hash: ≤ 2×|S| |S| = # non-zero cells
  • 18. State transitions: Tx and messages Transactions: signed data by initiator • To: 32-byte address of target (0 create new account) ⇾ • From, [Signature]: initiator address and signature on Tx (if owned) • Value: # Wei being sent with Tx (1 Wei = 10-18 ETH) • Tx fees (EIP 1559): gasLimit, maxFee, maxPriorityFee (later) • if To = 0: create new contract code = (init, body) • if To ≠ 0: data (what function to call & arguments) • nonce: must match current nonce of sender (prevents Tx replay)
  • 19. State transitions: Tx and messages Transaction types: owned owned: transfer ETH between users ⇾ owned contract: call contract with ETH & ⇾ data
  • 20. Example (block #10993504) From To msg.value Tx fee (ETH)
  • 21. Messages: virtual Tx initiated by a contract Same as Tx, but no signature (contract has no signing key) contract owned: contract sends funds to user ⇾ contract contract: one program calls another ⇾ (and sends funds) One Tx from user: can lead to many Tx processed. Composability! Tx from owned addr contract another contract ⇾ ⇾ another contract different owned ⇾
  • 22. Example Tx world state (four accounts) updated world state
  • 23. An Ethereum Block Block proposer creates a block of n Tx: (from Txs submitted by users) • To produce a block do: • for i=1,…,n: execute state change of Txi sequentially (can change state of >n accounts) • record updated world state in block Other validators re-execute all Tx to verify block ⇒ sign block if valid enough sigs, epoch is finalized. ⇒
  • 24. Block header data (simplified) (1) consensus data: proposer ID, parent hash, votes, etc. (2) address of gas beneficiary: where Tx fees will go (3) world state root: updated world state Merkle Patricia Tree hash of all accounts in the system (4) Tx root: Merkle hash of all Tx processed in block (5) Tx receipt root: Merkle hash of log messages generated in block (5) Gas used: used to adjust gas price (target 15M gas per block)
  • 25. The Ethereum blockchain: abstractly … prev hash updated world state Tx log messages accts. prev hash updated world state Tx log messages accts. …
  • 26. Amount of memory to run a node ETH total blockchain size (archival): 16 TB (Oct. 2023) ≈1.3 TB
  • 27. An example contract: NameCoin contract nameCoin { // Solidity code (next lecture) struct nameEntry { address owner; // address of domain owner bytes32 value; // IP address } // array of all registered domains mapping (bytes32 => nameEntry) data;
  • 28. An example contract: NameCoin function nameNew(bytes32 name) { // registration costs is 100 Wei if (data[name] == 0 && msg.value >= 100) { data[name].owner = msg.sender // record domain owner emit Register(msg.sender, name) // log event }} Code ensures that no one can take over a registered name Serious bug in this code! Front running. Solved using commitments.
  • 29. An example contract: NameCoin nction nameUpdate( bytes32 name, bytes32 newValue, address newOwner) // check if message is from domain owner, // and update cost of 10 Wei is paid if (data[name].owner == msg.sender && msg.value >= 10) { data[name].value = newValue; // record new valu data[name].owner = newOwner; // record new ow }}
  • 30. An example contract: NameCoin function nameLookup(bytes32 name) { return data[name]; } } // end of contract Used by other contracts Humans do not need this (use etherscan.io)
  • 31. EVM mechanics: execution environment Write code in Solidity (or another front-end language) ⇒ compile to EVM bytecode (some projects use WASM or BPF bytecode) ⇒ validators use the EVM to execute contract bytecode in response to a Tx
  • 32. The EVM Stack machine (like Bitcoin) but with JUMP • max stack depth = 1024 • program aborts if stack size exceeded; block proposer keeps gas • contract can create or call another contract In addition: two types of zero initialized memory • Persistent storage (on blockchain): SLOAD, SSTORE (expensive) • Volatile memory (for single Tx): MLOAD, MSTORE (cheap) • LOG0(data): write data to log see https://www.evm.codes
  • 33. Every instruction costs gas, examples: SSTORE addr (32 bytes), value (32 bytes) • zero non-zero: ⇾ 20,000 gas • non-zero non-zero: ⇾ 5,000 gas (for a cold slot) • non-zero zero: ⇾ 15,000 gas refund (example) CREATE : 32,000 + 200×(code size) gas; CALL gas, addr, value, args SELFDESTRUCT addr: kill current contract (5000 gas) Refund is given for reducing size of blockchain state
  • 34. Gas calculation Why charge gas? • Tx fees (gas) prevents submitting Tx that runs for many steps. • During high load: block proposer chooses Tx from mempool that maximize its income. Old EVM: (prior to EIP1559, live on 8/2021) • Every Tx contains a gasPrice ``bid’’ (gas Wei conversion price) ⇾ • Producer chooses Tx with highest gasPrice (max sum(gasPrice×gasLimit)) ⟹ not an efficient auction mechanism (first price auction)
  • 35. Gas prices spike during congestion GasPrice in Gwei: 86 Gwei = 86×10-9 ETH Average Tx fee in USD congestion
  • 36. Gas calculation: EIP1559 (since 8/2021) EIP1559 goals (informal): • users incentivized to bid their true utility for posting Tx, • block proposer incentivized to not create fake Tx, and • disincentivize off chain agreements. [ Transaction Fee Mechanism Design, by T. Roughgarden, 2021 ]
  • 37. Gas calculation: EIP1559 Every block has a “baseFee”: the minimum gasPrice for all Tx in the block baseFee is computed from total gas in earlier blocks: • earlier blocks at gas limit (30M gas) base fee goes up 12.5% ⟹ • earlier blocks empty base fee decreases by 12.5% ⟹ If earlier blocks at “target size” (15M gas) base fee does not change ⟹ interpolate in between
  • 38. Computed gasPrice bid: gasPrice min( ⇽ maxFee, baseFee + maxPriorityFee) Gas calculation EIP1559 Tx specifies three parameters: • gasLimit: max total gas allowed for Tx • maxFee: maximum allowed gas price (max gas Wei conversion) ⇾ • maxPriorityFee: additional “tip” to be paid to block proposer Max Tx fee: gasLimit × gasPrice
  • 39. Gas calculation (informal) gasUsed gas used by Tx ⇽ Send gasUsed×(gasPrice – baseFee) to block proposer BURN gasUsed× baseFee ⇒ total supply of ETH can decrease
  • 40. Gas calculation (1) if gasPrice < baseFee: abort (2) If gasLimit×gasPrice < msg.sender.balance: abort (3) deduct gasLimit×gasPrice from msg.sender.balance (4) set Gas ⇽ gasLimit (5) execute Tx: deduct gas from Gas for each instruction if at end (Gas < 0): abort, Tx is invalid (proposer keeps gasLimit×gasPrice) (6) Refund Gas×gasPrice to msg.sender.balance (7) gasUsed ⇽ gasLimit – Gas (7a) BURN gasUsed× baseFee (7b) Send gasUsed×(gasPrice – baseFee) to block producer
  • 41. Example baseFee and effect of burn block # gasUsed baseFee (Gwei) ETH burned 15763570 21,486,058 16.92 0.363 15763569 14,609,185 16.97 0.248 15763568 25,239,720 15.64 0.394 15763567 29,976,215 13.90 0.416 15763566 14,926,172 13.91 0.207 15763565 1,985,580 15.60 0.031 ≈ gasUsed×baseFee baseFee < 16Gwei new issuance > burn ETH inflates ⇒ ⇒ baseFee > 16Gwei new issuance < burn ETH deflates ⇒ ⇒ (<15M) ↓ (<15M) ↓ (<15M) ↓ beacon chain
  • 42. Why burn ETH ??? Recall: EIP1559 goals (informal) • users incentivized to bid their true utility for posting Tx, • block proposer incentivized to not create fake Tx, and • disincentivize off chain agreements. Suppose no burn (i.e., baseFee given to block producer): ⟹ in periods of low Tx volume proposer would try to increase volume by offering to refund the baseFee off chain to users.
  • 43. Note: transactions are becoming more complex Gas usage is increasing each Tx takes more instructions to execute ⇒
  • 44. Next lecture: writing Solidity contracts END OF LECTURE

Editor's Notes

  • #2: GST: global stabilization time. Slide 1: Konsensus - Ringkasan Cepat "Pada slide ini, kita akan melihat kembali dua tujuan utama dari protokol konsensus dalam blockchain, yaitu safety dan liveness. Safety mengacu pada tidak adanya ‘fork’ dalam blockchain. Fork adalah ketika blockchain bercabang menjadi dua atau lebih jalur berbeda, yang dapat menyebabkan perpecahan dalam jaringan dan mengancam keabsahan transaksi. Liveness berarti jaringan tetap aktif dan tidak ada sensor terhadap transaksi yang sah. Artinya, setiap transaksi yang valid harus bisa masuk ke dalam blok dan akhirnya dikonfirmasi. Kemudian, kita juga perlu memahami perbedaan antara model jaringan sinkron dan model jaringan asinkron: Pada jaringan sinkron, ada jaminan waktu komunikasi antar node, sehingga bisa lebih mudah memastikan bahwa semua node di jaringan akan mencapai konsensus dalam waktu yang sama. Sementara itu, pada jaringan asinkron, tidak ada jaminan mengenai waktu komunikasi ini, sehingga jaringan lebih rentan terhadap latensi dan delay. Ini merupakan tantangan yang dihadapi protokol konsensus seperti yang digunakan di Bitcoin dan Ethereum. Ada dua tipe pengaturan partisipan yang kita lihat dalam konsensus blockchain: Fixed set of participants (peserta tetap) yang menggunakan PKI (Public Key Infrastructure) dan kanal otentikasi. Di sini, partisipan tetap dikenal dan dapat dipercaya, misalnya dalam jaringan tertutup. Open participation (partisipasi terbuka), yang kita lihat pada jaringan seperti Bitcoin dan Ethereum. Dalam model ini, jaringan terbuka untuk siapa saja, sehingga memerlukan mekanisme sybil resistance, untuk mencegah serangan di mana satu entitas menciptakan banyak identitas untuk mengendalikan jaringan. Contohnya adalah Proof-of-Work (PoW) seperti pada Bitcoin dan Proof-of-Stake (PoS) seperti pada Ethereum yang jauh lebih efisien energi."
  • #3: a UTXO being spent cannot tell how many of my other UTXOs were spent during that day. Slide 2: Batasan Bitcoin "Pada slide ini, kita akan mengeksplorasi batasan-batasan yang dimiliki oleh Bitcoin dalam hal pemrograman kontrak yang kompleks. Bitcoin menggunakan model UTXO (Unspent Transaction Output), di mana setiap UTXO mewakili sebagian dari saldo pengguna yang bisa dibelanjakan. Namun, model ini memiliki beberapa keterbatasan, terutama dalam kontrak multi-tahap dan aturan global terkait aset. Kontrak multi-tahap: Dalam model UTXO, sulit untuk melacak status dari suatu kontrak yang memerlukan beberapa tahap transaksi. Hal ini karena setiap UTXO tidak memiliki kemampuan untuk secara langsung mengetahui informasi tentang UTXO lainnya yang mungkin relevan dalam sebuah kontrak. Aturan global: Sulit juga untuk memberlakukan aturan global pada aset yang tersebar dalam beberapa UTXO. Sebagai contoh, misalkan saya memiliki kebijakan bahwa dompet saya hanya bisa mentransfer 2 BTC per hari. Dalam sistem UTXO, tidak ada mekanisme yang memungkinkan satu UTXO mengetahui berapa banyak UTXO lain yang sudah dihabiskan pada hari tersebut. Contoh yang lebih sederhana adalah rate limiting. Jika saya ingin memastikan bahwa dompet saya hanya bisa mengirim sejumlah maksimum dalam sehari, sistem UTXO tidak dapat memantau berapa banyak yang telah dikirim sebelumnya. Ini adalah salah satu batasan utama Bitcoin dalam menangani kontrak yang lebih kompleks."
  • #5: Script: top line checks that owner properly signed Tx; bottom line pushes data onto stack and ensures that top of stack ends in <1> to make script succeed. Here <NAMECOIN> pushes the word NAMECOIN onto the stack so everyone can tell that this UTXO is a NameCoin UTXO.
  • #7: CryptoPunks
  • #11: https://etherscan.io/blocks
  • #12: https://beaconscan.com/stat/validator Correct behavior: don’t sign two different blocks for same slot and other mischief.
  • #13: https://ultrasound.money/#monetary-premium (see validator rewards section) See graph of size of staking pools at: https://dune.com/queries/96263/192763 (and https://dune.com/LidoAnalytical/Lido-Finance-Extended ) Also see: https://www.coinbase.com/earn/staking/ethereum
  • #14: 32 blocks make an epoch. Validators vote on blocks.
  • #17: The computed address for a contract created with CREATE is H(CreatorAddr, CreatorNonce) as shown in the table above. Same when contract is created by an owned account. However, the computed address for a contract created with CREATE2 is H(CreatorAddr, InitCodeOfNewContract, Salt). This means that CREATE2 can be used to overwrite the code of a previous contract that resided in that address. This is only possible if the earlier contract did a SELFDESTRUCT. Either way, the nonce of a newly created contract is initialized to zero.
  • #18: Store suffix in nodes. Ethereum’s Merkle Patricia Tree has a branching factor of 16.
  • #19: nonce must match current nonce of sender in sender’s account data. When Tx processed successfully, nonce in sender’s account data is incremented by 1. chain_id: ensures that a Tx signed for the testnet cannot be submitting on the mainnet (same with L1/L2 confusion).
  • #21: Some Tx go to contracts, others go to owned addresses
  • #24: Other blockchains allow for non-interfering parallel execution: Flow, Avalanche.
  • #27: https://etherscan.io/chartsync/chaindefault https://etherscan.io/chartsync/chainarchive
  • #34: Selfdestruct addr: sends all account funds to specified address. Refund removed to avoid gastokens. CREATE: create a new contract CALL: contract at address addr, with max gas, and value
  • #36: https://ycharts.com/indicators/ethereum_average_gas_price https://ycharts.com/indicators/ethereum_average_transaction_fee
  • #37: If a second price auction were used: proposers would be incentivized to create fake transactions. See https://arxiv.org/pdf/2106.01340.pdf for an analysis.
  • #39: gas for each instruction defined by a hard coded table.
  • #40: gas for each instruction defined by a hard coded table. BURN: deflates the currency
  • #41: gas for each instruction defined by a hard coded table. BURN: deflates the currency
  • #42: https://etherscan.io/blocks When previous block is light (<15M gas), baseFee goes down. When previous block is heavy (>15M gas), baseFee goes up.
  • #43: If a second price auction were used: proposers would be incentivized to create fake transactions. See https://arxiv.org/pdf/2106.01340.pdf for an analysis.
  • #44: https://etherchain.org/charts/totalGasUsage