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 "!".

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_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.

Lemma reserve_check_read_only revision s : snd (dip revision s) = s.
Proof. 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 →
  accountReserveViolated s addr original (accountAt s addr) = false.
Proof.
  intro Hcheck.
  unfold Reserve_balance.dipped_into_reserve in Hcheck.
  cbn -[Seq._exists Seq.filter_map Seq.filter Seq.of_list] in Hcheck.
  try rewrite Bool.andb_true_r in Hcheck.
  change (Seq._exists
    (fun '(a, old, post) ⇒ accountReserveViolated s a old post)
    (Seq.filter_map
      (fun '(a, old) ⇒ if @A.is_smart_contract (accountAt s a)
        then None else Some (a, old, accountAt s a))
      (Seq.filter (fun '(a, _) ⇒ negb
        (Addr._Set.(RocqOfOCaml.OCamlSet.S.mem) a (S.t.self_destruct s)))
        (Seq.of_list (W.t.accounts (S.t.initial_world_state s))))) = false) in Hcheck.
  intros Hin Hdes Hsc.
  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. reflexivity.
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 (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 Hsender.
  pose proof (checked_account s addr original Hcheck Hin Hdes Hsc) 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 →
  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 Hempty Hrange.
  pose proof (checked_account s (S.t.tx_origin s) original Hcheck Hin Hdes Hsc) 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.