Library QedkConcrete.hostcode

Code and destruction tracking through concrete Host operations

Code can change at newly created addresses; SELFDESTRUCT can add a deletion exemption only for such addresses. The relation below retains these facts through nested execution and rollback. It does not assume that creation avoids signer addresses: that cryptographic condition is separate.
From Stdlib Require Import List String Bool ZArith.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import MonadVM.Host QedkConcrete.accountcode QedkConcrete.hostframe
  QedkConcrete.worldaccounts QedkConcrete.hostbalance QedkConcrete.reserveprecompileeffects.
Set Default Goal Selector "!".
Module H := Host.Make.
Module S := State.TransactionState.
Module W := State.WorldState.
Module A := Chain.Ethereum.Account.
Module Addr := Chain.Ethereum.Address.

List membership is sufficient here. These two facts hold even before proving that the generated set representation is sorted.
Lemma address_set_add_members addr addresses query :
  List.In query (Addr._Set.(OCamlSet.S.add) addr addresses) ↔
  query = addr ∨ List.In query addresses.
Proof.
  change (List.In query (OCamlSet.Make.add stringmaps.stringOrder addr addresses) ↔
    query = addr ∨ List.In query addresses).
  induction addresses as [|head tail IH].
  - cbn. intuition congruence.
  - cbn [OCamlSet.Make.add].
    destruct (OCamlSet.Make.before stringmaps.stringOrder addr head).
    + cbn. intuition congruence.
    + destruct (OCamlSet.Make.equal_elt stringmaps.stringOrder addr head) eqn:Heq.
      × change (OCamlMap.Make.key_equal stringmaps.stringOrder addr head = true) in Heq.
        apply stringmaps.equal_true in Heq. subst head. cbn. intuition congruence.
      × cbn. rewrite IH. intuition congruence.
Qed.

Lemma address_set_mem_member addr addresses :
  Addr._Set.(OCamlSet.S.mem) addr addresses = true → List.In addr addresses.
Proof.
  change (OCamlSet.Make.mem stringmaps.stringOrder addr addresses = true → List.In addr addresses).
  unfold OCamlSet.Make.mem. induction addresses as [|head tail IH]; [discriminate|].
  cbn [OCamlSet.Make.find_opt].
  destruct (OCamlSet.Make.before stringmaps.stringOrder addr head); [discriminate|].
  destruct (OCamlSet.Make.equal_elt stringmaps.stringOrder addr head) eqn:Heq.
  - intros _. change (OCamlMap.Make.key_equal stringmaps.stringOrder addr head = true) in Heq.
    apply stringmaps.equal_true in Heq. subst head. left. reflexivity.
  - intro Hmem. right. apply IH. exact Hmem.
Qed.

Section Frame.
Context {U64 : Basics.Unreachable Numeric.U64.t} {UF : Basics.Unreachable Numeric.U256.t}.
Local Abbreviation readAccount := (fun world addr ⇒
  State.op_pointcaretlparenrparen world (@W.account None addr)).

The sets are part of the actual transaction state. The relation permits code changes only at recorded creations and new destruction entries only at recorded creations. Old destruction entries remain harmless premises of a nested call, rather than being assumed absent at every call.
Record creationFrame (before after : S.t) : Prop := {
  creations_retained : List.incl (S.t.accounts_created_in_current_transaction before)
    (S.t.accounts_created_in_current_transaction after);
  destruction_covered : ∀ addr, List.In addr (S.t.self_destruct after) →
    List.In addr (S.t.self_destruct before) ∨
    List.In addr (S.t.accounts_created_in_current_transaction after);
  noncreated_code : ∀ addr,
    ¬ List.In addr (S.t.accounts_created_in_current_transaction after) →
    A.t.code (readAccount (S.t.world_state after) addr) =
      A.t.code (readAccount (S.t.world_state before) addr)
}.

Lemma creation_frame_refl s : creationFrame s s.
Proof. constructor; [apply incl_refl|intros; left; assumption|intros; reflexivity]. Qed.

Lemma creation_frame_trans before middle after :
  creationFrame before middle → creationFrame middle after → creationFrame before after.
Proof.
  intros [Hcreated1 Hdestroyed1 Hcode1] [Hcreated2 Hdestroyed2 Hcode2].
  constructor.
  - eapply incl_tran; eassumption.
  - intros addr Hin. destruct (Hdestroyed2 addr Hin) as [Hmiddle|Hnew]; [|right; exact Hnew].
    destruct (Hdestroyed1 addr Hmiddle) as [Hbefore|Hnew];
      [left; exact Hbefore|right; apply Hcreated2; exact Hnew].
  - intros addr Habsent. transitivity (A.t.code (readAccount (S.t.world_state middle) addr)).
    + apply Hcode2. exact Habsent.
    + apply Hcode1. intro Hin. apply Habsent, Hcreated2, Hin.
Qed.

Definition preservesCreation {R : Set} (action : S.t → R × S.t) : Prop :=
  ∀ s, stringmaps.WellFormed (W.t.accounts (S.t.world_state s)) →
  stringmaps.WellFormed (W.t.accounts (S.t.world_state (snd (action s)))) ∧
  creationFrame s (snd (action s)).

Lemma creation_bind {R T : Set} (action : S.t → R × S.t) (next : R → S.t → T × S.t) :
  preservesCreation action → (∀ value, preservesCreation (next value)) →
  preservesCreation (S.M.(Monad.State.State_result.op_letdollar) action next).
Proof.
  intros Haction Hnext s Hwf. specialize (Haction s Hwf).
  change (stringmaps.WellFormed (W.t.accounts (S.t.world_state
    (snd (let '(value, middle) := action s in next value middle)))) ∧
    creationFrame s (snd (let '(value, middle) := action s in next value middle))).
  destruct (action s) as [value middle]. destruct Haction as [Hmiddle Hframe].
  destruct (Hnext value middle Hmiddle) as [Hafter HnextFrame].
  split; [exact Hafter|eapply creation_frame_trans; eassumption].
Qed.

Lemma creation_return {R : Set} (value : R) :
  preservesCreation (S.M.(Monad.State.State_result._return) value).
Proof. intros s Hwf. split; [exact Hwf|apply creation_frame_refl]. Qed.

Lemma creation_read {R : Set} (lens : Lens.t S.t R) :
  preservesCreation (S.M.(Monad.State.State_result.op_exclamation) lens).
Proof. intros s Hwf. split; [exact Hwf|apply creation_frame_refl]. Qed.

Lemma world_write_code_frame s keep addr value :
  stringmaps.WellFormed (W.t.accounts (S.t.world_state s)) →
  (A.t.code value = A.t.code (readAccount (S.t.world_state s) addr) ∨
    List.In addr (S.t.accounts_created_in_current_transaction s)) →
  let after := S.t.with_world_state
    (State.op_pointcaretlparenrparenltminus (S.t.world_state s)
      (@W.account (Some keep) addr) value) s in
  stringmaps.WellFormed (W.t.accounts (S.t.world_state after)) ∧ creationFrame s after.
Proof.
  intros Hwf Hcode. cbn zeta. split.
  - apply account_write_wellformed. exact Hwf.
  - constructor; [apply incl_refl|intros; left; assumption|].
    intros query Habsent. cbv beta.
    change (A.t.code (readAccount
      (State.op_pointcaretlparenrparenltminus (S.t.world_state s)
        (@W.account (Some keep) addr) value) query) =
      A.t.code (readAccount (S.t.world_state s) query)).
    cbv beta. rewrite code_after_account_write by exact Hwf.
    destruct (String.eqb addr query) eqn:Heq; [|reflexivity].
    apply String.eqb_eq in Heq. subst query.
    destruct Hcode as [Hcode|Hcreated]; [exact Hcode|contradiction].
Qed.

Context {F : H.FArgs}.

Value transfers change balances, not code, even if they delete an empty map entry or sender and recipient coincide. No balance-range premise is needed for this code-only result.
Lemma transfer_preserves_creation sender recipient amount :
  preservesCreation (@H.transfer_ether F sender recipient amount).
Proof.
  intro s. intro Hwf. unfold H.transfer_ether.
  cbn -[Numeric.U256.op_gteq Numeric.U256.op_plus Numeric.U256.op_minus W.account].
  match goal with |- context [if ?b then _ else _] ⇒ destruct b end.
  2: { split; [exact Hwf|apply creation_frame_refl]. }
  cbn beta iota zeta delta [Monad.Identity.Impl._return fst snd].
  match goal with |- _ ∧ creationFrame _ (S.t.with_world_state _ ?middle) ⇒
    set (debited := middle) in × end.
  assert (Hdebit : stringmaps.WellFormed (W.t.accounts (S.t.world_state debited)) ∧
    creationFrame s debited).
  { unfold debited. apply world_write_code_frame; [exact Hwf|left; reflexivity]. }
  destruct Hdebit as [HdebitWf HdebitFrame].
  match goal with |- stringmaps.WellFormed (W.t.accounts (S.t.world_state ?after)) ∧ _ ⇒
    assert (Hcredit : stringmaps.WellFormed (W.t.accounts (S.t.world_state after)) ∧
      creationFrame debited after)
  end.
  { apply (world_write_code_frame debited false recipient); [exact HdebitWf|left; reflexivity]. }
  destruct Hcredit as [HcreditWf HcreditFrame].
  split; [exact HcreditWf|eapply creation_frame_trans; eassumption].
Qed.

Lemma creation_unchanged_fields before after :
  W.t.accounts (S.t.world_state after) = W.t.accounts (S.t.world_state before) →
  S.t.accounts_created_in_current_transaction after = S.t.accounts_created_in_current_transaction before →
  S.t.self_destruct after = S.t.self_destruct before →
  creationFrame before after.
Proof.
  intros Haccounts Hcreated Hdestroyed. constructor.
  - rewrite Hcreated. apply incl_refl.
  - intros addr Hin. left. rewrite <- Hdestroyed. exact Hin.
  - intros addr _. change (A.t.code (match Addr.Map.find_opt addr
      (W.t.accounts (S.t.world_state after)) with
      | Some account ⇒ account | None ⇒ @A.empty end) =
      A.t.code (readAccount (S.t.world_state before) addr)).
    rewrite Haccounts. reflexivity.
Qed.

Lemma mark_creation_frame s addr :
  creationFrame s (S.t.with_accounts_created_in_current_transaction
    (Addr._Set.(OCamlSet.S.add) addr (S.t.accounts_created_in_current_transaction s)) s).
Proof.
  constructor.
  - intros query Hin. apply address_set_add_members. right. exact Hin.
  - intros query Hin. left. exact Hin.
  - intros. reflexivity.
Qed.

Lemma mark_destruction_frame s addr :
  List.In addr (S.t.accounts_created_in_current_transaction s) →
  creationFrame s (S.t.with_self_destruct
    (Addr._Set.(OCamlSet.S.add) addr (S.t.self_destruct s)) s).
Proof.
  intro Hcreated. constructor; [apply incl_refl| |intros; reflexivity].
  intros query Hin. apply address_set_add_members in Hin as [Heq|Hin].
  - subst query. right. exact Hcreated.
  - left. exact Hin.
Qed.

Context {UI : Basics.Unreachable int}
  {U32 : Basics.Unreachable Byte_string.B32.(Byte_string.Fixed.Fixed_result.t)}
  {UU : Basics.Unreachable unit}.

Lemma storage_preserves_creation addr key value :
  preservesCreation (@H.set_storage F addr key value).
Proof.
  intros s Hwf. eapply world_write_code_frame; [exact Hwf|left; reflexivity].
Qed.

Lemma selfdestruct_preserves_creation addr beneficiary :
  preservesCreation (@H.selfdestruct F addr beneficiary).
Proof.
  intros s Hwf. unfold H.selfdestruct.
  cbn -[H.transfer_ether Addr._Set W.account].
  match goal with |- context [H.transfer_ether ?from ?to ?value ?initial] ⇒
    pose proof (transfer_preserves_creation from to value initial Hwf) as Htransfer;
    destruct (H.transfer_ether from to value initial) as [ok middle]
  end.
  cbn beta iota zeta delta [snd] in Htransfer.
  destruct Htransfer as [Hmiddle Hframe].
  cbn -[Addr._Set W.account].
  destruct (Addr._Set.(OCamlSet.S.mem) addr
    (S.t.accounts_created_in_current_transaction middle)) eqn:Hcreated.
  - pose proof (mark_destruction_frame middle addr
      (address_set_mem_member addr _ Hcreated)) as Hmark.
    set (marked := S.t.with_self_destruct
      (Addr._Set.(OCamlSet.S.add) addr (S.t.self_destruct middle)) middle) in ×.
    match goal with |- stringmaps.WellFormed (W.t.accounts (S.t.world_state ?after)) ∧ _ ⇒
      assert (Hwrite : stringmaps.WellFormed (W.t.accounts (S.t.world_state after)) ∧
        creationFrame marked after)
    end.
    { apply (world_write_code_frame marked false addr
        (A.t.with_balance (@Numeric.U256.zero)
          (readAccount (S.t.world_state middle) addr)) Hmiddle).
      left. reflexivity. }
    destruct Hwrite as [Hfinal HfinalFrame]. split; [exact Hfinal|].
    eapply creation_frame_trans; [exact Hframe|].
    eapply creation_frame_trans; eassumption.
  - split; assumption.
Qed.
End Frame.

Section ReserveSetter.
Context {UZ : Basics.Unreachable Z.t} {Uarr : Basics.Unreachable (OCamlIarray.t int)}
  {UN : Basics.Unreachable Support.UintN.t} {U64 : Basics.Unreachable Numeric.U64.t}
  {UR : Basics.Unreachable Numeric.U256.Repr.t} {UF : Basics.Unreachable Numeric.U256.t}
  {UA : Basics.Unreachable Addr.t} {UB : Basics.Unreachable Byte_string.Bytes.t}
  {UU : Basics.Unreachable unit} {US : Basics.Unreachable string}
  {UI : Basics.Unreachable int} {UC : Basics.Unreachable ascii}
  {UP : Basics.Unreachable (int × int)}
  {U32 : Basics.Unreachable Byte_string.B32.(Byte_string.Fixed.Fixed_result.t)}.
Local Abbreviation readAccount := (fun world addr ⇒
  State.op_pointcaretlparenrparen world (@W.account None addr)).
Local Abbreviation activate := (@Reserve_balance.activate_precompile).
Local Abbreviation setter := (@Reserve_balance.set_reserve_balance).

Lemma account_write_same_code keep world addr value query :
  stringmaps.WellFormed (W.t.accounts world) →
  A.t.code value = A.t.code (readAccount world addr) →
  A.t.code (readAccount (State.op_pointcaretlparenrparenltminus world
    (@W.account (Some keep) addr) value) query) = A.t.code (readAccount world query).
Proof.
  intros Hwf Hcode. cbv beta.
  rewrite code_after_account_write by exact Hwf.
  destruct (String.eqb addr query) eqn:Heq; [|reflexivity].
  apply String.eqb_eq in Heq. subst query. exact Hcode.
Qed.

Configuration writes cannot change any account's code, including the precompile account's code. Activating that account changes only its nonce.
Lemma setter_code_frame world block addr value after :
  stringmaps.WellFormed (W.t.accounts world) → setter world block addr value = Some after →
  stringmaps.WellFormed (W.t.accounts after) ∧
  ∀ query, A.t.code (readAccount after query) = A.t.code (readAccount world query).
Proof.
  intros Hwf Hset. unfold Reserve_balance.set_reserve_balance in Hset.
  match type of Hset with context [match ?configResult with None ⇒ _ | Some _ ⇒ _ end] ⇒
    destruct configResult as [record|] end; [|discriminate].
  injection Hset as <-.
  assert (Hactive : stringmaps.WellFormed (W.t.accounts (activate world))).
  { apply account_write_wellformed. exact Hwf. }
  split.
  - apply (@account_write_wellformed false (activate world)
      (@Reserve_balance.precompile_address)). exact Hactive.
  - intro query. transitivity (A.t.code (readAccount (activate world) query)).
    + eapply (account_write_same_code false (activate world)
        (@Reserve_balance.precompile_address)); [exact Hactive|reflexivity].
    + eapply account_write_same_code; [exact Hwf|reflexivity].
Qed.

Context {F : Reserve_balance_introspection.Make.FArgs}
  {Useq : Basics.Unreachable (OCamlSeq.t (Addr.Map.key × A.t))}
  {U64i : Basics.Unreachable MonadVM.Int64.t} {UG : Basics.Unreachable Gas.t}.
Local Abbreviation precompile := (@Reserve_balance_introspection.Make.precompile
  F ).

Lemma reserve_precompile_preserves_creation msg : @preservesCreation _ (precompile msg).
Proof.
  intros s Hwf.
  change (stringmaps.WellFormed (W.t.accounts (S.t.world_state (snd (precompile msg s)))) ∧
    @creationFrame s (snd (precompile msg s))).
  destruct (@reserveprecompileeffects.precompile_world_effect F msg s) as [Hsame|[value [world [Hwrite Hafter]]]].
  - rewrite Hsame. split; [exact Hwf|apply creation_frame_refl].
  - rewrite Hafter.
    destruct (setter_code_frame _ _ _ _ _ Hwf Hwrite) as [Hworld Hcode].
    split; [exact Hworld|]. constructor; [apply incl_refl|intros; left; assumption|].
    intros query _. apply Hcode.
Qed.
End ReserveSetter.

Print Assumptions transfer_preserves_creation.
Print Assumptions storage_preserves_creation.
Print Assumptions selfdestruct_preserves_creation.
Print Assumptions reserve_precompile_preserves_creation.

Section Creation.
Context {F : H.FArgs}
  {UN : Basics.Unreachable Support.UintN.t} {U64 : Basics.Unreachable Numeric.U64.t}
  {UF : Basics.Unreachable Numeric.U256.t} {UG : Basics.Unreachable Gas.t}
  {UA : Basics.Unreachable Addr.t} {UB : Basics.Unreachable Byte_string.Bytes.t}
  {UU : Basics.Unreachable unit} {US : Basics.Unreachable string}
  {UI : Basics.Unreachable int} {UC : Basics.Unreachable ascii}
  {U64i : Basics.Unreachable int64}
  {U32 : Basics.Unreachable Byte_string.B32.(Byte_string.Fixed.Fixed_result.t)}.
Local Abbreviation frame := (@creationFrame).
Local Abbreviation preserves := (@preservesCreation Evmc.Result.t).

The recursive invocation must preserve the same relation; this is an induction step, not a new VM contract. CREATE records its target before running initcode, and cannot install code outside that recorded set.
Lemma process_create_preserves_creation msg :
  (∀ nested code, (0 ≤ Evmc.Message.t.gas nested < 2^63)%Z →
    preserves ((@H.Vm F).(Evmc.Vm.SIG.execute) nested code)) →
  (0 ≤ Evmc.Message.t.gas msg < 2^63)%Z →
  preserves (@H.process_create F msg).
Proof.
  intros Hvm Hgas s Hwf.
  unfold H.process_create, H.contract_creation_address, H.M.
  cbn -[Addr.of_contract_creation W.account Numeric.U64.op_ltgt
    Byte_string.Bytes.op_ltgt H.transfer_ether].
  match goal with |- context [if ?test then _ else _] ⇒ destruct test eqn:Hcollision end.
  { split; [exact Hwf|apply creation_frame_refl]. }
  match goal with |- context [H.transfer_ether _ ?addr _ _] ⇒ set (target := addr) in × end.
  match goal with |- context [H.transfer_ether _ _ _
    (S.t.with_world_state ?nonceWorld (S.t.with_world_state ?storageWorld ?created))] ⇒
    set (marked := created) in *;
    set (stored := S.t.with_world_state storageWorld marked) in *;
    set (prepared := S.t.with_world_state nonceWorld stored) in ×
  end.
  assert (Hmarked : frame s marked) by apply mark_creation_frame.
  assert (Hstored : stringmaps.WellFormed (W.t.accounts (S.t.world_state stored)) ∧ frame marked stored).
  { unfold stored. apply (world_write_code_frame marked false target); [exact Hwf|left; reflexivity]. }
  destruct Hstored as [HstoredWf HstoredFrame].
  assert (Hprepared : stringmaps.WellFormed (W.t.accounts (S.t.world_state prepared)) ∧ frame stored prepared).
  { unfold prepared. apply (world_write_code_frame stored false target); [exact HstoredWf|left; reflexivity]. }
  destruct Hprepared as [HpreparedWf HpreparedFrame].
  assert (Hentry : frame s prepared).
  { eapply creation_frame_trans; [exact Hmarked|]. eapply creation_frame_trans; eassumption. }
  pose proof (@transfer_preserves_creation UF F (Evmc.Message.t.sender msg)
    target (Evmc.Message.t.value msg) prepared HpreparedWf) as Htransfer.
  destruct (@H.transfer_ether F (Evmc.Message.t.sender msg)
    target (Evmc.Message.t.value msg) prepared) as [ok middle] eqn:HtransferRun.
  cbn beta iota zeta delta [fst snd] in Htransfer.
  destruct Htransfer as [HmiddleWf HmiddleFrame].
  cbn -[W.account Addr.of_contract_creation target stored prepared marked].
  destruct ok.
  2: { cbn -[W.account Addr.of_contract_creation target stored prepared marked].
    split; [exact HmiddleWf|eapply creation_frame_trans; eassumption]. }
  cbn -[W.account Addr.of_contract_creation target stored prepared marked].
  match goal with |- context [(@H.Vm F).(Evmc.Vm.SIG.execute) ?nested ?code middle] ⇒
    pose proof (Hvm nested code Hgas middle HmiddleWf) as Hrecursive;
    destruct ((@H.Vm F).(Evmc.Vm.SIG.execute) nested code middle) as [result afterVm]
  end.
  cbn beta iota zeta delta [fst snd] in Hrecursive.
  destruct Hrecursive as [HafterWf HafterFrame].
  assert (Hcomplete : frame s afterVm).
  { eapply creation_frame_trans; [exact Hentry|]. eapply creation_frame_trans; eassumption. }
  assert (HtargetPrepared : List.In target (S.t.accounts_created_in_current_transaction prepared)).
  { change (List.In target (Addr._Set.(OCamlSet.S.add) target
      (S.t.accounts_created_in_current_transaction s))).
    apply address_set_add_members. left. reflexivity. }
  assert (HtargetAfter : List.In target (S.t.accounts_created_in_current_transaction afterVm)).
  { apply (creations_retained _ _ HafterFrame), (creations_retained _ _ HmiddleFrame).
    exact HtargetPrepared. }
  destruct result as [status gasleft refund output address]. destruct status;
    cbn -[W.account Addr.of_contract_creation target stored prepared marked];
    try (split; [exact HafterWf|exact Hcomplete]).
  try match goal with |- context [if andb ?enabled ?adopted then _ else _] ⇒
    destruct (andb enabled adopted);
      [split; [exact HafterWf|exact Hcomplete]|] end.
  match goal with |- context [match ?failure with Some _ ⇒ _ | None ⇒ _ end] ⇒
    destruct failure as [error|] end.
  - split; [exact HafterWf|exact Hcomplete].
  - pose proof (@world_write_code_frame UF afterVm false target
      (A.t.with_code output (State.op_pointcaretlparenrparen (S.t.world_state afterVm)
        (@W.account None target))) HafterWf (or_intror HtargetAfter))
      as [Hfinal Hinstall].
    split; [exact Hfinal|]. eapply creation_frame_trans; eassumption.
Qed.
End Creation.

Print Assumptions process_create_preserves_creation.