Library SetcodeConcrete.transactionfinalize

Reserve lower bounds survive complete transaction finalization

The bound is taken at transactionFinished, after the actual VM call or the migrated-sender no-VM path. The beneficiary credit cannot wrap: the already proved supply bound and the upfront fee debit cover it. Deletion affects only addresses in the actual SELFDESTRUCT list. This lemma derives the finalization bound, not validation success.
From Stdlib Require Import List ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml MonadVM.Execution.
Require Import QedkConcrete.transactionframes QedkConcrete.transactionentrywords
  QedkConcrete.transactionfees QedkConcrete.nativeinputs
  QedkConcrete.authorization QedkConcrete.hostcontextwords QedkConcrete.supply
  QedkConcrete.hostaccountformat QedkConcrete.hostchecked QedkConcrete.wordrange
  QedkConcrete.vmcallchecked QedkConcrete.hashwords QedkConcrete.assemblychecked.
Require Import QedkConcrete.validation QedkConcrete.transactiondata
  QedkConcrete.vmsupplywords QedkConcrete.hostframe QedkConcrete.blockentry.
Require Import SetcodeConcrete.executionsupply SetcodeConcrete.nativeoutputs SetcodeConcrete.transactionsupply
  SetcodeConcrete.transactionentry QedkConcrete.transactionfinalize.
Set Default Goal Selector "!".
Import ListNotations.
Local Open Scope Z_scope.
#[local] Hint Extern 100 (Basics.Unreachable _) ⇒
  (apply Opaque.legacy_witness; Opaque.opaque_inhabit 64%nat) : typeclass_instances.
Module E := Execution.Make.
Module S := State.TransactionState.
Module B := State.BlockState.
Module W := State.WorldState.
Module A := Chain.Ethereum.Account.
Module T := Chain.Ethereum.Transaction.
Module U := Numeric.U256.
Section Execution.
Context {F : E.FArgs}.
Context {UI0 : Basics.Unreachable Support.UintN.Impl.t}
  {UB : Basics.Unreachable Bloom.t}
  {U8 : Basics.Unreachable Byte_string.B8.(Byte_string.Fixed.Fixed_result.t)}.
Local Abbreviation args := (@E.Instantiation_fargs F).
Local Abbreviation params := args.(Host.Instantiate.ChainParams).
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).
Context (Hhash : keccak256OutputSize) (Hnative : @nativeOutputBounds args).

Theorem process_transaction_retains_execution_balance block tx validation post :
    wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  Forall (fun n ⇒ 0 ≤ n < 2^64)
    [Support.UintN.to_z (Chain.Ethereum.Block.Header.t.number
      (Chain.Ethereum.Block.t.header (B.t.current_block block)));
     Chain.Ethereum.Block.Header.t.timestamp (Chain.Ethereum.Block.t.header (B.t.current_block block));
     Support.UintN.to_z (Chain.Ethereum.Block.Header.t.gas_limit
      (Chain.Ethereum.Block.t.header (B.t.current_block block)))] →
  OCamlString.length (Chain.Ethereum.Block.Header.t.prev_randao
    (Chain.Ethereum.Block.t.header (B.t.current_block block))) ≤ 32 →
  balanceInvariant (B.t.world_state block) → worldFormat (B.t.world_state block) →
  Forall (fun auth ⇒ OCamlString.length (T.Authorization.t.address auth) = 20)
    (T.authorization_list tx) →
  transactionValueAndDataBounds tx →
  @E.validate_transaction F block tx = inl validation →
  @E.process_transaction F block tx = inl post →
  ∀ query, ¬ In query (S.t.self_destruct (transactionFinished block tx validation)) →
    U.to_z (A.t.balance (State.op_pointcaretlparenrparen
      (S.t.world_state (transactionFinished block tx validation)) (W.account None query))) ≤
    U.to_z (A.t.balance (State.op_pointcaretlparenrparen
      (B.t.world_state post) (W.account None query))).
Proof.
  intros Hchain Hheader Hrandao Hinitial Hformat Hwidth Hvalue Hvalidation Hrun.
  unfold E.process_transaction in Hrun.
  rewrite Hvalidation in Hrun.
  unfold transactionFinished, transactionVmInput, transactionPrefix, migratedSender.
  pose proof (@account_balance_bounded_by_supply (B.t.world_state block)
    (E.transaction_validation.sender validation) (proj1 (proj2 Hinitial))) as Hbalance.
  pose proof (proj2 (proj2 Hinitial)) as Hsupply.
  pose proof (validated_debit_range block tx validation Hvalidation ltac:(cbn beta in Hbalance; lia))
    as [Hfee Hdebit].
  assert (HfeeNonnegative : 0 ≤ U.to_z (E.transaction_validation.total_fee validation)).
  { rewrite Hfee. apply N2Z.is_nonneg. }
  pose proof (@transaction_initial_context_words F UI0 UB U8 params block tx validation
    Hvalidation Hinitial Hchain Hheader Hrandao) as HinitialContext.
  destruct validation as [sender fee price intrinsic].
  cbn [E.transaction_validation.total_fee E.transaction_validation.sender] in Hdebit, HfeeNonnegative.
  change (@Result.op_letdollar) with
    (fun (A B C : Set) (r : A + B) (f : A → C + B) ⇒
      match r with inl value ⇒ f value | inr error ⇒ inr error end) in Hrun.
  cbn beta iota zeta delta [E.transaction_validation.sender E.transaction_validation.total_fee
    E.transaction_validation.intrinsic_gas E.transaction_validation.effective_gas_price] in Hrun |- ×.
  match type of Hrun with context [Setcode_rules.advance_sender_nonce ?flag _ _] ⇒
    set (migrated := flag) in × end.
  set (nextNonce := fun account ⇒ Setcode_rules.advance_sender_nonce migrated
    (A.t.nonce account) (T.nonce tx)).
  set (initial := S.t.with_tx_chain_id E.Params.(Execution.Make_Params_signature.chain_id)
    (@S.make block sender tx)) in ×.
  change (hostContextWords params initial) in HinitialContext.
  pose proof (@transaction_entry_balances_with_nonce F nextNonce initial sender fee (T.authorization_list tx)
    (proj1 Hinitial) Hdebit) as [_ [HauthContext _]].
  assert (HinitialFormat : hostFormat initial) by (apply transaction_initial_format; exact Hformat).
  pose proof (@transaction_entry_format_with_nonce F nextNonce initial sender fee (T.authorization_list tx) Hwidth HinitialFormat) as HauthFormat.
  pose proof (@transaction_entry_supply_with_nonce F nextNonce initial sender fee (T.authorization_list tx) Hinitial HfeeNonnegative Hdebit)
    as [Hauth HauthTotal].
  match type of Hrun with context [Result.List.fold_left ?f ?start (T.authorization_list tx)] ⇒
    set (authorized := Result.List.fold_left f start (T.authorization_list tx)) in ×
  end.
  change (balanceInvariant (S.t.world_state (snd authorized))) in Hauth.
  change (totalBalance (S.t.world_state (snd authorized)) = totalBalance (B.t.world_state block) - U.to_z fee)
    in HauthTotal.
  change (hostFormat (snd authorized)) in HauthFormat.
  change (transactionContext (snd authorized) = transactionContext initial) in HauthContext.
  destruct authorized as [authorities prepared]. cbn beta iota zeta delta [snd] in Hauth, HauthTotal, HauthFormat, HauthContext, Hrun |- ×.
  match type of Hrun with context [@S.initialize_access_sets tx ?s ?precompiles] ⇒
    set (beforeVm := @S.initialize_access_sets tx s precompiles) in ×
  end.
  set (activity := if Setcode_rules.enabled E.Params.(Execution.Make_Params_signature.revision)
    then Result.List.filter_map T.Authorization.authority (T.authorization_list tx)
    else authorities).
  assert (Hbefore : balanceInvariant (S.t.world_state beforeVm)).
  { change (balanceInvariant (S.t.world_state (@E.bump_emptying_transaction_counters F activity prepared))).
    apply bump_counters_balance_invariant. exact Hauth. }
  assert (HbeforeFormat : hostFormat beforeVm).
  { change (hostFormat (@E.bump_emptying_transaction_counters F activity prepared)).
    apply bump_counters_format. exact HauthFormat. }
  assert (HbeforeTotal : totalBalance (S.t.world_state beforeVm) = totalBalance (B.t.world_state block) - U.to_z fee).
  { change (totalBalance (S.t.world_state (@E.bump_emptying_transaction_counters F activity prepared)) =
      totalBalance (B.t.world_state block) - U.to_z fee).
    rewrite bump_counters_total. exact HauthTotal. }
  assert (HbeforeContext : hostContextWords params beforeVm).
  { change (hostContextWords params prepared).
    eapply host_context_words_preserved; eassumption. }
  pose proof (@validated_message_bounds F cold warm access write reserve Hrevision Hcold Hwarm
    block tx _ (S.t.world_state beforeVm)
    Hvalidation Hvalue) as Hmsg.
  match type of Hrun with context [E.Host.call_from_eoa tx ?message beforeVm] ⇒
    set (msg := message) in ×
  end.
  pose proof (@execution_call_from_sender_supply F cold warm access write reserve
    (totalBalance (S.t.world_state beforeVm)) Hrevision Hcold Hwarm Hhash Hnative
    tx msg beforeVm Hmsg
    (conj (conj (conj Hbefore (Z.le_refl _)) HbeforeFormat) HbeforeContext)) as Hsafe.
  destruct (E.Host.call_from_eoa tx msg beforeVm) as [result afterVm] eqn:Hcall.
  cbn beta iota zeta delta [snd fst] in Hsafe.
  destruct Hsafe as [[[[Hafter HafterTotal] HafterFormat] _] _].
  destruct migrated; cbn beta iota zeta in Hrun |- ×.
  all: try (destruct (Evmc.Message.CallKind.is_create (Evmc.Message.t.kind msg));
    cbn beta iota zeta in Hrun).
  all: match type of Hrun with context [E.bump_emptying_transaction_counters (?who :: nil) ?state] ⇒
    set (finished := state) in × end.
  all: assert (Hfinished : balanceInvariant (S.t.world_state finished)) by
    (unfold finished; first [exact Hafter|exact Hbefore]).
  all: assert (HfinishedTotal : totalBalance (S.t.world_state finished) ≤
    totalBalance (B.t.world_state block) - U.to_z fee) by
    (unfold finished; first
      [eapply Z.le_trans; [exact HafterTotal|apply Z.eq_le_incl; exact HbeforeTotal]
      |apply Z.eq_le_incl; exact HbeforeTotal]).
  all: assert (HfinishedFormat : hostFormat finished) by
    (unfold finished; first [exact HafterFormat|exact HbeforeFormat]).
  all: pose proof (proj1 (bump_counters_format finished (sender :: nil) HfinishedFormat))
    as HfinalFormat.
  all: pose proof (bump_counters_balance_invariant finished (sender :: nil) Hfinished) as HfinalCounters.
  all: pose proof (bump_counters_total finished (sender :: nil)) as HfinalTotal.
  all: pose proof (@beneficiary_credit_reuses_fee F block tx _
    (S.t.world_state (@E.bump_emptying_transaction_counters F (sender :: nil) finished))
    Hvalidation Hinitial HfinalCounters ltac:(cbn [E.transaction_validation.total_fee]; lia))
    as [Hcredited [HcreditTotal Hcredit]].
  all: intros query HnotDeleted.
  all: change (@Result._return) with (fun (A B : Set) (value : A) ⇒ @inl A B value) in Hrun.
  all: injection Hrun as <-.
  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].
  all: change (@Result.Seq.fold_left) with (@OCamlSeq.fold_left).
  all: match goal with |- context [OCamlSeq.fold_left ?f ?credited ?addresses] ⇒
    pose proof (@delete_accounts_preserves_other credited (S.t.self_destruct finished)
      query (proj1 Hcredited) HnotDeleted) as [_ Hread]
  end.
  all: eapply Z.le_trans; [| apply Z.eq_le_incl; symmetry;
    exact (f_equal (fun account ⇒ U.to_z (A.t.balance account)) Hread)].
  all: eapply Z.le_trans; [|exact (Hcredit query)].
  all: change (U.to_z (A.t.balance (State.op_pointcaretlparenrparen
    (S.t.world_state finished) (W.account None query))) ≤
    U.to_z (A.t.balance (State.op_pointcaretlparenrparen
    (S.t.world_state (E.bump_emptying_transaction_counters [sender] finished))
    (W.account None query)))).
  all: reflexivity.
Qed.
End Execution.
Print Assumptions process_transaction_retains_execution_balance.