Library QedkConcrete.transactionstoragewf

Storage-map ordering through complete transaction and block execution

Only the initial storage maps must be well formed. Authorization handling, the recursive VM, beneficiary credits, SELFDESTRUCT deletion and system messages preserve that property. This supplies the representation premise for reserve-slot lookup laws; fee solvency is proved separately.
From Stdlib Require Import List ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import MonadVM.Execution QedkConcrete.executionstoragewf
  QedkConcrete.hoststoragewf QedkConcrete.hoststoragewords
  QedkConcrete.hostframe QedkConcrete.worldaccounts
  QedkConcrete.validation QedkConcrete.emptyinghistory.
Set Default Goal Selector "!".
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}.

Lemma authorization_preserves_storage_wf s auth :
  hostStorageWf s → hostStorageWf (snd (@E.process_authorization F s auth)).
Proof.
  intro Hworld. unfold E.process_authorization.
  match goal with |- context [if ?b then _ else _] ⇒ destruct b end.
  { exact Hworld. }
  match goal with |- context [match ?a with Some _ ⇒ _ | None ⇒ _ end] ⇒
    destruct a as [authority|] end.
  2: exact Hworld.
  cbn beta iota zeta delta [S.t.with_accessed_addresses S.t.world_state].
  match goal with |- context [if ?b then _ else _] ⇒ destruct b end.
  2: exact Hworld.
  match goal with |- context [State.op_pointcaretlparenrparenltminus _
    (@S.account None authority) ?value] ⇒ set (updated := value) end.
  assert (Hupdated : stringmaps.WellFormed (A.t.storage updated)).
  { unfold updated. apply read_account_storage_wf. exact Hworld. }
  match goal with |- context [if ?b then _ else _] ⇒ destruct b end.
  all: change (worldStorageWf (State.op_pointcaretlparenrparenltminus (S.t.world_state s)
      (@W.account (Some false) authority) updated));
    apply write_account_storage_wf; assumption.
Qed.

Lemma authorizations_preserve_storage_wf auths authorities s :
  hostStorageWf s →
  let result := MonadVM.Result.List.fold_left
    (fun '(authorities, state) auth ⇒
      match @E.process_authorization F state auth with
      | (None, next) ⇒ (authorities, next)
      | (Some authority, next) ⇒ (authority :: authorities, next)
      end) (authorities, s) auths in
  hostStorageWf (snd result).
Proof.
  revert authorities s.
  induction auths as [|auth auths IH]; intros authorities s Hwf.
  { exact Hwf. }
  change (@MonadVM.Result.List.fold_left) with (@OCamlList.fold_left) in ×.
  cbn [OCamlList.fold_left].
  pose proof (authorization_preserves_storage_wf s auth Hwf) as Hnext.
  destruct (@E.process_authorization F s auth) as [[authority|] next];
    cbn [snd] in Hnext; apply IH; exact Hnext.
Qed.

Lemma transaction_entry_storage_wf s sender fee auths :
  hostStorageWf s →
  let charged := State.op_pointcaretdollarlparenrparenltminus s
    (@S.account None sender)
    (fun account ⇒ A.t.with_balance (@U.op_minus (A.t.balance account) fee)
      (A.t.with_nonce (@Numeric.U64.op_plus (A.t.nonce account)
        (@Numeric.U64.one)) account)) in
  let result := MonadVM.Result.List.fold_left
    (fun '(authorities, state) auth ⇒
      match @E.process_authorization F state auth with
      | (None, next) ⇒ (authorities, next)
      | (Some authority, next) ⇒ (authority :: authorities, next)
      end) (nil, charged) auths in
  hostStorageWf (snd result).
Proof.
  intros Hworld charged. apply authorizations_preserve_storage_wf.
  unfold charged. apply write_account_storage_wf; [exact Hworld|].
  apply read_account_storage_wf. exact Hworld.
Qed.

Lemma bump_counters_storage_wf s addresses :
  hostStorageWf s → hostStorageWf (@E.bump_emptying_transaction_counters F addresses s).
Proof.
  intro Hworld.
  unfold hostStorageWf, worldStorageWf, E.bump_emptying_transaction_counters.
  cbn beta iota zeta delta [S.t.with_world_state S.t.world_state].
  rewrite counter_writes_accounts. exact Hworld.
Qed.

Lemma delete_accounts_storage_wf block addresses :
  worldStorageWf (B.t.world_state block) →
  worldStorageWf (B.t.world_state (OCamlSeq.fold_left
    (fun s addr ⇒ State.op_pointcaretlparenrparenltminus s
      (@B.account_opt None addr) None) block addresses)).
Proof.
  revert block. induction addresses as [|addr addresses IH]; intros block Hstorage_wf.
  - exact Hstorage_wf.
  - cbn [OCamlSeq.fold_left]. apply IH.
    change (List.Forall (fun entry ⇒ stringmaps.WellFormed (A.t.storage (snd entry)))
      (OCamlMap.Make.remove stringmaps.stringOrder addr (W.t.accounts (B.t.world_state block)))).
    apply (map_remove_value_property _ (fun ac ⇒ stringmaps.WellFormed (A.t.storage ac))).
    exact Hstorage_wf.
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)}.

Theorem process_transaction_preserves_storage_wf block tx :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  worldStorageWf (B.t.world_state block) →
  match @E.process_transaction F block tx with
  | inl post ⇒ worldStorageWf (B.t.world_state post)
  | inr _ ⇒ True
  end.
Proof.
  intros Hrevision Hworld. unfold E.process_transaction.
  destruct (@E.validate_transaction F block tx) as [validation|error] eqn:Hvalidation.
  2: exact I.
  destruct validation as [sender fee price intrinsic].
  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).
  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].
  match goal with |- context [@S.make block sender tx] ⇒
    set (initial := @S.make block sender tx)
  end.
  assert (Hinitial : hostStorageWf initial) by (exact Hworld).
  pose proof (transaction_entry_storage_wf initial sender fee (T.authorization_list tx) Hinitial) as Hauth.
  match goal with |- context [Result.List.fold_left ?f ?start (T.authorization_list tx)] ⇒
    set (authorized := Result.List.fold_left f start (T.authorization_list tx))
  end.
  change (hostStorageWf (snd authorized)) in Hauth.
  destruct authorized as [authorities prepared]. cbn beta iota zeta delta [snd] in Hauth |- ×.
  match goal with |- context [@S.initialize_access_sets tx ?s ?precompiles] ⇒
    set (beforeVm := @S.initialize_access_sets tx s precompiles)
  end.
  assert (Hbefore : hostStorageWf beforeVm).
  { change (hostStorageWf (@E.bump_emptying_transaction_counters F authorities prepared)).
    apply bump_counters_storage_wf. exact Hauth. }
  pose proof (validated_message_gas block tx _ (S.t.world_state beforeVm) Hvalidation) as Hgas.
  match goal with |- context [E.Host.call_from_eoa tx ?message beforeVm] ⇒
    pose proof (@execution_call_from_eoa_preserves_storage_wf F
      tx message Hrevision Hgas beforeVm Hbefore) as Hvm;
    destruct (E.Host.call_from_eoa tx message beforeVm) as [result afterVm]
  end.
  cbn [snd] in Hvm.
  pose proof (bump_counters_storage_wf afterVm (sender :: nil) Hvm) as Hafter.
  change (@Result._return) with (fun (A B : Set) (value : A) ⇒ @inl A B value).
  cbn beta iota zeta delta [B.t.with_transactions_processed B.t.with_gas_used B.t.world_state].
  apply delete_accounts_storage_wf.
  apply write_account_storage_wf; [exact Hafter|].
  apply read_account_storage_wf. exact Hafter.
Qed.

Theorem process_monad_system_transaction_preserves_storage_wf block tx :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  worldStorageWf (B.t.world_state block) →
  match @E.process_monad_system_transaction F block tx with
  | inl post ⇒ worldStorageWf (B.t.world_state post)
  | inr _ ⇒ True
  end.
Proof.
  intros Hrevision Hworld. unfold E.process_monad_system_transaction.
  destruct (@E.validate_monad_system_transaction F block tx Chain.Monad.system_sender)
    as [[]|error]; [|exact I].
  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).
  cbv beta iota zeta.
  match goal with |- context [@S.initialize_access_sets tx ?s ?precompiles] ⇒
    set (beforeVm := @S.initialize_access_sets tx s precompiles)
  end.
  assert (Hbefore : hostStorageWf beforeVm).
  { apply write_account_storage_wf; [exact Hworld|].
    apply read_account_storage_wf. exact Hworld. }
  match goal with |- context [E.Host.call_from_monad_system_transaction ?message beforeVm] ⇒
    assert (Hgas : (0 ≤ Evmc.Message.t.gas message < 2^63)%Z) by
      (unfold E.prepare_message; destruct (T.call_or_create_value tx) as [[]|[]];
       change (0 ≤ 0 < 2^63)%Z; lia);
    pose proof (@execution_call_from_monad_system_transaction_preserves_storage_wf F
      message Hrevision Hgas beforeVm Hbefore) as Hafter;
    destruct (E.Host.call_from_monad_system_transaction message beforeVm) as [result afterVm]
  end.
  unfold Result.when_.
  destruct (negb (Evmc.Result.StatusCode.is_success (Evmc.Result.t.status_code result)));
    [exact I|].
  exact Hafter.
Qed.

Theorem dispatch_transaction_preserves_storage_wf block tx :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  worldStorageWf (B.t.world_state block) →
  match @E.dispatch_transaction F block tx with
  | inl post ⇒ worldStorageWf (B.t.world_state post)
  | inr _ ⇒ True
  end.
Proof.
  intros Hrevision Hworld. unfold E.dispatch_transaction.
  destruct (T.chain_id tx) as [cid|];
    [destruct (Support.UintN.op_ltgt cid (@E.Params F).(Execution.Make_Params_signature.chain_id));
      [exact I|]|].
  all: destruct (@E.sender_kind_value F tx) as [[sender|]|];
    [apply process_transaction_preserves_storage_wf; assumption
    |apply process_monad_system_transaction_preserves_storage_wf; assumption
    |exact I].
Qed.

System messages have no authorizations and use the protocol's fixed gas allowance. This covers their actual Host calls, not an assumption that the system contracts have no state effects.
Lemma system_message_preserves_storage_wf block addr data :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  worldStorageWf (B.t.world_state block) →
  worldStorageWf (B.t.world_state (snd (@E.process_system_message F
    block addr data))).
Proof.
  intros Hrevision Hworld. unfold E.process_system_message.
  match goal with |- context [if ?b then _ else _] ⇒ destruct b end.
  { exact Hworld. }
  cbn beta iota zeta.
  match goal with |- context [E.Host.call ?message ?initial] ⇒
    assert (Hinitial : hostStorageWf initial) by (exact Hworld);
    assert (Hgas : (0 ≤ Evmc.Message.t.gas message < 2^63)%Z)
      by (change (0 ≤ 30000000 < 2^63)%Z; lia);
    pose proof (@execution_call_preserves_storage_wf F
      message Hrevision Hgas initial Hinitial) as Hcall;
    destruct (E.Host.call message initial) as [result after]
  end.
  exact Hcall.
Qed.

Lemma withdrawal_preserves_storage_wf block withdrawal :
  worldStorageWf (B.t.world_state block) →
  worldStorageWf (B.t.world_state (@E.process_withdrawal F block withdrawal)).
Proof.
  intro Hworld. unfold E.process_withdrawal.
  apply write_account_storage_wf; [exact Hworld|].
  apply read_account_storage_wf. exact Hworld.
Qed.

Local Lemma result_fold_invariant {Acc Element Error : Set}
    (P : Acc → Prop) (Q : Element → Prop) (step : Acc → Element → Acc + Error) entries :
  (∀ acc entry, Q entry → P acc →
    match step acc entry with inl next ⇒ P next | inr _ ⇒ True end) →
  List.Forall Q entries → ∀ acc, P acc →
  match Result.List.fold_leftM step acc entries with inl next ⇒ P next | inr _ ⇒ True end.
Proof.
  intros Hstep Hentries. induction Hentries as [|entry entries Hentry Hrest IH]; intros acc Hacc.
  - exact Hacc.
  - change (match Result.op_letdollar (step acc entry)
      (fun next ⇒ Result.List.fold_leftM step next entries) with
      | inl final ⇒ P final | inr _ ⇒ True end).
    specialize (Hstep acc entry Hentry Hacc).
    destruct (step acc entry) as [next|error]; [apply IH; exact Hstep|exact I].
Qed.

Lemma transactions_preserve_storage_wf block txs :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  worldStorageWf (B.t.world_state block) →
  match Result.List.fold_leftM (@E.process_transaction F) block txs with
  | inl post ⇒ worldStorageWf (B.t.world_state post) | inr _ ⇒ True end.
Proof.
  intros Hrevision Hworld.
  apply result_fold_invariant with (Q := fun _ ⇒ True).
  - intros state tx _ Hstate. apply process_transaction_preserves_storage_wf; assumption.
  - apply Forall_forall. intros; exact I.
  - exact Hworld.
Qed.

Lemma dispatched_transactions_preserve_storage_wf block txs :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  worldStorageWf (B.t.world_state block) →
  match Result.List.fold_leftM (@E.dispatch_transaction F) block txs with
  | inl post ⇒ worldStorageWf (B.t.world_state post) | inr _ ⇒ True end.
Proof.
  intros Hrevision Hworld.
  apply result_fold_invariant with (Q := fun _ ⇒ True).
  - intros state tx _ Hstate. apply dispatch_transaction_preserves_storage_wf; assumption.
  - apply Forall_forall. intros; exact I.
  - exact Hworld.
Qed.

Lemma withdrawals_preserve_storage_wf block withdrawals :
  worldStorageWf (B.t.world_state block) →
  worldStorageWf (B.t.world_state (Result.List.fold_left (@E.process_withdrawal F) block withdrawals)).
Proof.
  revert block. induction withdrawals as [|wd withdrawals IH]; intros block Hworld.
  - exact Hworld.
  - change (worldStorageWf (B.t.world_state (Result.List.fold_left
      (@E.process_withdrawal F) (@E.process_withdrawal F block wd) withdrawals))).
    apply IH, withdrawal_preserves_storage_wf. exact Hworld.
Qed.

Context {UTries : Basics.Unreachable (OCamlIarray.t Mpt.Trie.t)}
  {UChar : Basics.Unreachable OCamlChar.t} {UWorld : Basics.Unreachable W.t}
  {UTrie : Basics.Unreachable Mpt.Trie.t} {UNibbles : Basics.Unreachable Mpt.Nibbles.t}
  {UBlock : Basics.Unreachable Chain.Ethereum.Block.t}.

Block-entry reserve-precompile activation, both system messages, all transactions, and withdrawals preserve the representation. Validation errors return no post-state; successful root checks only add history.
Theorem process_block_preserves_storage_wf verify world block :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  worldStorageWf world →
  match @E.process_block F verify world block with
  | inl post ⇒ worldStorageWf post | inr _ ⇒ True end.
Proof.
  intros Hrevision Hworld. unfold E.process_block. rewrite Hrevision.
  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).
  destruct (@E.validate_block F world block) as [[]|error] eqn:Hvalidation.
  2: exact I.
  cbn beta iota zeta.
  match goal with |- context [B.make ?w block] ⇒ set (initial := B.make w block) end.
  assert (Hinitial : worldStorageWf (B.t.world_state initial)).
  { apply activate_preserves_storage_wf. exact Hworld. }
  match goal with |- context [E.process_system_message initial ?addr ?data] ⇒
    pose proof (system_message_preserves_storage_wf initial addr data Hrevision Hinitial) as Hbeacon;
    destruct (E.process_system_message initial addr data) as [beaconResult afterBeacon]
  end.
  cbn beta iota zeta delta [snd] in Hbeacon |- ×.
  match goal with |- context [E.process_system_message afterBeacon ?addr ?data] ⇒
    pose proof (system_message_preserves_storage_wf afterBeacon addr data Hrevision Hbeacon) as Hhistory;
    destruct (E.process_system_message afterBeacon addr data) as [historyResult afterHistory]
  end.
  cbn beta iota zeta delta [snd] in Hhistory |- ×.
  pose proof (dispatched_transactions_preserve_storage_wf afterHistory
    (Chain.Ethereum.Block.t.transactions block) Hrevision Hhistory) as Htransactions.
  match goal with |- context [Result.List.fold_leftM ?step afterHistory ?txs] ⇒
    destruct (Result.List.fold_leftM step afterHistory txs) as [afterTransactions|error]
  end.
  2: exact I.
  cbn beta iota zeta in Htransactions |- ×.
  pose proof (withdrawals_preserve_storage_wf afterTransactions
    (Chain.Ethereum.Block.t.withdrawals block) Htransactions) as Hwithdrawals.
  match goal with |- context [E.validate_block ?world ?block] ⇒
    destruct (E.validate_block world block) as [[]|error]
  end.
  2: exact I.
  match goal with |- context [if verify then ?check else _] ⇒
    destruct verify; [destruct check as [[]|error]; [|exact I]|]
  end.
  all: exact Hwithdrawals.
Qed.

End Execution.

Print Assumptions process_transaction_preserves_storage_wf.
Print Assumptions process_block_preserves_storage_wf.