Library SetcodeConcrete.vmterminal

Gas at terminal outcomes of the generated VM loop

CALL/CREATE instructions cannot terminate a frame successfully or raise Revert: a child's revert is an ordinary child result. The VM resumes the caller after it. Thus terminal gas is bounded by the nonrecursive opcode proofs, without assuming an arbitrary Host callback returns valid gas.
From Stdlib Require Import List NArith ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml MonadVM.Vm.
Require Import QedkConcrete.vminvariant QedkConcrete.vmopcodeframe QedkConcrete.vmhostframe.
Require Import QedkConcrete.hostframe.
Require Import SetcodeConcrete.vmprogress SetcodeConcrete.vmgasframe
  SetcodeConcrete.vmgasopcodes SetcodeConcrete.vmnoncesetcode.
Require Import MonadExecutionSpecs.Termination.VmDispatchProgress.
Set Default Goal Selector "!".
Local Open Scope Z_scope.

Section Machine.
Context {Host_t : Set} {F : @V.FArgs Host_t}.
Definition noRevertError {A : Set} (action : @V.M.t Host_t F A) : Prop :=
  ∀ state, fst (action state) ≠ inr Evmc.Result.StatusCode.Revert.

Lemma no_revert_bind {A B : Set} (action : @V.M.t Host_t F A)
    (next : A → @V.M.t Host_t F B) :
  noRevertError action → (∀ value, noRevertError (next value)) →
  noRevertError (@V.M.op_letdollar Host_t F A B action next).
Proof.
  intros Ha Hnext state. specialize (Ha state).
  change (fst (match action state with
    | (inl value, middle) ⇒ next value middle
    | (inr error, middle) ⇒ (inr error, middle) end) ≠ inr Evmc.Result.StatusCode.Revert).
  destruct (action state) as [[value|error] middle]; cbn [fst] in ×.
  - apply Hnext.
  - intro Heq. apply Ha. inversion Heq. reflexivity.
Qed.
Lemma no_revert_return {A : Set} value : noRevertError (@V.M._return Host_t F A value).
Proof. intros state; discriminate. Qed.
Lemma no_revert_fail {A : Set} error : error ≠ Evmc.Result.StatusCode.Revert →
  noRevertError (@V.M.fail Host_t F A error).
Proof. intros Herror state Heq. apply Herror. inversion Heq; reflexivity. Qed.
Lemma no_revert_fmap {A B : Set} (f : A → B) action :
  noRevertError action → noRevertError (@V.M.op_ltdollargt Host_t F A B f action).
Proof.
  intro Haction. change (noRevertError (@V.M.op_letdollar Host_t F A B action
    (fun value ⇒ @V.M._return Host_t F B (f value)))).
  apply no_revert_bind; [exact Haction|intros; apply no_revert_return].
Qed.
Lemma no_revert_option {A : Set} error (value : option A) :
  error ≠ Evmc.Result.StatusCode.Revert →
  noRevertError (@V.M.Option.or_fail Host_t F A error value).
Proof. intro Herror; destruct value; [apply no_revert_return|apply no_revert_fail; exact Herror]. Qed.
Lemma no_revert_lift {A : Set} (action : Host_t → A × Host_t) :
  noRevertError (@V.M.HostAPI.lift Host_t F A action).
Proof. intro state; unfold V.M.HostAPI.lift. destruct (action (MS.t.host state)); discriminate. Qed.
Lemma no_revert_seq {A B : Set} (f : A → @V.M.t Host_t F B) :
  (∀ x, noRevertError (f x)) → ∀ values, noRevertError (@V.M.Seq.mapM Host_t F A B f values).
Proof.
  intro Hf. induction values as [|value values IH].
  all: unfold V.M.Seq.mapM, Monad.Make_Monad.Seq.mapM, Monad.Make_Monad.Seq.sequence.
  all: rewrite Init.Wf.Fix_eq; [|intros seq left right Heq;
    destruct seq; cbn [OCamlSeq.uncons]; [reflexivity|rewrite Heq; reflexivity]].
  - apply no_revert_return.
  - change (noRevertError (@V.M.op_letdollar Host_t F B (OCamlSeq.t B)
      (f value) (fun result ⇒ @V.M.op_letdollar Host_t F (OCamlSeq.t B) (OCamlSeq.t B)
        (@V.M.Seq.mapM Host_t F A B f values)
        (fun results ⇒ @V.M._return Host_t F (OCamlSeq.t B) (OCamlSeq.cons result results))))).
    apply no_revert_bind; [apply Hf|]. intro result.
    apply no_revert_bind; [exact IH|]. intro results. apply no_revert_return.
Qed.
End Machine.

Ltac no_revert_extra := lazymatch goal with |- ?g ⇒ fail 1 "Unhandled error case" g end.
Ltac solve_no_revert :=
  lazymatch goal with
  | |- noRevertError (@V.M.op_letdollar _ _ _ _ _ _) ⇒
    apply no_revert_bind; [solve_no_revert|]; let value := fresh "value" in intro value;
    repeat match goal with x : _ × _ |- _ ⇒ destruct x end;
    cbn beta iota zeta; solve_no_revert
  | |- noRevertError (@V.M.op_gtgteq _ _ _ _ _ _) ⇒
    apply no_revert_bind; [solve_no_revert|]; let value := fresh "value" in intro value;
    repeat match goal with x : _ × _ |- _ ⇒ destruct x end;
    cbn beta iota zeta; solve_no_revert
  | |- noRevertError (@V.M.op_ltdollargt _ _ _ _ _ _) ⇒ apply no_revert_fmap; solve_no_revert
  | |- noRevertError (@V.M.fmap _ _ _ _ _ _) ⇒ apply no_revert_fmap; solve_no_revert
  | |- noRevertError (@V.M.when_ _ _ ?condition _) ⇒
    unfold V.M.when_, Monad.Make_Monad.when_; destruct condition; solve_no_revert
  | |- noRevertError (@V.M._return _ _ _ _) ⇒ apply no_revert_return
  | |- noRevertError (@V.M.fail _ _ _ _) ⇒ apply no_revert_fail; discriminate
  | |- noRevertError (@V.M.Option.or_fail _ _ _ _ _) ⇒ apply no_revert_option; discriminate
  | |- noRevertError (@V.M.HostAPI.lift _ _ _ _) ⇒ apply no_revert_lift
  | |- noRevertError (@V.M.Seq.mapM _ _ _ _ _ _) ⇒ apply no_revert_seq; intro; solve_no_revert
  | |- noRevertError (@V.pop _ _) ⇒ let state := fresh "state" in intro state; unfold V.pop; destruct (MS.t.stack state); discriminate
  | |- noRevertError (@V.pop2 _ _) ⇒ let state := fresh "state" in intro state; unfold V.pop2; destruct (MS.t.stack state) as [|a [|b tail]]; discriminate
  | |- noRevertError (@V.pop3 _ _) ⇒ let state := fresh "state" in intro state; unfold V.pop3; destruct (MS.t.stack state) as [|a [|b [|c tail]]]; discriminate
  | |- noRevertError (@V.push _ _ _) ⇒ let state := fresh "state" in intro state; unfold V.push; destruct (Z.geb (MS.t.stack_depth state) V.max_stack_depth); discriminate
  | |- noRevertError (@V.spend _ _ ?amount) ⇒ let state := fresh "state" in intro state; unfold V.spend; destruct (Gas.op_lt (MS.t.gas state) amount); discriminate
  | |- noRevertError (@V.increase_pc_and_continue _ _) ⇒ intro state; discriminate
  | |- noRevertError (@V.update_pc_and_continue _ _ _) ⇒ intro state; discriminate
  | |- noRevertError (@V.M.op_exclamation _ _ _ _) ⇒ intro state; discriminate
  | |- noRevertError (@V.M.op_coloneq _ _ _ _ _) ⇒ intro state; discriminate
  | |- noRevertError (@V.M.update_field _ _ _ _ _) ⇒ intro state; discriminate
  | |- noRevertError (@V.finish_execution _ _ _) ⇒ unfold V.finish_execution; solve_no_revert
  | |- noRevertError (if ?condition then _ else _) ⇒ destruct condition; solve_no_revert
  | |- noRevertError (match ?value with _ ⇒ _ end) ⇒ destruct value; cbn beta iota zeta; solve_no_revert
  | |- noRevertError (fun state ⇒ _) ⇒ intro state; discriminate
  | |- noRevertError (Monad.SIG_MONAD._return _ _) ⇒ intro state; discriminate
  | _ ⇒ no_revert_extra
  end.

Section VM.
Context {Host_t : Set} {F : @V.FArgs Host_t} {E : @V.Executor.FArgs Host_t F}.

Lemma recursive_no_revert opcode :
  recursiveCallOpcode opcode = true → noRevertError (dispatch opcode).
Proof.
  intro Hrecursive. destruct opcode; cbn [recursiveCallOpcode] in Hrecursive; try discriminate.
  all: unfold dispatch, V.Executor.execute_opcode.
  all: unfold V.Executor.call, V.Executor.callcode, V.Executor.staticcall,
    V.Executor.delegatecall, V.Executor.create, V.Executor.create2,
    V.Executor.call_opcode_impl, V.Executor.generic_call_impl,
    V.Executor.generic_create_impl, V.Executor.merge_child_gas_and_refund,
    V.Executor.extend_memory_to, V.M.HostAPI.call.
  all: unfold V.Executor.access_delegation, V.Executor.check_write_permissions, V.Executor.self,
    V.M.HostAPI.access_account, V.M.HostAPI.get_balance, V.M.HostAPI.account_exists,
    V.M.HostAPI.copy_code, V.M.HostAPI.Base.
  all: cbn beta iota zeta; cbn [negb].
  all: solve_no_revert.
Qed.

Definition noFalse (action : @V.M.t Host_t F bool) : Prop :=
  ∀ state, fst (action state) ≠ inl false.
Lemma no_false_bind {A : Set} (action : @V.M.t Host_t F A) next :
  (∀ value, noFalse (next value)) → noFalse (V.M.op_letdollar action next).
Proof.
  intros Hnext state. change (fst (match action state with
    | (inl value, middle) ⇒ next value middle
    | (inr error, middle) ⇒ (inr error, middle) end) ≠ inl false).
  destruct (action state) as [[value|error] middle]; [apply Hnext|discriminate].
Qed.
Ltac solve_no_false :=
  lazymatch goal with
  | |- noFalse (@V.M.op_letdollar _ _ _ _ _ _) ⇒
    apply no_false_bind; intro;
    repeat match goal with x : _ × _ |- _ ⇒ destruct x end;
    cbn beta iota zeta; solve_no_false
  | |- noFalse (@V.increase_pc_and_continue _ _) ⇒ intro; discriminate
  | |- noFalse (match ?value with _ ⇒ _ end) ⇒ destruct value; solve_no_false
  end.

Lemma recursive_no_false opcode :
  recursiveCallOpcode opcode = true → noFalse (dispatch opcode).
Proof.
  intro Hrecursive. destruct opcode; cbn [recursiveCallOpcode] in Hrecursive; try discriminate.
  all: unfold dispatch, V.Executor.execute_opcode.
  all: unfold V.Executor.call, V.Executor.callcode, V.Executor.staticcall,
    V.Executor.delegatecall, V.Executor.create, V.Executor.create2,
    V.Executor.call_opcode_impl.
  all: solve_no_false.
Qed.
End VM.

Section GasReturns.
Context {F : @V.FArgs S.t} {E : @V.Executor.FArgs S.t F}.
Context (cold warm access write reserve : N).
Context (Hrevision : V.Params.(Vm.Make_Params_signature.revision) =
  Support.Variants.Revision.Setcode (cold, warm, access, write, reserve)).
Context (Hdebug : V.Params.(Vm.Make_Params_signature.debug_tstore) = false).
Context (Hprogress : @setcodeGasProgress S.t F).

Lemma nonrecursive_gas_bound opcode :
  recursiveCallOpcode opcode = false → gasBound (dispatch opcode).
Proof.
  intro Hrecursive. destruct (machineOnlyOpcode opcode) eqn:Hmachine.
  - apply machine_gas_bound; [| |exact Hdebug|exact Hmachine].
    + unfold dispatch, V.Executor.execute_opcode, V.Executor.clz.
      rewrite Hrevision. solve_gas_bound.
    + intros extra Hextra. destruct extra; cbn in Hextra; try contradiction.
      × unfold dispatch, V.Executor.execute_opcode.
        eapply setcode_opcode_gas_bound; eassumption.
      × unfold dispatch, V.Executor.execute_opcode, V.Executor.undefined. apply gas_fail.
  - apply primitive_gas_bound; [exact Hdebug|].
    destruct opcode; cbn [machineOnlyOpcode recursiveCallOpcode primitiveHostOpcode] in *; congruence.
Qed.

Theorem terminal_gas_bound opcode state after outcome :
  dispatch opcode state = (outcome, after) →
  (outcome = inl false ∨ outcome = inr Evmc.Result.StatusCode.Revert) →
  (MS.t.gas after ≤ MS.t.gas state)%N.
Proof.
  intros Hstep Hterminal. destruct (recursiveCallOpcode opcode) eqn:Hrecursive.
  - destruct Hterminal as [-> | ->].
    + pose proof (recursive_no_false opcode Hrecursive state) as Hbad.
      rewrite Hstep in Hbad. contradiction Hbad. reflexivity.
    + pose proof (recursive_no_revert opcode Hrecursive state) as Hbad.
      rewrite Hstep in Hbad. contradiction Hbad. reflexivity.
  - pose proof (nonrecursive_gas_bound opcode Hrecursive state) as Hgas.
    rewrite Hstep in Hgas. exact Hgas.
Qed.

Theorem run_returned_gas_bound state :
  Z.of_N (MS.t.gas state) < 2^63 →
  (fst (@generated_run S.t F E state) = inl tt ∨
   fst (@generated_run S.t F E state) = inr Evmc.Result.StatusCode.Revert) →
  (MS.t.gas (snd (@generated_run S.t F E state)) ≤ MS.t.gas state)%N.
Proof.
  remember (MS.t.gas state) as budget eqn:Hbudget.
  revert state Hbudget.
  induction budget as [budget IH] using (well_founded_induction N.lt_wf_0).
  intros state Hbudget Hbound Hreturns.
  rewrite Hbudget in Hbound |- ×.
  rewrite generated_run_step_eq in Hreturns |- ×. unfold generated_run_step in Hreturns |- ×.
  destruct (dispatch (run_selected_opcode state) state) as [[continue|error] next] eqn:Hstep.
  - destruct continue.
    + pose proof (setcode_dispatch_progress cold warm access write reserve _ Hrevision Hprogress
        (selected_opcode_well_formed state) state next Hbound Hstep) as Hdecreases.
      assert (Hguard : Gas.op_lt (MS.t.gas next) (MS.t.gas state) = true)
        by (apply N.ltb_lt; exact Hdecreases).
      rewrite Hguard in Hreturns |- ×.
      pose proof (IH (MS.t.gas next) ltac:(lia) next eq_refl ltac:(lia) Hreturns) as Hnext.
      lia.
    + eapply terminal_gas_bound; [exact Hstep|left; reflexivity].
  - cbn [fst] in Hreturns. destruct Hreturns as [Hbad|Hrevert]; [discriminate|].
    injection Hrevert as →. eapply terminal_gas_bound; [exact Hstep|right; reflexivity].
Qed.
End GasReturns.

Print Assumptions recursive_no_revert.
Print Assumptions recursive_no_false.
Print Assumptions run_returned_gas_bound.