Library SetcodeConcrete.consensuscorrectness
SETCODEFROM: consensus checks and successful block execution
What consensus knows
snapshot after h | block h+1 | block h+2 | block n
<----- known transactions ----->
<--- unknown execution states -->
What changes when an account adopts code
The actual consensus checks
Public consensus checks for the SETCODE experiment
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.
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.
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.
Definition accountAt (snapshot : W.t) (a : Addr.t) : A.t :=
State.op_pointcaretlparenrparen snapshot (W.account None a).
State.op_pointcaretlparenrparen snapshot (W.account None a).
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.
Definition reserveAt snapshot height a :=
Numeric.U256.to_z (Reserve_balance.user_reserve_balance snapshot height a).
Numeric.U256.to_z (Reserve_balance.user_reserve_balance snapshot height a).
Public accounting before checking the next transaction, not an execution
state. The designated execution snapshot is supplied separately.
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.
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.
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).
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) |}.
{| 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.
Definition allowsEmptying snapshot previous sender height authorities : bool :=
Byte_string.Bytes.op_eq (A.t.code (accountAt snapshot sender)) Byte_string.Bytes.empty &&
asbool (State.op_pointcaretlparenrparen snapshot
(W.next_emptying_transaction_block_for sender) ≤ height)%N &&
asbool (¬ elem_of sender (authorities ++ admissionActivity previous)).
Section Checks.
Byte_string.Bytes.op_eq (A.t.code (accountAt snapshot sender)) Byte_string.Bytes.empty &&
asbool (State.op_pointcaretlparenrparen snapshot
(W.next_emptying_transaction_block_for sender) ≤ height)%N &&
asbool (¬ elem_of sender (authorities ++ admissionActivity previous)).
Section Checks.
F supplies the executor's chain ID, revision and tracing flag. These
public checks use the chain ID, not future execution states.
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.
: 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.
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.
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.
Definition consensusAccepts snapshot height blocks : Prop :=
∃ next, checkBlocks snapshot (initialAdmission snapshot height) blocks = Some next.
End Checks.
∃ next, checkBlocks snapshot (initialAdmission snapshot height) blocks = Some next.
End Checks.
From Stdlib Require Import List NArith.
Require Export SetcodeConcrete.consensuschecks SetcodeConcrete.consensusconditions.
Require Import QedkConcrete.miscblockchecks.
Import ListNotations.
Require Export SetcodeConcrete.consensuschecks SetcodeConcrete.consensusconditions.
Require Import QedkConcrete.miscblockchecks.
Import ListNotations.
Main guarantee
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.
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.
Definition executeBlocks (snapshot : W.t) (blocks : list Block.t) :=
Result.List.fold_leftM (E.process_block false) snapshot blocks.
Result.List.fold_leftM (E.process_block false) snapshot blocks.
Parameters of the main proposition:
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.
- 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.
Definition setcodeConsensusCorrect : Prop :=
∀ snapshot senders until height past rest,
ResourceProtocolConditions cold warm access write reserve →
SetcodeWindowConditions senders until false snapshot (past ++ rest) →
miscBlockChecks snapshot (past ++ rest) = true →
consensusAccepts snapshot height (past ++ rest) →
∃ post,
executeBlocks snapshot past = inl post ∧
RemainingWindowInvariant senders until false snapshot height past rest post ∧
miscBlockChecks post rest = true.
End Consensus.
∀ snapshot senders until height past rest,
ResourceProtocolConditions cold warm access write reserve →
SetcodeWindowConditions senders until false snapshot (past ++ rest) →
miscBlockChecks snapshot (past ++ rest) = true →
consensusAccepts snapshot height (past ++ rest) →
∃ post,
executeBlocks snapshot past = inl post ∧
RemainingWindowInvariant senders until false snapshot height past rest post ∧
miscBlockChecks post rest = true.
End Consensus.
Illustration: migration after admission
- Consensus snapshotAlice is delegated.Admit T0, then T1.
- Execute T0Alice adopts regular code.Reserve remains protected.
- Execute admitted T1Charge full gas-limit fee.No body or value transfer; failed receipt.
- Block processing succeedsNo validation/block error.Fresh admission would reject T1.