Library SetcodeConcrete.transactionsenderreserve

The sender's reserve after a complete ordinary transaction

An ordinary transaction may reduce the protected reserve by its maximum fee, but not by its value transfer or by a later call. This includes adoption during execution and the failed-receipt path of an already migrated sender. Validation is a premise of this preservation lemma; the admission proof must establish it before applying the lemma.
From Stdlib Require Import List String ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml MonadVM.Execution.
Require Import QedkConcrete.authorization QedkConcrete.transactionfees
  QedkConcrete.transactionentrywords QedkConcrete.transactionframes
  QedkConcrete.validation QedkConcrete.hostframe QedkConcrete.reservecheck
  QedkConcrete.reservestorage QedkConcrete.reserveencoding
  QedkConcrete.hoststoragewords QedkConcrete.hostaccountformat
  QedkConcrete.hashwords QedkConcrete.assemblychecked QedkConcrete.nativeinputs
  QedkConcrete.supply QedkConcrete.worldaccounts QedkConcrete.wordrange.
Require Import SetcodeConcrete.reserve SetcodeConcrete.transactionentry SetcodeConcrete.transactionfinalize
  SetcodeConcrete.transactionsupply SetcodeConcrete.executionsenderreserve
  SetcodeConcrete.executiondestruction SetcodeConcrete.contextframe.
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.
Local Abbreviation readAccount := (fun world addr ⇒
  State.op_pointcaretlparenrparen world (W.account None addr)).

Lemma configured_reserve_word world block addr :
  worldFormat world →
  wordRange (Reserve_balance.user_reserve_balance world block addr).
Proof.
  intro Hformat.
  pose proof (proj1 (proj1 (world_format_components world) Hformat)) as Hstorage.
  pose proof (read_account_storage_words world Reserve_balance.precompile_address Hstorage) as Hbytes.
  assert (Hfield : ∀ offset,
    (readConfigField (A.t.storage (readAccount world Reserve_balance.precompile_address))
      addr offset < 2^256)%N).
  { intro offset. apply read_config_bounded. exact Hbytes. }
  unfold Reserve_balance.user_reserve_balance.
  match goal with |- wordRange (U.of_uint_exn (Reserve_config.active ?r block)) ⇒
    set (record := r) end.
  assert (Hsettled : (Reserve_config.t.settled record < 2^256)%N) by (exact (Hfield 0)).
  assert (Hpending : (Reserve_config.t.pending record < 2^256)%N) by (exact (Hfield 1)).
  assert (Hactive : (Reserve_config.active record block < 2^256)%N).
  { unfold Reserve_config.active.
    match goal with |- context [if ?b then _ else _] ⇒ destruct b end.
    - change (10000000000000000000 < 2^256)%N. lia.
    - match goal with |- context [if ?b then _ else _] ⇒ destruct b end; assumption. }
  unfold wordRange. rewrite u256_of_uint by lia.
  split; [apply N2Z.is_nonneg|lia].
Qed.

Section Entry.
Context {F : E.FArgs}.
Lemma transaction_entry_map block tx validation :
  E.validate_transaction block tx = inl validation →
  balanceInvariant (B.t.world_state block) →
  stringmaps.WellFormed (W.t.accounts
    (S.t.world_state (snd (transactionVmInput block tx validation)))).
Proof.
  intros Hv Hinitial.
  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 Hv ltac:(cbn beta in Hbalance; lia))
    as [_ Hdebit].
  pose proof (@transaction_entry_balances_with_nonce F
    (fun account ⇒ Setcode_rules.advance_sender_nonce
      (migratedSender block (E.transaction_validation.sender validation))
      (A.t.nonce account) (T.nonce tx))
    (S.t.with_tx_chain_id E.Params.(Execution.Make_Params_signature.chain_id)
      (S.make block (E.transaction_validation.sender validation) tx))
    (E.transaction_validation.sender validation) (E.transaction_validation.total_fee validation)
    (T.authorization_list tx) (proj1 Hinitial) Hdebit) as [Hmap _].
  change (stringmaps.WellFormed (W.t.accounts
    (S.t.world_state (snd (transactionPrefix block tx validation))))) in Hmap.
  unfold transactionVmInput. destruct (transactionPrefix block tx validation) as [applied prepared].
  cbn beta iota zeta delta [fst snd] in Hmap |- ×.
  change (stringmaps.WellFormed (W.t.accounts (S.t.world_state
    (E.bump_emptying_transaction_counters
      (if Setcode_rules.enabled E.Params.(Execution.Make_Params_signature.revision)
       then Result.List.filter_map T.Authorization.authority (T.authorization_list tx)
       else applied) prepared)))).
  rewrite bump_counters_accounts. exact Hmap.
Qed.

Lemma transaction_entry_fee block tx validation :
  E.validate_transaction block tx = inl validation →
  balanceInvariant (B.t.world_state block) →
  let entry := snd (transactionVmInput block tx validation) in
  Z.of_N (S.t.tx_gas_limit entry × S.t.tx_gas_price entry) =
    U.to_z (E.transaction_validation.total_fee validation).
Proof.
  intros Hv Hinitial.
  pose proof (transaction_prefix_context block tx validation) as Hcontext.
  pose proof (validated_effective_price block tx validation Hv) as Hprice.
  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 Hv ltac:(cbn beta in Hbalance; lia)) as [Hfee _].
  unfold transactionVmInput. destruct (transactionPrefix block tx validation) as [applied prepared].
  cbn beta iota zeta delta [fst snd] in Hcontext |- ×.
  unfold migrationContext, transactionContext in Hcontext.
  injection Hcontext as Hsnapshot Hblock Hsender Hlimit Hgasprice Hhistory Hcounters Hprior Hchain.
  change (Z.of_N (S.t.tx_gas_limit prepared × S.t.tx_gas_price prepared) =
    U.to_z (E.transaction_validation.total_fee validation)).
  rewrite Hlimit, Hgasprice, Hprice. exact (eq_sym Hfee).
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).

block is the state before tx, post its actual returned state, and original its sender's account before upfront charging. The sender is not eligible for emptying at VM entry. The result bounds its final balance by min(initial balance, active reserve) minus the maximum fee. No restriction to non-contract senders is needed: a migrated sender's failed receipt is covered as well.
Theorem process_transaction_sender_reserve block tx validation post original :
  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
  Addr.Map.find_opt sender (W.t.accounts (B.t.world_state block)) = Some original →
  sender ≠ Reserve_balance.precompile_address →
  mayEmpty (snd (transactionVmInput block tx validation)) = false →
  ¬ In sender (S.t.accounts_created_in_current_transaction (transactionFinished block tx validation)) →
  U.to_z (U.min (Reserve_balance.user_reserve_balance (B.t.world_state block)
    (Chain.Ethereum.Block.Header.t.number (Chain.Ethereum.Block.t.header (B.t.current_block block))) sender)
    (A.t.balance original)) - 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.
  intros Hchain [Hbase [Hheader Hrandao]] Hinitial Hformat Hwidth Hvalue
    Hv Hrun sender Hfind HnotNative Hordinary Hcreated.
  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 Hheader Hrandao Hinitial Hformat Hwidth Hvalue Hv Hrun) as Hfinal.
  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 Hmap.
  pose proof (transaction_entry_balances block tx validation Hv Hinitial sender) as Hbalance.
  pose proof (transaction_entry_fee block tx validation Hv Hinitial) as Hfee.
  assert (Hmsg : 0 ≤ Evmc.Message.t.gas (fst (transactionVmInput block tx validation)) < 2^63).
  { unfold transactionVmInput. destruct (transactionPrefix block tx validation) as [applied prepared].
    exact (proj1 (@validated_message_bounds F cold warm access write reserve Hrevision Hcold Hwarm
      block tx validation _ Hv Hvalue)). }
  unfold transactionFinished in Hcreated, Hfinal.
  destruct (transactionVmInput block tx validation) as [msg entry] eqn:Hinput.
  cbn beta iota zeta delta [fst snd] in Hsnapshot, Hblock, Hsender, Hdestruct,
    Hmap, Hbalance, Hfee, Hmsg, Hordinary, Hcreated, Hfinal.
  fold sender in Hsender, Hbalance, Hcreated, Hfinal.
  assert (Horiginal : readAccount (B.t.world_state block) sender = original).
  { change ((match Addr.Map.find_opt sender (W.t.accounts (B.t.world_state block)) with
      Some account ⇒ account | None ⇒ A.empty end) = original).
    rewrite Hfind. reflexivity. }
  rewrite String.eqb_refl in Hbalance. cbv beta in Hbalance, Horiginal.
  rewrite Horiginal in Hbalance.
  assert (Hprotected : protected entry sender original = U.min
    (Reserve_balance.user_reserve_balance (B.t.world_state block)
      (Chain.Ethereum.Block.Header.t.number (Chain.Ethereum.Block.t.header (B.t.current_block block))) sender)
    (A.t.balance original)).
  { unfold protected. rewrite Hsnapshot, Hblock. reflexivity. }
  assert (Hrange : 0 ≤ U.to_z (protected entry sender original) < 2^256).
  { pose proof (configured_reserve_word (B.t.world_state block)
      (Chain.Ethereum.Block.Header.t.number (Chain.Ethereum.Block.t.header (B.t.current_block block)))
      sender Hformat) as Hconfigured.
    pose proof (account_balance_bounded_by_supply (B.t.world_state block) sender
      (proj1 (proj2 Hinitial))) as Haccount.
    pose proof (proj2 (proj2 Hinitial)) as Htotal.
    cbv beta in Haccount. rewrite Horiginal in Haccount.
    unfold wordRange in Hconfigured. rewrite Hprotected, u256_min. lia. }
  assert (Hentry : U.to_z (protected entry sender original) -
    U.to_z (E.transaction_validation.total_fee validation) ≤
    U.to_z (A.t.balance (accountAt entry sender))).
  { change (U.to_z (A.t.balance (accountAt entry sender)) =
      U.to_z (A.t.balance original) - U.to_z (E.transaction_validation.total_fee validation)) in Hbalance.
    rewrite Hbalance, Hprotected, u256_min. apply Z.sub_le_mono_r, Z.le_min_r. }
  rewrite <- Hprotected.
  destruct (migratedSender block sender) eqn:Hmigrated.
  - eapply Z.le_trans; [exact Hentry|]. apply Hfinal. rewrite Hdestruct. tauto.
  - assert (HnotDestroyed : ¬ In sender (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 sender Hmsg Hdestruct Hcreated). }
    eapply Z.le_trans; [|exact (Hfinal sender HnotDestroyed)].
    rewrite <- Hfee, <- Hsender.
    apply (transaction_call_protects_sender cold warm access write reserve Hrevision Hcold Hwarm
      tx msg entry original).
    + rewrite Hsender. exact HnotNative.
    + exact Hmap.
    + exact Hmsg.
    + exact Hdestruct.
    + rewrite Hsender, Hsnapshot. apply address_find_member. exact Hfind.
    + exact Hordinary.
    + rewrite Hsender. exact Hrange.
    + rewrite Hsender, Hfee. exact Hentry.
    + rewrite Hsender. exact Hcreated.
Qed.
End Execution.
Print Assumptions process_transaction_sender_reserve.