Library SetcodeConcrete.transactionsupply

Supply preservation through SETCODE transaction execution

The migrated-sender path charges fees without a VM call. The ordinary path uses the proved recursive VM bound. Both reuse the initial debit for beneficiary payment and cannot mint balance during finalization.
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.
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).

Lemma validated_message_bounds block tx validation world :
  @E.validate_transaction F block tx = inl validation →
  transactionValueAndDataBounds tx →
  @vmMessageBounds (@E.prepare_message F (E.transaction_validation.sender validation)
    (@Gas.op_minus
      (T.gas_limit tx) (E.transaction_validation.intrinsic_gas validation)) tx world).
Proof.
  intros Hvalidated Hinput.
  pose proof (transaction_data_counter_bound tx Hinput) as Hlength.
  destruct Hinput as [Hvalue HnativeLength].
  pose proof (validated_message_gas block tx validation world Hvalidated) as Hgas.
  pose proof (validated_message_data_length block tx validation world Hlength Hvalidated) as Hdata.
  cbn zeta in Hgas, Hdata.
  unfold vmMessageBounds. split; [exact Hgas|].
  split.
  { unfold E.prepare_message. destruct (T.call_or_create_value tx); exact Hvalue. }
  split; [lia|].
  unfold E.prepare_message. destruct (T.call_or_create_value tx).
  all: apply (encoded_capacity_all_decoders (UI := Opaque.legacy_witness 0%Z)).
  all: unfold E.vm_max_memory_usage; rewrite Hrevision; vm_compute; reflexivity.
Qed.

Theorem process_transaction_preserves_supply block tx 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.process_transaction F block tx = inl post →
  balanceInvariant (B.t.world_state post) ∧
    totalBalance (B.t.world_state post) ≤ totalBalance (B.t.world_state block) ∧
    worldFormat (B.t.world_state post).
Proof.
  intros Hchain Hheader Hrandao Hinitial Hformat Hwidth Hvalue Hrun.
  unfold E.process_transaction in Hrun.
  destruct (@E.validate_transaction F block tx) as [validation|error] eqn:Hvalidation.
  2: discriminate Hrun.
  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 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 _]].
  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 |- balanceInvariant (B.t.world_state (OCamlSeq.fold_left ?f ?state ?addresses)) ∧ _ ⇒
    pose proof (delete_accounts_supply state addresses Hcredited) as [Hdeleted HdeleteTotal]
  end.
  all: split; [exact Hdeleted|]; split.
  all: try (eapply Z.le_trans; [exact HdeleteTotal|exact HcreditTotal]).
  all: apply delete_accounts_format.
  all: eapply (@write_account_format false
    (S.t.world_state (@E.bump_emptying_transaction_counters F (sender :: nil) finished))
    (Chain.Ethereum.Block.Header.t.beneficiary
      (Chain.Ethereum.Block.t.header (B.t.current_block block))));
    [exact HfinalFormat|apply balance_update_format, read_account_format; exact HfinalFormat].
Qed.

Lemma system_message_preserves_supply block addr data :
  wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  headerWords (Chain.Ethereum.Block.t.header (B.t.current_block block)) →
  OCamlString.length data < 2^62 →
  balanceInvariant (B.t.world_state block) → worldFormat (B.t.world_state block) →
  let post := snd (@E.process_system_message F
    block addr data) in
  balanceInvariant (B.t.world_state post) ∧
    totalBalance (B.t.world_state post) ≤ totalBalance (B.t.world_state block) ∧
    worldFormat (B.t.world_state post).
Proof.
  intros Hchain [Hbase [Hheader Hrandao]] Hdata Hinitial Hformat.
  cbn zeta. unfold E.process_system_message.
  match goal with |- context [if ?test then _ else _] ⇒ destruct test end.
  { split; [exact Hinitial|]; split; [apply Z.le_refl|exact Hformat]. }
  cbn beta iota zeta.
  match goal with |- context [E.Host.call ?message ?entry] ⇒
    set (msg := message); set (initial := entry)
  end.
  assert (Hmsg : @vmMessageBounds msg).
  { split; [change (0 ≤ 30000000 < 2^63); lia|].
    split; [change (0 ≤ 0 < 2^256); lia|]. split; [exact Hdata|].
    apply (encoded_capacity_all_decoders (UI := Opaque.legacy_witness 0%Z)).
    unfold E.vm_max_memory_usage. rewrite Hrevision. vm_compute. reflexivity. }
  assert (Hcontext : hostContextWords params initial).
  { split.
    - constructor; [change (0 ≤ 0 < 2^256); lia|].
      constructor; [exact Hbase|]. constructor; [exact Hchain|constructor].
    - split; assumption. }
  assert (HformatEntry : hostFormat initial) by (split; [exact Hformat|constructor]).
  pose proof (@execution_host_call_supply F cold warm access write reserve
    (totalBalance (B.t.world_state block)) Hrevision Hcold Hwarm Hhash Hnative
    msg initial Hmsg
    (conj (conj (conj Hinitial (Z.le_refl _)) HformatEntry) Hcontext)) as Hsafe.
  destruct (E.Host.call msg initial) as [result afterVm].
  destruct Hsafe as [[[[Hafter Htotal] [HformatAfter _]] _] _].
  split; [exact Hafter|]. split; assumption.
Qed.
End Execution.
Print Assumptions process_transaction_preserves_supply.