Library QedkConcrete.transactionchecked

Supply preservation through concrete transaction processing

The transaction wrapper derives the VM entry bounds from validation. Fees are debited before execution and beneficiary credits reuse that debit, so they need no external supply budget. Native precompile-output bounds are an explicit premise here (discharged in precompileoutputs), not a VM axiom.
From Stdlib Require Import List ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import MonadVM.Execution QedkConcrete.transactionsupply
  QedkConcrete.executionchecked QedkConcrete.transactionentrywords
  QedkConcrete.transactiondata QedkConcrete.transactionfees
  QedkConcrete.authorization QedkConcrete.hostcontextwords
  QedkConcrete.hostframe QedkConcrete.wordrange QedkConcrete.vmcallchecked
  QedkConcrete.vmsupplywords QedkConcrete.assemblychecked QedkConcrete.hashwords
  QedkConcrete.supply QedkConcrete.validation QedkConcrete.transactionformat
  QedkConcrete.worldaccounts QedkConcrete.hostaccountformat
  QedkConcrete.precompilesframe QedkConcrete.stakingaccounting QedkConcrete.stakingsupply.
Require Import QedkConcrete.nativeinputs.
Set Default Goal Selector "!".
Import ListNotations.
Local Open Scope Z_scope.
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.

Section Execution.
Context {F : E.FArgs}.

Local Abbreviation args := (@E.Instantiation_fargs F).
Local Abbreviation params := args.(Host.Instantiate.ChainParams).

Lemma validated_message_bounds block tx validation world :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  @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 Hrevision 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.

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)}.

This is about the generated process_transaction, not an assumed VM step. Header/transaction bounds describe their concrete encodings; successful validation supplies gas, input-size and price bounds.
Theorem process_transaction_preserves_supply block tx post :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  keccak256OutputSize → @nativeOutputBounds args →
  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).
Proof.
  intros Hrevision Hhash Hnative 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 [@S.make block sender tx] ⇒
    set (initial := @S.make block sender tx) in ×
  end.
  change (hostContextWords params initial) in HinitialContext.
  pose proof (@transaction_entry_balances F 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 F initial sender fee (T.authorization_list tx) Hwidth HinitialFormat) as HauthFormat.
  pose proof (@transaction_entry_supply F 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.
  assert (Hbefore : balanceInvariant (S.t.world_state beforeVm)).
  { change (balanceInvariant (S.t.world_state (@E.bump_emptying_transaction_counters F authorities prepared))).
    apply bump_counters_balance_invariant. exact Hauth. }
  assert (HbeforeFormat : hostFormat beforeVm).
  { change (hostFormat (@E.bump_emptying_transaction_counters F authorities 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 authorities 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)
    Hrevision 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_eoa_supply_and_output F

     (totalBalance (S.t.world_state beforeVm)) tx msg beforeVm
    Hrevision Hhash Hnative 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] _] _] _].
  pose proof (bump_counters_balance_invariant afterVm (sender :: nil) Hafter) as HfinalCounters.
  pose proof (bump_counters_total afterVm (sender :: nil)) as HfinalTotal.
  pose proof (@beneficiary_credit_reuses_fee F block tx _
    (S.t.world_state (@E.bump_emptying_transaction_counters F (sender :: nil) afterVm))
    Hvalidation Hinitial HfinalCounters ltac:(cbn [E.transaction_validation.total_fee]; lia))
    as [Hcredited [HcreditTotal _]].
  change (@Result._return) with (fun (A B : Set) (value : A) ⇒ @inl A B value) in Hrun.
  injection Hrun as <-.
  cbn beta iota zeta delta [B.t.with_transactions_processed B.t.with_gas_used B.t.world_state].
  change (@Result.Seq.fold_left) with (@OCamlSeq.fold_left).
  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.
  split; [exact Hdeleted|]. eapply Z.le_trans; [exact HdeleteTotal|exact HcreditTotal].
Qed.

Lemma delete_accounts_current_block block addresses :
  B.t.current_block (OCamlSeq.fold_left
    (fun s addr ⇒ State.op_pointcaretlparenrparenltminus s
      (@B.account_opt None addr) None) block addresses) = B.t.current_block block.
Proof.
  revert block. induction addresses as [|addr addresses IH]; intro block.
  - reflexivity.
  - cbn [OCamlSeq.fold_left]. rewrite IH. reflexivity.
Qed.

Lemma process_transaction_current_block block tx post :
  @E.process_transaction F block tx = inl post →
  B.t.current_block post = B.t.current_block block.
Proof.
  intro Hrun. unfold E.process_transaction in Hrun.
  destruct (@E.validate_transaction F block tx) as [[sender fee price intrinsic]|error];
    [|discriminate Hrun].
  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 [Result.List.fold_left ?f ?start (T.authorization_list tx)] ⇒
    destruct (Result.List.fold_left f start (T.authorization_list tx)) as [authorities prepared]
  end.
  cbn beta iota zeta in Hrun.
  match type of Hrun with context [E.Host.call_from_eoa tx ?msg ?initial] ⇒
    destruct (E.Host.call_from_eoa tx msg initial) as [result afterVm]
  end.
  injection Hrun as <-.
  cbn beta iota zeta delta [B.t.with_transactions_processed B.t.with_gas_used B.t.current_block].
  change (@Result.Seq.fold_left) with (@OCamlSeq.fold_left).
  rewrite delete_accounts_current_block. reflexivity.
Qed.

Lemma process_monad_system_transaction_current_block block tx post :
  @E.process_monad_system_transaction F block tx = inl post →
  B.t.current_block post = B.t.current_block block.
Proof.
  intro Hrun. unfold E.process_monad_system_transaction in Hrun.
  destruct (@E.validate_monad_system_transaction F block tx Chain.Monad.system_sender)
    as [[]|error]; [|discriminate Hrun].
  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 in Hrun.
  match type of Hrun with context [E.Host.call_from_monad_system_transaction ?msg ?initial] ⇒
    destruct (E.Host.call_from_monad_system_transaction msg initial) as [result afterVm]
  end.
  unfold Result.when_ in Hrun.
  destruct (negb (Evmc.Result.StatusCode.is_success (Evmc.Result.t.status_code result)));
    [discriminate Hrun|].
  injection Hrun as <-. reflexivity.
Qed.

Lemma dispatch_transaction_current_block block tx post :
  @E.dispatch_transaction F block tx = inl post →
  B.t.current_block post = B.t.current_block block.
Proof.
  intro Hrun.
  destruct (@dispatch_transaction_cases F block tx post Hrun)
    as [[_ [_ Hproc]] | [_ Hsys]].
  - exact (process_transaction_current_block block tx post Hproc).
  - exact (process_monad_system_transaction_current_block block tx post Hsys).
Qed.

Lemma validate_monad_system_transaction_is_call block tx sender :
  @E.validate_monad_system_transaction F block tx sender = inl tt →
  ∀ gas world,
    Evmc.Message.t.kind (@E.prepare_message F sender gas tx world) = Evmc.Message.CallKind.Call ∧
    Evmc.Message.t.value (@E.prepare_message F sender gas tx world) = T.value tx.
Proof.
  unfold E.validate_monad_system_transaction.
  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).
  change (@Result._return) with (fun (A B : Set) (value : A) ⇒ @inl A B value).
  cbn beta iota zeta.
  destruct (Result.when_ (Chain.Ethereum.Address.op_ltgt sender Chain.Monad.system_sender) _)
    as [[]|]; [|discriminate].
  destruct tx as [[? ? ? ? ? [to_|] ? ? ?] | | | ]; try discriminate.
  intros _ gas world.
  split; reflexivity.
Qed.

Lemma call_from_monad_system_transaction_state_cases msg s :
  Evmc.Message.t.kind msg = Evmc.Message.CallKind.Call →
  snd (@E.Host.call_from_monad_system_transaction F msg s) = s ∨
  ∃ fb0,
    snd (@E.Host.call_from_monad_system_transaction F msg s) =
      snd (MonadVM.Staking.staking_syscalls fb0 msg s).
Proof.
  intro Hkind.
  unfold E.Host.call_from_monad_system_transaction.
  cbv beta iota zeta delta [E.Instantiation Host.Instantiate.functor
    Host.Instantiate.Instantiate_result.Host Host.Instantiate.Host
    Host.Make.functor Host.Make.Make_result.call_from_monad_system_transaction
    Host.Make.call_from_monad_system_transaction].
  unfold Host.Make.call_impl, Host.Make.process_syscall.
  rewrite Hkind. cbn -[Chain.Ethereum.Address.Map.find_opt MonadVM.Staking.staking_syscalls].
  match goal with
  | |- context [@Chain.Ethereum.Address.Map.find_opt ?T (Evmc.Message.t.recipient msg) ?endpoints] ⇒
    destruct (@Chain.Ethereum.Address.Map.find_opt T (Evmc.Message.t.recipient msg) endpoints)
      as [precompile|] eqn:Hfind
  end.
  - apply find_singleton_value in Hfind as [_ Hpre].
    destruct (precompile msg s) as [res s1] eqn:Hsys.
    cbn; unfold Monad.Make_Monad.when_; cbn.
    destruct (negb (Evmc.Result.StatusCode.is_success (Evmc.Result.t.status_code res)));
      cbn; [left; reflexivity |].
    right. rewrite Hpre in Hsys.
    eexists. exact (f_equal snd (eq_sym Hsys)).
  - cbn; unfold Monad.Make_Monad.when_; cbn; left; reflexivity.
Qed.

Theorem process_monad_system_transaction_supply_with_credits block tx allowance remaining post :
  supply_with_credits (B.t.world_state block) (allowance :: remaining) →
  0 ≤ U.to_z (T.value tx) ≤ allowance →
  @E.process_monad_system_transaction F block tx = inl post →
  supply_with_credits (B.t.world_state post) remaining ∧
  totalBalance (B.t.world_state post) ≤
    totalBalance (B.t.world_state block) + U.to_z (T.value tx) ∧
  ∀ query,
    U.to_z (A.t.balance (State.op_pointcaretlparenrparen (B.t.world_state block) (@W.account None query))) ≤
      U.to_z (A.t.balance (State.op_pointcaretlparenrparen (B.t.world_state post) (@W.account None query))).
Proof.
  intros Hsup Hval Hrun.
  unfold E.process_monad_system_transaction in Hrun.
  destruct (@E.validate_monad_system_transaction F block tx Chain.Monad.system_sender)
    as [[]|error] eqn:Hvalid; [|discriminate Hrun].
  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 in 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 (w0 := B.t.world_state block).
  set (sender := Chain.Monad.system_sender).
  set (updated := A.t.with_nonce
    (Numeric.U64.op_plus (A.t.nonce (State.op_pointcaretlparenrparen w0 (@W.account None sender)))
      Numeric.U64.one)
    (State.op_pointcaretlparenrparen w0 (@W.account None sender))).
  assert (HbeforeSupply : balanceInvariant (S.t.world_state beforeVm) ∧
    totalBalance (S.t.world_state beforeVm) = totalBalance w0).
  { change (S.t.world_state beforeVm) with
      (State.op_pointcaretlparenrparenltminus w0 (@W.account (Some false) sender) updated).
    apply (account_write_preserves_supply false w0 sender updated (proj1 Hsup)).
    reflexivity. }
  assert (HbeforeCredits : supply_with_credits (S.t.world_state beforeVm) (allowance :: remaining)).
  { destruct Hsup as [_ [Hall Hbound]].
    split; [exact (proj1 HbeforeSupply) |].
    split; [exact Hall |].
    rewrite (proj2 HbeforeSupply). exact Hbound. }
  assert (HbeforeBalances : ∀ query,
    U.to_z (A.t.balance (State.op_pointcaretlparenrparen (S.t.world_state beforeVm) (@W.account None query))) =
      U.to_z (A.t.balance (State.op_pointcaretlparenrparen w0 (@W.account None query)))).
  { intro query.
    change (S.t.world_state beforeVm) with
      (State.op_pointcaretlparenrparenltminus w0 (@W.account (Some false) sender) updated).
    apply (account_write_preserves_balances false w0 sender updated query (proj1 (proj1 Hsup))).
    reflexivity. }
  match type of Hrun with context [E.Host.call_from_monad_system_transaction ?message beforeVm] ⇒
    set (msg := message) in *;
    destruct (validate_monad_system_transaction_is_call block tx Chain.Monad.system_sender Hvalid
      Gas.zero (S.t.world_state beforeVm)) as [Hkind HmsgVal];
    change (Evmc.Message.t.kind msg = Evmc.Message.CallKind.Call) in Hkind;
    change (Evmc.Message.t.value msg = T.value tx) in HmsgVal;
    pose proof (call_from_monad_system_transaction_state_cases msg beforeVm Hkind) as Hcases;
    destruct (E.Host.call_from_monad_system_transaction msg beforeVm) as [result afterVm]
  end.
  cbn [snd] in Hcases.
  unfold Result.when_ in Hrun.
  destruct (negb (Evmc.Result.StatusCode.is_success (Evmc.Result.t.status_code result)));
    [discriminate Hrun |].
  injection Hrun as <-.
  change (B.t.world_state (E.append_transaction_receipt
    (B.t.with_world_state (S.t.world_state afterVm) block) tx result afterVm))
    with (S.t.world_state afterVm).
  destruct Hcases as [-> | [fb0 ->]].
  - destruct HbeforeCredits as [Hinv [Hall Hbound]].
    inversion Hall as [|? ? Hall_nonneg Hrem]; subst.
    split.
    + apply (supply_with_credits_preserved (S.t.world_state beforeVm) (S.t.world_state beforeVm)
        [allowance] remaining).
      × exact (conj Hinv (conj Hall Hbound)).
      × exact Hinv.
      × change (totalBalance (S.t.world_state beforeVm) ≤
          totalBalance (S.t.world_state beforeVm) + (allowance + 0)).
        lia.
    + split.
      × rewrite (proj2 HbeforeSupply). unfold w0. lia.
      × intro query. rewrite HbeforeBalances. apply Z.le_refl.
  - pose proof (staking_syscalls_supply_with_credits
      fb0 msg beforeVm allowance remaining
      HbeforeCredits ltac:(rewrite HmsgVal; exact Hval))
      as [HsupAfter [HtotAfter HmonoAfter]].
    split; [exact HsupAfter |].
    split.
    + rewrite HmsgVal in HtotAfter. rewrite (proj2 HbeforeSupply) in HtotAfter.
      unfold w0 in HtotAfter. exact HtotAfter.
    + intro query. rewrite <- HbeforeBalances. exact (HmonoAfter query).
Qed.

Corollary process_monad_system_transaction_zero_value_preserves_supply block tx post :
  balanceInvariant (B.t.world_state block) →
  U.to_z (T.value tx) = 0 →
  @E.process_monad_system_transaction F block tx = inl post →
  balanceInvariant (B.t.world_state post) ∧
  totalBalance (B.t.world_state post) ≤ totalBalance (B.t.world_state block) ∧
  ∀ query,
    U.to_z (A.t.balance (State.op_pointcaretlparenrparen (B.t.world_state block) (@W.account None query))) ≤
      U.to_z (A.t.balance (State.op_pointcaretlparenrparen (B.t.world_state post) (@W.account None query))).
Proof.
  intros Hinv Hzero Hrun.
  assert (Hsup : supply_with_credits (B.t.world_state block) (0 :: [])).
  { split; [exact Hinv |].
    split; [constructor; [lia | constructor] |].
    pose proof (proj2 (proj2 Hinv)).
    change (totalBalance (B.t.world_state block) + (0 + 0) < 2^256). lia. }
  destruct (process_monad_system_transaction_supply_with_credits block tx 0 [] post
    Hsup ltac:(lia) Hrun) as [HsupPost [HtotPost HmonoPost]].
  apply supply_with_credits_nil in HsupPost.
  refine (conj HsupPost (conj _ HmonoPost)).
  lia.
Qed.

Theorem dispatch_transaction_supply_with_credits block tx allowance remaining post :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  keccak256OutputSize → @nativeOutputBounds args →
  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 →
  supply_with_credits (B.t.world_state block) (allowance :: remaining) →
  worldFormat (B.t.world_state block) →
  Forall (fun auth ⇒ OCamlString.length (T.Authorization.t.address auth) = 20)
    (T.authorization_list tx) →
  transactionValueAndDataBounds tx →
  (@E.sender_kind_value F tx ≠ Some E.System ∨ U.to_z (T.value tx) ≤ allowance) →
  @E.dispatch_transaction F block tx = inl post →
  supply_with_credits (B.t.world_state post) remaining ∧
  totalBalance (B.t.world_state post) ≤ totalBalance (B.t.world_state block) + allowance.
Proof.
  intros Hrevision Hhash Hnative Hchain Hheader Hrandao Hsup Hformat Hwidth Hvalue Hall Hrun.
  destruct (@dispatch_transaction_cases F block tx post Hrun)
    as [[sender [_ Hproc]] | [HsysKind Hsys]].
  - destruct (process_transaction_preserves_supply block tx post
      Hrevision Hhash Hnative Hchain Hheader Hrandao (proj1 Hsup) Hformat Hwidth Hvalue Hproc)
      as [Hpost Htot].
    destruct Hsup as [Hinv [Hfor Hbound]].
    inversion Hfor as [|? ? Hall_nonneg Hrem]; subst.
    split.
    + apply (supply_with_credits_preserved (B.t.world_state block) (B.t.world_state post)
        [allowance] remaining (conj Hinv (conj Hfor Hbound)) Hpost).
      change (totalBalance (B.t.world_state post) ≤
        totalBalance (B.t.world_state block) + (allowance + 0)).
      lia.
    + lia.
  - destruct Hall as [HnotSys | Hval_le]; [contradiction (HnotSys HsysKind) |].
    pose proof (proj1 (proj1 Hvalue)) as Hval_nonneg.
    destruct (process_monad_system_transaction_supply_with_credits block tx allowance remaining post
      Hsup (conj Hval_nonneg Hval_le) Hsys) as [HsupPost [HtotPost _]].
    split; [exact HsupPost | lia].
Qed.

Corollary dispatch_transaction_preserves_supply block tx post :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  keccak256OutputSize → @nativeOutputBounds args →
  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.sender_kind_value F tx ≠ Some E.System ∨ U.to_z (T.value tx) = 0) →
  @E.dispatch_transaction F block tx = inl post →
  balanceInvariant (B.t.world_state post) ∧
    totalBalance (B.t.world_state post) ≤ totalBalance (B.t.world_state block).
Proof.
  intros Hrevision Hhash Hnative Hchain Hheader Hrandao Hinitial Hformat Hwidth Hvalue Hzero Hrun.
  assert (Hsup : supply_with_credits (B.t.world_state block) (0 :: [])).
  { split; [exact Hinitial |].
    split; [constructor; [lia | constructor] |].
    pose proof (proj2 (proj2 Hinitial)).
    change (totalBalance (B.t.world_state block) + (0 + 0) < 2^256). lia. }
  assert (Hall : @E.sender_kind_value F tx ≠ Some E.System ∨ U.to_z (T.value tx) ≤ 0).
  { destruct Hzero as [HnotSys | Hz]; [left; exact HnotSys | right; lia]. }
  destruct (dispatch_transaction_supply_with_credits block tx 0 [] post
    Hrevision Hhash Hnative Hchain Hheader Hrandao Hsup Hformat Hwidth Hvalue Hall Hrun)
    as [HsupPost HtotPost].
  apply supply_with_credits_nil in HsupPost.
  split; [exact HsupPost | lia].
Qed.

Definition headerWords (header : Chain.Ethereum.Block.Header.t) : Prop :=
  wordRange (Support.UintN.to_z (Chain.Ethereum.Block.Header.t.base_fee_per_gas header)) ∧
  Forall (fun n ⇒ 0 ≤ n < 2^64)
    [Support.UintN.to_z (Chain.Ethereum.Block.Header.t.number header);
     Chain.Ethereum.Block.Header.t.timestamp header;
     Support.UintN.to_z (Chain.Ethereum.Block.Header.t.gas_limit header)] ∧
  OCamlString.length (Chain.Ethereum.Block.Header.t.prev_randao header) ≤ 32.

No invariant is assumed at intermediate transaction boundaries: each transaction establishes it for the next, including when its VM reverts.
Theorem transactions_preserve_supply block txs post :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  keccak256OutputSize → @nativeOutputBounds args →
  wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  headerWords (Chain.Ethereum.Block.t.header (B.t.current_block block)) →
  Forall (fun tx ⇒ transactionValueAndDataBounds tx ∧ Forall
    (fun auth ⇒ OCamlString.length (T.Authorization.t.address auth) = 20) (T.authorization_list tx)) txs →
  balanceInvariant (B.t.world_state block) → worldFormat (B.t.world_state block) →
  Result.List.fold_leftM (@E.process_transaction F) block txs = inl post →
  balanceInvariant (B.t.world_state post) ∧
    totalBalance (B.t.world_state post) ≤ totalBalance (B.t.world_state block).
Proof.
  intros Hrevision Hhash Hnative Hchain Hheader Htxs. revert block Hheader.
  induction Htxs as [|tx txs [Hvalue Hwidth] Htxs IH];
    intros block Hheader Hinitial Hformat Hrun.
  - injection Hrun as <-. split; [exact Hinitial|lia].
  - change (Result.op_letdollar (@E.process_transaction F block tx)
      (fun next ⇒ Result.List.fold_leftM (@E.process_transaction F) next txs) = inl post) in Hrun.
    destruct (@E.process_transaction F block tx) as [next|error] eqn:Hstep;
      [|discriminate Hrun].
    pose proof (process_transaction_preserves_supply block tx next Hrevision Hhash Hnative Hchain
      (proj1 (proj2 Hheader)) (proj2 (proj2 Hheader)) Hinitial Hformat Hwidth Hvalue Hstep)
      as [Hnext Htotal].
    pose proof (@process_transaction_preserves_format F
      block tx Hrevision Hwidth Hformat) as HnextFormat.
    rewrite Hstep in HnextFormat.
    assert (HnextHeader : headerWords (Chain.Ethereum.Block.t.header (B.t.current_block next))).
    { rewrite (process_transaction_current_block block tx next Hstep). exact Hheader. }
    destruct (IH next HnextHeader Hnext HnextFormat Hrun) as [Hpost HpostTotal].
    split; [exact Hpost|lia].
Qed.

Theorem dispatched_transactions_preserve_supply block txs post :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  keccak256OutputSize → @nativeOutputBounds args →
  wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  headerWords (Chain.Ethereum.Block.t.header (B.t.current_block block)) →
  Forall (fun tx ⇒ transactionValueAndDataBounds tx ∧
    Forall (fun auth ⇒ OCamlString.length (T.Authorization.t.address auth) = 20) (T.authorization_list tx) ∧
    (@E.sender_kind_value F tx ≠ Some E.System ∨ U.to_z (T.value tx) = 0)) txs →
  balanceInvariant (B.t.world_state block) → worldFormat (B.t.world_state block) →
  Result.List.fold_leftM (@E.dispatch_transaction F) block txs = inl post →
  balanceInvariant (B.t.world_state post) ∧
    totalBalance (B.t.world_state post) ≤ totalBalance (B.t.world_state block).
Proof.
  intros Hrevision Hhash Hnative Hchain Hheader Htxs. revert block Hheader.
  induction Htxs as [|tx txs [Hvalue [Hwidth Hzero]] Htxs IH];
    intros block Hheader Hinitial Hformat Hrun.
  - injection Hrun as <-. split; [exact Hinitial|lia].
  - change (Result.op_letdollar (@E.dispatch_transaction F block tx)
      (fun next ⇒ Result.List.fold_leftM (@E.dispatch_transaction F) next txs) = inl post) in Hrun.
    destruct (@E.dispatch_transaction F block tx) as [next|error] eqn:Hstep;
      [|discriminate Hrun].
    pose proof (dispatch_transaction_preserves_supply block tx next Hrevision Hhash Hnative Hchain
      (proj1 (proj2 Hheader)) (proj2 (proj2 Hheader)) Hinitial Hformat Hwidth Hvalue Hzero Hstep)
      as [Hnext Htotal].
    pose proof (@dispatch_transaction_preserves_format F
      block tx Hrevision Hwidth Hformat) as HnextFormat.
    rewrite Hstep in HnextFormat.
    assert (HnextHeader : headerWords (Chain.Ethereum.Block.t.header (B.t.current_block next))).
    { rewrite (dispatch_transaction_current_block block tx next Hstep). exact Hheader. }
    destruct (IH next HnextHeader Hnext HnextFormat Hrun) as [Hpost HpostTotal].
    split; [exact Hpost|lia].
Qed.

Theorem dispatched_transactions_supply_with_credits
    (txAllowance : T.t → Z) block txs suffix post :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  keccak256OutputSize → @nativeOutputBounds args →
  wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  headerWords (Chain.Ethereum.Block.t.header (B.t.current_block block)) →
  Forall (fun tx ⇒ transactionValueAndDataBounds tx ∧
    Forall (fun auth ⇒ OCamlString.length (T.Authorization.t.address auth) = 20) (T.authorization_list tx) ∧
    (@E.sender_kind_value F tx ≠ Some E.System ∨ U.to_z (T.value tx) ≤ txAllowance tx)) txs →
  supply_with_credits (B.t.world_state block)
    (Stdlib.Lists.List.map txAllowance txs ++ suffix) →
  worldFormat (B.t.world_state block) →
  Result.List.fold_leftM (@E.dispatch_transaction F) block txs = inl post →
  supply_with_credits (B.t.world_state post) suffix ∧
    totalBalance (B.t.world_state post) ≤
      totalBalance (B.t.world_state block) +
      externalCreditTotal (Stdlib.Lists.List.map txAllowance txs).
Proof.
  intros Hrevision Hhash Hnative Hchain Hheader Htxs. revert block Hheader.
  induction Htxs as [|tx txs [Hvalue [Hwidth Hall]] Htxs IH];
    intros block Hheader Hsup Hformat Hrun.
  - injection Hrun as <-. cbn [Stdlib.Lists.List.map app] in Hsup |- ×.
    change (externalCreditTotal []) with 0. split; [exact Hsup|lia].
  - change (Result.op_letdollar (@E.dispatch_transaction F block tx)
      (fun next ⇒ Result.List.fold_leftM (@E.dispatch_transaction F) next txs) = inl post) in Hrun.
    destruct (@E.dispatch_transaction F block tx) as [next|error] eqn:Hstep;
      [|discriminate Hrun].
    cbn [Stdlib.Lists.List.map app] in Hsup.
    destruct (dispatch_transaction_supply_with_credits block tx (txAllowance tx)
      (Stdlib.Lists.List.map txAllowance txs ++ suffix) next
      Hrevision Hhash Hnative Hchain (proj1 (proj2 Hheader)) (proj2 (proj2 Hheader))
      Hsup Hformat Hwidth Hvalue Hall Hstep) as [HnextSup HnextTotal].
    pose proof (@dispatch_transaction_preserves_format F
      block tx Hrevision Hwidth Hformat) as HnextFormat.
    rewrite Hstep in HnextFormat.
    assert (HnextHeader : headerWords (Chain.Ethereum.Block.t.header (B.t.current_block next))).
    { rewrite (dispatch_transaction_current_block block tx next Hstep). exact Hheader. }
    destruct (IH next HnextHeader HnextSup HnextFormat Hrun) as [HpostSup HpostTotal].
    change (externalCreditTotal (Stdlib.Lists.List.map txAllowance (tx :: txs)))
      with (txAllowance tx + externalCreditTotal (Stdlib.Lists.List.map txAllowance txs)).
    split; [exact HpostSup|lia].
Qed.

Lemma system_message_current_block block addr data :
  B.t.current_block (snd (@E.process_system_message F
    block addr data)) = B.t.current_block block.
Proof.
  unfold E.process_system_message.
  match goal with |- context [if ?test then _ else _] ⇒ destruct test end; [reflexivity|].
  cbn beta iota zeta.
  match goal with |- context [E.Host.call ?msg ?initial] ⇒
    destruct (E.Host.call msg initial) as [result afterVm]
  end. reflexivity.
Qed.

System calls use the same concrete VM proof. They have zero value and price, but their code is not assumed harmless.
Lemma system_message_preserves_supply block addr data :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  keccak256OutputSize → @nativeOutputBounds args →
  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).
Proof.
  intros Hrevision Hhash Hnative 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|apply Z.le_refl]. }
  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_call_supply_and_output F

     (totalBalance (B.t.world_state block)) msg initial
    Hrevision Hhash Hnative Hmsg
    (conj (conj (conj Hinitial (Z.le_refl _)) HformatEntry) Hcontext)) as Hsafe.
  destruct (E.Host.call msg initial) as [result afterVm].
  exact (proj1 (proj1 (proj1 Hsafe))).
Qed.

End Execution.

Print Assumptions process_transaction_preserves_supply.

Print Assumptions transactions_preserve_supply.

Print Assumptions system_message_preserves_supply.