Library QedkConcrete.reservecheck

Per-account guarantees of the generated reserve check

The concrete predicate enumerates the original accounts, rather than trusting a VM-supplied list of changed accounts. Its success therefore protects every original account except the explicit contract, destruction, and sender-emptying exemptions.
From Stdlib Require Import ZArith NArith List Bool Lia.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import MonadVM.Reserve_balance QedkConcrete.wordrange.
Set Default Goal Selector "!".
Import ListNotations.

Module S := MonadVM.State.TransactionState.
Module W := MonadVM.State.WorldState.
Module A := MonadVM.Chain.Ethereum.Account.
Module Addr := MonadVM.Chain.Ethereum.Address.
Module U := MonadVM.Numeric.U256.
Module Uint := MonadVM.Support.UintN.
Module Seq := RocqOfOCaml.OCamlSeq.

Lemma seq_exists_pointwise {X : Set} (f g : X → bool) (xs : Seq.t X) :
  (∀ x, f x = g x) → Seq._exists f xs = Seq._exists g xs.
Proof.
  intro Hfg. induction xs; cbn; [reflexivity|]. rewrite Hfg, IHxs. reflexivity.
Qed.

Lemma seq_checked_member {X Y : Set} (xs : list X)
    (keep : X → bool) (project : X → option Y) (bad : Y → bool) (x : X) (y : Y) :
  Seq._exists bad (Seq.filter_map project (Seq.filter keep (Seq.of_list xs))) = false →
  List.In x xs → keep x = true → project x = Some y → bad y = false.
Proof.
  induction xs as [|head tail IH]; cbn; [contradiction|].
  destruct (keep head) eqn:Hkeep; cbn.
  - destruct (project head) as [value|] eqn:Hproject; cbn.
    + rewrite Bool.orb_false_iff. intros [Hhead Htail] [Heq|Hin] Hkx Hpx.
      × subst head. rewrite Hpx in Hproject. inversion Hproject; subst. exact Hhead.
      × exact (IH Htail Hin Hkx Hpx).
    + intros Htail [Heq|Hin] Hkx Hpx.
      × subst head. congruence.
      × exact (IH Htail Hin Hkx Hpx).
  - intros Htail [Heq|Hin] Hkx Hpx.
    + subst head. congruence.
    + exact (IH Htail Hin Hkx Hpx).
Qed.

Lemma u256_lt x y : U.op_lt x y = Z.ltb (U.to_z x) (U.to_z y).
Proof.
  change (Z.ltb (match Z.compare x y with Eq ⇒ 0 | Lt ⇒ -1 | Gt ⇒ 1 end) 0 = Z.ltb x y).
  unfold Z.ltb at 2. destruct (Z.compare x y); reflexivity.
Qed.

Lemma u256_to_uint x :
  (0 ≤ U.to_z x)%Z → @U.to_uint x = Z.to_N (U.to_z x).
Proof.
  intro Hx. change (@Uint.of_z_exn x = Z.to_N x).
  unfold Uint.of_z_exn, Uint.of_z_opt, Uint.in_range.
  assert (Hz : Z.leb 0 x = true) by (apply Z.leb_le; exact Hx).
  rewrite Hz. reflexivity.
Qed.

Lemma u256_of_uint n :
  (Z.of_N n < 2^256)%Z → U.to_z (@U.of_uint_exn n) = Z.of_N n.
Proof.
  intro Hn. change (U.of_z_exn (Z.of_N n) = Z.of_N n).
  apply word_of_z. split; [apply N2Z.is_nonneg | exact Hn].
Qed.

Lemma u256_sub x y :
  (0 ≤ U.to_z x - U.to_z y < 2^256)%Z →
  U.to_z (@U.op_minus x y) = (U.to_z x - U.to_z y)%Z.
Proof.
  intro Hrange.
  change (Z.land (Z.shiftl (x-y) 0) (Z.ones 256) = (x-y)%Z).
  rewrite Z.shiftl_0_r, Z.land_ones by lia.
  apply Z.mod_small. exact Hrange.
Qed.

Lemma address_eq_refl a : Addr.op_eq a a = true.
Proof.
  change (Z.eqb (OCamlString.compare a a) 0 = true).
  rewrite OCamlString.compare_matches_structural.
  unfold OCamlString.compare_structural. rewrite String.eqb_refl. reflexivity.
Qed.

Lemma address_compare_eq a b : OCamlString.compare a b = 0%Z → a = b.
Proof.
  rewrite OCamlString.compare_matches_structural. unfold OCamlString.compare_structural. destruct (String.eqb a b) eqn:Heq.
  - intros _. apply String.eqb_eq. exact Heq.
  - destruct (Basics.String.ltb a b); discriminate.
Qed.

Lemma address_find_member (m : Addr.Map.t A.t) addr original :
  Addr.Map.find_opt addr m = Some original → List.In (addr, original) m.
Proof.
  induction m as [|[key value] tail IH]; [discriminate|].
  change ((if Z.ltb (OCamlString.compare addr key) 0 then None
    else if Z.eqb (OCamlString.compare addr key) 0 then Some value
    else Addr.Map.find_opt addr tail) = Some original → List.In (addr, original) ((key, value) :: tail)).
  destruct (Z.ltb (OCamlString.compare addr key) 0); [discriminate|].
  destruct (Z.eqb (OCamlString.compare addr key) 0) eqn:Hkey.
  - change (Z.eqb (OCamlString.compare addr key) 0 = true) in Hkey.
    apply Z.eqb_eq in Hkey. apply address_compare_eq in Hkey. subst key.
    intro Hvalue. inversion Hvalue; subst. left. reflexivity.
  - intro Hfind. right. apply IH. exact Hfind.
Qed.

Lemma u256_min x y : U.to_z (U.min x y) = Z.min (U.to_z x) (U.to_z y).
Proof.
  change ((if U.op_lt x y then U.to_z x else U.to_z y) =
    Z.min (U.to_z x) (U.to_z y)).
  rewrite u256_lt. destruct (Z.ltb (U.to_z x) (U.to_z y)) eqn:Hlt.
  - apply Z.ltb_lt in Hlt. rewrite Z.min_l by lia. reflexivity.
  - apply Z.ltb_ge in Hlt. rewrite Z.min_r by lia. reflexivity.
Qed.

Section Check.
Context `{_rocq_assumption_0 : RocqOfOCaml.Basics.Unreachable Z.t}
  `{_rocq_assumption_1 :
    RocqOfOCaml.Basics.Unreachable
      (RocqOfOCaml.OCamlSeq.t
        (MonadVM.Chain.Ethereum.Address.Map.key ×
          MonadVM.Chain.Ethereum.Account.t))}
  `{_rocq_assumption_2 :
    RocqOfOCaml.Basics.Unreachable (RocqOfOCaml.OCamlIarray.t int)}
  `{_rocq_assumption_3 : RocqOfOCaml.Basics.Unreachable MonadVM.Support.UintN.t}
  `{_rocq_assumption_4 : RocqOfOCaml.Basics.Unreachable MonadVM.Numeric.U64.t}
  `{_rocq_assumption_5 :
    RocqOfOCaml.Basics.Unreachable MonadVM.Numeric.U256.Repr.t}
  `{_rocq_assumption_6 : RocqOfOCaml.Basics.Unreachable MonadVM.Numeric.U256.t}
  `{_rocq_assumption_7 :
    RocqOfOCaml.Basics.Unreachable MonadVM.Chain.Ethereum.Address.t}
  `{_rocq_assumption_8 :
    RocqOfOCaml.Basics.Unreachable MonadVM.Byte_string.Bytes.t}
  `{_rocq_assumption_9 : RocqOfOCaml.Basics.Unreachable unit}
  `{_rocq_assumption_10 : RocqOfOCaml.Basics.Unreachable string}
  `{_rocq_assumption_11 : RocqOfOCaml.Basics.Unreachable int}
  `{_rocq_assumption_12 : RocqOfOCaml.Basics.Unreachable ascii}
  `{_rocq_assumption_13 : RocqOfOCaml.Basics.Unreachable (int × int)}
  `{_rocq_assumption_14 :
    RocqOfOCaml.Basics.Unreachable
      MonadVM.Byte_string.B32.(MonadVM.Byte_string.Fixed.Fixed_result.t)} .

Local Abbreviation dip := (@Reserve_balance.dipped_into_reserve).
Local Abbreviation threshold := (@Reserve_balance.user_reserve_balance).
Local Abbreviation emptying := (@Reserve_balance.is_emptying_tx).
Local Definition accountAt s addr : A.t :=
  match Addr.Map.find_opt addr (W.t.accounts (S.t.world_state s)) with
  | Some a ⇒ a
  | None ⇒ @A.empty end.
Local Definition protected s addr original : U.t := U.min
  (threshold (S.t.initial_world_state s)
    (Chain.Ethereum.Block.Header.t.number
      (Chain.Ethereum.Block.t.header (S.t.current_block s))) addr)
  (A.t.balance original).

Lemma accountAt_lens s addr :
  accountAt s addr = State.op_pointcaretlparenrparen s
    (@S.account None addr).
Proof. reflexivity. Qed.

Definition accountReserveViolated s addr original (post : A.t) : bool :=
  let reserve := protected s addr original in
  let current := A.t.balance post in
  if Addr.op_eq addr (S.t.tx_origin s) then
    if fst (emptying s) then false else
    let fee := @Uint.op_star
      (S.t.tx_gas_limit s) (S.t.tx_gas_price s) in
    orb (Uint.op_gt fee (@U.to_uint reserve))
      (U.op_lt current (@U.op_minus reserve
        (@U.of_uint_exn fee)))
  else U.op_lt current reserve.

The generated check keeps the historical threshold calculation, but an excessive sender fee now rejects even when that threshold is zero.
Lemma reserve_violation_form reserve current fee sender empty :
  andb (orb (negb sender) (negb empty))
    (orb (andb sender (Uint.op_gt fee (U.to_uint reserve)))
      (U.op_lt current (if sender then
        if Uint.op_gteq (U.to_uint reserve) fee
        then U.op_minus reserve (U.of_uint_exn fee) else U.zero
        else reserve))) =
  if sender then if empty then false else
    orb (Uint.op_gt fee (U.to_uint reserve))
      (U.op_lt current (U.op_minus reserve (U.of_uint_exn fee)))
  else U.op_lt current reserve.
Proof.
  destruct sender, empty; cbn beta iota delta [andb orb negb]; try reflexivity.
  unfold Uint.op_gt, Uint.op_gteq.
  destruct (N.ltb (U.to_uint reserve) fee) eqn:Hfee;
    cbn beta iota delta [orb]; [reflexivity|].
  apply N.ltb_ge in Hfee. rewrite (proj2 (N.leb_le _ _) Hfee). reflexivity.
Qed.

Eight/Nine use the fixed reserve; Eleven reads account configuration. These are the three executable revisions of the OCaml model.
Definition protectedAtRevision revision s addr original : U.t := U.min
  (match revision with
   | Support.Variants.Revision.Eleven ⇒
       threshold (S.t.initial_world_state s)
         (Chain.Ethereum.Block.Header.t.number
           (Chain.Ethereum.Block.t.header (S.t.current_block s))) addr
   | _ ⇒ Reserve_balance.default_reserve_balance
   end) (A.t.balance original).

Definition accountViolationAtRevision revision s addr original (post : A.t) : bool :=
  let reserve := protectedAtRevision revision s addr original in
  if Addr.op_eq addr (S.t.tx_origin s) then
    if fst (emptying s) then false else
    orb (Uint.op_gt (S.t.tx_gas_limit s × S.t.tx_gas_price s)%N (U.to_uint reserve))
      (U.op_lt (A.t.balance post) (U.op_minus reserve
        (U.of_uint_exn (S.t.tx_gas_limit s × S.t.tx_gas_price s)%N)))
  else U.op_lt (A.t.balance post) reserve.

Lemma reserve_check_read_only revision s : snd (dip revision s) = s.
Proof. reflexivity. Qed.

Lemma checked_account_at_revision revision s addr original :
  List.In revision [Support.Variants.Revision.Eight;
    Support.Variants.Revision.Nine; Support.Variants.Revision.Eleven] →
  fst (dip revision s) = false →
  List.In (addr, original) (W.t.accounts (S.t.initial_world_state s)) →
  Addr._Set.(RocqOfOCaml.OCamlSet.S.mem) addr (S.t.self_destruct s) = false →
  @A.is_smart_contract (accountAt s addr) = false →
  Addr.op_eq addr MonadVM.Staking.staking_address = false →
  accountViolationAtRevision revision s addr original (accountAt s addr) = false.
Proof.
  intros Hrevision Hcheck.
  let original := constr:(W.t.accounts (S.t.initial_world_state s)) in
  change (Seq._exists
    (fun '(a, old, post) ⇒
      let reserve := protectedAtRevision revision s a old in
      andb (orb (negb (Addr.op_eq a (S.t.tx_origin s))) (negb (fst (emptying s))))
        (orb (andb (Addr.op_eq a (S.t.tx_origin s))
          (Uint.op_gt (S.t.tx_gas_limit s × S.t.tx_gas_price s)%N (U.to_uint reserve)))
          (U.op_lt (A.t.balance post)
            (if Addr.op_eq a (S.t.tx_origin s) then
               if Uint.op_gteq (U.to_uint reserve) (S.t.tx_gas_limit s × S.t.tx_gas_price s)%N
               then U.op_minus reserve (U.of_uint_exn (S.t.tx_gas_limit s × S.t.tx_gas_price s)%N)
               else U.zero
             else reserve))))
    (Seq.filter_map
      (fun '(a, old) ⇒ if orb (A.is_smart_contract (accountAt s a))
        (Addr.op_eq a MonadVM.Staking.staking_address)
        then None else Some (a, old, accountAt s a))
      (match revision with
       | Support.Variants.Revision.Eight ⇒ Seq.of_list original
       | Support.Variants.Revision.Nine | Support.Variants.Revision.Eleven ⇒
           Seq.filter (fun '(a, _) ⇒ negb
             (Addr._Set.(RocqOfOCaml.OCamlSet.S.mem) a (S.t.self_destruct s)))
             (Seq.of_list original)
       | _ ⇒ Reserve_balance._rocq_fallback_dipped_into_reserve_0
       end)) = false) in Hcheck.
  erewrite (seq_exists_pointwise _
    (fun '(a, old, post) ⇒ accountViolationAtRevision revision s a old post) _) in Hcheck.
  2: { intros [[a old] post]. apply reserve_violation_form. }
  intros Hin Hdes Hsc Hstaking.
  cbn in Hrevision. destruct Hrevision as [<-|[<-|[<-|[]]]].
  - cbn beta iota in Hcheck.
    assert (Hfilter : ∀ (xs : list (Addr.t × A.t)),
      Seq.filter (fun _ ⇒ true) (Seq.of_list xs) = Seq.of_list xs).
    { induction xs; cbn; congruence. }
    rewrite <- Hfilter in Hcheck.
    refine (seq_checked_member _ _ _ _ (addr, original)
      (addr, original, accountAt s addr) Hcheck Hin eq_refl _).
    cbn beta iota zeta. rewrite Hsc, Hstaking. reflexivity.
  - cbn beta iota in Hcheck.
    refine (seq_checked_member _ _ _ _ (addr, original)
      (addr, original, accountAt s addr) Hcheck Hin _ _).
    + cbn beta iota zeta. rewrite Hdes. reflexivity.
    + cbn beta iota zeta. rewrite Hsc, Hstaking. reflexivity.
  - cbn beta iota in Hcheck.
    refine (seq_checked_member _ _ _ _ (addr, original)
      (addr, original, accountAt s addr) Hcheck Hin _ _).
    + cbn beta iota zeta. rewrite Hdes. reflexivity.
    + cbn beta iota zeta. rewrite Hsc, Hstaking. reflexivity.
Qed.

Lemma checked_account s addr original :
  fst (dip Support.Variants.Revision.Eleven s) = false →
  List.In (addr, original) (W.t.accounts (S.t.initial_world_state s)) →
  Addr._Set.(RocqOfOCaml.OCamlSet.S.mem) addr (S.t.self_destruct s) = false →
  A.is_smart_contract (accountAt s addr) = false →
  Addr.op_eq addr MonadVM.Staking.staking_address = false →
  accountReserveViolated s addr original (accountAt s addr) = false.
Proof.
  apply (checked_account_at_revision Support.Variants.Revision.Eleven).
  cbn; auto.
Qed.

All executable revisions reject a checked non-emptying sender's excessive gas charge. This is a property of the generated execution check, not a premise that consensus already excluded such a transaction.
Theorem excessive_sender_fee_rejected revision s original :
  List.In revision [Support.Variants.Revision.Eight;
    Support.Variants.Revision.Nine; Support.Variants.Revision.Eleven] →
  List.In (S.t.tx_origin s, original) (W.t.accounts (S.t.initial_world_state s)) →
  Addr._Set.(RocqOfOCaml.OCamlSet.S.mem) (S.t.tx_origin s) (S.t.self_destruct s) = false →
  A.is_smart_contract (accountAt s (S.t.tx_origin s)) = false →
  Addr.op_eq (S.t.tx_origin s) MonadVM.Staking.staking_address = false →
  fst (emptying s) = false →
  (U.to_uint (protectedAtRevision revision s (S.t.tx_origin s) original) <
    S.t.tx_gas_limit s × S.t.tx_gas_price s)%N →
  fst (dip revision s) = true.
Proof.
  intros Hrevision Hin Hdes Hsc Hstaking Hempty Hfee.
  destruct (fst (dip revision s)) eqn:Hcheck; [reflexivity|].
  pose proof (checked_account_at_revision revision s _ original
    Hrevision Hcheck Hin Hdes Hsc Hstaking) as Hbad.
  unfold accountViolationAtRevision in Hbad.
  rewrite address_eq_refl, Hempty in Hbad. cbn zeta in Hbad.
  unfold Uint.op_gt in Hbad. rewrite (proj2 (N.ltb_lt _ _) Hfee) in Hbad.
  discriminate.
Qed.

A non-sender that is neither a remaining contract nor a same-transaction destruction must retain its entire protected amount.
Lemma nonsender_reserve_bound s addr original :
  fst (dip Support.Variants.Revision.Eleven s) = false →
  List.In (addr, original) (W.t.accounts (S.t.initial_world_state s)) →
  Addr._Set.(RocqOfOCaml.OCamlSet.S.mem) addr (S.t.self_destruct s) = false →
  @A.is_smart_contract (accountAt s addr) = false →
  Addr.op_eq addr MonadVM.Staking.staking_address = false →
  Addr.op_eq addr (S.t.tx_origin s) = false →
  (U.to_z (protected s addr original) ≤
    U.to_z (A.t.balance (accountAt s addr)))%Z.
Proof.
  intros Hcheck Hin Hdes Hsc Hstaking Hsender.
  pose proof (checked_account s addr original Hcheck Hin Hdes Hsc Hstaking) as Hbound.
  unfold accountReserveViolated in Hbound. rewrite Hsender in Hbound.
  rewrite u256_lt in Hbound.
  apply Z.ltb_ge in Hbound. exact Hbound.
Qed.

The sender guard checks the fee before subtracting it. Under the U256 representation invariant this rules out both a reserve shortfall and unsigned subtraction wrapping.
Lemma sender_reserve_bound s original :
  let addr := S.t.tx_origin s in
  let reserve := protected s addr original in
  let fee := (S.t.tx_gas_limit s × S.t.tx_gas_price s)%N in
  fst (dip Support.Variants.Revision.Eleven s) = false →
  List.In (addr, original) (W.t.accounts (S.t.initial_world_state s)) →
  Addr._Set.(RocqOfOCaml.OCamlSet.S.mem) addr (S.t.self_destruct s) = false →
  @A.is_smart_contract (accountAt s addr) = false →
  Addr.op_eq addr MonadVM.Staking.staking_address = false →
  fst (emptying s) = false →
  (0 ≤ U.to_z reserve < 2^256)%Z →
  (Z.of_N fee ≤ U.to_z reserve ∧
    U.to_z reserve - Z.of_N fee ≤ U.to_z (A.t.balance (accountAt s addr)))%Z.
Proof.
  cbn zeta. intros Hcheck Hin Hdes Hsc Hstaking Hempty Hrange.
  pose proof (checked_account s (S.t.tx_origin s) original Hcheck Hin Hdes Hsc Hstaking) as Hbound.
  unfold accountReserveViolated in Hbound.
  rewrite address_eq_refl, Hempty in Hbound.
  apply Bool.orb_false_iff in Hbound as [Hfee Hbal].
  unfold Uint.op_gt, Uint.op_star in Hfee, Hbal.
  rewrite u256_to_uint in Hfee by lia.
  apply N.ltb_ge in Hfee. apply N2Z.inj_le in Hfee.
  rewrite Z2N.id in Hfee by lia.
  assert (Hof : U.to_z (@U.of_uint_exn
    (S.t.tx_gas_limit s × S.t.tx_gas_price s)%N) =
    Z.of_N (S.t.tx_gas_limit s × S.t.tx_gas_price s)%N) by
    (apply u256_of_uint; lia).
  rewrite u256_lt in Hbal.
  rewrite u256_sub in Hbal by (rewrite Hof; pose proof
    (N2Z.is_nonneg (S.t.tx_gas_limit s × S.t.tx_gas_price s)%N); lia).
  rewrite Hof in Hbal. apply Z.ltb_ge in Hbal.
  split; assumption.
Qed.

End Check.

Print Assumptions nonsender_reserve_bound.
Print Assumptions sender_reserve_bound.
Print Assumptions excessive_sender_fee_rejected.