Library QedkConcrete.persistentcodehost

Existing contract code through calls, creations and rollback

The invariant includes absence from creation/deletion sets. CREATE's collision check maintains it; the reserve check can only roll back to a state that already satisfies it. No assumption about called code is used.
From Stdlib Require Import List String ZArith.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import QedkConcrete.persistentcode QedkConcrete.creationhost
  QedkConcrete.creationassembly QedkConcrete.nondebitframe QedkConcrete.hostnocalls
  QedkConcrete.hostcode QedkConcrete.hostframe QedkConcrete.contexthostinstance
  QedkConcrete.vmhostframe QedkConcrete.assemblychecked
  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.

Lemma persistent_bind {U64 : Basics.Unreachable Numeric.U64.t}
    {UF : Basics.Unreachable Numeric.U256.t} {A B : Set} query code
    (action : S.t → A × S.t) (next : A → S.t → B × S.t) :
  preservesCallback (@persistentCode query code) action →
  (∀ value, preservesCallback (@persistentCode query code) (next value)) →
  preservesCallback (@persistentCode query code) (S.M.(Monad.State.State_result.op_letdollar) action next).
Proof.
  intros Haction Hnext s Hinitial.
  change (@persistentCode query code (snd (let '(value, middle) := action s in next value middle))).
  specialize (Haction s Hinitial). destruct (action s) as [value middle].
  apply Hnext. exact Haction.
Qed.

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 := (@persistentCode).
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 native_preserves_persistent_code query code msg addr action :
  F.(Host.Instantiate.ChainParams).(Chain.Monad.PARAMS.revision) = Support.Variants.Revision.Eleven →
  nativeDispatch vm msg addr = Some action → preservesCallback (protected query code) action.
Proof.
  intros Hrevision Hselected s Hinitial.
  destruct (native_preserves_creation vm msg addr action Hrevision Hselected s
    (persistent_code_map _ _ _ Hinitial)) as [Hmap Hframe].
  eapply persistent_code_frame; [exact Hinitial|exact Hmap|exact Hframe|].
  pose proof (native_preserves_creation_set vm msg addr action Hrevision Hselected s) as Hset.
  match type of Hset with ?created = _ ⇒ change (¬ List.In query created) end.
  rewrite Hset. exact (persistent_code_uncreated _ _ _ Hinitial).
Qed.

Lemma concrete_primitives_preserve_persistent_code query code :
  PrimitiveHostFrame (HostF vm) (protected query code).
Proof.
  constructor; intros.
  all: intros s Hinitial.
  all: pose proof (@concrete_primitives_preserve_creation F vm s) as Hcreation.
  all: pose proof (@concrete_primitives_preserve_creation_set F vm s) as Hsets.
  all: assert (Hentry : @creationInvariant s s) by
    (split; [exact (persistent_code_map _ _ _ Hinitial)|apply creation_frame_refl]).
  all: destruct Hcreation; destruct Hsets.
  all: unfold preservesCallback in ×.
  all: match goal with |- persistentCode _ _ (snd (?action ?entry)) ⇒
    assert (Hframe : @creationInvariant entry (snd (action entry))) by eauto;
    assert (Hset : S.t.accounts_created_in_current_transaction (snd (action entry)) =
      S.t.accounts_created_in_current_transaction entry) by eauto
  end.
  all: eapply persistent_code_frame; [exact Hinitial|exact (proj1 Hframe)|exact (proj2 Hframe)|].
  all: rewrite Hset; exact (persistent_code_uncreated _ _ _ Hinitial).
Qed.
Local Abbreviation processCall := (@H.process_call (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 process_call_preserves_persistent_code from_tx query code msg :
  (∀ addr action, nativeDispatch vm msg addr = Some action →
    preservesCallback (protected query code) action) →
  (∀ body s, protected query code s →
    protected query code (snd (vm.(Evmc.Vm.SIG.execute) msg body s))) →
  preservesCallback (protected query code) (processCall from_tx msg).
Proof.
  intros Hnative Hvm s Hinitial.
  assert (Htransfer : protected query code (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_persistent_code|]; 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 code (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.
Qed.
Lemma process_syscall_preserves_persistent_code query code msg :
  preservesCallback (protected query code)
    (@H.process_syscall (H.Build_FArgs F.(Host.Instantiate.ChainParams) vm) msg).
Proof.
  intros s Hinitial.
  destruct (process_syscall_preserves_creation vm msg s
    (persistent_code_map _ _ _ Hinitial)) as [Hmap Hframe].
  eapply persistent_code_frame; [exact Hinitial|exact Hmap|exact Hframe|].
  unfold H.process_syscall, H.M; cbn zeta.
  match goal with |- context [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 [_ ->].
    match goal with |- context [MonadVM.Staking.staking_syscalls ?fb0 msg] ⇒
      destruct (staking_syscalls_uframe fb0 msg s)
        as [[[_ [_ [_ [Hcreated _]]]] _] | [[_ [_ [_ [Hcreated _]]]] _]]
end;
      exact (eq_ind_r (fun l ⇒ ¬ List.In query l) (persistent_code_uncreated _ _ _ Hinitial) Hcreated).
  - exact (persistent_code_uncreated _ _ _ Hinitial).
Qed.

Lemma call_impl_preserves_persistent_code from_tx query code msg :
  code ≠ Byte_string.Bytes.empty →
  F.(Host.Instantiate.ChainParams).(Chain.Monad.PARAMS.revision) = Support.Variants.Revision.Eleven →
  (∀ nested body, (0 ≤ Evmc.Message.t.gas nested < 2^63)%Z →
    preservesCallback (protected query code) (vm.(Evmc.Vm.SIG.execute) nested body)) →
  (0 ≤ Evmc.Message.t.gas msg < 2^63)%Z →
  preservesCallback (protected query code)
    (callImpl (match from_tx with Some tx ⇒ H.Eoa_tx tx | None ⇒ H.Evm_call end) msg).
Proof.
  intros Hnonempty Hrevision Hvm Hgas s Hinitial.
  pose proof (process_call_preserves_persistent_code from_tx query code msg
    (fun addr action Hselected ⇒ native_preserves_persistent_code query code msg addr action Hrevision Hselected)
    (fun body ⇒ Hvm msg body Hgas)) as Hcall.
  pose proof (process_create_preserves_existing_code (F := H.Build_FArgs F.(Host.Instantiate.ChainParams) vm)
    query code msg Hnonempty Hvm Hgas) as Hcreate.
  unfold H.call_impl.
  Local Opaque H.process_call H.process_syscall H.process_create
    Chain.Ethereum.Address.of_contract_creation Reserve_balance.dipped_into_reserve.
  destruct (Evmc.Message.t.kind msg); destruct from_tx as [tx|]; cbn.
  all: match goal with
  | |- context [Monad.Identity.Impl.op_gtgteq ?run _] ⇒
    assert (Hcore : protected query code (snd run)) by
      (lazymatch run with ?action ?initial ⇒
        assert (Hentry : protected query code initial) by
          (destruct Hinitial; constructor; assumption);
        first [exact (Hcall initial Hentry)|exact (Hcreate initial Hentry)]
       end);
    destruct run as [result intermediate] eqn:Hrun
  end.
  all: cbn beta iota zeta delta [snd] in Hcore.
  all: destruct result as [status gasleft refund output address].
  all: destruct status;
    cbn; unfold Monad.Make_Monad.when_; cbn;
    try exact Hcore;
    try (destruct Hinitial; constructor; assumption).
  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; [destruct Hinitial; constructor; assumption|exact Hcore].
Qed.

Lemma call_from_monad_system_transaction_preserves_persistent_code query code msg :
  Evmc.Message.t.kind msg = Evmc.Message.CallKind.Call →
  preservesCallback (protected query code) (callImpl H.System_tx msg).
Proof.
  intros Hkind s Hinitial.
  pose proof (process_syscall_preserves_persistent_code query code msg s Hinitial) as Hcore.
  unfold H.call_impl. rewrite Hkind.
  Local Opaque H.process_syscall.
  cbn.
  destruct (@H.process_syscall (H.Build_FArgs F.(Host.Instantiate.ChainParams) vm) 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_persistent_code query code msg :
  code ≠ Byte_string.Bytes.empty →
  F.(Host.Instantiate.ChainParams).(Chain.Monad.PARAMS.revision) = Support.Variants.Revision.Eleven →
  (∀ nested body, (0 ≤ Evmc.Message.t.gas nested < 2^63)%Z →
    preservesCallback (protected query code) (vm.(Evmc.Vm.SIG.execute) nested body)) →
  (0 ≤ Evmc.Message.t.gas msg < 2^63)%Z → preservesCallback (protected query code) (hostCall msg).
Proof.
  intros Hnonempty Hrevision Hvm Hgas. unfold H.call, H.M.
  apply persistent_bind.
  - match goal with |- preservesCallback _ (if ?test then _ else _) ⇒ destruct test end.
    + apply increment_nonce_preserves_persistent_code.
    + intros s Hinitial. exact Hinitial.
  - intros ok. destruct ok.
    + apply (call_impl_preserves_persistent_code None); assumption.
    + intros s Hinitial. exact Hinitial.
Qed.
End Host.