Library SetcodeConcrete.vmnoncecallops

CALL instructions charge the gas they forward

Account access and delegation lookup preserve the queried nonce. The quoted charge pays for the child's gas, including a possible value stipend. A failed balance/depth check refunds only that allocated gas. These lemmas connect the generated CALL code to the child induction bound; they do not assume a bound on a complete VM execution.
From Stdlib Require Import NArith ZArith Lia.
Require Import RocqOfOCaml.RocqOfOCaml MonadVM.Vm.
Require Import QedkConcrete.hostnonce QedkConcrete.vmhostframe
  SetcodeConcrete.checkednonce SetcodeConcrete.noncecreate SetcodeConcrete.nonceeffects
  SetcodeConcrete.noncebudget SetcodeConcrete.noncegas
  SetcodeConcrete.vmnoncecalls SetcodeConcrete.vmnonceops.
Require Import MonadExecutionSpecs.Termination.VmCallGas
  MonadExecutionSpecs.Termination.VmChildGasMerge
  MonadExecutionSpecs.Termination.VmCallHandlerProgress.
Set Default Goal Selector "!".
Local Open Scope Z_scope.

Section VM.
Context {F : @V.FArgs S.t} {E : @V.Executor.FArgs S.t F}.
Context (query : Addr.t).
Local Abbreviation measure := (fun host ⇒ nonceAt (S.t.world_state host) query).
Local Abbreviation total := (@nonceAndGas S.t F measure).

Definition unchangedNonce {A : Set} (action : @V.M.t S.t F A) : Prop :=
  ∀ state, nonceState query (MS.t.host state) →
  nonceState query (MS.t.host (snd (action state))) ∧
  measure (MS.t.host (snd (action state))) = measure (MS.t.host state) ∧
  MS.t.gas (snd (action state)) = MS.t.gas state.

Lemma nonce_frame_resources {A : Set} (action : @V.M.t S.t F A) :
  unchangedResources action → unchangedNonce action.
Proof.
  intros Hframe state Hinitial. destruct (Hframe state) as [Hhost Hgas].
  rewrite Hhost, Hgas. split; [exact Hinitial|]. split; reflexivity.
Qed.

Lemma nonce_frame_bind {A B : Set} (action : @V.M.t S.t F A) next :
  unchangedNonce action → (∀ value, unchangedNonce (next value)) →
  unchangedNonce (@V.M.op_letdollar S.t F A B action next).
Proof.
  intros Hfirst Hnext state Hinitial. specialize (Hfirst state Hinitial).
  change (let after := snd (match action state with
    | (inl value, middle) ⇒ next value middle
    | (inr error, middle) ⇒ (inr error, middle) end) in
    nonceState query (MS.t.host after) ∧ measure (MS.t.host after) = measure (MS.t.host state) ∧
    MS.t.gas after = MS.t.gas state).
  destruct (action state) as [[value|error] middle]; cbn [snd] in *; [|exact Hfirst].
  destruct Hfirst as [Hmiddle [Hnonce Hgas]].
  destruct (Hnext value middle Hmiddle) as [Hafter [Hnonce' Hgas']].
  split; [exact Hafter|]. split; congruence.
Qed.

Lemma nonce_frame_fmap {A B : Set} (f : A → B) action :
  unchangedNonce action → unchangedNonce (@V.M.op_ltdollargt S.t F A B f action).
Proof.
  intro H. change (unchangedNonce (@V.M.op_letdollar S.t F A B action
    (fun value ⇒ V.M._return (f value)))).
  apply nonce_frame_bind; [exact H|]. intro value.
  apply nonce_frame_resources. intro state. split; reflexivity.
Qed.

Lemma nonce_frame_lift {A : Set} (action : S.t → A × S.t) :
  (∀ nonce, preservesCallback (nonceInvariant query nonce) action) →
  unchangedNonce (V.M.HostAPI.lift action).
Proof.
  intros Hcallback state [Hmap Hnonnegative].
  pose proof (Hcallback (measure (MS.t.host state)) (MS.t.host state)
    (conj Hmap eq_refl)) as Hafter.
  unfold V.M.HostAPI.lift.
  destruct (action (MS.t.host state)) as [value host].
  destruct Hafter as [Hwf Hnonce].
  split.
  - split; [exact Hwf|].
    change (0 ≤ nonceAt (S.t.world_state host) query).
    change (nonceAt (S.t.world_state host) query =
      nonceAt (S.t.world_state (MS.t.host state)) query) in Hnonce.
    rewrite Hnonce. exact Hnonnegative.
  - split; [exact Hnonce|reflexivity].
Qed.

Lemma bounded_nonce_prefix {A B : Set} (action : @V.M.t S.t F A) (next : A → @V.M.t S.t F B) allowance :
  0 ≤ allowance → unchangedNonce action →
  (∀ value, boundedNonce query allowance (next value)) →
  boundedNonce query allowance (@V.M.op_letdollar S.t F A B action next).
Proof.
  intros Hallowance Hframe Hnext state Hgas Hinitial.
  destruct (Hframe state Hinitial) as [Hstate [Hnonce Hremaining]].
  change (let after := snd (match action state with
    | (inl value, middle) ⇒ next value middle
    | (inr error, middle) ⇒ (inr error, middle) end) in
    nonceState query (MS.t.host after) ∧ total after ≤ total state + allowance).
  destruct (action state) as [[value|error] middle]; cbn [snd] in ×.
  - specialize (Hnext value middle ltac:(rewrite Hremaining; exact Hgas) Hstate).
    destruct Hnext as [Hafter Hbound]. split; [exact Hafter|].
    unfold nonceAndGas in ×. rewrite Hremaining in Hbound.
    change (measure (MS.t.host middle) = measure (MS.t.host state)) in Hnonce.
    rewrite Hnonce in Hbound. exact Hbound.
  - split; [exact Hstate|]. unfold nonceAndGas. rewrite Hremaining, Hnonce. lia.
Qed.

Hypothesis primitives : ∀ nonce, PrimitiveHostFrame V.Host (nonceInvariant query nonce).

Lemma bounded_nonce_map_prefix {A B C : Set} (f : A → B)
    (action : @V.M.t S.t F A) (next : B → @V.M.t S.t F C) allowance :
  0 ≤ allowance → unchangedNonce action →
  (∀ value, boundedNonce query allowance (next (f value))) →
  boundedNonce query allowance (V.M.op_letdollar (V.M.op_ltdollargt f action) next).
Proof.
  intros Ha Hframe Hnext state Hgas Hinitial.
  pose proof (bounded_nonce_prefix action (fun value ⇒ next (f value)) allowance
    Ha Hframe Hnext state Hgas Hinitial) as Hbound.
  assert (Heq : V.M.op_letdollar (V.M.op_ltdollargt f action) next state =
    V.M.op_letdollar action (fun value ⇒ next (f value)) state).
  { unfold V.M.op_letdollar, V.M.op_ltdollargt,
      Monad.Make_Monad.op_letdollar, Monad.Make_Monad.op_ltdollargt.
    cbn. destruct (action state) as [[value|error] middle]; reflexivity. }
  rewrite Heq. exact Hbound.
Qed.

Lemma read_gas_bind {A : Set} (next : N → @V.M.t S.t F A) state :
  V.M.op_letdollar (V.M.op_exclamation MS.gas) next state = next (MS.t.gas state) state.
Proof. reflexivity. Qed.

Lemma access_account_nonce_frame addr : unchangedNonce (V.M.HostAPI.access_account addr).
Proof.
  unfold V.M.HostAPI.access_account, V.M.HostAPI.Base.
  apply nonce_frame_lift. intro nonce. exact (frame_access_account _ _ (primitives nonce) addr).
Qed.
Lemma get_balance_nonce_frame addr : unchangedNonce (V.M.HostAPI.get_balance addr).
Proof.
  unfold V.M.HostAPI.get_balance, V.M.HostAPI.Base.
  apply nonce_frame_lift. intro nonce. exact (frame_get_balance _ _ (primitives nonce) addr).
Qed.
Lemma account_exists_nonce_frame addr : unchangedNonce (V.M.HostAPI.account_exists addr).
Proof.
  unfold V.M.HostAPI.account_exists, V.M.HostAPI.Base.
  apply nonce_frame_lift. intro nonce. exact (frame_account_exists _ _ (primitives nonce) addr).
Qed.
Lemma delegation_nonce_frame addr : unchangedNonce (V.Executor.access_delegation addr).
Proof.
  unfold V.Executor.access_delegation.
  apply nonce_frame_bind.
  - unfold V.M.HostAPI.copy_code, V.M.HostAPI.Base.
    apply nonce_frame_lift. intro nonce. apply (frame_copy_code _ _ (primitives nonce)).
  - intro code. destruct (Delegation.get_delegated_address code).
    + apply nonce_frame_bind; [apply nonce_frame_fmap, access_account_nonce_frame|].
      intro gas. apply nonce_frame_resources. intro state. split; reflexivity.
    + apply nonce_frame_resources. intro state. split; reflexivity.
Qed.

Lemma uncalled_nonce_refund forwarded :
  boundedNonce query (Z.of_N forwarded)
    (V.M.op_letdollar (V.push Numeric.U256.zero) (fun _ ⇒
      V.M.op_letdollar (V.M.update_field MS.gas (fun gas ⇒ (gas + forwarded)%N))
        (fun _ ⇒ V.M.op_coloneq MS.output_buffer Byte_string.Bytes.empty))).
Proof.
  apply bounded_prefix; [lia|intro initial; apply vmnoncecalls.push_nonce_frame|].
  intros [] state Hgas Hinitial. split; [exact Hinitial|].
  change (measure (MS.t.host state) + Z.of_N (MS.t.gas state + forwarded)%N ≤
    measure (MS.t.host state) + Z.of_N (MS.t.gas state) + Z.of_N forwarded).
  rewrite N2Z.inj_add. lia.
Qed.

Theorem call_opcode_nonce_bound kind requested value sender recipient codeAddr
    inputStart inputSize outputStart outputSize static :
  (∀ msg host, Evmc.Message.t.kind msg = kind →
    0 ≤ Evmc.Message.t.gas msg < 2^63 → nonceState query host →
    let '(result, after) := V.Host.(Evmc.HOST.call) msg host in
    checkedNonceResult query (Evmc.Message.t.gas msg) 0 host result after) →
  boundedNonce query 0 (V.Executor.call_opcode_impl kind requested value sender recipient codeAddr
    inputStart inputSize outputStart outputSize static).
Proof.
  intro Hcall. unfold V.Executor.call_opcode_impl.
  apply bounded_prefix; [lia|apply resources_memory|]. intro inputGas.
  apply bounded_prefix; [lia|apply resources_memory|]. intro outputGas.
  apply bounded_nonce_map_prefix; [lia|apply access_account_nonce_frame|]. intro accessStatus.
  apply bounded_nonce_prefix; [lia|apply delegation_nonce_frame|]. intro delegation.
  apply bounded_nonce_prefix; [lia|apply account_exists_nonce_frame|]. intro targetAlive.
  intros state Hgas Hinitial.
  rewrite read_gas_bind. cbn beta iota zeta.
  set (transfer := andb (Evmc.Message.CallKind.op_ltgt kind Evmc.Message.CallKind.DelegateCall)
    (Numeric.U256.op_ltgt value Numeric.U256.zero)) in ×.
  set (memoryGas := Gas.op_plus inputGas outputGas) in ×.
  match goal with |- context [Gas.call_gas_value transfer requested (MS.t.gas state) memoryGas ?cost] ⇒
    set (extra := cost) in ×
  end.
  assert (Hextra : (100 + (if transfer then Gas.call_value else 0) ≤ extra)%N).
  { unfold extra. pose proof (account_access_min accessStatus).
    destruct transfer, delegation, targetAlive;
      cbn [andb negb]; unfold Gas.op_plus, Gas.zero, UintN.op_plus, UintN.zero; lia. }
  match goal with |- context [V.spend ?amount] ⇒ set (charge := amount) in × end.
  match goal with |- context [V.M.op_letdollar (V.spend charge) ?next] ⇒ set (tail := next) in × end.
  change (let after := snd (match V.spend charge state with
    | (inl value, middle) ⇒ tail value middle
    | (inr error, middle) ⇒ (inr error, middle) end) in
    nonceState query (MS.t.host after) ∧ total after ≤ total state + 0).
  destruct (V.spend charge state) as [[[]|error] charged] eqn:Hspent.
  2: { unfold V.spend in Hspent. destruct (Gas.op_lt (MS.t.gas state) charge);
    inversion Hspent; subst charged. split; [exact Hinitial|cbn [snd]; lia]. }
  destruct (spend_success_exact _ _ _ Hspent) as [Hafford Hcharged].
  pose proof (spend_preserves_host _ _ _ Hspent) as Hhost.
  pose proof (call_quote_total_decreases transfer requested (MS.t.gas state) memoryGas extra
    Hextra Hafford) as HchildBound.
  set (forwarded := Gas.call_gas.callee_available_gas
    (Gas.call_gas_value transfer requested (MS.t.gas state) memoryGas extra)) in ×.
  assert (Hforwarded : Z.of_N forwarded < 2^63) by (cbn zeta in HchildBound; lia).
  assert (Hpaid : (forwarded ≤ charge)%N).
  { change (MS.t.gas state - charge + forwarded < MS.t.gas state)%N in HchildBound.
    lia. }
  assert (Htail : boundedNonce query (Z.of_N forwarded) (tail tt)).
  { unfold tail. cbn beta iota zeta.
    apply bounded_prefix; [lia| |].
    { unfold V.M.when_, Monad.Make_Monad.when_, V.Executor.check_write_permissions.
      repeat match goal with |- context [if ?test then _ else _] ⇒ destruct test end;
        intro initial; split; reflexivity. }
    intros []. apply bounded_nonce_prefix; [lia|apply get_balance_nonce_frame|]. intro balance.
    apply bounded_suffix; [|intros []; apply resources_pc].
    match goal with |- context [if ?test then _ else _] ⇒ destruct test end.
    - apply uncalled_nonce_refund.
    - intros before Hbound Hbefore. apply generic_call_nonce_bound; assumption. }
  destruct (Htail charged ltac:(rewrite Hcharged; pose proof (N.le_sub_l (MS.t.gas state) charge); lia)
    ltac:(rewrite Hhost; exact Hinitial)) as [Hstate Htotal].
  split; [exact Hstate|]. unfold nonceAndGas in ×.
  rewrite Hhost, Hcharged, N2Z.inj_sub in Htotal by exact Hafford.
  change (measure (MS.t.host (snd (tail tt charged))) + Z.of_N (MS.t.gas (snd (tail tt charged))) ≤
    measure (MS.t.host state) + (Z.of_N (MS.t.gas state) - Z.of_N charge) + Z.of_N forwarded) in Htotal.
  cbv beta in Htotal. lia.
Qed.

Theorem call_family_nonce_bound :
  (∀ msg host, Evmc.Message.CallKind.is_create (Evmc.Message.t.kind msg) = false →
    0 ≤ Evmc.Message.t.gas msg < 2^63 → nonceState query host →
    let '(result, after) := V.Host.(Evmc.HOST.call) msg host in
    checkedNonceResult query (Evmc.Message.t.gas msg) 0 host result after) →
  boundedNonce query 0 (@V.Executor.call S.t F E) ∧
  boundedNonce query 0 (@V.Executor.callcode S.t F E) ∧
  boundedNonce query 0 (@V.Executor.delegatecall S.t F E) ∧
  boundedNonce query 0 (@V.Executor.staticcall S.t F E).
Proof.
  intro Hcall.
  assert (Hpop2 : unchangedResources (@V.pop2 S.t F)).
  { intro state. unfold V.pop2. destruct (MS.t.stack state) as [|a [|b rest]];
    split; reflexivity. }
  split; [|split; [|split]].
  all: unfold V.Executor.call, V.Executor.callcode, V.Executor.delegatecall, V.Executor.staticcall.
  all: apply bounded_prefix; [lia|apply resources_fmap, resources_pop|]; intro requested.
  all: apply bounded_prefix; [lia|apply resources_fmap, resources_pop|]; intro target.
  all: apply bounded_prefix; [lia|apply resources_pop3|]; intros [[a b] c].
  all: apply bounded_prefix; [lia|first [exact Hpop2|apply resources_pop]|]; intro last.
  all: repeat match goal with x : _ × _ |- _ ⇒ destruct x end; cbn beta iota zeta.
  all: apply call_opcode_nonce_bound.
  all: intros msg host Hkind Hgas Hinitial; apply Hcall;
    [rewrite Hkind; reflexivity|exact Hgas|exact Hinitial].
Qed.
End VM.

Print Assumptions call_opcode_nonce_bound.
Print Assumptions call_family_nonce_bound.