Library SetcodeConcrete.transactionguardedreserve

Complete-transaction reserve and code bounds for SETCODE accounts

Combines the guarded-account VM proof, recent-sender reserve proof, ordinary-sender reserve proof, and empty-account nondebit proof into complete-transaction bounds over readAccount (B.t.world_state block).
From Stdlib Require Import List String ZArith Bool Lia.
Require Import RocqOfOCaml.RocqOfOCaml MonadVM.Execution.
Require Import QedkConcrete.authorization QedkConcrete.authorizationcodecore
  QedkConcrete.accountcode
  QedkConcrete.worldaccounts QedkConcrete.hostframe QedkConcrete.transactionframes
  QedkConcrete.validation QedkConcrete.reservecheck QedkConcrete.reservestorage
  QedkConcrete.reserveencoding QedkConcrete.hoststoragewords
  QedkConcrete.hostaccountformat QedkConcrete.hashwords QedkConcrete.assemblychecked
  QedkConcrete.nativeinputs QedkConcrete.supply QedkConcrete.wordrange
  QedkConcrete.protectedstorage QedkConcrete.protectedstoragenative
  QedkConcrete.protectedstorageboundarycore.
Require Import SetcodeConcrete.consensuschecks SetcodeConcrete.reserve
  SetcodeConcrete.transactionentry SetcodeConcrete.transactionentrysafe
  SetcodeConcrete.transactionfinalize SetcodeConcrete.transactionaccountfinalize
  QedkConcrete.vmcallframe
  SetcodeConcrete.transactionsupply SetcodeConcrete.executionemptyaccount
  SetcodeConcrete.emptyaccount SetcodeConcrete.accountframe
  SetcodeConcrete.executiondestruction SetcodeConcrete.codeactivity
  SetcodeConcrete.transactionnondebit SetcodeConcrete.transactionconfig
  SetcodeConcrete.executionconfig SetcodeConcrete.guardedaccountframe
  SetcodeConcrete.executionguardedaccount SetcodeConcrete.transactionreserve
  SetcodeConcrete.transactionsenderreserve SetcodeConcrete.blockconfig.
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.
Module Addr := Chain.Ethereum.Address.
Module Block := Chain.Ethereum.Block.
Local Abbreviation readAccount := (fun world addr ⇒
  State.op_pointcaretlparenrparen world (W.account None addr)).
Local Abbreviation number := (fun state ⇒
  Block.Header.t.number (Block.t.header (B.t.current_block state))).
Local Abbreviation native := Reserve_balance.precompile_address.

Lemma noncontract_code_empty_or_delegated account :
  A.is_smart_contract account = false →
  A.t.code account = Byte_string.Bytes.empty ∨
  Delegation.is_valid_delegation (A.t.code account) = true.
Proof.
  intro Hsc.
  change (andb
    (negb (Byte_string.Bytes.op_eq (A.t.code account) Byte_string.Bytes.empty))
    (negb (Delegation.is_valid_delegation (A.t.code account))) = false) in Hsc.
  apply Bool.andb_false_iff in Hsc as [Hempty|Hdel].
  - apply Bool.negb_false_iff in Hempty.
    change (Z.eqb (OCamlString.compare (A.t.code account) Byte_string.Bytes.empty) 0 = true) in Hempty.
    apply Z.eqb_eq in Hempty. left. apply address_compare_eq, Hempty.
  - apply Bool.negb_false_iff in Hdel. right. exact Hdel.
Qed.

Lemma empty_code_noncontract account :
  A.t.code account = Byte_string.Bytes.empty →
  A.is_smart_contract account = false.
Proof.
  intro Hcode.
  change (andb
    (negb (Byte_string.Bytes.op_eq (A.t.code account) Byte_string.Bytes.empty))
    (negb (Delegation.is_valid_delegation (A.t.code account))) = false).
  rewrite Hcode. reflexivity.
Qed.

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

Lemma transaction_entry_preserves_noncontract block tx validation query :
  stringmaps.WellFormed (W.t.accounts (B.t.world_state block)) →
  Forall (fun auth ⇒ OCamlString.length (T.Authorization.t.address auth) = 20)
    (T.authorization_list tx) →
  A.is_smart_contract (readAccount (B.t.world_state block) query) = false →
  A.is_smart_contract
    (readAccount (S.t.world_state (snd (transactionVmInput block tx validation))) query) = false.
Proof.
  intros Hmap Hwidth Hbefore. unfold transactionVmInput, transactionPrefix.
  match goal with |- context [Result.List.fold_left ?step (nil, ?start) ?auths] ⇒
    set (charged := start) in × end.
  assert (HchargedMap : stringmaps.WellFormed (W.t.accounts (S.t.world_state charged)))
    by (apply account_write_wellformed; exact Hmap).
  assert (HchargedSc : A.is_smart_contract (readAccount (S.t.world_state charged) query) = false).
  { assert (Hcode : A.t.code (readAccount (S.t.world_state charged) query) =
      A.t.code (readAccount (B.t.world_state block) query)).
    { change (A.t.code (readAccount
        (State.op_pointcaretlparenrparenltminus (B.t.world_state block)
          (W.account (Some false) (E.transaction_validation.sender validation))
          (A.t.with_balance
            (U.op_minus (A.t.balance (readAccount (B.t.world_state block)
              (E.transaction_validation.sender validation))) (E.transaction_validation.total_fee validation))
            (A.t.with_nonce (Setcode_rules.advance_sender_nonce
              (migratedSender block (E.transaction_validation.sender validation))
              (A.t.nonce (readAccount (B.t.world_state block) (E.transaction_validation.sender validation)))
              (T.nonce tx))
              (readAccount (B.t.world_state block) (E.transaction_validation.sender validation))))) query) =
        A.t.code (readAccount (B.t.world_state block) query)).
      cbv beta. rewrite code_after_account_write by exact Hmap.
      destruct (String.eqb (E.transaction_validation.sender validation) query) eqn:Heq;
        [apply String.eqb_eq in Heq; subst query|]; reflexivity. }
    cbv beta in Hcode.
    change (andb
      (negb (Byte_string.Bytes.op_eq (A.t.code (State.op_pointcaretlparenrparen (S.t.world_state charged) (W.account None query))) Byte_string.Bytes.empty))
      (negb (Delegation.is_valid_delegation (A.t.code (State.op_pointcaretlparenrparen (S.t.world_state charged) (W.account None query))))) = false).
    rewrite Hcode. exact Hbefore. }
  pose proof (authorizations_preserve_noncontract (T.authorization_list tx) nil charged query
    Hwidth HchargedMap HchargedSc) as Hauth.
  match goal with |- context [Result.List.fold_left ?step (nil, charged) ?auths] ⇒
    destruct (Result.List.fold_left step (nil, charged) auths) as [applied prepared] end.
  cbn beta iota zeta delta [fst snd] in Hauth |- ×.
  unfold State.op_pointcaretlparenrparen, W.account, W.account_opt.
  cbn -[E.bump_emptying_transaction_counters Addr.Map.find_opt A.is_smart_contract].
  rewrite bump_counters_accounts. exact Hauth.
Qed.
End Entry.

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_preserves_empty_code block tx validation post query :
  query ≠ native →
  balanceInvariant (B.t.world_state block) →
  E.validate_transaction block tx = inl validation →
  E.process_transaction block tx = inl post →
  A.t.code (readAccount (S.t.world_state (snd (transactionVmInput block tx validation))) query) =
    Byte_string.Bytes.empty →
  ¬ In query (S.t.accounts_created_in_current_transaction (transactionFinished block tx validation)) →
  A.t.code (readAccount (B.t.world_state post) query) = Byte_string.Bytes.empty.
Proof using F Hcold Hrevision Hwarm access cold reserve warm write.
  intros HnotNative Hinitial Hv Hrun Hempty Hcreated.
  pose proof (transaction_entry_map block tx validation Hv Hinitial) as HentryMap.
  pose proof (transaction_entry_destruction block tx validation) as Hdestruct.
  pose proof (transaction_entry_message block tx validation) as [_ [_ [Htarget _]]].
  assert (Hgas : 0 ≤ Evmc.Message.t.gas (fst (transactionVmInput block tx validation)) < 2^63).
  { unfold transactionVmInput. destruct (transactionPrefix block tx validation).
    apply (validated_message_gas block tx validation _ Hv). }
  set (expected := A.t.nonce (readAccount (S.t.world_state (snd (transactionVmInput block tx validation))) query)).
  set (P := fun code nonce ⇒ code = Byte_string.Bytes.empty ∧ nonce = expected).
  assert (Hpost : worldAccount query P (B.t.world_state post)).
  { apply (process_transaction_retains_finished_account block tx validation post query P Hv Hrun).
    all: unfold transactionFinished in Hcreated |- ×.
    all: destruct (transactionVmInput block tx validation) as [msg entry].
    all: cbn beta iota zeta delta [fst snd] in HentryMap, Hdestruct, Htarget, Hgas, Hempty, expected.
    all: destruct (migratedSender block (E.transaction_validation.sender validation)).
    - split; [exact HentryMap|split; [exact Hempty|reflexivity]].
    - assert (HtargetAllowed : Evmc.Message.t.kind msg = Evmc.Message.CallKind.Create ∨
        Evmc.Message.t.kind msg = Evmc.Message.CallKind.Create2 ∨
        (Evmc.Message.t.recipient msg = query → Evmc.Message.t.code_address msg = query))
        by (right; right; intro H; rewrite Htarget; exact H).
      pose proof (@transaction_call_preserves_empty_account F query expected HnotNative
        cold warm access write reserve Hcold Hwarm Hrevision tx msg Hgas HtargetAllowed
        entry (conj HentryMap (or_intror (conj Hempty eq_refl)))) as [Hwf [Hin|HP]].
      + contradiction.
      + split; assumption.
    - rewrite Hdestruct. tauto.
    - exact (@uncreated_sender_not_destroyed F cold warm access write reserve
        Hrevision Hcold Hwarm tx msg entry query Hgas Hdestruct Hcreated). }
  exact (proj1 (proj2 Hpost)).
Qed.

Theorem process_transaction_empty_without_recovery block tx validation post query :
  wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  headerWords (Chain.Ethereum.Block.t.header (B.t.current_block block)) →
  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 →
  query ≠ native →
  ¬ In query (recoveredAuthorities tx) →
  E.validate_transaction block tx = inl validation →
  E.process_transaction block tx = inl post →
  A.t.code (readAccount (B.t.world_state block) query) = Byte_string.Bytes.empty →
  ¬ In query (S.t.accounts_created_in_current_transaction (transactionFinished block tx validation)) →
  A.t.code (readAccount (B.t.world_state post) query) = Byte_string.Bytes.empty ∧
  Z.max (U.to_z (A.t.balance (readAccount (B.t.world_state block) query)) -
    (if String.eqb (E.transaction_validation.sender validation) query
     then U.to_z (E.transaction_validation.total_fee validation) + U.to_z (T.value tx)
     else 0)) 0 ≤ U.to_z (A.t.balance (readAccount (B.t.world_state post) query)).
Proof using F Hcold Hhash Hnative Hrevision Hwarm U8 UB UI0 access cold reserve warm write.
  intros Hchain Hheader Hinitial Hformat Hwidth Hvalue HnotNative HnoAuth Hv Hrun Hcode Hcreated.
  pose proof (transaction_entry_code_without_recovery block tx validation query (proj1 Hinitial) HnoAuth) as HentryCode.
  cbv beta in HentryCode, Hcode. rewrite Hcode in HentryCode.
  split.
  - exact (process_transaction_preserves_empty_code block tx validation post query
      HnotNative Hinitial Hv Hrun HentryCode Hcreated).
  - exact (process_transaction_empty_account cold warm access write reserve
      Hrevision Hcold Hwarm Hhash Hnative block tx validation post query
      Hchain Hheader Hinitial Hformat Hwidth Hvalue Hv Hrun HentryCode Hcreated).
Qed.

Theorem process_transaction_protects_guarded_nonsender block tx validation post query initial :
  wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  headerWords (Chain.Ethereum.Block.t.header (B.t.current_block block)) →
  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 →
  signaturesAvoidAddress tx native →
  stringmaps.WellFormed initial → storageWords initial →
  worldConfig (number block) initial (B.t.world_state block) →
  E.validate_transaction block tx = inl validation →
  E.process_transaction block tx = inl post →
  query ≠ E.transaction_validation.sender validation →
  query ≠ native →
  A.is_smart_contract (readAccount (B.t.world_state block) query) = false →
  Reserve_balance.user_reserve_balance (B.t.world_state block) (number block) query ≠ 0 →
  ¬ In query (S.t.accounts_created_in_current_transaction (transactionFinished block tx validation)) →
  A.is_smart_contract (readAccount (B.t.world_state post) query) = false ∧
  Z.min (U.to_z (A.t.balance (readAccount (B.t.world_state block) query)))
    (U.to_z (Reserve_balance.user_reserve_balance (B.t.world_state block) (number block) query)) ≤
    U.to_z (A.t.balance (readAccount (B.t.world_state post) query)).
Proof using F Hcold Hhash Hnative Hrevision Hwarm U8 UB UI0 access cold reserve warm write.
  intros Hchain Hheader Hinitial Hformat Hwidth Hvalue Hsig HstorageMap HstorageWords Hconfig
    Hv Hrun Hother HnotNative Hnoncontract Hpositive Hcreated.
  pose proof (transaction_entry_preserves_noncontract block tx validation query
    (proj1 Hinitial) Hwidth Hnoncontract) as HentrySc.
  destruct (noncontract_code_empty_or_delegated _ HentrySc) as [HentryEmpty|HentryDel].
  - pose proof (process_transaction_preserves_empty_code block tx validation post query
      HnotNative Hinitial Hv Hrun HentryEmpty Hcreated) as HpostEmpty.
    pose proof (process_transaction_empty_account cold warm access write reserve
      Hrevision Hcold Hwarm Hhash Hnative block tx validation post query
      Hchain Hheader Hinitial Hformat Hwidth Hvalue Hv Hrun HentryEmpty Hcreated) as Hbal.
    assert (Hneq : String.eqb (E.transaction_validation.sender validation) query = false)
      by (apply String.eqb_neq; congruence).
    rewrite Hneq in Hbal.
    split; [apply empty_code_noncontract; exact HpostEmpty|lia].
  - set (delegated := A.t.code (readAccount (S.t.world_state (snd (transactionVmInput block tx validation))) query)) in ×.
    assert (HthresholdEq : Reserve_balance.user_reserve_balance (B.t.world_state block) (number block) query =
      initialThreshold initial (number block) query).
    { destruct Hconfig as [_ [_ [_ [updates Hwrites]]]].
      pose proof (reserve_storage_writes_threshold_any_account _ _ _ _ query (number block)
        HstorageMap HstorageWords Hwrites ltac:(lia)) as Hth.
      unfold Reserve_balance.user_reserve_balance, Reserve_balance.stored_config, initialThreshold.
      f_equal. exact Hth. }
    assert (HinitPos : initialThreshold initial (number block) query ≠ 0)
      by (rewrite <- HthresholdEq; exact Hpositive).
    assert (HentryConfig : configStorage (number block) initial (snd (transactionVmInput block tx validation))).
    { apply (transaction_entry_config block tx validation native
        (reachableReserveStorage (number block) initial) Hsig Hv).
      destruct Hconfig as [Hm [Hn [Hc Hw]]]. repeat split; assumption. }
    pose proof (transaction_entry_metadata block tx validation) as [Hsnapshot [Hblock Hsender]].
    pose proof (transaction_entry_destruction block tx validation) as Hdestruct.
    pose proof (transaction_entry_map block tx validation Hv Hinitial) as HentryMap.
    pose proof (transaction_entry_balances block tx validation Hv Hinitial query) as Hbalance.
    pose proof (@process_transaction_retains_execution_balance F UI0 UB U8
      cold warm access write reserve Hrevision Hcold Hwarm Hhash Hnative
      block tx validation post Hchain (proj1 (proj2 Hheader)) (proj2 (proj2 Hheader))
      Hinitial Hformat Hwidth Hvalue Hv Hrun) as Hfinal.
    pose proof (@process_transaction_preserves_supply F UI0 UB U8
      cold warm access write reserve Hrevision Hcold Hwarm Hhash Hnative
      block tx post Hchain (proj1 (proj2 Hheader)) (proj2 (proj2 Hheader))
      Hinitial Hformat Hwidth Hvalue Hrun) as [HpostSupply _].
    pose proof (account_balance_bounded_by_supply (B.t.world_state post) query
      (proj1 (proj2 HpostSupply))) as HpostNonneg.
    assert (Hgas : 0 ≤ Evmc.Message.t.gas (fst (transactionVmInput block tx validation)) < 2^63).
    { unfold transactionVmInput. destruct (transactionPrefix block tx validation).
      apply (validated_message_gas block tx validation _ Hv). }
    assert (Htarget : let msg := fst (transactionVmInput block tx validation) in
      Evmc.Message.t.kind msg = Evmc.Message.CallKind.Create ∨
      Evmc.Message.t.kind msg = Evmc.Message.CallKind.Create2 ∨
      (Evmc.Message.t.recipient msg = native → Evmc.Message.t.code_address msg = native)).
    { unfold transactionVmInput. destruct (transactionPrefix block tx validation).
      unfold E.prepare_message. destruct (T.call_or_create_value tx) as [[target]|[code]];
        cbn beta iota zeta; [right; right; exact (fun H ⇒ H)|left; reflexivity]. }
    assert (HentryGuarded : guardedAccount query delegated initial (number block)
      (E.transaction_validation.sender validation) (snd (transactionVmInput block tx validation))).
    { split; [exact HentryConfig|]. split; [exact Hsender|].
      split; [exact HentryMap|right; reflexivity]. }
    assert (HpostDel : worldAccount query (fun code _ ⇒ code = delegated) (B.t.world_state post)).
    { apply (process_transaction_retains_finished_account block tx validation post query
        (fun code _ ⇒ code = delegated) Hv Hrun).
      all: unfold transactionFinished in Hcreated |- ×.
      all: destruct (transactionVmInput block tx validation) as [msg entry].
      all: cbn beta iota zeta delta [fst snd] in HentryGuarded, Hgas, Htarget, Hdestruct, HentryMap.
      all: destruct (migratedSender block (E.transaction_validation.sender validation)).
      - split; [exact HentryMap|exact (eq_refl delegated)].
      - pose proof (@transaction_call_guarded_account F query delegated initial (number block)
          (E.transaction_validation.sender validation) Hother HnotNative HentryDel
          HstorageMap HstorageWords HinitPos cold warm access write reserve Hrevision Hcold Hwarm
          tx msg Hgas Htarget entry HentryGuarded) as [_ [_ [Hwf [Hin|Hcode]]]];
          [contradiction|split; assumption].
      - rewrite Hdestruct. tauto.
      - exact (@uncreated_sender_not_destroyed F cold warm access write reserve
          Hrevision Hcold Hwarm tx msg entry query Hgas Hdestruct Hcreated). }
    assert (HpostSc : A.is_smart_contract (readAccount (B.t.world_state post) query) = false).
    { destruct HpostDel as [_ Hcode].
      change (A.t.code (State.op_pointcaretlparenrparen (B.t.world_state post) (W.account None query)) = delegated) in Hcode.
      change (andb
        (negb (Byte_string.Bytes.op_eq (A.t.code (State.op_pointcaretlparenrparen (B.t.world_state post) (W.account None query))) Byte_string.Bytes.empty))
        (negb (Delegation.is_valid_delegation (A.t.code (State.op_pointcaretlparenrparen (B.t.world_state post) (W.account None query))))) = false).
      rewrite Hcode, HentryDel, Bool.andb_false_r. reflexivity. }
    split; [exact HpostSc|].
    destruct (Addr.Map.find_opt query (W.t.accounts (B.t.world_state block))) as [original|] eqn:Hfind.
    + assert (Horiginal : readAccount (B.t.world_state block) query = original).
      { change ((match Addr.Map.find_opt query (W.t.accounts (B.t.world_state block)) with
          Some ac ⇒ ac | None ⇒ A.empty end) = original). rewrite Hfind. reflexivity. }
      assert (Hneq : String.eqb (E.transaction_validation.sender validation) query = false)
        by (apply String.eqb_neq; congruence).
      rewrite Hneq in Hbalance.
      unfold transactionFinished in Hcreated, Hfinal.
      destruct (transactionVmInput block tx validation) as [msg entry].
      cbn beta iota zeta delta [fst snd] in Hsnapshot, Hblock, Hsender, Hdestruct,
        Hbalance, Hgas, Htarget, HentryGuarded, Hcreated, Hfinal.
      cbv beta in Hbalance, Horiginal. rewrite Horiginal in Hbalance |- ×.
      change (A.t.balance (accountAt entry query) = A.t.balance original) in Hbalance.
      assert (HentryBound : protected entry query original ≤ A.t.balance (accountAt entry query)).
      { rewrite Hbalance. change (U.to_z (protected entry query original) ≤ U.to_z (A.t.balance original)).
        unfold protected. rewrite u256_min. apply Z.le_min_r. }
      assert (Hprotected : U.to_z (protected entry query original) =
        Z.min (U.to_z (Reserve_balance.user_reserve_balance (B.t.world_state block) (number block) query))
          (U.to_z (A.t.balance original))).
      { unfold protected. rewrite Hsnapshot, Hblock, u256_min. reflexivity. }
      rewrite Z.min_comm, <- Hprotected.
      destruct (migratedSender block (E.transaction_validation.sender validation)).
      × eapply Z.le_trans; [exact HentryBound|apply Hfinal; rewrite Hdestruct; tauto].
      × assert (HnotDestroyed : ¬ In query (S.t.self_destruct (snd (E.Host.call_from_eoa tx msg entry)))).
        { exact (@uncreated_sender_not_destroyed F cold warm access write reserve
            Hrevision Hcold Hwarm tx msg entry query Hgas Hdestruct Hcreated). }
        pose proof (@transaction_call_protects_guarded_nonsender F query delegated initial (number block)
          (E.transaction_validation.sender validation) Hother HnotNative HentryDel
          HstorageMap HstorageWords HinitPos cold warm access write reserve Hrevision Hcold Hwarm
          tx msg entry original Hgas Htarget Hdestruct
          ltac:(rewrite Hsnapshot; apply address_find_member; exact Hfind)
          HentryGuarded HentryBound Hcreated) as [_ [_ Hbound]].
        eapply Z.le_trans; [exact Hbound|exact (Hfinal query HnotDestroyed)].
    + assert (Hzero : U.to_z (A.t.balance (readAccount (B.t.world_state block) query)) = 0).
      { change (U.to_z (A.t.balance
          (match Addr.Map.find_opt query (W.t.accounts (B.t.world_state block)) with
           Some ac ⇒ ac | None ⇒ A.empty end)) = 0). rewrite Hfind. reflexivity. }
      pose proof (configured_reserve_word (B.t.world_state block) (number block) query Hformat) as HresWord.
      unfold wordRange in HresWord. cbv beta in HpostNonneg. rewrite Hzero. lia.
Qed.

Theorem process_transaction_recent_sender_bound block tx validation post query :
  wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  headerWords (Chain.Ethereum.Block.t.header (B.t.current_block block)) →
  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 block tx = inl validation →
  E.process_transaction block tx = inl post →
  query ≠ E.transaction_validation.sender validation →
  Reserve_balance.sent_in_window
    (S.t.with_tx_chain_id E.Params.(Execution.Make_Params_signature.chain_id)
      (S.make block (E.transaction_validation.sender validation) tx)) query = true →
  ¬ In query (S.t.accounts_created_in_current_transaction (transactionFinished block tx validation)) →
  Z.min (U.to_z (A.t.balance (readAccount (B.t.world_state block) query)))
    (U.to_z (Reserve_balance.user_reserve_balance (B.t.world_state block) (number block) query)) ≤
    U.to_z (A.t.balance (readAccount (B.t.world_state post) query)).
Proof using F Hcold Hhash Hnative Hrevision Hwarm U8 UB UI0 access cold reserve warm write.
  intros Hchain Hheader Hinitial Hformat Hwidth Hvalue Hv Hrun Hother Hrecent Hcreated.
  destruct (Addr.Map.find_opt query (W.t.accounts (B.t.world_state block))) as [original|] eqn:Hfind.
  - assert (Horiginal : readAccount (B.t.world_state block) query = original).
    { change ((match Addr.Map.find_opt query (W.t.accounts (B.t.world_state block)) with
        Some ac ⇒ ac | None ⇒ A.empty end) = original). rewrite Hfind. reflexivity. }
    pose proof (process_transaction_protects_recent_sender cold warm access write reserve
      Hrevision Hcold Hwarm Hhash Hnative block tx validation post query original
      Hchain Hheader Hinitial Hformat Hwidth Hvalue Hv Hrun Hfind Hother Hrecent Hcreated) as Hbound.
    rewrite u256_min in Hbound. cbv beta in Horiginal |- ×. rewrite Horiginal. lia.
  - assert (Hzero : U.to_z (A.t.balance (readAccount (B.t.world_state block) query)) = 0).
    { change (U.to_z (A.t.balance
        (match Addr.Map.find_opt query (W.t.accounts (B.t.world_state block)) with
         Some ac ⇒ ac | None ⇒ A.empty end)) = 0). rewrite Hfind. reflexivity. }
    pose proof (@process_transaction_preserves_supply F UI0 UB U8
      cold warm access write reserve Hrevision Hcold Hwarm Hhash Hnative
      block tx post Hchain (proj1 (proj2 Hheader)) (proj2 (proj2 Hheader))
      Hinitial Hformat Hwidth Hvalue Hrun) as [HpostSupply _].
    pose proof (account_balance_bounded_by_supply (B.t.world_state post) query
      (proj1 (proj2 HpostSupply))) as HpostNonneg.
    pose proof (configured_reserve_word (B.t.world_state block) (number block) query Hformat) as HresWord.
    unfold wordRange in HresWord. cbv beta in HpostNonneg |- ×. rewrite Hzero. lia.
Qed.

Theorem process_transaction_ordinary_sender_bound block tx validation post :
  wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  headerWords (Chain.Ethereum.Block.t.header (B.t.current_block block)) →
  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 block tx = inl validation →
  E.process_transaction block tx = inl post →
  let sender := E.transaction_validation.sender validation in
  sender ≠ native →
  mayEmpty (snd (transactionVmInput block tx validation)) = false →
  ¬ In sender (S.t.accounts_created_in_current_transaction (transactionFinished block tx validation)) →
  Z.min (U.to_z (A.t.balance (readAccount (B.t.world_state block) sender)))
    (U.to_z (Reserve_balance.user_reserve_balance (B.t.world_state block) (number block) sender)) -
    U.to_z (E.transaction_validation.total_fee validation) ≤
    U.to_z (A.t.balance (readAccount (B.t.world_state post) sender)).
Proof using F Hcold Hhash Hnative Hrevision Hwarm U8 UB UI0 access cold reserve warm write.
  cbn zeta. intros Hchain Hheader Hinitial Hformat Hwidth Hvalue Hv Hrun HnotNative Hordinary Hcreated.
  destruct (Addr.Map.find_opt (E.transaction_validation.sender validation)
    (W.t.accounts (B.t.world_state block))) as [original|] eqn:Hfind.
  - assert (Horiginal : readAccount (B.t.world_state block)
      (E.transaction_validation.sender validation) = original).
    { change ((match Addr.Map.find_opt (E.transaction_validation.sender validation)
        (W.t.accounts (B.t.world_state block)) with
        Some ac ⇒ ac | None ⇒ A.empty end) = original). rewrite Hfind. reflexivity. }
    pose proof (process_transaction_sender_reserve cold warm access write reserve
      Hrevision Hcold Hwarm Hhash Hnative block tx validation post original
      Hchain Hheader Hinitial Hformat Hwidth Hvalue Hv Hrun Hfind HnotNative Hordinary Hcreated) as Hbound.
    rewrite u256_min in Hbound. cbv beta in Horiginal |- ×. rewrite Horiginal. lia.
  - assert (Hzero : U.to_z (A.t.balance (readAccount (B.t.world_state block)
      (E.transaction_validation.sender validation))) = 0).
    { change (U.to_z (A.t.balance
        (match Addr.Map.find_opt (E.transaction_validation.sender validation)
          (W.t.accounts (B.t.world_state block)) with
         Some ac ⇒ ac | None ⇒ A.empty end)) = 0). rewrite Hfind. reflexivity. }
    pose proof (@process_transaction_preserves_supply F UI0 UB U8
      cold warm access write reserve Hrevision Hcold Hwarm Hhash Hnative
      block tx post Hchain (proj1 (proj2 Hheader)) (proj2 (proj2 Hheader))
      Hinitial Hformat Hwidth Hvalue Hrun) as [HpostSupply _].
    pose proof (account_balance_bounded_by_supply (B.t.world_state post)
      (E.transaction_validation.sender validation)
      (proj1 (proj2 HpostSupply))) as HpostNonneg.
    pose proof (account_balance_bounded_by_supply (B.t.world_state block)
      (E.transaction_validation.sender validation)
      (proj1 (proj2 Hinitial))) as HsenderBal.
    pose proof (proj2 (proj2 Hinitial)) as Htotal.
    pose proof (validated_debit_range block tx validation Hv ltac:(cbn beta in HsenderBal; lia))
      as [Hfee _].
    pose proof (configured_reserve_word (B.t.world_state block) (number block)
      (E.transaction_validation.sender validation) Hformat) as HresWord.
    pose proof (N2Z.is_nonneg (T.gas_limit tx × E.transaction_validation.effective_gas_price validation)).
    change (0 ≤ U.to_z (A.t.balance (readAccount (B.t.world_state post)
      (E.transaction_validation.sender validation))) ≤
      totalBalance (B.t.world_state post)) in HpostNonneg.
    change (U.to_z (E.transaction_validation.total_fee validation) =
      Z.of_N (T.gas_limit tx × E.transaction_validation.effective_gas_price validation)) in Hfee.
    change (0 ≤ U.to_z (Reserve_balance.user_reserve_balance (B.t.world_state block)
      (number block) (E.transaction_validation.sender validation)) < 2^256) in HresWord.
    cbv beta in Hzero |- ×. rewrite Hzero, Hfee. lia.
Qed.
End Execution.

Print Assumptions process_transaction_empty_without_recovery.
Print Assumptions process_transaction_protects_guarded_nonsender.
Print Assumptions process_transaction_recent_sender_bound.
Print Assumptions process_transaction_ordinary_sender_bound.