Library QedkConcrete.vmnondebitchecked

Empty-account protection through the checked instruction loop

Once the tracked address is created, the invariant records that exception. Until then, CALL must resolve its empty code and cannot debit it. Keeping this property alongside supply and representation bounds makes the child hypotheses applicable to real VM entries rather than arbitrary messages.
From Stdlib Require Import List String ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import QedkConcrete.vmsupplywords.
Require Import QedkConcrete.nondebitframe QedkConcrete.vmcallprotected
  QedkConcrete.vmcreateprotected QedkConcrete.vmcallframe QedkConcrete.vmframe QedkConcrete.creationassembly
  QedkConcrete.hostcode QedkConcrete.vmhostframe QedkConcrete.vmboundedframe
  QedkConcrete.vmchecked QedkConcrete.vmcallchecked QedkConcrete.vmmachinewords
  QedkConcrete.vmmemorywords QedkConcrete.vmsizes QedkConcrete.vmrun
  QedkConcrete.vmenvironmentwords QedkConcrete.vmdispatchwords
  QedkConcrete.vmopcodeframe QedkConcrete.contexthostinstance
  QedkConcrete.hostframe QedkConcrete.supply QedkConcrete.worldaccounts
  QedkConcrete.wordrange QedkConcrete.hashwords QedkConcrete.vminvariant.
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.

Lemma primitive_frame_at_conj {Host_t : Set} (host : Evmc.HOST (t := Host_t)) P Q self :
  PrimitiveHostFrameAt host P self → PrimitiveHostFrameAt host Q self →
  PrimitiveHostFrameAt host (fun s ⇒ P s ∧ Q s) self.
Proof.
  intros HP HQ. destruct HP, HQ. constructor; unfold preservesCallback in *;
    intros; split; intuition eauto.
Qed.
Section Concrete.
Context {HF : Host.Instantiate.FArgs}.
Local Abbreviation HostF := (@Evmc.Instantiate.HostF S.t (@recursiveArgs HF)).
Context (vm : Evmc.Vm.SIG (_fargs := Evmc.Vm.Build_FArgs (@Evmc.Instantiate.T S.t (@recursiveArgs HF)))).
Context (params : Vm.Make_Params_signature) (limit : Z).
Local Abbreviation F := (V.Build_FArgs params (HostF vm)).

Local Abbreviation U64 := (Opaque.legacy_witness 0%Z).
Local Abbreviation UF := (Opaque.legacy_witness 0%Z).
Local Abbreviation contextInvariant := (hostSupplyContext HF.(Host.Instantiate.ChainParams) limit).
Local Abbreviation floor := (@uncreatedBalanceFloor).
Context (query : Chain.Ethereum.Address.t) (minimum : Z).
Local Abbreviation protected := (fun s ⇒ contextInvariant s ∧ floor query minimum s).
Local Abbreviation stillUncreated := (fun s ⇒ contextInvariant s ∧
  (floor query minimum s ∧ ¬ List.In query (S.t.accounts_created_in_current_transaction s))).

Lemma protected_primitives self : self ≠ query →
  PrimitiveHostFrameAt (HostF vm) protected self.
Proof.
  intro Hself. apply primitive_frame_at_conj.
  - apply primitive_frame_at, supply_context_primitives.
  - apply concrete_primitives_preserve_uncreated_balance. exact Hself.
Qed.

Lemma still_uncreated_primitives self : self ≠ query →
  PrimitiveHostFrameAt (HostF vm) stillUncreated self.
Proof.
  intro Hself. apply primitive_frame_at_conj.
  - apply primitive_frame_at, supply_context_primitives.
  - apply concrete_primitives_preserve_still_uncreated_balance. exact Hself.
Qed.
Section Instructions.
Context {E : @V.Executor.FArgs S.t F}.
  Context `{U0 : RocqOfOCaml.Basics.Unreachable Z.t}.
  Context `{U1 :
    RocqOfOCaml.Basics.Unreachable (RocqOfOCaml.OCamlSeq.t int)}.
  Context `{U2 : RocqOfOCaml.Basics.Unreachable RocqOfOCaml.OCamlInt32.t}.
  Context `{U3 : RocqOfOCaml.Basics.Unreachable MonadVM.Uint64.t}.
  Context `{U4 :
    RocqOfOCaml.Basics.Unreachable MonadVM.Support.UintN.t}.
  Context `{U5 :
    RocqOfOCaml.Basics.Unreachable MonadVM.Numeric.U256.Repr.t}.
  Context `{U7 :
    RocqOfOCaml.Basics.Unreachable MonadVM.Numeric.Integer.t}.
  Context `{U8 :
    RocqOfOCaml.Basics.Unreachable MonadVM.Numeric.I256.t}.
  Context `{U9 : RocqOfOCaml.Basics.Unreachable MonadVM.Gas.t}.
  Context `{U10 :
    RocqOfOCaml.Basics.Unreachable MonadVM.Delegation.Address.t}.
  Context `{U11 :
    RocqOfOCaml.Basics.Unreachable MonadVM.Chain.Ethereum.Address.t}.
  Context `{U12 :
    RocqOfOCaml.Basics.Unreachable MonadVM.Byte_string.Bytes.t}.
  Context `{U13 :
    RocqOfOCaml.Basics.Unreachable
      (@MonadVM.Vm.Make.M.Option.t S.t F MonadVM.Numeric.U256.t)}.
  Context `{U15 : RocqOfOCaml.Basics.Unreachable unit}.
  Context `{U16 : RocqOfOCaml.Basics.Unreachable string}.
  Context `{U17 :
    RocqOfOCaml.Basics.Unreachable (option MonadVM.Numeric.U256.t)}.
  Context `{U18 : RocqOfOCaml.Basics.Unreachable (option string)}.
  Context `{U19 :
    RocqOfOCaml.Basics.Unreachable
      (list MonadVM.Byte_string.Bytes.t)}.
  Context `{U20 : RocqOfOCaml.Basics.Unreachable (list int)}.
  Context `{U21 : RocqOfOCaml.Basics.Unreachable int}.
  Context `{U22 : RocqOfOCaml.Basics.Unreachable ascii}.
  Context `{U23 : RocqOfOCaml.Basics.Unreachable (int × int)}.
  Context `{U24 :
    RocqOfOCaml.Basics.Unreachable
      (Z.t → MonadVM.Numeric.U256.t)}.
  Context `{U25 :
    RocqOfOCaml.Basics.Unreachable
      (MonadVM.Support.UintN.t → MonadVM.Support.UintN.t)}.
  Context `{U26 :
    RocqOfOCaml.Basics.Unreachable
      (unit → RocqOfOCaml.OCamlSeq.node int)}.
  Context `{U27 :
    RocqOfOCaml.Basics.Unreachable
      (@MonadVM.Vm.Make.opcode_impl S.t F)}.
  Context `{U28 :
    RocqOfOCaml.Basics.Unreachable
      MonadVM.Numeric.IntegerBase.(MonadVM.Numeric.Make.Make_result.t)}.
  Context `{U31 :
    RocqOfOCaml.Basics.Unreachable
      MonadVM.Byte_string.B32.(MonadVM.Byte_string.Fixed.Fixed_result.t)}.
  Context `{U32 :
    RocqOfOCaml.Basics.Unreachable
      (MonadVM.Numeric.U256.t → MonadVM.Numeric.U256.t →
        @MonadVM.Vm.Make.Memory.t S.t F →
        @MonadVM.Vm.Make.M.Option.t S.t F
          (@MonadVM.Vm.Make.Memory.t S.t F))}.
  Context `{U33 :
    RocqOfOCaml.Basics.Unreachable
      (@MonadVM.Vm.Make.Memory.t S.t F →
        MonadVM.Support.UintN.t)}.

  Let State := @MonadVM.Vm.Make.MachineState.t S.t F.

Local Abbreviation executeOpcode := (@dispatch S.t F E).

Lemma instruction_preserves_creation opcode state :
  params.(Vm.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  params.(Vm.Make_Params_signature.debug_tstore) = false →
  creationHost (HostF vm) →
  Z.of_N (MS.t.gas state) < 2^63 →
  stringmaps.WellFormed (W.t.accounts (S.t.world_state (MS.t.host state))) →
  @creationFrame (MS.t.host state) (MS.t.host (snd (executeOpcode opcode state))).
Proof.
  intros Hrevision Hdebug [Hprimitive [Hread Hcall]] Hgas Hwf.
  assert (Hpres : preservesBoundedHost (@creationInvariant (MS.t.host state))
    (executeOpcode opcode)).
  { destruct (recursiveCallOpcode opcode) eqn:Hrecursive.
    - apply recursive_opcode_preserves; [apply Hprimitive| |exact Hrecursive].
      intros msg Hbound. apply creation_callback. apply Hcall. exact Hbound.
    - apply bounded_from_unbounded. destruct (machineOnlyOpcode opcode) eqn:Hlocal.
      + apply machine_only_preserves_host; assumption.
      + apply primitive_host_preserves; try assumption; [apply Hprimitive|].
        destruct opcode; cbn [recursiveCallOpcode machineOnlyOpcode primitiveHostOpcode] in *;
          congruence. }
  exact (proj2 (Hpres state Hgas (conj Hwf (creation_frame_refl _)))).
Qed.

Lemma dispatch_preserves_uncreated_checked opcode state :
  params.(Vm.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  params.(Vm.Make_Params_signature.debug_tstore) = false →
  keccak256OutputSize →
  environmentWords ((@V.Executor.C S.t F E).(V.Executor_C_signature.execution_environment)) →
  opcodeWordParameters opcode →
  creationHost (HostF vm) →
  (∀ msg, @vmMessageBounds msg → ∀ host, contextInvariant host →
    let result := (HostF vm).(Evmc.HOST.call) msg host in
    (contextInvariant (snd result) ∧ OCamlString.length (Evmc.Result.t.output_data (fst result)) < 2^256) ∨
    badMemoryInitComparison) →
  (∀ msg, @vmMessageBounds msg →
    childCallFrom (@V.Executor.self S.t F E) 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)) →
    ∀ host, protected host →
    let result := (HostF vm).(Evmc.HOST.call) msg host in
    (protected (snd result) ∧ OCamlString.length (Evmc.Result.t.output_data (fst result)) < 2^256) ∨
    badMemoryInitComparison) →
  @V.Executor.self S.t F E ≠ query →
  Z.of_N (MS.t.gas state) < 2^63 → checkedMachine protected state →
  checkedMachine protected (snd (executeOpcode opcode state)) ∨ badMemoryInitComparison.
Proof.
  intros Hrevision Hdebug Hhash Henv Hparams Hcreation Hsupply Hchild Hself Hgas Hinitial.
  assert (Hcontext : checkedMachine contextInvariant state).
  { eapply checked_machine_weaken with (pre := protected); [intros h Hh; exact (proj1 Hh)|exact Hinitial]. }
  destruct (dispatch_preserves_supply_context_from_child vm params limit (E := E)
    opcode state
    Hrevision Hdebug Hhash Henv Hparams Hsupply Hgas Hcontext) as [Hafter|Hbad];
    [|right; exact Hbad].
  pose proof (proj2 (proj1 (proj2 (proj2 (proj1 Hinitial))))) as Hfloor.
  destruct (List.in_dec String.string_dec query
    (S.t.accounts_created_in_current_transaction (MS.t.host state))) as [Hcreated|Habsent].
  - pose proof (instruction_preserves_creation opcode state Hrevision Hdebug Hcreation Hgas
      (proj1 (proj1 Hfloor))) as Htracking.
    left. unfold checkedMachine, machineWords in Hafter |- ×.
    destruct Hafter as [[Hstack [Hpc [Hhost Hmemory]]] Hsizes].
    split; [|exact Hsizes]. split; [exact Hstack|]. split; [exact Hpc|]. split; [|exact Hmemory].
    split; [exact Hhost|]. split; [exact (proj1 (proj1 (proj1 Hhost)))|].
    left. exact (creations_retained _ _ Htracking query Hcreated).
  - destruct (recursiveCallOpcode opcode) eqn:Hrecursive.
    + assert (Hvalue : wordRange (Env.t.value
        ((@V.Executor.C S.t F E).(V.Executor_C_signature.execution_environment)))).
      { exact (List.Forall_inv (List.Forall_inv_tail (proj1 Henv))). }
      assert (Hpre : checkedMachine stillUncreated state).
      { unfold checkedMachine, machineWords in Hinitial |- ×. tauto. }
      assert (Hempty : ∀ host, stillUncreated host →
        (HostF vm).(Evmc.HOST.copy_code) query 0 (@Delegation.eoa_delegated_code_length) host =
          (Byte_string.Bytes.empty, host)).
      { intros host [_ [Hprotected Hnot]]. apply concrete_copy_empty_code.
        exact (proj2 (uncreated_balance_floor_not_created query minimum host Hprotected Hnot)). }
      assert (Hweaken : ∀ host, stillUncreated host → protected host) by (intros; tauto).
      assert (Hprimitive : PrimitiveHostFrameAt (HostF vm) protected (@V.Executor.self S.t F E))
        by (apply protected_primitives; exact Hself).
      assert (HprimitivePre : PrimitiveHostFrameAt (HostF vm) stillUncreated (@V.Executor.self S.t F E))
        by (apply still_uncreated_primitives; exact Hself).
      assert (Hlift : ∀ action : @V.M.t S.t F bool,
        boundedCheckedSafe protected (fun _ ⇒ True) action →
        checkedMachine protected (snd (action state)) ∨ badMemoryInitComparison).
      { intros action Hsafe. destruct (Hsafe state Hgas Hinitial) as [[H _]|Hbad];
          [left; exact H|right; exact Hbad]. }
      assert (HliftPre : ∀ action : @V.M.t S.t F bool,
        (∀ before, Z.of_N (MS.t.gas before) < 2^63 → checkedMachine stillUncreated before →
          (checkedMachine protected (snd (action before)) ∧
            match fst (action before) with inl _ ⇒ True | inr _ ⇒ True end) ∨ badMemoryInitComparison) →
        checkedMachine protected (snd (action state)) ∨ badMemoryInitComparison).
      { intros action Hsafe. destruct (Hsafe state Hgas Hpre) as [[H _]|Hbad];
          [left; exact H|right; exact Hbad]. }
      destruct opcode; cbn [recursiveCallOpcode] in Hrecursive; try discriminate.
      all: cbn [dispatch V.Executor.execute_opcode].
      × apply Hlift, create_checked_from_self; try assumption.
        intros msg Hbounds Hkind Horigin. apply Hchild; [exact Hbounds|exact Horigin|tauto].
      × apply HliftPre. apply call_checked_empty_recipient with (query := query); try assumption.
        intros msg Hbounds Horigin Hcode. apply Hchild; [exact Hbounds|exact Horigin|].
        right; right. intro Heq. exact (proj1 (Hcode Heq)).
      × apply Hlift, callcode_checked_from_self; try assumption.
        intros msg Hbounds Hkind Horigin. apply Hchild; [exact Hbounds|exact Horigin|].
        right; right. intro Heq. exfalso. unfold childCallFrom in Horigin. rewrite Hkind in Horigin.
        apply Hself. destruct Horigin as [_ Hrecipient]. congruence.
      × apply Hlift, delegatecall_checked_from_self; try assumption.
        intros msg Hbounds Hkind Horigin. apply Hchild; [exact Hbounds|exact Horigin|].
        right; right. intro Heq. exfalso. unfold childCallFrom in Horigin. rewrite Hkind in Horigin.
        apply Hself. congruence.
      × apply Hlift, create2_checked_from_self; try assumption.
        intros msg Hbounds Hkind Horigin. apply Hchild; [exact Hbounds|exact Horigin|tauto].
      × apply HliftPre. apply staticcall_checked_empty_recipient with (query := query); try assumption.
        intros msg Hbounds Horigin Hcode. apply Hchild; [exact Hbounds|exact Horigin|].
        right; right. intro Heq. exact (proj1 (Hcode Heq)).
    + assert (Hframe : preservesHost (floor query minimum) (executeOpcode opcode)).
      { destruct (machineOnlyOpcode opcode) eqn:Hlocal.
        - apply machine_only_preserves_host; assumption.
        - apply primitive_host_preserves_at; try assumption.
          + apply concrete_primitives_preserve_uncreated_balance. exact Hself.
          + destruct opcode; cbn [recursiveCallOpcode machineOnlyOpcode primitiveHostOpcode] in *;
              congruence. }
      specialize (Hframe state Hfloor). left.
      unfold checkedMachine, machineWords in ×. tauto.
Qed.
Lemma run_preserves_uncreated_checked
    {Urun : Basics.Unreachable (sum unit Evmc.Result.StatusCode.t × State)} state :
  params.(Vm.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  params.(Vm.Make_Params_signature.debug_tstore) = false →
  keccak256OutputSize →
  environmentWords ((@V.Executor.C S.t F E).(V.Executor_C_signature.execution_environment)) →
  creationHost (HostF vm) →
  (∀ msg, @vmMessageBounds msg → ∀ host, contextInvariant host →
    let result := (HostF vm).(Evmc.HOST.call) msg host in
    (contextInvariant (snd result) ∧ OCamlString.length (Evmc.Result.t.output_data (fst result)) < 2^256) ∨
    badMemoryInitComparison) →
  (∀ msg, @vmMessageBounds msg →
    childCallFrom (@V.Executor.self S.t F E) 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)) →
    ∀ host, protected host →
    let result := (HostF vm).(Evmc.HOST.call) msg host in
    (protected (snd result) ∧ OCamlString.length (Evmc.Result.t.output_data (fst result)) < 2^256) ∨
    badMemoryInitComparison) →
  @V.Executor.self S.t F E ≠ query →
  Z.of_N (MS.t.gas state) < 2^63 → checkedMachine protected state →
  checkedMachine protected (snd (@generated_run S.t F E state)) ∨ badMemoryInitComparison.
Proof.
  intros Hrevision Hdebug Hhash Henv Hcreation Hsupply Hchild Hself Hgas Hinitial.
  apply (@run_preserves S.t F E
    (fun st ⇒ checkedMachine protected st ∨ badMemoryInitComparison) state).
  - right; exact Hrevision.
  - intros before Hbound [Hbefore|Hbad]; [|right; exact Hbad].
    apply dispatch_preserves_uncreated_checked; try assumption.
    apply selected_opcode_word_parameters.
  - exact Hgas.
  - left; exact Hinitial.
Qed.
End Instructions.
End Concrete.

Print Assumptions dispatch_preserves_uncreated_checked.

Print Assumptions run_preserves_uncreated_checked.