Library SetcodeConcrete.executiondelegatedaccount

Delegated sender nonce agreement until adoption

For a delegated account not created in this transaction, VM execution either preserves its marker and nonce or leaves it with regular code. The proof permits adoption, nested calls, CREATE after adoption in a new frame, and rollback. It does not posit nonce preservation by the VM.
From Stdlib Require Import List String ZArith.
Require Import RocqOfOCaml.RocqOfOCaml MonadVM.Execution.
Require Import QedkConcrete.vminvariant QedkConcrete.vmopcodeframe QedkConcrete.vmhostframe QedkConcrete.hostnonce
  QedkConcrete.vmcallframe QedkConcrete.vmcreateframe QedkConcrete.vmboundedframe
  QedkConcrete.hostcode QedkConcrete.hostframe QedkConcrete.recursiveassembly.
Require Import SetcodeConcrete.accountframe SetcodeConcrete.accounthost
  SetcodeConcrete.executionaccountframe SetcodeConcrete.executiontracking
  SetcodeConcrete.codeevolution SetcodeConcrete.vmcontextframe
  SetcodeConcrete.vmcreationguard SetcodeConcrete.assembly
  SetcodeConcrete.transactioncode SetcodeConcrete.vmprogress SetcodeConcrete.creationtracking.
Require Import MonadExecutionSpecs.Termination.VmDispatchProgress.
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.
Module E := Execution.Make.

Definition codeOrNonce (marker : string) (expected : Numeric.U64.t) code nonce :=
  regularCode code ∨ (code = marker ∧ nonce = expected).

Section Execution.
Context {F : E.FArgs}.
Local Abbreviation args := (@E.Instantiation_fargs F).
Local Abbreviation HostF := (@Evmc.Instantiate.HostF S.t (@recursiveArgs args)).
Local Abbreviation VmF := (@Evmc.Instantiate.VmF S.t (@recursiveArgs args)).
Context (query : Addr.t) (marker : string) (expected : Numeric.U64.t).
Context (Hdifferent : query ≠ Reserve_balance.precompile_address).
Context (Hmarker : Delegation.is_valid_delegation marker = true).
Context (cold warm access write reserve : N).
Context (Hcold : (0 < cold)%N) (Hwarm : (0 < warm)%N).
Context (Hrevision : E.Params.(Execution.Make_Params_signature.revision) =
  Support.Variants.Revision.Setcode (cold, warm, access, write, reserve)).
Local Abbreviation P := (codeOrNonce marker expected).
Local Abbreviation protected := (accountFrame query P).
Local Abbreviation regular := (fun code (_ : Numeric.U64.t) ⇒ regularCode code).

Definition delegatedAccountHost (host : Evmc.HOST (t := S.t)) :=
  PrimitiveHostFrame host protected ∧
  (∀ current source static gas, preservesCallback protected
    (host.(Evmc.HOST.setcodefrom) current source static gas)) ∧
  (∀ params, @setcodeGasProgress S.t (Vm.Make.Build_FArgs params host)) ∧
  (∀ addr s, snd (host.(Evmc.HOST.get_code_size) addr s) = s) ∧
  (∀ addr offset size s, snd (host.(Evmc.HOST.copy_code) addr offset size s) = s) ∧
  (∀ s, snd (host.(Evmc.HOST.get_tx_context) s) = s) ∧
  (∀ params s,
    A.t.code (State.op_pointcaretlparenrparen (S.t.world_state s) (W.account None query)) = marker →
    @entryDelegated S.t (Vm.Make.Build_FArgs params host) query s = true) ∧
  (∀ msg, 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.sender msg ≠ query) →
    preservesCallback protected (host.(Evmc.HOST.call) msg)).
Local Abbreviation delegatedAccountVm := (accountVm query P).

Lemma regular_account_implies_delegated s :
  accountFrame query regular s → protected s.
Proof.
  intros [Hwf [Hcreated|Hregular]]; split; [exact Hwf|left; exact Hcreated|exact Hwf|].
  right. left. exact Hregular.
Qed.

Lemma delegated_vm_constructor host :
  accountHost query regular host → delegatedAccountHost host →
  delegatedAccountVm (VmF host).
Proof.
  intros HregularHost [Hprimitive [Hsetcode [Hprogress [Hsize [Hcopy [Hread [Hentry Hcall]]]]]]]
msg body Hgas initial Hinitial.
  assert (HregularVm : accountVm query regular (VmF host)).
  { eapply execution_vm_constructor_account_frame; eassumption. }
  destruct (proj2 Hinitial) as [Hcreated|[Hregular|[Hcode Hnonce]]].
  1,2: apply regular_account_implies_delegated, HregularVm; [exact Hgas|];
    split; [exact (proj1 Hinitial)|]; auto.
  cbn -[Vm.Make.execute].
  eapply execute_preserves_at_context with (P := protected).
  - exact Hrevision.
  - reflexivity.
  - apply Hprogress.
  - exact Hread.
  - exact Hsize.
  - exact Hcopy.
  - apply primitive_frame_at. exact Hprimitive.
  - apply Hsetcode.
  - intros env opcode before Hself Hflag Hopcode Hbound HP.
    assert (HprimitiveAt : PrimitiveHostFrameAt host protected (@V.Executor.self S.t _ env)).
    { exact (eq_ind_r (fun self ⇒ PrimitiveHostFrameAt host protected self)
        (primitive_frame_at host protected (Evmc.Message.t.recipient msg) Hprimitive) Hself). }
    assert (Hnormal : ∀ nested, 0 ≤ Evmc.Message.t.gas nested < 2^63 →
      childCallFrom (@V.Executor.self S.t _ env) nested →
      Evmc.Message.t.kind nested ≠ Evmc.Message.CallKind.Create →
      Evmc.Message.t.kind nested ≠ Evmc.Message.CallKind.Create2 →
      preservesCallback protected (host.(Evmc.HOST.call) nested)).
    { intros nested Hb _ Hno Hno2. apply Hcall; [exact Hb|].
      intros [Heq|Heq]; contradiction. }
    assert (Hframe : preservesBoundedHost protected (@dispatch S.t _ env opcode)).
    { destruct opcode; cbn [recursiveCallOpcode] in Hopcode; try discriminate.
      all: cbn [dispatch V.Executor.execute_opcode].
      2: apply call_preserves_without_creation; assumption.
      2: apply callcode_preserves_without_creation; assumption.
      2: apply delegatecall_preserves_without_creation; assumption.
      3: apply staticcall_preserves_without_creation; assumption.
      all: destruct (String.string_dec (Evmc.Message.t.recipient msg) query) as [Heq|Hneq].
      1,3: apply bounded_from_unbounded;
        lazymatch goal with
        | |- preservesHost _ (@V.Executor.create _ _ _) ⇒ eapply create_entry_delegated
        | |- preservesHost _ (@V.Executor.create2 _ _ _) ⇒ eapply create2_entry_delegated
        end;
        [exact Hrevision|rewrite Heq in Hflag; rewrite (Hentry _ initial Hcode) in Hflag; exact Hflag|exact HprimitiveAt].
      all: lazymatch goal with
      | |- preservesBoundedHost _ (@V.Executor.create _ _ _) ⇒ apply create_preserves_from_self
      | |- preservesBoundedHost _ (@V.Executor.create2 _ _ _) ⇒ apply create2_preserves_from_self
      end;
        [exact HprimitiveAt|]; intros nested Hb Horigin;
        apply Hcall; [exact Hb|]; intros [Hkind|Hkind];
        unfold childCallFrom in Horigin; rewrite Hkind in Horigin; congruence. }
    exact (Hframe before Hbound HP).
  - exact Hgas.
  - exact Hinitial.
Qed.

Lemma concrete_marker_entry vm params s :
  A.t.code (State.op_pointcaretlparenrparen (S.t.world_state s) (W.account None query)) = marker →
  @entryDelegated S.t (Vm.Make.Build_FArgs params (HostF vm)) query s = true.
Proof.
  intro Hcode.
  assert (Hvalid : Delegation.is_valid_delegation
    (A.t.code (State.op_pointcaretlparenrparen (S.t.world_state s) (W.account None query))) = true)
    by (rewrite Hcode; exact Hmarker).
  assert (Hlength : Byte_string.Bytes.length
    (A.t.code (State.op_pointcaretlparenrparen (S.t.world_state s) (W.account None query))) = 23).
  { unfold Delegation.is_valid_delegation in Hvalid.
    apply Bool.andb_true_iff in Hvalid as [Hlen _]. apply Z.eqb_eq in Hlen. exact Hlen. }
  unfold entryDelegated. cbn -[H.get_code_size H.copy_code].
  unfold H.get_code_size. cbn -[W.account Byte_string.Bytes.length H.copy_code Uint64.of_int].
  match goal with |- context [Byte_string.Bytes.length ?code] ⇒
    change (Byte_string.Bytes.length code = 23) in Hlength end.
  rewrite Hlength. cbn -[H.copy_code].
  pose proof (copy_code_delegated (F := H.Build_FArgs args.(Host.Instantiate.ChainParams) vm) query s Hvalid) as Hcopy.
  exact (eq_trans (f_equal (fun result ⇒ Delegation.is_valid_delegation (fst result)) Hcopy) Hvalid).
Qed.

Lemma delegated_host_constructor vm :
  (∀ initial, trackingVm initial vm) → delegatedAccountVm vm →
  delegatedAccountHost (HostF vm).
Proof.
  intros Htracking Hvm. split; [apply concrete_primitives_account_frame|].
  split.
  - intros. apply setcode_account_frame. intros code nonce Hsource.
    left. apply regular_source_is_regular. exact Hsource.
  - split.
    + intro params. exact (@concrete_setcode_gas_progress args vm params
        cold warm access write reserve Hrevision Hcold Hwarm).
    + split; [intros; reflexivity|].
      split; [intros; apply copy_code_read_only|].
      split; [intros; reflexivity|].
      split; [apply concrete_marker_entry|].
      intros msg Hgas Hcreator.
      apply (@call_account_frame_noncreator args cold warm access write reserve query Hdifferent vm P msg).
      × exact Hcreator.
      × exact Hrevision.
      × intros nested body Hbound initial. exact (Htracking initial nested body Hbound).
      × exact Hvm.
      × exact Hgas.
Qed.

Lemma regular_host_constructor vm :
  (∀ initial, trackingVm initial vm) → accountVm query regular vm →
  accountHost query regular (HostF vm).
Proof.
  apply (@host_constructor_account_frame F query regular Hdifferent
    (fun code nonce Hsource ⇒ regular_source_is_regular code Hsource)
    (fun code nonce HP ⇒ HP) cold warm access write reserve Hcold Hwarm vm Hrevision).
Qed.

Theorem execution_vm_preserves_delegated_account msg body :
  0 ≤ Evmc.Message.t.gas msg < 2^63 →
  preservesCallback protected (@Host.Instantiate.Vm.execute args msg body).
Proof.
  intro Hgas.
  assert (Hassembly :
    (delegatedAccountHost (@Evmc.Instantiate.Host S.t (@recursiveArgs args)) ∧
      delegatedAccountVm (@Evmc.Instantiate.Vm S.t (@recursiveArgs args))) ∧
    (accountHost query regular (@Evmc.Instantiate.Host S.t (@recursiveArgs args)) ∧
      accountVm query regular (@Evmc.Instantiate.Vm S.t (@recursiveArgs args))) ∧
    (∀ initial, trackingHost initial (@Evmc.Instantiate.Host S.t (@recursiveArgs args)) ∧
      trackingVm initial (@Evmc.Instantiate.Vm S.t (@recursiveArgs args)))).
  { unfold Evmc.Instantiate.Host, Evmc.Instantiate.Vm,
      Evmc.Instantiate._recursive_modules_Host_Vm.
    generalize Evmc.Instantiate.recursive_module_fuel. intro fuel.
    induction fuel as [|fuel IH].
    - split.
      + split.
        × apply delegated_host_constructor.
          -- intros initial nested code Hbound s HP; exact HP.
          -- intros nested code Hbound s HP; exact HP.
        × intros nested code Hbound s HP; exact HP.
      + split.
        × split.
          -- apply regular_host_constructor.
             ++ intros initial nested code Hbound s HP; exact HP.
             ++ intros nested code Hbound s HP; exact HP.
          -- intros nested code Hbound s HP; exact HP.
        × intro initial. split.
          -- apply (@host_constructor_tracking initial F cold warm access write reserve
               Hrevision Hcold Hwarm). intros nested code Hbound s HP; exact HP.
          -- intros nested code Hbound s HP; exact HP.
    - cbn [recursive_module_unroll fst snd].
      destruct IH as [[HmarkerHost HmarkerVm] [[HregularHost HregularVm] Htracking]].
      split.
      + split.
        × apply delegated_host_constructor; [intro initial; exact (proj2 (Htracking initial))|exact HmarkerVm].
        × apply delegated_vm_constructor; assumption.
      + split.
        × split.
          -- apply regular_host_constructor; [intro initial; exact (proj2 (Htracking initial))|exact HregularVm].
          -- eapply execution_vm_constructor_account_frame; eassumption.
        × intro initial. split.
          -- apply (@host_constructor_tracking initial F cold warm access write reserve
               Hrevision Hcold Hwarm). exact (proj2 (Htracking initial)).
          -- apply (@vm_constructor_tracking initial F cold warm access write reserve Hrevision).
             exact (proj1 (Htracking initial)). }
  exact (proj2 (proj1 Hassembly) msg body Hgas).
Qed.
Local Opaque Evmc.Instantiate._recursive_modules_Host_Vm.

Theorem transaction_call_preserves_delegated_account tx msg :
  0 ≤ Evmc.Message.t.gas msg < 2^63 →
  preservesCallback protected (@E.Host.call_from_eoa F tx msg).
Proof.
  intro Hgas. unfold E.Host.call_from_eoa.
  cbv beta iota zeta delta [E.Instantiation Host.Instantiate.functor
    Host.Instantiate.Instantiate_result.Host Host.Instantiate.Host
    H.functor H.Make_result.call_from_eoa H.call_from_eoa].
  apply (@call_impl_account_frame args cold warm access write reserve query Hdifferent
    (@H.Vm (@Host.Instantiate.Host_fargs args)) (Some tx) P msg).
  - exact Hrevision.
  - intros nested code Hbound initial.
    exact (@execution_vm_preserves_tracking initial F cold warm access write reserve
      Hrevision Hcold Hwarm nested code Hbound).
  - intros nested code Hbound.
    pose proof (execution_vm_preserves_delegated_account nested code Hbound) as Hvm.
    cbv beta iota zeta delta [Host.Instantiate.Vm.execute Host.Instantiate.Vm] in Hvm |- ×.
    exact Hvm.
  - exact Hgas.
Qed.

If this address is still eligible as an EOA after the call, execution has not changed its nonce. The only excluded alternative is creation at its address, discharged by the transaction-sender creation premise.
Corollary transaction_call_unmigrated_delegated_nonce tx msg initial :
  0 ≤ Evmc.Message.t.gas msg < 2^63 →
  stringmaps.WellFormed (W.t.accounts (S.t.world_state initial)) →
  A.t.code (State.op_pointcaretlparenrparen (S.t.world_state initial) (W.account None query)) = marker →
  A.t.nonce (State.op_pointcaretlparenrparen (S.t.world_state initial) (W.account None query)) = expected →
  let post := snd (E.Host.call_from_eoa tx msg initial) in
  ¬ In query (S.t.accounts_created_in_current_transaction post) →
  A.is_smart_contract (State.op_pointcaretlparenrparen (S.t.world_state post) (W.account None query)) = false →
  A.t.nonce (State.op_pointcaretlparenrparen (S.t.world_state post) (W.account None query)) = expected.
Proof.
  intros Hgas Hmap Hcode Hnonce post Hnot Hnonregular.
  pose proof (transaction_call_preserves_delegated_account tx msg Hgas initial
    (conj Hmap (or_intror (or_intror (conj Hcode Hnonce))))) as Hafter.
  destruct Hafter as [_ [Hcreated|[Hregular|[_ Hnonce']]]];
    [contradiction| |exact Hnonce'].
  apply regular_code_contract in Hregular. exfalso.
  exact (Bool.diff_true_false (eq_trans (eq_sym Hregular) Hnonregular)).
Qed.
End Execution.
Print Assumptions transaction_call_unmigrated_delegated_nonce.