fevm is an EVM written in Fe and compiled
to native code by Fe's native backend (Sonatina and Cranelift). It implements
Osaka, the current mainnet fork, and Amsterdam, the next: every opcode and
precompile, and the state transition of one transaction, by the rules of the
fork a host selects. It passes all 14,640 runnable Osaka and 16,883 runnable
Amsterdam state tests of execution-spec-tests tests@v21.0.2. It also drives
Fe's native compiler, standard library and language development with a real
systems program.
The repo is a Fe workspace:
ingots/evm: the interpreter library and thefevmCLIingots/precompiles: the precompiled contracts, which Amsterdam keepsingots/rlp: RLP encoding and strict decodingingots/chain: the chain layer, which decodes, validates and imports blocksnative/client: a Rust client forfevm serve, the session modenative/conformance: the Ethereum state and blockchain test drivernative/differential: frame and state comparisons against revmnative/bench: state-test benchmarks against revm and evmonenative/soak,native/fixtures,native/arith: resident-memory, allocation-failure and compiler arithmetic checksnative/tools: the acceptance suite, the state-test and benchmark runners and fevm's other checks written in Fenative/bootstrap.py: the pinned compiler build
The interpreter depends on swisstable
for growable hash tables and keccak for
Keccak-256; ingots/evm/fe.toml pins both to Git revisions.
fevm needs Fe master 6ccb3ca8e
(argotorg/fe#1992) with its pinned
Sonatina and Rust 1.99.0.
native/toolchain.json records the revisions and lock
hash, and bootstrap builds that compiler. Native hosts are x86_64 Linux and
AArch64 macOS.
python3 native/bootstrap.py --out native/out/toolchain --toolchain 1.99.0
native/out/toolchain/bin/fe build . --backend native --ingot fevm -O 2 --out-dir outfevm [--fork osaka|amsterdam] <hex-bytecode> [hex-calldata] runs the code
once in an empty world with default call and block values, by the rules of
the fork it names (Osaka without --fork). It prints the returned bytes, or
the top of the stack as a 32-byte word, or empty. On failure it prints the
status name (revert with the revert data) and exits with the status code.
./out/fevm 0x600260030100 # PUSH1 2; PUSH1 3; ADD; STOP
0x0000000000000000000000000000000000000000000000000000000000000005
./out/fevm 0x602a5f5260205ff3 # RETURN 32 bytes
./out/fevm 0x5f3500 0x1234 # CALLDATALOAD
./out/fevm 0x01 # stack_underflow, exit 10
./out/fevm --fork amsterdam 0x600160026003e88e50 # EXCHANGE, then POP: 1fevm serve keeps one world and answers binary requests on stdin: settings,
block values, account and storage writes and reads, transactions that commit
or only simulate, snapshots and reverts. It is how programs not written in Fe
use fevm; native/client has a Rust client and
the protocol.
An Evm holds a world across transactions, with the allocations they
reuse (frame memory, stacks and child frames, the journal and a transaction's
tables):
var evm = Evm::new(world, Config::osaka())
let receipt = evm.transact(request, block, mut tracer)
let balance = evm.world().balance(address)
transact runs one transaction and keeps its changes; simulate runs it the
same way and keeps none; validate only checks that it could be included.
Between transactions a host reads the world with world() and writes it with
world_mut(); set_world and into_world replace it and take it back.
WorldStateholds accounts, code, storage and block hashes. Set up accounts withset_balance,set_nonce,set_codeandstorage_store, and block hashes withset_block_hash.try_clonecopies the world, so a host can keep a snapshot and return to it.- A
TxRequestholds aTxEnv(envelope kind, signed chain ID, recovered sender, recipient or creation flag, nonce, gas limit, fee fields, value) with owned calldata or initcode, access-list entries, blob hashes and EIP-7702 authorizations. fevm takes the recovered sender; decoding and checking signed envelopes belongs to the host. BlockEnvholds the block's values and the chain ID.Configholds the host's settings, whichset_configchanges between transactions: the fork, the EIP-170 and EIP-3860 code size limits, EIP-7825's 2^24 gas cap, and the chain ID, nonce, base fee and EIP-3607 sender checks.Config::osaka()andConfig::amsterdam()are mainnet's; Amsterdam raises the code size limits (EIP-7954), and from it the cap bounds a transaction's execution gas, the gas past it being state gas (EIP-8037). A test harness may raise the limits or skip the checks; a transaction priced below the base fee then pays its own price and no priority fee.tracerwatches the transaction run (below);()traces nothing.
An invalid transaction changes nothing and returns a receipt whose
invalid field names the reason. A valid one buys its gas, increments the
sender's nonce, warms the sender, recipient, coinbase, precompiles and access
list, applies its authorizations, runs the call or creation, charges at least
the EIP-7623 calldata floor, refunds unused gas and the capped refund, pays the
priority fee, and deletes self-destructed new accounts and touched empty
accounts. The receipt has the status, gas used and refunded, the gas it adds
to the block's totals (from Amsterdam, execution gas before refunds and state
gas apart), the created contract's address, the output and the logs. A host failure (allocation,
balance overflow) undoes the transaction and reports that status.
A Block runs a block's transactions on an Evm's world, which it holds
from begin to finish or abandon:
var block = Block::begin(evm, env, parent_hash, parent_beacon_block_root)
let receipt = block.transact(request, mut tracer)
let (evm, finished) = block.finish(withdrawals) // or: let evm = block.abandon()
begin records the parent hash for BLOCKHASH and makes the system calls
that store the parent beacon block root (EIP-4788) and the parent hash
(EIP-2935), except for the genesis block, which has no parent. transact
runs a transaction if the block has the gas and blob gas left for it
(Config has the fork's blob limit), and its receipt has the cumulative gas
used; simulate tries one without counting it. finish
credits the withdrawals (EIP-4895), collects the block's requests (EIP-7685):
the deposits its transactions logged (EIP-6110) and those the withdrawal and
consolidation request contracts return to their system calls (EIP-7002,
EIP-7251; from Amsterdam the builder request contracts too, EIP-8282). It
returns the Evm, and a BlockOutput with what the header commits to apart
from its Merkle roots: gas used (from Amsterdam the larger of execution and
state gas, EIP-7778), blob gas used, the logs bloom, the requests with their
hash, from Amsterdam the block's access list (EIP-7928) with its hash, and
the block's changes. A block whose request contract is missing or fails,
whose deposit contract logged a malformed deposit, or whose access list is
too large for its gas limit gives a BlockError instead, and finish undoes
it.
The access list is built as the block runs. A read is noted where its gas has been paid, the point at which an account or slot is warmed, and stays through reverts. Changes are not tracked as they are written: when a transaction ends, the journal's surviving entries name what it changed with the values it began with, so a write that restored a value counts as a read. Outside a block, and in a simulation, nothing is recorded.
The block's changes (BlockChanges) are each account it changed, with
whether it existed and the balance, nonce and code it changed as they were
before, each storage slot it changed with its value before, and the
BLOCKHASH entries begin wrote. The values after are the world's, and may
be those before. Code changes only on an account without code or with an
EIP-7702 delegation, so the code before is none or a delegation. A host
persists the changes or computes the state root from them, and undoes the
block with them. They come from the journal in the same pass as the access
list, when each transaction, system call or the withdrawals end, and only a
Block records them. A transaction whose changes cannot be recorded for
want of memory is undone and fails as a host failure, so the changes always
undo the block:
let Result::Ok(output) = finished else { return }
for account in output.changes.accounts() {} // account.address, .existed, .balance, .nonce, .code
for slot in output.changes.slots() {} // slot.address, .slot, .value
output.changes.undo(mut evm.world_mut()) // the world as it was before `begin`
abandon undoes the block as it stands. Block does not check a header
against its parent, decode transactions or compute Merkle roots; a Chain
does these.
ingots/chain (fevm_chain) imports blocks as a client does, from their
RLP. A Chain holds an Evm on the world after its head block, the state
trie of that world (StateTrie), the forks by activation time (Schedule,
each fork a Config with its blob schedule) and the chain ID:
var schedule = Schedule::new(Config::osaka())
schedule.add(timestamp: 15_000, bpo1)
var chain = Chain::new(world, schedule, chain_id: 1, genesis: Header::decode(genesis_rlp).unwrap())
match chain.import(block_rlp, mut tracer) {
Import::Valid(imported) => {}, // imported.receipts, imported.output
Import::Invalid(reason) => {}, // the rule the block breaks
Import::Failed(failure) => {}, // a host failure: no verdict
}
let head = chain.head().hash
let root = chain.state_root() // the head's, from the trie
import follows the specification's execute_block: it rejects a block
whose RLP is longer than EIP-7934's limit, decodes the block, checks its
header against the head's by the rules in force at its timestamp and that it
has no ommers, then runs its transactions through Block, decoding each and
recovering its sender as it comes to it (tracer sees them run), credits
its withdrawals, and
compares the gas used, the transactions, state, receipts and withdrawals
roots, the logs bloom, the blob gas used, the requests hash and, from
Amsterdam, the access list hash with the header's. A valid block becomes the
head, and Imported has its receipts and BlockOutput. InvalidBlock names
the first rule an invalid block breaks; a host failure (an allocation, a
balance past 2^256, a blob base fee too large to compute) is no verdict on
the block.
Either leaves the world and the head as they were: the chain undoes the
block from its changes.
The state root is kept incrementally. Chain::new builds the trie of the
whole world once. After each block the chain rereads into it the accounts
and slots the block's changes name, and the root rehashes only their
paths; a block rejected after it ran is undone and its keys reread. The trie holds a
node for every account and slot of the world with its hash, besides the
world itself: about 100 MB more for 100,000 accounts of 10 slots, a third of
what that world takes. A trie that an allocation failed is rebuilt from the
world before the next block. A host that keeps the state in its own storage
would not use Chain, but Block, the changes it gives, and its own trie.
state_root(world) computes the root of a whole world in one pass.
The chain has one head: a block whose parent is not the head fails header validation, so side branches and reorganizations are left to a host. Forks before Osaka are not implemented.
The fork is a type. Rules gives a fork's rules as constants, each defined
once from the fork it begins in, so a fork is one line:
pub trait Rules {
const FORK: Fork
// EIP-7843: SLOTNUM pushes the slot number.
const SLOTNUM: bool = Self::FORK.since(Fork::Amsterdam)
// EIP-2929 and EIP-8038: the first access of an account in a transaction.
const COLD_ACCOUNT_ACCESS: u64 = if Self::FORK.since(Fork::Amsterdam) { 3000 } else { 2600 }
// ...
}
pub struct Amsterdam {}
impl Rules for Amsterdam { const FORK: Fork = Fork::Amsterdam }
Evm's transact, simulate and validate, and Vm::run, match Config.fork once and
run code generic over its Rules type, as they are over the tracer. Each fork
compiles to its own interpreter, with its rules folded into its code: Osaka's
dispatch table sends SLOTNUM and DUPN to the invalid opcode path, and its code
has no state gas in it. A host may switch forks between transactions; the
world and the Evm's allocations are the same for every fork.
A tracer is any type that implements Tracer, whose hooks do nothing by
default:
pub trait Tracer {
fn step(mut self, _ step: Step) {}
fn enter(mut self, _ call: CallStart, input: MemSpan) {}
fn leave(mut self, _ call: CallEnd, output: MemSpan) {}
}
step runs before every opcode with its pc, the gas, stack depth and memory
size, and the call depth. enter runs when a call or creation enters its frame
(opcode, caller, target, value, gas, input) and leave when it leaves (status,
gas left, output), the transaction's own message included. transact is
generic over the tracer, so () compiles to the same code as an interpreter
without hooks. Trace is a tracer that records the steps, the calls or both;
fevm serve uses it.
ingots/evm/src/status.fe defines every status with its name
(write_status_name, write_invalid_name):
| code | name | kind |
|---|---|---|
| 0 | success |
EVM outcome |
| 19 | revert |
EVM outcome |
| 10, 11 | stack_underflow, stack_overflow |
exceptional halt |
| 15, 16, 17, 18 | out_of_gas, invalid_jump, invalid_opcode, return_data_oob |
exceptional halt |
| 23, 24, 25 | static_write, code_prefix, precompile_failure |
exceptional halt |
| 27 | address_collision |
exceptional halt (creation transactions) |
| 21, 26 | host_allocation, balance_overflow |
host failure |
Exceptional halts consume all of a frame's gas. Host failures abort the whole
execution; EVM code never sees them. Validity codes (VALID and
INVALID_*, such as nonce, intrinsic_gas, chain_id) are in the same
file.
execute and execute_vm run one frame's code against a Transaction, the
journaled view of a WorldState during a transaction. Transaction
checkpoints nest: a child commit stays reversible by its parent, and every
frame runs under its own. finish(commit, gas_spent) returns the state, logs,
capped refund and net gas used. CALL and CREATE children run on an explicit
frame stack, so the 1,024-frame depth limit does not depend on the native
stack.
Every owner, from results and logs to the world, frees its memory when it goes out of scope or is overwritten. Allocation failure is a host failure, distinct from an EVM halt.
native/out/toolchain/bin/fe build . --ingot fevm_tools --backend native -O 2 \
--emit executable --out-dir native/out/tools
native/out/tools/fevm_tools accept --build native/out/toolchain/build.json \
--out native/out/acceptance --check-only
native/out/tools/fevm_tools conformance --fe native/out/toolchain/bin/fe \
--fixtures <execution-spec-tests>/fixtures/state_tests --out native/out/conformanceAcceptance runs nine stages: the workspace tests at O0, O1 and O2, CLI and
allocation-failure checks, the Osaka frame and state comparisons against revm,
a build of fevm_tools, the session client's tests and the arithmetic matrix
(native/README.md). The
state and blockchain test runner is
separate; the 25 state tests of each fork it does not count have malformed
signatures, which fevm, given a recovered sender, never sees. Benchmarks time the
evm-benchmarks state tests against revm and evmone.
fevm is licensed under the Apache License, Version 2.0.