Library SetcodeConcrete.consensuscorrectness

SETCODEFROM: consensus checks and successful block execution

Consensus checks an ordered list of transactions before the preceding blocks have executed. It knows their signatures and public fields, but not the balances or code produced by those executions. Ordinary fees must fit a remaining gas budget G; eligible emptying transactions may instead use the snapshot balance. Execution enforces reserve checks that protect the money needed by subsequent admitted transactions.
This page describes the pre-MCP configurable-reserve model with SETCODEFROM enabled. It uses execution delay K = 3 and explicit experimental gas prices, not a deployed network revision. The native changes follow the pinned MIP-19 and its adopted portions of EIP-8298.

What consensus knows

For block n, the intended designated snapshot is the execution state after h = n-3. Consensus checks the ordered blocks h+1 through n against that fixed snapshot. It does not execute their contract code.
    snapshot after h | block h+1 | block h+2 | block n
                     <----- known transactions ----->
                     <--- unknown execution states -->
A successful, non-reverted reserve setting in block b becomes effective at b+3. Consequently, settings requested after h cannot change the thresholds used through n. reserveAt reads the snapshot's stored configuration at the candidate block height, including a pending value once effective. Empty blocks also apply the height-based budget cap. A reserve increase does not replenish an already initialized gas budget.

What changes when an account adopts code

SETCODEFROM replaces the execution-context account's code with existing code. For a delegated account, adoption requires either that it is the current transaction sender or that its active reserve is zero. Reverting the call rolls back adoption. The current frame keeps its loaded code; later calls use the new code.
A sender that adopts regular code remains reserve-protected in its own transaction. A send in block b also protects the account in later blocks t satisfying b < t < b+3. Merely becoming a contract does not release that protection. See the generated contract-exemption rule and reserve check.
If a subsequent, already-admitted transaction's sender now has regular code, execution charges its full gas-limit fee and records failure. It does not execute the body or transfer its value; authorization processing still occurs. The sender nonce becomes max(actual nonce, signed nonce)+1. Fresh admission still rejects senders with regular code. Thus the theorem retains the original admission; it does not promise fresh admission from the post-migration state.

The actual consensus checks

The definitions in consensuschecks are the ones used in the proofs. The HTML build inserts their checked source here, with original links; it does not maintain another implementation for presentation. In source form, follow AdmissionState, initialAdmission, checkTransaction, and checkBlocks.

Public consensus checks for the SETCODE experiment

The designated snapshot stays fixed while consensus checks the ordered blocks. No VM execution is performed. Nonces use the shared QEDK authorization calculation. Gas budgets use the QEDK ordinary/emptying rules; MIP-19 changes emptying activity to include every recovered authority, including authorizations that do not apply.
Fresh admission rejects regular-code senders in the snapshot. These checks must not be rerun against an intermediate execution state to justify transactions that were already admitted before migration.
From Stdlib Require Import List String ZArith Bool.
From stdpp Require Import decidable numbers strings list.
Require Import RocqOfOCaml.RocqOfOCaml MonadVM.Execution
  QedkConcrete.transactionchecks QedkConcrete.admissionnonces.
Set Default Goal Selector "!".
Import ListNotations.
Local Open Scope Z_scope.
asbool P is true exactly when the decidable proposition P holds. All budget arithmetic below uses mathematical integers measured in wei.
Local Abbreviation asbool := bool_decide.
Module E := Execution.Make.
Module W := State.WorldState.
Module A := Chain.Ethereum.Account.
Module T := Chain.Ethereum.Transaction.
Module Addr := Chain.Ethereum.Address.
Module Block := Chain.Ethereum.Block.

Read address a's account in execution state snapshot. An absent address gives the native empty account, not an error.
Whether a has empty code or a delegation marker in snapshot. Regular contract code returns false; this does not test a signature.
Account a's snapshot balance in wei, read as a mathematical integer.
Account a's configured reserve in wei for block height, read only from snapshot. The generated lookup reads the reserve precompile's storage and selects the pending value when its activation height is reached. It does not execute a setter or mutate the snapshot. See user_reserve_balance and active.
Public accounting before checking the next transaction, not an execution state. The designated execution snapshot is supplied separately.
Record AdmissionState := {
  
For each address, its next predicted nonce after the transactions already checked. Sender increments precede applied authorizations. VM creation after migration can make the actual nonce differ.
Addresses of prior senders and all recovered authorities after the snapshot. Membership, not order or multiplicity, governs emptying. It includes earlier blocks and earlier transactions in this block, but not the candidate until checkTransaction updates this record.
  admissionActivity : list Addr.t;
  
For address a, remaining gas budget G_a in wei. Earlier fee bounds, emptying value debits and block-boundary caps are already deducted. This is neither its balance nor its configured reserve.
  admissionBudgets : Addr.t → Z
}.

Return all recovered authorities of tx. Chain-ID, nonce and code checks do not filter this list: they affect nonce increments, not this activity.
Definition recoveredAuthorities (tx : T.t) : list Addr.t :=
  Stdlib.Lists.List.fold_right (fun auth rest ⇒ match T.Authorization.authority auth with
    | Some a ⇒ a :: rest | None ⇒ rest end) [] (T.authorization_list tx).

Initialize consensus before checking any transaction. snapshot supplies balances, nonces, code and stored reserve settings. height is the reserve lookup height, normally the snapshot's height. Result: snapshot nonces, empty subsequent activity, and G_a = min(snapshot balance, reserve effective at height). The empty activity list does not erase earlier history: emptying also checks the counter stored in snapshot.
Definition initialAdmission snapshot height : AdmissionState :=
  {| admissionNonces := fun a ⇒ A.t.nonce (accountAt snapshot a);
     admissionActivity := [];
     admissionBudgets := fun a ⇒ Z.min (balanceAt snapshot a) (reserveAt snapshot height a) |}.

Test emptying for sender in height, including the candidate's recovered authorities. previous accounts for earlier transactions after snapshot. The snapshot counter accounts for earlier history. authorities is the current transaction's recovered-authority list, including authorizations that will not apply. True permits the budget exception; false requires the ordinary budget. No state is changed. Requiring empty snapshot code rules out delegated and regular accounts.
F supplies the executor's chain ID, revision and tracing flag. These public checks use the chain ID, not future execution states.
Context {F : E.FArgs}.

Check tx in header against the fixed snapshot and the result previous of preceding public checks. None rejects it. Some next contains its updated nonce prediction, activity and remaining budgets. snapshot is the designated execution state, never the state resulting from earlier transactions. header supplies candidate height and base fee. previous already includes the block's reserve cap. tx is the signed transaction. The snapshot and other senders' budgets are unchanged.
The fee bound is gas limit times effective gas price, in wei. An ordinary sender requires fee <= G and subtracts the fee. An emptying sender requires fee <= snapshot balance and sets its remaining budget to min(max(snapshot balance - fee - value, 0), current reserve). A zero remaining budget is acceptance, not rejection.
transactionChecks checks the predicted nonce, sender-code eligibility and public transaction constraints; the following comparison checks fees. admittedNoncesAfter increments the sender, then processes authorizations in order. Only applicable authorizations increment predicted nonces, whereas every recovered authority counts for emptying activity.
Definition checkTransaction snapshot (header : Block.Header.t) previous tx
    : option AdmissionState :=
  match T.sender E.Params.(Execution.Make_Params_signature.chain_id) tx,
    Gas.tx_effective_gas_price (Block.Header.t.base_fee_per_gas header) tx with
  | Some sender, Some price ⇒
      if transactionChecks header tx (admissionNonces previous sender)
        (A.is_smart_contract (accountAt snapshot sender)) then
      let authorities := recoveredAuthorities tx in
      let fee := Z.of_N (T.gas_limit tx × price) in
      let height := Block.Header.t.number header in
      let emptying := allowsEmptying snapshot previous sender height authorities in
      let available := if emptying then balanceAt snapshot sender else admissionBudgets previous sender in
      if asbool (fee ≤ available) then
      let remaining := if emptying
        then Z.min (Z.max (available - fee - Numeric.U256.to_z (T.value tx)) 0)
          (reserveAt snapshot height sender)
        else available - fee in
      Some {| admissionNonces := admittedNoncesAfter (eligibleAt snapshot)
                (admissionNonces previous) sender tx;
              admissionActivity := sender :: authorities ++ admissionActivity previous;
              admissionBudgets := fun a ⇒ if asbool (sender = a)
                then remaining else admissionBudgets previous a |}
      else None else None
  | _, _ ⇒ None
  end.

Check txs in order against one block header. Return the state after all checks, or None at the first rejection. No transaction is reordered or dropped. snapshot is fixed, header is common to these transactions, previous is the state before txs. The empty list returns previous. The caller caps budgets for the block before calling this.
Fixpoint checkTransactions snapshot header previous txs : option AdmissionState :=
  match txs with
  | [] ⇒ Some previous
  | tx :: rest ⇒ match checkTransaction snapshot header previous tx with
      | None ⇒ None | Some next ⇒ checkTransactions snapshot header next rest end
  end.

Check blocks in order, retaining snapshot for all account reads. Before every block, including an empty block, cap each G at that block's configured reserve. Increases do not replenish G. Return Some next exactly when every public transaction check passes; otherwise None. previous is freshly initialized or returned for an earlier prefix checked against this same snapshot. Empty blocks returns previous. Header rules and aggregate gas limits belong to miscBlockChecks, not this function. No VM code runs and no block is skipped.
Fixpoint checkBlocks snapshot previous blocks : option AdmissionState :=
  match blocks with
  | [] ⇒ Some previous
  | block :: rest ⇒
      let header := Block.t.header block in
      let capped := {| admissionNonces := admissionNonces previous;
        admissionActivity := admissionActivity previous;
        admissionBudgets := fun a ⇒ Z.min (admissionBudgets previous a)
          (reserveAt snapshot (Block.Header.t.number header) a) |} in
      match checkTransactions snapshot header capped (Block.t.transactions block) with
      | None ⇒ None | Some next ⇒ checkBlocks snapshot next rest end
  end.

Proposition that consensus accepts ordered blocks, starting with balances/nonces/configuration in snapshot and reserve lookup height. It holds exactly when checkBlocks returns a state rather than None. It does not assert execution success, the initial-state conditions or the additional block checks.
From Stdlib Require Import List NArith.
Require Export SetcodeConcrete.consensuschecks SetcodeConcrete.consensusconditions.
Require Import QedkConcrete.miscblockchecks.
Import ListNotations.

Main guarantee

The checks protect fee payment; they do not promise a successful VM receipt. Neither a VM revert nor the intentional failure of a migrated sender's transaction is an Invalid_transaction or Invalid_block.
ResourceProtocolConditions selects the experimental revision, requires positive cold/warm source-access gas prices and a bounded chain ID, and supplies the approved hash-size and BLS cofactor facts.
SetcodeWindowConditions requires native input bounds, well-formed initial accounts/configuration/counters, prescribed system bytecode, and total initial balance plus withdrawal credits below 2^256. Transaction senders initially have empty code or delegation markers. Their addresses cannot be created along the reached execution; senders and recovered authorities exclude the reserve precompile address. All block heights b satisfy b <= until < b+3. Protected initial nonces and the window's total nonce allowance are each below 2^63. The allowance counts transactions, authorization entries and gas limits; the proof bounds VM CREATE increments using gas. None of these premises assumes fee sufficiency, nonce agreement, validation success or successful prefix execution.
miscBlockChecks requires a parent header for nonempty input, consecutive heights, native header/data validity and total transaction gas limits within each block's limit. It does not execute the VM.
Block execution uses verify = false: it computes execution results but does not compare supplied execution commitments with them. Transaction validation and native block validation remain enabled. The model excludes staking. Library abstractions, opaque exception fallbacks and finite recursive-module translation remain; this is not a proof of native exception freedom, translator correctness or all deployed Monad code.
Section Consensus.
F supplies only the generated executor's chain ID, revision and tracing flag; it supplies no execution-state invariant or correctness premise. cold, warm, access, write and reserve are gas prices for cold/warm source access, current-account access, code writing and reserve lookup. The main proposition constrains their configured revision explicitly.
Context {F : E.FArgs}.
Context (cold warm access write reserve : N).

Execute the ordered blocks from execution state snapshot, with execution-result verification disabled. inl post returns the state after all blocks; inr error is the first block-processing error. The empty list returns snapshot. This wraps the generated process_block, not an abstract VM contract.
Parameters of the main proposition:
  • snapshot: execution state used for the original consensus check.
  • senders: list containing every recovered transaction sender in past ++ rest; duplicates are harmless.
  • until: upper height with b <= until < b+3 for every supplied block.
  • height: height used to read reserves when initializing gas budgets; for the intended new window, the designated snapshot's height.
  • past: ordered prefix to execute now; rest: ordered remaining blocks. Either list may be empty. All admission checks use the same snapshot.
Result: execution of past returns post. Its actual balances cover remaining consensus budgets, unmigrated senders' nonces agree with the original prediction, and capacity for remaining fees, nonce increments and withdrawals is preserved, as specified by RemainingWindowInvariant. The remaining miscellaneous block checks also pass.
setcode_consensus_correct proves this exact definition. Taking rest empty proves successful execution of the entire accepted window. The suffix corollary proves that rest executes from a reached post without either block error. It uses the original admission, not fresh sender-code checks. The equivalence lemma proves that this existential formulation has the same premises and conclusion as the earlier match-on-result statement.

Illustration: migration after admission

Both transactions were signed and admitted against a snapshot where Alice is delegated. Assume the theorem's fee, input and window conditions. T0 makes Alice adopt regular code. T1 was already admitted before that execution; it must not be reclassified as a fresh transaction.
  1. Consensus snapshotAlice is delegated.Admit T0, then T1.
  2. Execute T0Alice adopts regular code.Reserve remains protected.
  3. Execute admitted T1Charge full gas-limit fee.No body or value transfer; failed receipt.
  4. Block processing succeedsNo validation/block error.Fresh admission would reject T1.
Formal results: execution of the admitted suffix, migrated transaction inclusion, and fresh-admission rejection. These are general theorems, not a Rocq evaluation of this specific fixture. The signed native regression test_migration_and_inflight in tests/setcode/setcode_acceptance.ml separately checks adoption, full gas charging, no value transfer, failed receipt and complete-block processing. The release links its exact source revision.
The validation-only theorem is retained off this page: unlike the main theorem, it covers either verification flag without miscBlockChecks, but allows block errors.