Library QedkConcrete.protectedstoragehost

Protected configuration storage through concrete Host calls

Ordinary calls can transfer value to the protected account, but its empty code cannot write storage. CREATE is excluded by its nonzero nonce. This file supplies the Host induction step, including rollback; recursive VM and native-setter closure are discharged separately.
From Stdlib Require Import List String ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import QedkConcrete.protectedstorage QedkConcrete.nondebitframe
  QedkConcrete.storagehost QedkConcrete.vmcallframe QedkConcrete.hostcode
  QedkConcrete.hostframe QedkConcrete.vmhostframe QedkConcrete.assemblychecked
  QedkConcrete.contexthostinstance QedkConcrete.precompilesframe
  QedkConcrete.stakingaccounting.
Set Default Goal Selector "!".
#[local] Hint Extern 100 (Basics.Unreachable _) ⇒
  (apply Opaque.legacy_witness; Opaque.opaque_inhabit 64%nat) : typeclass_instances.
Local Open Scope Z_scope.
Section Host.
Context {F : Host.Instantiate.FArgs}.
Local Abbreviation U64 := (Opaque.legacy_witness 0%Z).
Local Abbreviation UF := (Opaque.legacy_witness 0%Z).
Local Abbreviation protected := (@protectedStorage).
Local Abbreviation HostF := (@Evmc.Instantiate.HostF S.t (@recursiveArgs F)).
Context (vm : Evmc.Vm.SIG (_fargs := Evmc.Vm.Build_FArgs
  (@Evmc.Instantiate.T S.t (@recursiveArgs F)))).

Lemma concrete_primitives_preserve_protected_storage self query P :
  self ≠ query → PrimitiveHostFrameAt (HostF vm) (protected query P) self.
Proof.
  intro Hdifferent. constructor; unfold preservesCallback; intros.
  all: cbn -[H.account_exists H.get_balance H.access_account H.get_storage
    H.set_storage H.access_storage H.get_transient_storage H.set_transient_storage
    H.get_code_size H.get_code_hash H.copy_code H.get_block_hash H.emit_log H.selfdestruct].
  all: try assumption.
  all: try (rewrite copy_code_read_only; assumption).
  all: try (eapply protected_storage_same_fields; [reflexivity|reflexivity|reflexivity|reflexivity|eassumption]).
  all: lazymatch goal with
  | |- protected _ _ (snd (@H.set_storage _ _ _ _ _)) ⇒
    apply sstore_preserves_protected_storage; assumption
  | |- protected _ _ (snd (@H.selfdestruct _ _ _ _)) ⇒
    apply selfdestruct_preserves_protected_storage; assumption
  | _ ⇒ unfold H.access_account, H.access_storage, H.set_transient_storage, H.emit_log;
    cbn; try match goal with |- context [if ?accessed then _ else _] ⇒ destruct accessed end;
    (eapply (@protected_storage_same_fields _ _ host);
      [reflexivity|reflexivity|reflexivity|reflexivity|assumption])
  end.
Qed.

Local Abbreviation processCall := (@H.process_call (H.Build_FArgs F.(Host.Instantiate.ChainParams) vm) ).

Local Abbreviation processSyscall := (@H.process_syscall (H.Build_FArgs F.(Host.Instantiate.ChainParams) vm) ).

Local Abbreviation callImpl := (@H.call_impl (H.Build_FArgs F.(Host.Instantiate.ChainParams) vm) ).

Local Abbreviation hostCall := (@H.call (H.Build_FArgs F.(Host.Instantiate.ChainParams) vm) ).

Lemma staking_contract_preserves_protected_storage fb0 fb1 fb2 query P msg :
  MonadVM.Staking.staking_address ≠ query →
  preservesCallback (protected query P) (MonadVM.Staking.staking_contract fb0 fb1 fb2 msg).
Proof.
  intros Hneq s Hbefore.
  destruct (staking_contract_uframe fb0 fb1 fb2 msg s)
    as [[_ [Hblock [_ [Hcreated [_ [_ [_ [Hdestruct _]]]]]]]] [_ [Haccounts _]]].
  destruct (Haccounts (protected_storage_map _ _ _ Hbefore)) as [Hwf' Hfields].
  destruct (Hfields query) as [Hnonce [Hcode Hstorage]].
  constructor.
  - exact Hwf'.
  - exact (eq_ind_r (fun n ⇒ n ≠ 0) (protected_storage_nonce _ _ _ Hbefore) Hnonce).
  - exact (eq_ind_r (fun c ⇒ c = Byte_string.Bytes.empty) (protected_storage_code _ _ _ Hbefore) Hcode).
  - unfold storageBlock.
    refine (eq_ind_r (fun b ⇒ P (Chain.Ethereum.Block.Header.t.number (Chain.Ethereum.Block.t.header b)) _) _ Hblock).
    exact (eq_ind_r (fun st ⇒ P (storageBlock s) st)
      (protected_storage_contents _ _ _ Hbefore)
      (Hstorage Hneq (protected_storage_nonce _ _ _ Hbefore))).
  - exact (eq_ind_r (fun l ⇒ ¬ In query l) (protected_storage_uncreated _ _ _ Hbefore) Hcreated).
  - exact (eq_ind_r (fun m ⇒ ¬ List.In query m) (protected_storage_undestroyed _ _ _ Hbefore) Hdestruct).
Qed.

Lemma staking_syscalls_preserves_protected_storage fb0 query P msg :
  MonadVM.Staking.staking_address ≠ query →
  preservesCallback (protected query P) (MonadVM.Staking.staking_syscalls fb0 msg).
Proof.
  intros Hneq s Hbefore.
  destruct (staking_syscalls_uframe fb0 msg s)
    as [[[_ [Hblock [_ [Hcreated [_ [_ [_ [Hdestruct _]]]]]]]] [_ [Haccounts _]]] |
        [[_ [Hblock [_ [Hcreated [_ [_ [_ [Hdestruct _]]]]]]]] [_ [Haccounts _]]]].
  - destruct (Haccounts (protected_storage_map _ _ _ Hbefore)) as [Hwf' Hfields].
    destruct (Hfields query) as [_ [Hnonce [Hcode Hstorage]]].
    constructor.
    + exact Hwf'.
    + exact (eq_ind_r (fun n ⇒ n ≠ 0) (protected_storage_nonce _ _ _ Hbefore) Hnonce).
    + exact (eq_ind_r (fun c ⇒ c = Byte_string.Bytes.empty) (protected_storage_code _ _ _ Hbefore) Hcode).
    + unfold storageBlock.
      refine (eq_ind_r (fun b ⇒ P (Chain.Ethereum.Block.Header.t.number (Chain.Ethereum.Block.t.header b)) _) _ Hblock).
      exact (eq_ind_r (fun st ⇒ P (storageBlock s) st)
        (protected_storage_contents _ _ _ Hbefore)
        (Hstorage Hneq)).
    + exact (eq_ind_r (fun l ⇒ ¬ In query l) (protected_storage_uncreated _ _ _ Hbefore) Hcreated).
    + exact (eq_ind_r (fun m ⇒ ¬ List.In query m) (protected_storage_undestroyed _ _ _ Hbefore) Hdestruct).
  - destruct (creditStakingAccount_fields (Evmc.Message.t.value msg) s) as [_ [_ [_ Hc_acc]]].
    destruct (Hc_acc (protected_storage_map _ _ _ Hbefore)) as [Hwf1 Hfields1].
    destruct (Hfields1 query) as [Hnonce1 [Hcode1 Hstorage1]].
    destruct (Haccounts Hwf1) as [Hwf' Hfields2].
    destruct (Hfields2 query) as [_ [Hnonce2 [Hcode2 Hstorage2]]].
    constructor.
    + exact Hwf'.
    + exact (eq_ind_r (fun n ⇒ n ≠ 0)
        (eq_ind_r (fun n ⇒ n ≠ 0) (protected_storage_nonce _ _ _ Hbefore) Hnonce1) Hnonce2).
    + exact (eq_ind_r (fun c ⇒ c = Byte_string.Bytes.empty)
        (eq_ind_r (fun c ⇒ c = Byte_string.Bytes.empty) (protected_storage_code _ _ _ Hbefore) Hcode1) Hcode2).
    + unfold storageBlock.
      refine (eq_ind_r (fun b ⇒ P (Chain.Ethereum.Block.Header.t.number (Chain.Ethereum.Block.t.header b)) _) _ Hblock).
      destruct (Hstorage1 Hneq) as [_ Hstor1].
      exact (eq_ind_r (fun st ⇒ P (storageBlock s) st)
        (eq_ind_r (fun st ⇒ P (storageBlock s) st) (protected_storage_contents _ _ _ Hbefore) Hstor1)
        (Hstorage2 Hneq)).
    + exact (eq_ind_r (fun l ⇒ ¬ In query l) (protected_storage_uncreated _ _ _ Hbefore) Hcreated).
    + exact (eq_ind_r (fun m ⇒ ¬ List.In query m) (protected_storage_undestroyed _ _ _ Hbefore) Hdestruct).
Qed.

Lemma process_syscall_preserves_protected_storage query P msg :
  MonadVM.Staking.staking_address ≠ query →
  preservesCallback (protected query P) (processSyscall msg).
Proof.
  intro Hneq. unfold H.process_syscall, H.M. cbn zeta.
  match goal with |- preservesCallback _ (match ?lookup with Some _ ⇒ _ | None ⇒ _ end) ⇒
    destruct lookup as [endpoint|] eqn:Hfind end.
  - unfold Precompiles.Make.syscall_endpoints in Hfind.
    apply precompilesframe.find_singleton_value in Hfind as [_ ->].
    apply staking_syscalls_preserves_protected_storage. exact Hneq.
  - intros s Hs. exact Hs.
Qed.

Lemma process_call_preserves_protected_storage from_tx query P msg :
  (∀ addr action, nativeDispatch vm msg addr = Some action →
    preservesCallback (protected query P) action) →
  (Evmc.Message.t.recipient msg = query → Evmc.Message.t.code_address msg = query) →
  (∀ code s, protected query P s →
    (Evmc.Message.t.recipient msg = query → code = Byte_string.Bytes.empty) →
    protected query P (snd (vm.(Evmc.Vm.SIG.execute) msg code s))) →
  preservesCallback (protected query P) (processCall from_tx msg).
Proof.
  intros Hnative HcodeAddress Hvm s Hinitial.
  assert (Htransfer : protected query P (snd
    ((if @H.should_transfer (H.Build_FArgs F.(Host.Instantiate.ChainParams) vm) msg
      then @H.transfer_ether (H.Build_FArgs F.(Host.Instantiate.ChainParams) vm)
        (Evmc.Message.t.sender msg) (Evmc.Message.t.recipient msg) (Evmc.Message.t.value msg)
      else fun st ⇒ (true, st)) s))).
  { destruct (H.should_transfer msg); [apply transfer_preserves_protected_storage|]; exact Hinitial. }
  unfold H.process_call, H.M.
  cbn -[H.should_transfer H.transfer_ether W.account Precompiles.Make.try_precompile].
  match goal with |- context [Monad.Identity.Impl.op_gtgteq ?run _] ⇒
    assert (Hmiddle : protected query P (snd run)) by exact Htransfer;
    destruct run as [ok middle] eqn:Hrun end.
  cbn beta iota zeta delta [snd] in Hmiddle.
  destruct ok; [|exact Hmiddle].
  destruct from_tx as [tx|].
  all: cbn -[W.account Precompiles.Make.try_precompile Delegation.get_delegated_address].
  all: try match goal with |- context [@Delegation.get_delegated_address ?bytes] ⇒
    destruct (@Delegation.get_delegated_address bytes) as [delegated|] eqn:Hdelegation end.
  all: cbn -[W.account Precompiles.Make.try_precompile].
  all: match goal with |- context [match ?selection with Some _ ⇒ _ | None ⇒ _ end] ⇒
    destruct selection as [action|] eqn:Hselected end.
  all: try (eapply Hnative; eassumption).
  all: apply Hvm; [exact Hmiddle|].
  all: intro Hrecipient;
    pose proof (protected_storage_code _ _ _ Hmiddle) as Hempty;
    first [rewrite (HcodeAddress Hrecipient); exact Hempty|idtac].
  exfalso. match type of Hdelegation with
  | @Delegation.get_delegated_address ?bytes = Some _ ⇒
    assert (Hbytes : bytes = Byte_string.Bytes.empty) by
      (rewrite (HcodeAddress Hrecipient); exact Hempty);
    pose proof (eq_trans
      (eq_sym (f_equal (@Delegation.get_delegated_address) Hbytes))
      Hdelegation) as Hfalse;
    discriminate Hfalse
  end.
Qed.
On failure the Host restores the call-entry state. On success it keeps the state protected by the recursive VM/native-call induction steps. The top-level reserve check is read-only and can only cause rollback.
Lemma call_impl_preserves_protected_storage from_tx query P msg :
  (∀ nested addr action, nativeDispatch vm nested addr = Some action →
    preservesCallback (protected query P) action) →
  (∀ nested code, 0 ≤ Evmc.Message.t.gas nested < 2^63 →
    ∀ s, protected query P s →
    (Evmc.Message.t.recipient nested = query → code = Byte_string.Bytes.empty) →
    protected query P (snd (vm.(Evmc.Vm.SIG.execute) nested code s))) →
  0 ≤ Evmc.Message.t.gas msg < 2^63 →
  (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)) →
  preservesCallback (protected query P)
    (callImpl (match from_tx with Some tx ⇒ H.Eoa_tx tx | None ⇒ H.Evm_call end) msg).
Proof.
  intros Hnative Hvm Hgas Htarget s Hinitial.
  pose proof (process_create_preserves_protected_storage (F := H.Build_FArgs F.(Host.Instantiate.ChainParams) vm)
    query P msg) as Hcreate.
  specialize (Hcreate (fun nested code Hbound Hneq initial Hprotected ⇒
    Hvm nested code Hbound initial Hprotected (fun Heq ⇒ False_rect _ (Hneq Heq))) Hgas).
  assert (Hcall :
    (Evmc.Message.t.recipient msg = query → Evmc.Message.t.code_address msg = query) →
    preservesCallback (protected query P) (processCall from_tx msg)).
  { intro Hcode. exact (process_call_preserves_protected_storage from_tx query P msg
      (Hnative msg) Hcode (fun code initial ⇒ Hvm msg code Hgas initial)). }
  unfold H.call_impl.
  Local Opaque H.process_call H.process_syscall H.process_create
    Addr.of_contract_creation Reserve_balance.dipped_into_reserve.
  destruct (Evmc.Message.t.kind msg) eqn:Hkind; destruct from_tx as [tx|]; cbn.
  all: match goal with
  | |- context [Monad.Identity.Impl.op_gtgteq ?run _] ⇒
    assert (Hcore : protected query P (snd run)) by
      (lazymatch run with ?f ?initial ⇒
        assert (Hentry : protected query P initial) by
          (eapply (@protected_storage_same_fields query P s);
            [reflexivity|reflexivity|reflexivity|reflexivity|exact Hinitial]);
        lazymatch f with
        | context [H.process_create] ⇒ exact (Hcreate initial Hentry)
        | context [H.process_call] ⇒
          destruct Htarget as [Hbad|[Hbad|Htarget]]; try discriminate;
          exact (Hcall Htarget initial Hentry)
        end end);
    destruct run as [result intermediate] eqn:Hrun
  end.
  all: destruct result as [status gasleft refund output address].
  all: destruct status;
    cbn; unfold Monad.Make_Monad.when_; cbn;
    try exact Hcore; try exact Hinitial.
  all: try (eapply (@protected_storage_same_fields query P s);
    [reflexivity|reflexivity|reflexivity|reflexivity|exact Hinitial]).
  all: match goal with
  | |- context [Monad.Identity.Impl.op_gtgteq (Monad.Identity.Impl.op_gtgteq ?check _) _] ⇒
    assert (Hcheck : snd check = intermediate) by reflexivity;
    destruct check as [dipped checked]; cbn [snd] in Hcheck; subst checked
  end.
  all: destruct dipped; cbn; first [exact Hinitial|exact Hcore|
    eapply (@protected_storage_same_fields query P s);
    [reflexivity|reflexivity|reflexivity|reflexivity|exact Hinitial]].
Qed.

Lemma call_from_monad_system_transaction_preserves_protected_storage query P msg :
  MonadVM.Staking.staking_address ≠ query →
  Evmc.Message.t.kind msg = Evmc.Message.CallKind.Call →
  preservesCallback (protected query P) (callImpl H.System_tx msg).
Proof.
  intros Hneq Hkind s Hinitial.
  pose proof (process_syscall_preserves_protected_storage query P msg Hneq s Hinitial) as Hcore.
  unfold H.call_impl. rewrite Hkind.
  Local Opaque H.process_syscall.
  cbn.
  destruct (processSyscall msg s) as [[status gasleft refund output address] intermediate].
  cbn [snd] in Hcore.
  destruct status; cbn; first [exact Hcore|exact Hinitial].
Qed.

Lemma call_preserves_protected_storage self query P msg :
  (∀ nested addr action, nativeDispatch vm nested addr = Some action →
    preservesCallback (protected query P) action) →
  (∀ nested code, 0 ≤ Evmc.Message.t.gas nested < 2^63 →
    ∀ s, protected query P s →
    (Evmc.Message.t.recipient nested = query → code = Byte_string.Bytes.empty) →
    protected query P (snd (vm.(Evmc.Vm.SIG.execute) nested code s))) →
  0 ≤ Evmc.Message.t.gas msg < 2^63 →
  self ≠ query → childCallFrom self msg →
  (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)) →
  preservesCallback (protected query P) (hostCall msg).
Proof.
  intros Hnative Hvm Hgas Hdifferent Horigin Htarget s Hinitial.
  pose proof (call_impl_preserves_protected_storage None query P msg
    Hnative Hvm Hgas Htarget) as Himpl.
  unfold H.call.
  destruct (Evmc.Message.t.kind msg) eqn:Hkind.
  all: cbn -[H.call_impl H.try_increment_nonce].
  all: try (apply Himpl; exact Hinitial).
  all: assert (Hsender : Evmc.Message.t.sender msg ≠ query) by
    (unfold childCallFrom in Horigin; rewrite Hkind in Horigin; rewrite Horigin; exact Hdifferent).
  all: pose proof (increment_nonce_preserves_protected_storage
    (F := H.Build_FArgs F.(Host.Instantiate.ChainParams) vm) query P
    (Evmc.Message.t.sender msg) Hsender s Hinitial) as Hincrement.
  all: match goal with |- context [Monad.Identity.Impl.op_gtgteq ?run _] ⇒
    destruct run as [ok middle] end.
  all: cbn [snd] in Hincrement; destruct ok;
    cbn -[H.call_impl]; [apply Himpl; exact Hincrement|exact Hincrement].
Qed.
End Host.

Print Assumptions concrete_primitives_preserve_protected_storage.
Print Assumptions process_call_preserves_protected_storage.
Print Assumptions call_preserves_protected_storage.