Library SetcodeConcrete.transactionnonce

Nonce allowance for transaction execution

Intrinsic gas is not forwarded to the VM. Its fixed base charge covers the additional initialized nonce when the transaction creates an account. These lemmas connect the concrete message preparation to the VM bound.
From Stdlib Require Import NArith ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml MonadVM.Execution.
Require Import QedkConcrete.validation SetcodeConcrete.noncebudget
  SetcodeConcrete.nonceeffects SetcodeConcrete.noncefinalize
  SetcodeConcrete.executionnonce SetcodeConcrete.checkednonce SetcodeConcrete.noncecreate.
Set Default Goal Selector "!".
Local Open Scope Z_scope.
Module B := State.BlockState.

Lemma intrinsic_positive tx : (1 ≤ Gas.tx_intrinsic_gas tx)%N.
Proof.
  unfold Gas.tx_intrinsic_gas, Gas.op_plus, Support.UintN.op_plus.
  change Gas.tx_base_gas with 21000%N. lia.
Qed.

Lemma prepared_message_gas {F : E.FArgs} state tx validation world :
  E.validate_transaction state tx = inl validation →
  let msg := E.prepare_message (E.transaction_validation.sender validation)
    (Gas.op_minus (T.gas_limit tx) (E.transaction_validation.intrinsic_gas validation)) tx world in
  0 ≤ Evmc.Message.t.gas msg < 2^63 ∧
  Evmc.Message.t.gas msg + 1 ≤ Z.of_N (T.gas_limit tx).
Proof.
  intro Hvalid. pose proof (validated_gas state tx validation Hvalid) as [Hintrinsic Hlimit].
  pose proof (intrinsic_positive tx) as Hpositive.
  rewrite <- (validated_intrinsic state tx validation Hvalid) in Hpositive.
  assert (Hfits : (E.transaction_validation.intrinsic_gas validation <=? T.gas_limit tx)%N = true)
    by (apply N.leb_le; exact Hintrinsic).
  assert (Hrange : 0 ≤ Z.of_N (T.gas_limit tx - E.transaction_validation.intrinsic_gas validation) < 2^63).
  { rewrite N2Z.inj_sub by exact Hintrinsic. lia. }
  unfold E.prepare_message. destruct (T.call_or_create_value tx);
    cbn beta iota zeta delta [Evmc.Message.t.gas].
  all: unfold Gas.to_int64, Support.UintN.to_int64, Gas.op_minus, Support.UintN.op_minus;
    rewrite Hfits; unfold OCamlZ.to_int64, OCamlZ.checked_signed, Support.UintN.to_z.
  all: assert (Hsigned : OCamlZ.fits_signed 64
      (Z.of_N (T.gas_limit tx - E.transaction_validation.intrinsic_gas validation)) = true)
    by (unfold OCamlZ.fits_signed; apply Bool.andb_true_iff; split; apply Z.leb_le;
      unfold OCamlZ.signed_min, OCamlZ.signed_max; cbn [Z.pred]; lia).
  all: rewrite Hsigned; split; [exact Hrange|rewrite N2Z.inj_sub by exact Hintrinsic; lia].
Qed.

Section Transaction.
Context {F : E.FArgs}.
Context (cold warm access write reserve : N).
Context (Hrevision : E.Params.(Execution.Make_Params_signature.revision) =
  Support.Variants.Revision.Setcode (cold, warm, access, write, reserve)).
Context (Hcold : (0 < cold)%N) (Hwarm : (0 < warm)%N).

Lemma bump_counters_nonce s addresses query :
  nonceAt (S.t.world_state (E.bump_emptying_transaction_counters addresses s)) query =
  nonceAt (S.t.world_state s) query.
Proof.
  unfold nonceAt, State.op_pointcaretlparenrparen, W.account, W.account_opt.
  cbn -[E.bump_emptying_transaction_counters Chain.Ethereum.Address.Map.find_opt].
  rewrite bump_counters_accounts. reflexivity.
Qed.

This is preservation through an executed transaction. Successful validation is a premise here; the accepted-window proof must derive it. The maximum covers the migrated-sender rule without assuming equality between the signed nonce and the actual execution nonce.
Theorem transaction_nonce_bound state tx validation query :
  query ≠ Reserve_balance.precompile_address →
  E.validate_transaction state tx = inl validation →
  stringmaps.WellFormed (W.t.accounts (B.t.world_state state)) →
  0 ≤ nonceAt (B.t.world_state state) query < 2^64-1 →
  0 ≤ T.nonce tx < 2^64-1 →
  ∃ post,
    E.process_transaction state tx = inl post ∧
    stringmaps.WellFormed (W.t.accounts (B.t.world_state post)) ∧
    0 ≤ nonceAt (B.t.world_state post) query ≤
      Z.max (nonceAt (B.t.world_state state) query) (T.nonce tx) + transactionNonceBudget tx.
Proof.
  intros Hnative Hvalidation Hmap Hnonce Hproposed.
  pose proof (prepared_message_gas state tx validation) as Hmessage.
  unfold E.process_transaction. rewrite Hvalidation.
  destruct validation as [sender fee price intrinsic].
  change (@Result.op_letdollar) with
    (fun (A Error C : Set) (first : A + Error) (next : A → C + Error) ⇒
      match first with inl value ⇒ next value | inr error ⇒ inr error end).
  cbn beta iota zeta.
  match goal with |- context [Setcode_rules.advance_sender_nonce ?flag _ _] ⇒
    set (migrated := flag) in × end.
  match goal with |- context [Result.List.fold_left ?step (nil, ?initial) ?auths] ⇒
    set (prepared := initial) end.
  assert (HpreparedWorld : S.t.world_state prepared =
    State.op_pointcaretlparenrparenltminus (B.t.world_state state) (W.account (Some false) sender)
      (A.t.with_nonce
        (Setcode_rules.advance_sender_nonce migrated (nonceAt (B.t.world_state state) sender) (T.nonce tx))
        (A.t.with_balance
          (Numeric.U256.op_minus
            (A.t.balance (State.op_pointcaretlparenrparen (B.t.world_state state) (W.account None sender))) fee)
          (State.op_pointcaretlparenrparen (B.t.world_state state) (W.account None sender))))).
  { reflexivity. }
  assert (HpreparedMap : stringmaps.WellFormed (W.t.accounts (S.t.world_state prepared))) by
    (rewrite HpreparedWorld; apply worldaccounts.account_write_wellformed; exact Hmap).
  assert (HpreparedNonce : 0 ≤ nonceAt (S.t.world_state prepared) query ≤
    Z.max (nonceAt (B.t.world_state state) query) (T.nonce tx) + 1).
  { rewrite HpreparedWorld, nonce_after_write by exact Hmap.
    destruct (String.eqb sender query) eqn:Heq.
    - apply String.eqb_eq in Heq. subst query.
      cbn [A.t.with_nonce A.t.nonce]. unfold Setcode_rules.advance_sender_nonce.
      destruct migrated.
      + rewrite rules.u64_max, rules.u64_increment by lia. lia.
      + rewrite rules.u64_increment by lia. lia.
    - change (0 ≤ nonceAt (B.t.world_state state) query ≤ Z.max (nonceAt (B.t.world_state state) query) (T.nonce tx) + 1). lia. }
  pose proof (authorizations_nonce_bound (T.authorization_list tx) prepared nil query
    HpreparedMap (proj1 HpreparedNonce)) as Hauth.
  match goal with |- context [Result.List.fold_left ?step (nil, prepared) ?auths] ⇒
    change (Result.List.fold_left step (nil, prepared) auths)
      with (processAuthorizations prepared nil auths) end.
  destruct (processAuthorizations prepared nil (T.authorization_list tx))
    as [authorities authorized] eqn:HauthRun.
  cbn beta iota zeta delta [fst snd] in Hauth |- ×.
  destruct Hauth as [HauthorizedMap HauthorizedNonce].
  match goal with |- context [S.initialize_access_sets tx ?entry ?precompiles] ⇒
    set (beforeVm := S.initialize_access_sets tx entry precompiles) in × end.
  assert (HbeforeAccounts : W.t.accounts (S.t.world_state beforeVm) =
    W.t.accounts (S.t.world_state authorized)) by
    (unfold beforeVm; apply bump_counters_accounts).
  assert (HbeforeMap : stringmaps.WellFormed (W.t.accounts (S.t.world_state beforeVm))) by
    (rewrite HbeforeAccounts; exact HauthorizedMap).
  assert (HbeforeNonce : nonceAt (S.t.world_state beforeVm) query = nonceAt (S.t.world_state authorized) query).
  { unfold nonceAt, State.op_pointcaretlparenrparen, W.account, W.account_opt.
    cbn -[Chain.Ethereum.Address.Map.find_opt beforeVm]. rewrite HbeforeAccounts. reflexivity. }
  match goal with |- context [E.Host.call_from_eoa tx ?message beforeVm] ⇒
    set (msg := message) in × end.
  specialize (Hmessage (S.t.world_state beforeVm) Hvalidation).
  change (0 ≤ Evmc.Message.t.gas msg < 2^63 ∧ Evmc.Message.t.gas msg + 1 ≤ Z.of_N (T.gas_limit tx)) in Hmessage.
  assert (Hbefore : nonceState query beforeVm) by
    (split; [exact HbeforeMap|rewrite HbeforeNonce; exact (proj1 HauthorizedNonce)]).
  pose proof (execution_transaction_call_nonce_bound cold warm access write reserve
    Hrevision Hcold Hwarm query Hnative tx msg beforeVm (proj1 Hmessage) Hbefore) as Hvm.
  destruct (E.Host.call_from_eoa tx msg beforeVm) as [result afterVm] eqn:HvmRun.
  destruct Hvm as [HafterVm HvmBound].
  assert (HvmNonce : 0 ≤ nonceAt (S.t.world_state afterVm) query ≤
    nonceAt (S.t.world_state authorized) query + Z.of_N (T.gas_limit tx)).
  { split; [exact (proj2 HafterVm)|].
    pose proof (checked_refund_bound (Evmc.Message.t.gas msg) result ltac:(lia)).
    rewrite HbeforeNonce in HvmBound.
    destruct (Evmc.Message.CallKind.is_create (Evmc.Message.t.kind msg)); lia. }
  destruct migrated; cbn beta iota zeta.
  all: try (destruct (Evmc.Message.CallKind.is_create (Evmc.Message.t.kind msg)); cbn beta iota zeta).
  all: eexists; split; [reflexivity|].
  all: cbn beta iota zeta delta [B.t.with_transactions_processed B.t.with_transaction_frames
    B.t.with_gas_used B.t.world_state E.transaction_validation.sender].
  all: match goal with |- context [E.bump_emptying_transaction_counters (?sender :: nil) ?entry] ⇒
    set (final := E.bump_emptying_transaction_counters (sender :: nil) entry) in × end.
  all: assert (HfinalMap : stringmaps.WellFormed (W.t.accounts (S.t.world_state final))) by
    (unfold final; rewrite bump_counters_accounts; first [exact HbeforeMap|exact (proj1 HafterVm)]).
  all: assert (HfinalBound : 0 ≤ nonceAt (S.t.world_state final) query ≤
    Z.max (nonceAt (B.t.world_state state) query) (T.nonce tx) + transactionNonceBudget tx) by
    (unfold final; rewrite bump_counters_nonce;
     unfold transactionNonceBudget; rewrite ?HbeforeNonce; lia).
  all: match goal with |- context [Result.Seq.fold_left ?step ?credited ?addresses] ⇒
    set (paid := credited) in *;
    assert (HpaidMap : stringmaps.WellFormed (W.t.accounts (B.t.world_state paid))) by
      (unfold paid; apply worldaccounts.account_write_wellformed; exact HfinalMap);
    assert (HpaidNonce : nonceAt (B.t.world_state paid) query = nonceAt (S.t.world_state final) query) by
      (unfold paid; apply balance_write_nonce; exact HfinalMap);
    pose proof (delete_accounts_nonce_bound paid (S.t.self_destruct final) query HpaidMap
      ltac:(rewrite HpaidNonce; exact (proj1 HfinalBound))) as Hdelete;
    change (@Result.Seq.fold_left) with (@OCamlSeq.fold_left);
    change (stringmaps.WellFormed (W.t.accounts (B.t.world_state (OCamlSeq.fold_left step paid addresses))) ∧
      0 ≤ nonceAt (B.t.world_state (OCamlSeq.fold_left step paid addresses)) query ≤
        Z.max (nonceAt (B.t.world_state state) query) (T.nonce tx) + transactionNonceBudget tx)
  end.
  all: destruct Hdelete as [HdeletedMap HdeletedBound].
  all: split; [exact HdeletedMap|].
  all: match type of HdeletedBound with 0 ≤ ?n ≤ _ ⇒
    change (0 ≤ n ≤ Z.max (nonceAt (B.t.world_state state) query) (T.nonce tx) + transactionNonceBudget tx) end.
  all: rewrite HpaidNonce in HdeletedBound; lia.
Qed.
End Transaction.
Print Assumptions transaction_nonce_bound.

Concrete transaction preservation of the remaining headroom. The half-range condition belongs only at the initial snapshot; this residual condition allows execution nonces to cross 2^63. Successful validation of the current transaction is still a premise of this preservation lemma.
Corollary transaction_retains_nonce_headroom {F : E.FArgs}
    cold warm access write reserve state tx validation query remaining :
  E.Params.(Execution.Make_Params_signature.revision) =
    Support.Variants.Revision.Setcode (cold, warm, access, write, reserve) →
  (0 < cold)%N → (0 < warm)%N → query ≠ Reserve_balance.precompile_address →
  E.validate_transaction state tx = inl validation →
  stringmaps.WellFormed (W.t.accounts (B.t.world_state state)) →
  nonceCapacity (nonceAt (B.t.world_state state) query) (T.nonce tx)
    (transactionNonceBudget tx + remaining) → 0 ≤ remaining →
  ∃ post,
    E.process_transaction state tx = inl post ∧
    stringmaps.WellFormed (W.t.accounts (B.t.world_state post)) ∧
    0 ≤ nonceAt (B.t.world_state post) query ∧
    nonceAt (B.t.world_state post) query + remaining < 2^64-1.
Proof.
  intros Hrevision Hcold Hwarm Hnative Hvalidation Hmap Hcapacity Hremaining.
  destruct (capacity_has_nonmaximal_nonces _ _ _ Hcapacity) as [Hactual Hproposed].
  destruct (transaction_nonce_bound cold warm access write reserve Hrevision Hcold Hwarm
    state tx validation query Hnative Hvalidation Hmap Hactual Hproposed)
    as [post [Hrun [Hafter Hbound]]].
  ∃ post. split; [exact Hrun|]. split; [exact Hafter|].
  unfold nonceCapacity in Hcapacity. split; lia.
Qed.
Print Assumptions transaction_retains_nonce_headroom.