Library QedkConcrete.consensuscorrectness

Configurable reserves: consensus checks and correctness

Consensus admits transactions before their preceding blocks have executed. It therefore cannot use their actual resulting balances. Instead it tracks a lower bound on the money protected for fees; execution reverts transfers that would invalidate that protection. Nonces are simulated exactly, not pessimistically budgeted.
This is the proved pre-MCP QEDK design: one ordered transaction sequence, revision Eleven, execution delay K = 3. The definitions below are the algorithms used by the proofs, not a second explanatory model.

What consensus knows

To validate block n, consensus uses the designated state after h = n-3, plus the ordered transactions in blocks h+1 through n. It does not execute their contract code or use their resulting balances.
    snapshot after h | block h+1 | block h+2 | block n
                     <----- known transactions ----->
                     <--- unknown execution states -->

Delayed configuration

A successful setting in block b becomes effective at b+3. Same-block settings use the last surviving value; a setting from an earlier block cannot be replaced while pending. Reverted calls discard their settings. Activation is a height-based lookup, including in empty blocks.
Thus, every setting that can activate by n is already in the snapshot after h. reserveAt reads that snapshot's threshold for the requested height. No simulation of configuration-changing contract calls is needed.
The end-to-end consensus tests below illustrate the difference: a signed transaction with a 20 MON fee bound passes checkBlocks using snapshot 103, but fails using snapshot 102.
From Stdlib Require Import List String ZArith Bool.
From stdpp Require Import decidable numbers strings list.
Require Export QedkConcrete.consensusconditions.
Require Export QedkConcrete.miscblockchecks.
Require Import QedkConcrete.consensushistory QedkConcrete.publictransaction
  QedkConcrete.transactionchecks.
Set Default Goal Selector "!".
Short names: T contains signed transaction types and their fields; Addr is the account-address type; Header contains block-header fields. W.t is an execution state and Block.t is a block.
asbool P tests a decidable proposition: it is true exactly when P holds. elem_of a xs means that address a occurs in list xs. to_z reads a native unsigned word as a mathematical integer.
Local Abbreviation asbool := bool_decide.
blockNumber header reads the block height from header.
Local Abbreviation blockNumber := Header.t.number.

Consensus accounting

As blocks and transactions are checked in order, ConsensusState records the remaining gas budget G from the QEDK draft's "Consensus accounting" section, together with the information needed for nonce checks and emptying eligibility. It is not an execution state.
Record ConsensusState := {
  
Nonces and addresses of senders/authorization signers from transactions already checked after the snapshot, including earlier blocks in this window. See ConsensusHistory for which authorizations count.
For account a, the remaining gas budget G_a, in wei. Earlier gas-fee bounds, emptying debits and block-boundary reserve caps have already been accounted for. This is neither a predicted account balance nor the account's configured reserve.
  consensusBudgets : Addr.t → Z
}.

Check the sender's gas-fee bound and calculate its remaining gas budget.
Arguments (all amounts are in wei):
  • emptying: whether this transaction is emptying-eligible, as determined by the caller. This function does not check that eligibility.
  • snapshotBalance: the sender's balance in the designated snapshot S_h.
  • threshold: its reserve R_h(sender,b) for this transaction's block b.
  • previous: its remaining gas budget G_sender before this transaction, already capped at threshold by checkBlocks.
  • fee: the gas-fee bound F(tx), gas limit times effective gas price.
  • value: the transaction's explicit value transfer.
Result: None means the applicable comparison of fee with snapshotBalance or previous fails. Some remaining gives the sender's gas budget after this transaction, not its execution balance. Ordinary transactions require fee ≤ previous and subtract only fee. Emptying-eligible transactions require fee ≤ snapshotBalance and deduct fee + value from that balance, flooring at zero and capping at threshold. A zero result accepts this transaction but prevents later positive fees.
See the end-to-end consensus tests at the end of this page for diagrams of complete transaction acceptance and rejection, with links to their proofs.
Local Open Scope Z_scope.
Definition checkSenderBudget (emptying : bool)
    (snapshotBalance threshold previous fee value : Z) : option Z :=
  if emptying then
    if asbool (fee ≤ snapshotBalance)
    then Some (Z.min (Z.max (snapshotBalance - fee - value) 0) threshold)
    else None
  else if asbool (fee ≤ previous) then Some (previous - fee) else None.

Section Consensus.
The implicit argument F supplies the OCaml executor's chain ID, revision and tracing flag. The consensus checks use the chain ID; F supplies no execution state.
Context {F : E.FArgs}.

Initialize the consensus checks before checking any transactions.
  • snapshot: the designated execution state S_h, supplying account balances, nonces, delegation and reserve configuration.
  • height: the block height whose effective reserve thresholds determine the initial gas budgets. For a new window this is h, the snapshot's height, not the first block h+1. After executing a prefix, the remaining check uses the first remaining block's height.
Result: a ConsensusState with snapshot nonces, no subsequent sender or authorization activity, and G_a = min(balance(S_h,a), R_h(a,height)). For a new window, an increase scheduled after h does not replenish G: delegated code could spend the surplus before the increase activates.
Definition initialConsensusState (snapshot : W.t) (height : N) : ConsensusState :=
  {| consensusHistory := initialHistory snapshot;
     consensusBudgets := fun a ⇒ Z.min
       (to_z (balance (accountAt snapshot a)))
       (to_z (reserveAt snapshot height a)) |}.

Check one transaction without executing its contract code.
  • snapshot: the fixed designated state S_h, not the state after earlier transactions in this window.
  • header: the candidate's block header; supplies its height and base fee.
  • previous: ConsensusState after all preceding transactions, with gas budgets already capped for this block by checkBlocks.
  • tx: the signed transaction being checked.
Result: None rejects tx. Some next accepts it and returns updated nonces, sender/authorization activity and the sender's remaining gas budget. Other accounts' gas budgets and snapshot are unchanged.
transactionSender recovers the sender first. When the sender is Chain.Monad.system_sender, systemTransactionChecks checks that tx is a legacy call to the staking precompile at the predicted nonce within the fixed system-transaction gas limit, and advanceHistory increments its nonce while leaving user gas budgets unchanged.
For user EOA senders, transactionQuote computes the gas-fee bound and transactionChecks checks the predicted nonce, chain ID and public gas/encoding constraints. Consensus does not check sender-code eligibility here. SnapshotConditions already requires each transaction sender to have empty code or an EIP-7702 delegation marker. The proof establishes that execution preserves this property, so the execution validator's sender-code check passes.
checkSenderBudget checks fee affordability separately for user senders. A non-emptying transaction requires the gas-fee bound to fit the sender's remaining gas budget. An emptying-eligible transaction instead requires it to fit the sender's balance in S_h. Neither comparison uses the actual balance after preceding unexecuted transactions.
advanceHistory consumes the sender nonce first, then processes EIP-7702 authorizations in order. Applied authorizations consume their authorities' nonces too, even if the subsequent VM execution reverts. For example, another sender's applied authorization for Alice at nonce 5 means Alice's next transaction must use nonce 6, not 5.
The current transaction's applied authorities affect its emptying decision; the updated history is carried to subsequent transactions.
Definition checkTransaction (snapshot : W.t) (header : Header.t)
    (previous : ConsensusState) (tx : T.t) : option ConsensusState :=
  match transactionSender tx with
  | None ⇒ None
  | Some sender ⇒
      if asbool (sender = Chain.Monad.system_sender) then
        if systemTransactionChecks tx
          (historyNonces (consensusHistory previous) sender) then
          let '(_, history) := advanceHistory snapshot (consensusHistory previous) sender tx in
          Some {| consensusHistory := history;
                  consensusBudgets := consensusBudgets previous |}
        else None
      else
        match transactionQuote header tx with
        | None ⇒ None
        | Some (_, fee) ⇒
            if transactionChecks header tx
              (historyNonces (consensusHistory previous) sender) then
            let '(authorities, history) := advanceHistory snapshot (consensusHistory previous) sender tx in
            let emptying := historyAllowsEmptying snapshot (consensusHistory previous) sender
              (blockNumber header) && asbool (¬ elem_of sender authorities) in
            match checkSenderBudget emptying
              (to_z (balance (accountAt snapshot sender)))
              (to_z (reserveAt snapshot (blockNumber header) sender))
              (consensusBudgets previous sender) (Z.of_N fee) (to_z (T.value tx)) with
            | None ⇒ None
            | Some remaining ⇒ Some
                {| consensusHistory := history;
                   consensusBudgets := fun a ⇒
                     if asbool (sender = a) then remaining else consensusBudgets previous a |}
            end
            else None
        end
  end.

Check a list of transactions from one block in their given order.
  • snapshot: the fixed designated execution state S_h.
  • header: the common block header for all transactions in txs.
  • previous: ConsensusState before the list, including the gas-budget cap for this block and any transactions already checked before txs.
  • txs: the ordered list still to check in this block.
Result: Some next is the state after every transaction passes; None means at least one failed. No transaction is dropped or reordered. An empty list returns Some previous. This function does not apply the block-boundary cap itself; checkBlocks does.
Fixpoint checkTransactions (snapshot : W.t) (header : Header.t)
    (previous : ConsensusState) (txs : list T.t) : option ConsensusState :=
  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 successive blocks while keeping the designated snapshot fixed.
  • snapshot: S_h, used for every account/configuration read in this call.
  • previous: ConsensusState before blocks, either freshly initialized or returned after checking preceding blocks against the same snapshot.
  • blocks: blocks to check, in the supplied order; each contains its header and ordered transactions.
Result: Some next means every transaction passed and gives the final ConsensusState; None rejects the sequence. An empty list returns Some previous. No contract code is executed and no block is dropped. Before each block, cap G_a at R_h(a,b), including for an empty block. A reserve increase does not replenish G. Ordering of block heights is required separately by WindowConditions, not checked by this function.
Fixpoint checkBlocks (snapshot : W.t) (previous : ConsensusState)
    (blocks : list Block.t) : option ConsensusState :=
  match blocks with
  | [] ⇒ Some previous
  | block :: rest ⇒
      let blockHeader := header block in
      let atBlock := {| consensusHistory := consensusHistory previous;
        consensusBudgets := fun a ⇒ Z.min (consensusBudgets previous a)
          (to_z (reserveAt snapshot (blockNumber blockHeader) a)) |} in
      match checkTransactions snapshot blockHeader atBlock (transactions block) with
      | None ⇒ None
      | Some next ⇒ checkBlocks snapshot next rest
      end
  end.
State that a fresh consensus check accepts the whole supplied sequence.
  • snapshot: designated execution state used for initialization and checks.
  • height: initial budgets use the reserve thresholds effective at this height, as recorded in snapshot. For a new window from S_h, use h; after executing a prefix, use the first remaining block's height. This selects a threshold, not a different execution state.
  • blocks: the ordered blocks to check.
Result: a proposition, not a boolean or execution result. It holds exactly when checkBlocks returns Some next from that initialized state, for some next. It does not itself assert WindowConditions or VM success.
miscBlockChecks snapshot blocks supplies the remaining block checks: a parent for a nonempty list, consecutive heights, native header rules, and per-block gas, Monad system-transaction ordering, and the 25 MON reward cap. It uses only supplied headers and transactions, not VM execution. The main theorem requires this boolean to be true as well as consensusAccepts.

What execution enforces

Let P = min(pre-transaction balance, effective reserve), and let F be the transaction's fee bound. At the final reserve check, a protected nonsender must retain at least P. A non-emptying sender requires F <= P and must retain at least P-F. An eligible emptying sender is exempt.
Host.call_impl runs this check after a successful top-level user EOA call or creation (Monad system transactions bypass it and must succeed without reverting). A violation reverts the transaction's VM effects, not its fee or protocol nonce/authorization processing. Temporary dips that are restored pass.
The staking account 0x1000, accounts with ordinary contract code at that checkpoint, and accounts created and selfdestructed in the same transaction are exempt. Contract creation at any sender address is excluded by the cryptographic premise below.

Main theorem

If consensus accepts a block window satisfying the stated conditions, executing any prefix succeeds, and the remaining blocks still pass consensus when checked from the resulting execution state.
More precisely, assume ProtocolConditions, WindowConditions, miscBlockChecks and consensus acceptance of prefix ++ rest. Execution of prefix returns a state post: neither Invalid_transaction nor Invalid_block occurs. Checking rest from post with freshly initialized budgets succeeds, and WindowConditions and miscBlockChecks still hold for rest. Successful prefix execution is a conclusion, not an assumption.
Individual transactions may still revert in the VM; this produces a transaction result, not a block-processing error. Execution uses verify = false: it computes block results without checking the supplied execution commitments against them.

Assumptions

ProtocolConditions: revision Eleven and a bounded chain ID. The hash-output contracts and two unproved BLS identities are named axioms in vendorAssumptions, not fields of this record. The main proof depends on those four axioms.
WindowConditions: ordered heights spanning at most three heights, with the last block supplying the upper height; decoded-input bounds; well-formed initial state and prescribed system-contract code; initial supply plus system-transaction reward credits and withdrawals below 2^256; sender accounts initially without ordinary contract code (delegation is allowed). Contract creation at any sender address and at the staking address 0x1000 is excluded along reached execution prefixes while the address has no ordinary contract code. Reached Monad staking system transactions satisfy their concrete calldata and staking-storage preconditions (windowValidStakingSyscalls). No transaction sender or recovered authorization signer is the reserve precompile address 0x1001, and no transaction sender is the staking address 0x1000; Chain.Monad.system_sender is permitted for Monad system transactions, and calling the reserve precompile or staking contract is allowed. Only transaction senders need the initial non-contract condition. The staking address is not added to the fee-protected sender list.
These premises assume neither fee solvency nor validation success.

Formal statement

Section ConcreteExecutor.
params contains the chain ID, revision and tracing flag of the OCaml executor. execution packages these as the implicit F above.
Parameters, for executor configuration params:
  • snapshot: the execution state from which the window is checked and its prefix will be executed.
  • signers: a list containing all transaction senders in prefix ++ rest. Other authorization signers need not be listed.
  • prefix: the initial segment of the accepted block list to execute.
  • rest: the blocks after prefix, in order. Either list may be empty.
Heights are derived from the blocks, not additional inputs. Initial budgets use the reserve thresholds effective one block before the first block; miscBlockChecks ensures this is the snapshot's height. The last block supplies the window's upper height. The remaining check uses the thresholds effective at its first block, as recorded in post.
For example, for prefix 104, 105 and rest 106, these heights are 103, 106 and 106. Empty lists need no meaningful height: their derived value is 0 and no transaction is checked.
Result: there exists a state post produced by executing prefix. From it, rest passes consensus, the window conditions and the block checks. Thus both block-processing errors are excluded.
Definition consensusCorrect : Prop :=
  ∀ (snapshot : W.t) (signers : list Addr.t)
    (prefix rest : list Block.t),
    let blocks := prefix ++ rest in
    let until := lastBlockHeight blocks in
    ProtocolConditions →
    WindowConditions signers until false snapshot blocks →
    miscBlockChecks snapshot blocks = true →
    consensusAccepts snapshot (N.pred (firstBlockHeight blocks)) blocks →
    ∃ post : W.t,
      executeBlocks params false snapshot prefix = inl post ∧
      consensusAccepts post (firstBlockHeight rest) rest ∧
      WindowConditions signers until false post rest ∧
      miscBlockChecks post rest = true.

End ConcreteExecutor.

Why the checks fit together

The consensus budget never exceeds the balance available before its sender's next transaction. Replacing the snapshot with an executed prefix therefore cannot invalidate the suffix's fee budgets. The nonce simulation agrees with that same executed prefix. Intermediate state invariants and nonce/code preservation are proved, not assumed again.
consensus_correct proves consensusCorrect. Taking rest empty gives the whole-window corollary: all blocks execute and the resulting state satisfies SnapshotConditions.
Source note. executeBlocks wraps E.process_block, automatically translated from OCaml by rocq-of-ocaml; LLM-supplied termination proofs are checked by Rocq. The proved source is upstream 2505f86 plus local configuration and proof-oriented adaptations, incorporating the reserve-configuration changes from PR 75 and the staking implementation, reward-cap fix, and typed ABI codecs from PR 16, PR 77, and PR 78. PR 75 additionally includes PR 74's counter update for recovered but invalid authorizations, absent from this proved source. The theorem does not certify the PRs' entire newer branches or the translator itself.
The translator constructs opaque fallback values, not axioms. executeBlocks uses its concrete entry point, without exceptional-result parameters. Proving absence of all original OCaml exceptions remains separate.

End-to-end consensus tests

The theorem above proves safety of accepted blocks, not that the design accepts useful transactions. A design that ignores reserve-increase requests could also satisfy a safety property of this form.
Here we prove how this design behaves for one reserve increase: once the increase is effective in the designated snapshot, consensus accepts a transaction whose gas-fee bound exceeds the old reserve. With an earlier snapshot, it rejects the same signed transaction.
Both cases run the complete checkBlocks function, not just checkSenderBudget. Both use Alice's balance of 100 MON and a reserve increase from 10 to 100 MON requested at block 100, effective at block 103. All amounts in the diagrams are MON. These test reserve/transaction accounting, not miscBlockChecks or whole-block execution.
The identical signed transaction has maximum gas fee 20, value zero, sender nonce 1 and authorization nonce 2. Its applied self-authorization disables emptying, so its fee must fit the ordinary gas budget. Neither proposed budget-refresh extension is enabled.

Accepted: snapshot 103, transaction in block 106

  1. Snapshot 103Reserve: 100Initial budget: 100
  2. Check empty blocks104 and 105Budget stays 100
  3. Check block 106Signed transactionFee 20 ≤ budget 100
  4. ACCEPTRemaining budget: 80Predicted nonce: 3
Proof: signed_transaction_accepted_at_106.

Rejected: snapshot 102, transaction in block 105

  1. Snapshot 102Reserve: 10Initial budget: 10
  2. Check empty blocks103 and 104Reserve becomes 100Budget stays 10
  3. Check block 105Same signed transactionFee 20 > budget 10
  4. REJECTInsufficient gas budgetNo accepted next state
Proof: signed_transaction_rejected_at_105.
The difference is budget initialization: reserve activation does not replenish a budget initialized before activation. The 80 MON result is a consensus budget, not a proved post-execution account balance.

Test caveats

These are end-to-end consensus checks, not execution of a chain of valid blocks. Setup invokes the generated storage setter directly, not a signed setting transaction.
Rocq models the signature-recovery libraries abstractly, so these tests assume the two recovery equations. The native companion checks both equations using the real libraries and checks successful execution of this transaction.