Skip to content
LogoLogo

Architecture

Guillotine Mini is structured around three boundaries: Evm orchestrates transaction state and nested calls, Frame executes bytecode for one call context, and HostInterface connects to external state when you do not want ephemeral in-memory maps.

Guillotine Mini — Three-Layer Execution Architecturesrc/*.zig
vm.call(CallParams) / root_c.zigEvm(config) · src/evm.zig — Transaction OrchestratorArenaAllocator (freed on deinit)Storagepersistent · originaltransient (EIP-1153)AccessListManagerwarm/cold addresseswarm/cold slots (2929)Snapshot Stacksbalances · nonces · codecopy-on-write rollbackNested Calls & Logsinner_call · inner_creategas_refund · Tracerframes stack (depth ≤ 1024)optional vtable (host != null)Frame(config) · src/frame.zig — Bytecode InterpreterStack1024 × u256Memorybyte-addressed · 32BBytecodeJUMPDEST bitmapHostInterface · src/host.zigget/setBalance · get/setCodeget/setStorage · get/setNonceaccountExists? · deleteAccount?Voltaire (@import("voltaire") · "crypto" · "precompiles")Address · Hardfork · GasConstants · RLP · Log · Keccak256 · secp256k1 · BN254 · BLS12-381 · KZG · P256VERIFY
Evm owns transaction-scoped state and nested call orchestration. Frame is a pure bytecode interpreter operating on stack, memory, and PC. HostInterface is an optional vtable for external state.

The Evm / Frame split

The Python execution-specs store stack, memory, program counter, storage, and call state on a single object. Guillotine Mini separates per-transaction state from per-call execution state so each module fits in one file and can be tested independently.

ComponentSourceOwnsDoes not own
Evm(config)src/evm.zigStorage (persistent, original, transient), AccessListManager, balances, nonces, code, copy-on-write snapshot stacks, gas_refund, logs, frames, tracer, arenaStack, memory, PC, opcode decoding
Frame(config)src/frame.zigOperand stack (≤ config.stack_size), byte-addressed memory, pc, gas_remaining, Bytecode (JUMPDEST bitmap), output, return_data, is_staticCross-frame storage, account balances, snapshots
HostInterfacesrc/host.zigExternal account/storage persistence via an 11-pointer vtableEVM semantics or nested call dispatch

Inside a frame, opcodes that touch account state or spawn sub-calls (SLOAD, SSTORE, BALANCE, CALL, CREATE, SELFDESTRUCT) call back into the parent EVM via frame.getEvm(). initTransactionState() reserves max_call_depth + 1 slots in Evm.frames so frame pointers stay stable through nested calls, and evm.zig indexes self.frames.items[self.frames.items.len - 1] after a nested call returns.

Memory and arena ownership

Evm embeds a std.heap.ArenaAllocator backed by the allocator passed to init(). Every transaction-scoped allocation — frame stacks, memory buffers, bytecode analysis, log slices, snapshots, and CallResult outputs — comes from that arena.

  • No per-frame leak risk. An execution error (OutOfGas, StackUnderflow, InvalidJump) returns immediately; deinit() frees the entire arena in one call.
  • Borrowed results by default. Slices inside a CallResult returned by vm.call() point into vm.arena. Call result.toOwnedResult(allocator) before vm.deinit() if the result must outlive the EVM.
  • Standalone tracer memory. Tracer takes its own allocator so traces survive after vm.deinit().

Exact lifecycle of vm.call()

Evm.call() is the single entry point for all six CallParams shapes (call, callcode, delegatecall, staticcall, create, create2).

Inside vm.call(params) — Exact Execution Ordersrc/evm.zig · call()
1Validateinput ≤ 4 MBinitcode ≤ 48 KB2Resolve TargetCREATE/2 addr or tosender = vm.origin3Reset & WarminitTransactionState()preWarmTransaction()4DispatchCREATE, or get_code()→ Precompile / FrameSTOP / RETURN (success = true)Copy output & logs · expose refund_counter · commit stategas_left = frame.gas_remainingREVERT / CallError (success = false)Reverse value transfer · restore snapshots · drop logsREVERT keeps gas_left + output; errors burn gas & set error_info5. End-of-tx cleanup: clear warm sets → clear transient storage (EIP-1153) → delete selfdestructed (EIP-6780) & empty accounts
Step 3 resets per-transaction state (original and transient storage, warm sets, logs, refunds) but keeps balances, nonces, code, and committed storage. Step 4 reads the target code after that reset.

Five implementation details in src/evm.zig are worth knowing before you write host code:

  1. Intrinsic gas is the caller's job. vm.call() assumes the gas passed in params is already net of the 21,000 transaction base fee, calldata cost (including EIP-7623 floor), access list fees, and create fees.
  2. Seeded state survives initTransactionState(). Each vm.call() first runs initTransactionState(), which resets original and transient storage, warm sets, logs, the refund counter, and the snapshot stacks. It does not clear balances, nonces, code, or storage seeded with setStoragePrestate(), so without a host you can seed any number of accounts with vm.code.put, vm.balances.put, and vm.nonces.put, and the state persists across calls.
  3. Top-level value transfer happens only with a host. In vm.call(), value is moved from caller to address when value > 0 and self.host != null (and reversed if the top-level call reverts or errors).
  4. Refunds are returned, not auto-applied. CallResult.refund_counter reports the raw refund counter; the caller applies the fork-dependent cap (gas_used / 5 from London onward, gas_used / 2 earlier) after settling coinbase fees.
  5. End-of-tx cleanup runs in spec order. Warm sets clear, transient storage (EIP-1153) clears, then accounts marked by SELFDESTRUCT (EIP-6780) and touched empty accounts (EIP-161) are removed.

Bytecode analysis and dispatch

src/bytecode.zig scans contract bytecode once when a Frame starts:

  • It builds a JUMPDEST bitmap by skipping over PUSH1..PUSH32 immediate bytes, so 0x5b bytes inside push data are never accepted by JUMP or JUMPI.
  • Truncated PUSH immediates at the end of bytecode are zero-padded on the right per the Ethereum specification.
  • Frame.execute() calls Frame.step() in a loop; Frame.executeOpcode() in src/frame.zig dispatches each opcode through a switch to the category handler files in src/instructions/ (handlers_arithmetic.zig, handlers_storage.zig, handlers_system.zig, etc.). src/instructions/dispatcher.zig is a standalone Dispatcher exported from root.zig; Frame does not use it.
  • In Debug and ReleaseSafe builds, EvmConfig.loop_quota defaults to 1_000_000 steps to catch runaway loops early; in ReleaseFast / ReleaseSmall it defaults to null (unlimited).

C ABI and WebAssembly surface

Both zig build native (static library libguillotine_mini.a) and zig build wasm (WASI Preview 1 reactor guillotine_mini.wasm) compile the same entry file: src/root_c.zig.

  • An opaque *EvmHandle wraps an ExecutionContext (the Evm, staged bytecode/calldata, access lists, blob hashes, and last CallResult).
  • Every exported function that takes a handle accepts null and returns a safe zero/false sentinel.
  • On wasm32-wasi, evm_alloc and evm_free manage host transfer buffers in linear memory, and the two env imports (js_opcode_callback, js_precompile_callback) let hosts intercept any precompile, or any opcode after evm_set_js_opcode_callbacks_enabled(true), without recompiling Zig.

Source layout

src/
├── root.zig                 # Public Zig module exports
├── evm.zig                  # Evm(config): state, call(), inner_call(), inner_create()
├── frame.zig                # Frame(config): stack, memory, PC, execute(), step()
├── bytecode.zig             # JUMPDEST bitmap & PUSH immediate reader
├── storage.zig              # Persistent, original, and EIP-1153 transient storage
├── access_list_manager.zig  # EIP-2929 warm/cold tracking + EIP-2930 pre-warming
├── host.zig                 # HostInterface vtable
├── call_params.zig          # 6-variant CallParams union & validation
├── call_result.zig          # CallResult, logs, selfdestructs, owned cloning
├── evm_config.zig           # Comptime EvmConfig, OpcodeOverride, PrecompileOverride
├── errors.zig               # CallError error set
├── trace.zig                # EIP-3155 Tracer, TraceEntry, TraceDiff
├── async_executor.zig       # Yield/resume state-injection state machine
├── storage_injector.zig     # Async cache & state-change JSON serializer
├── root_c.zig               # Exported C & WASM ABI (42 evm_* symbols)
└── instructions/            # Opcode handlers grouped by category