Library QedkConcrete.persistentnoncehost

Delegated nonce invariant through concrete Host calls

Creation may increment its caller, but ordinary calls may not. The VM frame supplies that distinction; collision checks protect the delegated account from being the target of creation. Rollback restores both code and nonce, while reserve setters affect only the native account's nonce.
From Stdlib Require Import List String ZArith.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import QedkConcrete.persistentnonce QedkConcrete.persistentcodehost
  QedkConcrete.hostnonce QedkConcrete.nativenonce QedkConcrete.vmhostframe
  QedkConcrete.persistentcode QedkConcrete.hostframe QedkConcrete.hostcode
  QedkConcrete.hostsupply QedkConcrete.hostbalance QedkConcrete.contexthostinstance
  QedkConcrete.assemblychecked QedkConcrete.creationhost
  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 nonce_bind {U64 : Basics.Unreachable Numeric.U64.t}
    {UF : Basics.Unreachable Numeric.U256.t} {A B : Set} query code nonce
    (action : S.t → A × S.t) (next : A → S.t → B × S.t) :
  preservesCallback (@persistentNonce query code nonce) action →
  (∀ value, preservesCallback (@persistentNonce query code nonce) (next value)) →
  preservesCallback (@persistentNonce query code nonce) (S.M.(Monad.State.State_result.op_letdollar) action next).
Proof.
  intros Haction Hnext s Hinitial.
  change (@persistentNonce query code nonce (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 := (@persistentNonce).
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)))).

Local Abbreviation native := (@Reserve_balance.precompile_address).

Lemma native_preserves_other_nonce query nonce msg addr action :
  query ≠ native →
  F.(Host.Instantiate.ChainParams).(Chain.Monad.PARAMS.revision) = Support.Variants.Revision.Eleven →
  nativeDispatch vm msg addr = Some action → preservesCallback (@nonceInvariant query nonce) action.
Proof.
  intros Hdifferent Hrevision Hselected. unfold nativeDispatch, Precompiles.Make.try_precompile in Hselected.
  match type of Hselected with context [@Chain.Ethereum.Address.Map.find_opt ?T addr ?entries] ⇒
    destruct (@Chain.Ethereum.Address.Map.find_opt T addr entries) as [pure|] eqn:Hethereum in Hselected end.
  - destruct (Evmc.Message.t.delegated msg) in Hselected; inversion Hselected; subst action;
      intros s Hinitial; exact Hinitial.
  - unfold Precompiles.Make.monad_precompiles in Hselected.
    change (@Precompiles.Make.Revision (@H.Precompiles_fargs
      (H.Build_FArgs F.(Host.Instantiate.ChainParams) vm))).(Precompiles.Make_Revision_signature.revision)
      with F.(Host.Instantiate.ChainParams).(Chain.Monad.PARAMS.revision) in Hselected.
    rewrite Hrevision in Hselected.
    match type of Hselected with context [@Chain.Ethereum.Address.Map.find_opt ?T addr ?entries] ⇒
      destruct (@Chain.Ethereum.Address.Map.find_opt T addr entries) as [native|] eqn:Hnative in Hselected end.
    2: discriminate.
    apply precompilesframe.find_pair_value in Hnative as [[_ ->] | [_ ->]];
      match type of Hselected with context [if ?reject then _ else _] ⇒ destruct reject in Hselected end;
      inversion Hselected; subst action.
    + intros s Hinitial; exact Hinitial.
    + apply reserve_precompile_preserves_other_nonce; exact Hdifferent.
    + intros s Hinitial; exact Hinitial.
    + intros s [Hwf Hnonce].
      match goal with |- context [MonadVM.Staking.staking_contract ?fb0 ?fb1 ?fb2 msg] ⇒
        destruct (staking_contract_uframe fb0 fb1 fb2 msg s) as [_ [_ [Haccounts _]]]
end.
      destruct (Haccounts Hwf) as [Hwf' Hfields].
      split; [exact Hwf'|].
      etransitivity; [exact (proj1 (Hfields query))|exact Hnonce].
Qed.

Lemma native_preserves_persistent_nonce query code nonce msg addr action :
  query ≠ native →
  F.(Host.Instantiate.ChainParams).(Chain.Monad.PARAMS.revision) = Support.Variants.Revision.Eleven →
  nativeDispatch vm msg addr = Some action →
  preservesCallback (protected query code nonce) action.
Proof.
  intros Hdifferent Hrevision Hselected s [Hcode Hnonce]. split.
  - exact (@native_preserves_persistent_code F vm query code msg addr action Hrevision Hselected s Hcode).
  - exact (native_preserves_other_nonce query nonce msg addr action Hdifferent Hrevision Hselected s Hnonce).
Qed.

Lemma concrete_primitives_preserve_nonce query nonce :
  PrimitiveHostFrame (HostF vm) (@nonceInvariant query nonce).
Proof.
  constructor; 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 nonceInvariant].
  all: try lazymatch goal with
    | |- preservesCallback _ (H.set_storage _ _ _) ⇒ apply storage_preserves_nonce
    | |- preservesCallback _ (H.selfdestruct _ _) ⇒ apply selfdestruct_preserves_nonce
    end.
  all: intros s Hinitial; eapply nonce_world_frame; [exact Hinitial|].
  all: first [reflexivity | apply access_account_preserves_world |
    apply access_storage_preserves_world | rewrite copy_code_read_only; reflexivity].
Qed.

Lemma concrete_primitives_preserve_persistent_nonce query code nonce :
  PrimitiveHostFrame (HostF vm) (protected query code nonce).
Proof.
  pose proof (@concrete_primitives_preserve_persistent_code F vm query code) as Hcode.
  pose proof (concrete_primitives_preserve_nonce query nonce) as Hnonce.
  constructor; intros; intros s [Hbefore Hnumber]; split.
  all: first [solve [destruct Hcode; unfold preservesCallback in *; eauto] |
    solve [destruct Hnonce; unfold preservesCallback in *; eauto]].
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_nonce from_tx query code nonce msg :
  (∀ addr action, nativeDispatch vm msg addr = Some action →
    preservesCallback (protected query code nonce) action) →
  (∀ body s, protected query code nonce s →
    protected query code nonce (snd (vm.(Evmc.Vm.SIG.execute) msg body s))) →
  preservesCallback (protected query code nonce) (processCall from_tx msg).
Proof.
  intros Hnative Hvm s Hinitial.
  assert (Htransfer : protected query code nonce (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_nonce|]; 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 nonce (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 call_impl_preserves_persistent_nonce from_tx query code nonce msg :
  query ≠ native →
  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 nonce) (vm.(Evmc.Vm.SIG.execute) nested body)) →
  (0 ≤ Evmc.Message.t.gas msg < 2^63)%Z →
  preservesCallback (protected query code nonce)
    (callImpl (match from_tx with Some tx ⇒ H.Eoa_tx tx | None ⇒ H.Evm_call end) msg).
Proof.
  intros Hdifferent Hnonempty Hrevision Hvm Hgas s Hinitial.
  pose proof (process_call_preserves_persistent_nonce from_tx query code nonce msg
    (fun addr action Hselected ⇒ native_preserves_persistent_nonce query code nonce msg addr action Hdifferent Hrevision Hselected)
    (fun body ⇒ Hvm msg body Hgas)) as Hcall.
  pose proof (process_create_preserves_existing_nonce (F := H.Build_FArgs F.(Host.Instantiate.ChainParams) vm)
    query code nonce 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 nonce (snd run)) by
      (lazymatch run with ?action ?initial ⇒
        assert (Hentry : protected query code nonce initial) by
          (destruct Hinitial as [Hcode Hnonce]; split; [destruct Hcode; constructor; assumption|exact Hnonce]);
        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 as [Hcode Hnonce]; split; [destruct Hcode; constructor; assumption|exact Hnonce]).
  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 as [Hcode Hnonce]; split; [destruct Hcode; constructor; assumption|exact Hnonce]|exact Hcore].
Qed.
Lemma call_preserves_persistent_nonce query code nonce msg :
  query ≠ native →
  (Evmc.Message.t.kind msg = Evmc.Message.CallKind.Create ∨
    Evmc.Message.t.kind msg = Evmc.Message.CallKind.Create2 →
    Evmc.Message.t.sender msg ≠ query) →
  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 nonce) (vm.(Evmc.Vm.SIG.execute) nested body)) →
  (0 ≤ Evmc.Message.t.gas msg < 2^63)%Z → preservesCallback (protected query code nonce) (hostCall msg).
Proof.
  intros Hdifferent Hcreator Hnonempty Hrevision Hvm Hgas. unfold H.call, H.M.
  apply nonce_bind.
  - match goal with |- preservesCallback _ (if ?test then _ else _) ⇒ destruct test eqn:Hkind end.
    + apply increment_preserves_other_persistent_nonce. apply Hcreator.
      destruct (Evmc.Message.t.kind msg); try discriminate; auto.
    + intros s Hinitial. exact Hinitial.
  - intros ok. destruct ok.
    + apply (call_impl_preserves_persistent_nonce None); assumption.
    + intros s Hinitial. exact Hinitial.
Qed.
End Host.