Library SetcodeConcrete.consensuschecks

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.