0% found this document useful (0 votes)
6 views11 pages

Lecture 7 Print

Lecture

Uploaded by

thotran.14042003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

Lecture 7 Print

Lecture

Uploaded by

thotran.14042003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

New topic: limitations of Bitcoin

Recall: UTXO contains (hash of) ScriptPK


• simple script: indicates conditions when UTXO can be spent
Ethereum: mechanics
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

1 3

An example: DNS A broken implementation


Domain name system on the blockchain: [google.com ⇾ IP addr] Name.new() and Name.upate() create a UTXO with ScriptPK:
DUP HASH256 <OwnerAddr> EQVERIFY CHECKSIG VERIFY
Need support for three operations: <DNS> <DomainName> <IPaddr> <1>
• Name.new(OwnerAddr, DomainName): intent to register only owner can “spend” this UTXO to update domain data
• Name.update(DomainName, newVal, newOwner, OwnerSig) verify
Contract: (should be enforced by miners)
• Name.lookup(DomainName) sig is valid
if domain google.com is registered,
ensure top
no one else can register that domain of stack is 1
Note: also need to ensure no front-running on Name.new()
Problem: this contract cannot be enforced using Bitcoin script

4 5
What to do? Ethereum: enables a world of applications
A world of Ethereum Decentralized apps (DAPPs)
NameCoin: a fork of Bitcoin that implements this contract
• New coins: ERC-20 standard interface
(see also the Ethereum Name Service -- ENS)
• DeFi: exchanges, lending, stablecoins, derivatives, etc.
Can we build a blockchain that natively supports generic • Insurance
contracts like this? • DAOs: decentralized organizations
• NFTs: Managing asset ownership (ERC-721 interface)
⇒ Ethereum

stateofthedapps.com, dapp.review

6 7

Bitcoin as a state transition system Ethereum as a state transition system


world state updated world state
Much richer state transition functions
UTXO1 UTXO1
… UTXO2 input UTXO3 … ⇒ one transition executes an entire program
⋮ Tx: UTXO2 ⇾ UTXO3 ⋮

Ethereum updated Ethereum


world state world state
Bitcoin rules: Fbitcoin : S × I ⇾ S
… input …
S: set of all possible world states, s0 ∈ S genesis state
I: set of all possible inputs Tx

8 9
Running a program on a blockchain (DAPP) The Ethereum system
… blockchain … Proof-of-Stake consensus
One block every 12 seconds.
Tx1 state1 Tx2 state2 …
state0 about 150 Tx per block.
program
code create a DAPP
Block proposer receives
compute layer (execution chain): The EVM Tx fees for block
(along with other rewards)
consensus layer (beacon chain)

10 11

A bit about the beacon chain (Eth2 consensus layer) The economics of staking
To become a validator: stake (lock up) 32 ETH … or use Lido.
Validator locks up 32 ETH. Oct 2023: 27M ETH staked (total)
Validators: - sign blocks to express correctness (finalized once enough sigs)
- occasionally act as block proposer (chosen at random) Annual validator income (an example):
Can be adjusted
- correct behavior ⇒ issued new ETH every epoch (32 blocks) • Issuance: 1.0 ETH (BASE_REWARD_FACTOR)

- incorrect behavior ⇒ slashed (lots of details) • Tx fees: 0.4 ETH A function of


• MEV: 0.4 ETH congestion
Staked ETH
# Validators
(843K)
(27M) • Total: 1.8 ETH (5.6% return on 32 ETH staked)

In practice: staking provider (e.g., Lido) takes a cut of the returns

12 13
The Ethereum system
update
world state compute layer (execution chain)
The Ethereum Compute Layer:
notify_new_payload(payload) [Engine API] The EVM
sends transactions to compute layer

32 blocks consensus layer (beacon chain)


in an epoch

14 15

Ethereum compute layer: the EVM Data associated with an account


World state: set of accounts identified by 32-byte address. Account data Owned (EOA) Contracts
address (computed): H(pk) H(CreatorAddr, CreatorNonce)
Two types of accounts:
code: ⊥ CodeHash
(1) externally owned accounts (EOA):
controlled by ECDSA signing key pair (pk,sk). storage root (state): ⊥ StorageRoot
sk: signing key known only to account owner
balance (in Wei): balance balance (1 Wei = 10−18 ETH)

(2) contracts: controlled by code. nonce: nonce nonce


code set at account creation time, does not change (#Tx sent) + (#accounts created): anti-replay mechanism
16 17
Account state: persistent storage State transitions: Tx and messages
Transactions: signed data by initiator
Every contract has an associated storage array S[]:
• To: 32-byte address of target (0 ⇾ create new account)
S[0], S[1], … , S[2256-1]: each cell holds 32 bytes, init to 0.
• From, [Signature]: initiator address and signature on Tx (if owned)
Account storage root: Merkle Patricia Tree hash of S[] • Value: # Wei being sent with Tx (1 Wei = 10-18 ETH)
• Cannot compute full Merkle tree hash: 2256 leaves • Tx fees (EIP 1559): gasLimit, maxFee, maxPriorityFee (later)
0 0, a • if To = 0: create new contract code = (init, body)
S[000] = a time to compute
S[010] = b 0 0 ⊥, b root hash: • if To ≠ 0: data (what function to call & arguments)
S[011] = c root 1 ≤ 2×|S| • nonce: must match current nonce of sender (prevents Tx replay)
S[110] = d 1 10, d 1 ⊥, c |S| = # non-zero cells • chain_id: ensures Tx can only be submitted to the intended chain

18 19

State transitions: Tx and messages Example (block #10993504)

From To msg.value Tx fee (ETH)


Transaction types:

owned ⇾ owned: transfer ETH between users


owned ⇾ contract: call contract with ETH & data

20 21
Messages: virtual Tx initiated by a contract Example Tx
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
world state (four accounts) updated world state
22 23

An Ethereum Block Block header data (simplified)

Block proposer creates a block of n Tx: (from Txs submitted by users) (1) consensus data: proposer ID, parent hash, votes, etc.
• To produce a block do: (2) address of gas beneficiary: where Tx fees will go
• for i=1,…,n: execute state change of Txi sequentially
(can change state of >n accounts) (3) world state root: updated world state
• record updated world state in block Merkle Patricia Tree hash of all accounts in the system
(4) Tx root: Merkle hash of all Tx processed in block

Other validators re-execute all Tx to verify block ⇒ (5) Tx receipt root: Merkle hash of log messages generated in block
sign block if valid ⇒ enough sigs, epoch is finalized.
(5) Gas used: used to adjust gas price (target 15M gas per block)

24 25
The Ethereum blockchain: abstractly Amount of memory to run a node

prev hash prev hash ≈1.3 TB



accts. accts.

updated Tx log updated Tx log


world messages world messages ETH total blockchain size (archival): 16 TB (Oct. 2023)
state state

26 27

An example contract: NameCoin An example contract: NameCoin


contract nameCoin { // Solidity code (next lecture) function nameNew(bytes32 name) {
// registration costs is 100 Wei
struct nameEntry {
if (data[name] == 0 && msg.value >= 100) {
address owner; // address of domain owner
data[name].owner = msg.sender // record domain owner
bytes32 value; // IP address
emit Register(msg.sender, name) // log event
}
}}
// array of all registered domains Code ensures that no one can take over a registered name
mapping (bytes32 => nameEntry) data;
Serious bug in this code! Front running. Solved using commitments.

28 29
An example contract: NameCoin An example contract: NameCoin
function nameUpdate(
bytes32 name, bytes32 newValue, address newOwner) { function nameLookup(bytes32 name) {
// check if message is from domain owner, return data[name];
// and update cost of 10 Wei is paid }
if (data[name].owner == msg.sender && msg.value >= 10) {
} // end of contract
data[name].value = newValue; // record new value
data[name].owner = newOwner; // record new owner Used by other contracts
}}} Humans do not need this
(use etherscan.io)

30 31

EVM mechanics: execution environment The EVM


Write code in Solidity (or another front-end language) Stack machine (like Bitcoin) but with JUMP
• max stack depth = 1024
⇒ compile to EVM bytecode • program aborts if stack size exceeded; block proposer keeps gas
(some projects use WASM or BPF bytecode) • contract can create or call another contract

⇒ validators use the EVM to execute contract bytecode


In addition: two types of zero initialized memory
in response to a Tx
• 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

32 33
Every instruction costs gas, examples: Gas calculation
SSTORE addr (32 bytes), value (32 bytes) Why charge gas?
• Tx fees (gas) prevents submitting Tx that runs for many steps.
• zero ⇾ non-zero: 20,000 gas
• During high load: block proposer chooses Tx from mempool
• non-zero ⇾ non-zero: 5,000 gas (for a cold slot) that maximize its income.
• non-zero ⇾ zero: 15,000 gas refund (example)
Old EVM: (prior to EIP1559, live on 8/2021)
Refund is given for reducing size of blockchain state
• Every Tx contains a gasPrice ``bid’’ (gas ⇾ Wei conversion price)
CREATE : 32,000 + 200×(code size) gas; CALL gas, addr, value, args • Producer chooses Tx with highest gasPrice (max sum(gasPrice×gasLimit))
SELFDESTRUCT addr: kill current contract (5000 gas) ⟹ not an efficient auction mechanism (first price auction)

34 35

Gas prices spike during congestion Gas calculation: EIP1559 (since 8/2021)

GasPrice in Gwei:
EIP1559 goals (informal):
86 Gwei = 86×10-9 ETH
• users incentivized to bid their true utility for posting Tx,
• block proposer incentivized to not create fake Tx, and
• disincentivize off chain agreements.

Average Tx fee in USD congestion

[ Transaction Fee Mechanism Design, by T. Roughgarden, 2021 ]

36 37
Gas calculation: EIP1559 Gas calculation
Every block has a “baseFee”:
EIP1559 Tx specifies three parameters:
the minimum gasPrice for all Tx in the block • gasLimit: max total gas allowed for Tx
• maxFee: maximum allowed gas price (max gas ⇾ Wei conversion)
baseFee is computed from total gas in earlier blocks: • maxPriorityFee: additional “tip” to be paid to block proposer
• earlier blocks at gas limit (30M gas) ⟹ base fee goes up 12.5% interpolate
in between
Computed gasPrice bid:
• earlier blocks empty ⟹ base fee decreases by 12.5%
gasPrice ⇽ min(maxFee, baseFee + maxPriorityFee)

If earlier blocks at “target size” (15M gas) ⟹ base fee does not change Max Tx fee: gasLimit × gasPrice

38 39

Gas calculation (informal) Gas calculation


gasUsed ⇽ gas used by Tx (1) if gasPrice < baseFee: abort
(2) If gasLimit×gasPrice < msg.sender.balance: abort
(3) deduct gasLimit×gasPrice from msg.sender.balance
Send gasUsed×(gasPrice – baseFee) to block proposer
(4) set Gas ⇽ gasLimit
BURN gasUsed× baseFee (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
⇒ total supply of ETH can decrease (7a) BURN gasUsed× baseFee
(7b) Send gasUsed×(gasPrice – baseFee) to block producer

40 41
Example baseFee and effect of burn Why burn ETH ???
block # gasUsed baseFee (Gwei) ETH burned
15763570 21,486,058 16.92 ↓ 0.363
Recall: EIP1559 goals (informal)
15763569 14,609,185 (<15M) 16.97 0.248 • users incentivized to bid their true utility for posting Tx,
15763568 25,239,720 15.64 0.394 • block proposer incentivized to not create fake Tx, and
15763567 29,976,215 13.90 ↓ 0.416 • disincentivize off chain agreements.
15763566 14,926,172 (<15M) 13.91 ↓ 0.207
15763565 1,985,580 (<15M) 15.60 0.031
Suppose no burn (i.e., baseFee given to block producer):
≈ gasUsed×baseFee
beacon chain ⟹ in periods of low Tx volume proposer would try to increase
baseFee < 16Gwei ⇒ new issuance > burn ⇒ ETH inflates volume by offering to refund the baseFee off chain to users.
baseFee > 16Gwei ⇒ new issuance < burn ⇒ ETH deflates
42 43

Note: transactions are becoming more complex

END OF LECTURE

Gas usage is increasing ⇒ each Tx takes more instructions to execute

44 45

You might also like