Library QedkConcrete.hostbalance

Concrete Host balance conservation

A transfer credits only after debiting. This order makes the original supply bound sufficient even for a transfer to the sender itself. Empty account normalization may change the map but not its aggregate balance.
From Stdlib Require Import ZArith Bool Lia.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import MonadVM.Host QedkConcrete.worldaccounts QedkConcrete.supply.
Set Default Goal Selector "!".
Local Open Scope Z_scope.

Module H := MonadVM.Host.Make.
Module S := MonadVM.State.TransactionState.

Section HostBalances.
Context {F : H.FArgs}.
Context {U64 : Basics.Unreachable Numeric.U64.t}.
Context {U256 : Basics.Unreachable U.t}.
Local Abbreviation readAccount := (fun world addr ⇒
  State.op_pointcaretlparenrparen world (@W.account None addr)).
Local Abbreviation writeAccount := (fun world addr value ⇒
  State.op_pointcaretlparenrparenltminus world (@W.account (Some false) addr) value).

Local Lemma transfer_equation sender recipient amount s :
  @H.transfer_ether F sender recipient amount s =
  let before := S.t.world_state s in
  let senderAccount := readAccount before sender in
  if U.op_gteq (A.t.balance senderAccount) amount then
    let debited := writeAccount before sender
      (A.t.with_balance (@U.op_minus (A.t.balance senderAccount) amount) senderAccount) in
    let recipientAccount := readAccount debited recipient in
    let credited := writeAccount debited recipient
      (A.t.with_balance (@U.op_plus (A.t.balance recipientAccount) amount) recipientAccount) in
    (true, S.t.with_world_state credited s)
  else (false, s).
Proof.
  unfold H.transfer_ether.
  cbn -[U.op_gteq U.op_plus U.op_minus W.account].
  repeat match goal with |- context [if ?b then _ else _] ⇒ destruct b eqn:?Hguard end.
  all: try reflexivity.
  all: match type of Hguard with _ = ?b ⇒
    change (U.op_gteq (A.t.balance (readAccount (S.t.world_state s) sender)) amount = b) in Hguard end.
  all: cbn beta in Hguard; congruence.
Qed.

Local Lemma u256_gteq x y : U.op_gteq x y = true → U.to_z y ≤ U.to_z x.
Proof.
  change ((Z.geb (match Z.compare (U.to_z x) (U.to_z y) with
    | Eq ⇒ 0 | Lt ⇒ -1 | Gt ⇒ 1 end) 0) = true → U.to_z y ≤ U.to_z x).
  destruct (Z.compare_spec (U.to_z x) (U.to_z y)) as [Heq|Hlt|Hgt].
  - intro. lia.
  - discriminate.
  - intro. lia.
Qed.

Lemma transfer_balance_effects sender recipient amount s :
  balanceInvariant (S.t.world_state s) →
  0 ≤ U.to_z amount →
  let result := @H.transfer_ether F sender recipient amount s in
  let after := snd result in
  balanceInvariant (S.t.world_state after) ∧
  totalBalance (S.t.world_state after) = totalBalance (S.t.world_state s) ∧
  ∀ query,
    U.to_z (A.t.balance (readAccount (S.t.world_state after) query)) =
    U.to_z (A.t.balance (readAccount (S.t.world_state s) query)) +
      if fst result then
        (if String.eqb recipient query then U.to_z amount else 0) -
        (if String.eqb sender query then U.to_z amount else 0)
      else 0.
Proof.
  intros [Hwf [Hnonnegative Hsupply]] Hamount.
  rewrite transfer_equation. cbn zeta.
  destruct (U.op_gteq (A.t.balance (readAccount (S.t.world_state s) sender)) amount) eqn:Henough.
  2: { split; [repeat split; assumption|]. split; [reflexivity|]. intro query. cbn [snd fst]. lia. }
  apply u256_gteq in Henough.
  set (before := S.t.world_state s) in ×.
  pose proof (@account_balance_bounded_by_supply before sender Hnonnegative) as Hsender.
  cbn beta in Hsender.
  assert (HdebitRange : 0 ≤ U.to_z (A.t.balance (readAccount before sender)) - U.to_z amount < 2^256).
  { cbn beta. lia. }
  set (newSender := A.t.with_balance
    (@U.op_minus (A.t.balance (readAccount before sender)) amount)
    (readAccount before sender)).
  assert (HdebitBalance : U.to_z (A.t.balance newSender) =
    U.to_z (A.t.balance (readAccount before sender)) - U.to_z amount).
  { unfold newSender. apply reservecheck.u256_sub. exact HdebitRange. }
  set (debited := writeAccount before sender newSender).
  assert (HdebitWF : stringmaps.WellFormed (W.t.accounts debited)).
  { unfold debited. apply account_write_wellformed. exact Hwf. }
  assert (HdebitNonnegative : nonnegativeBalances debited).
  { unfold debited. apply account_write_nonnegative; [exact Hnonnegative|].
    rewrite HdebitBalance. exact (proj1 HdebitRange). }
  assert (HdebitTotal : totalBalance debited = totalBalance before - U.to_z amount).
  { unfold debited. cbn beta. rewrite account_write_total.
    rewrite HdebitBalance. cbn beta. lia. }
  pose proof (@account_balance_bounded_by_supply debited recipient HdebitNonnegative) as Hrecipient.
  assert (HcreditRange : 0 ≤ U.to_z (A.t.balance (readAccount debited recipient)) + U.to_z amount < 2^256).
  { rewrite HdebitTotal in Hrecipient. cbn beta in ×. lia. }
  set (newRecipient := A.t.with_balance
    (@U.op_plus (A.t.balance (readAccount debited recipient)) amount)
    (readAccount debited recipient)).
  assert (HcreditBalance : U.to_z (A.t.balance newRecipient) =
    U.to_z (A.t.balance (readAccount debited recipient)) + U.to_z amount).
  { unfold newRecipient. apply u256_add. exact HcreditRange. }
  set (credited := writeAccount debited recipient newRecipient).
  assert (HcreditTotal : totalBalance credited = totalBalance before).
  { unfold credited. cbn beta. rewrite account_write_total.
    rewrite HcreditBalance, HdebitTotal. cbn beta. lia. }
  change (balanceInvariant credited ∧ totalBalance credited = totalBalance before ∧
    ∀ query, U.to_z (A.t.balance (readAccount credited query)) =
      U.to_z (A.t.balance (readAccount before query)) +
      ((if String.eqb recipient query then U.to_z amount else 0) -
       (if String.eqb sender query then U.to_z amount else 0))).
  split.
  - split.
    + unfold credited. apply account_write_wellformed. exact HdebitWF.
    + split.
      × unfold credited. apply account_write_nonnegative; [exact HdebitNonnegative|].
        rewrite HcreditBalance. exact (proj1 HcreditRange).
      × rewrite HcreditTotal. exact Hsupply.
  - split; [exact HcreditTotal|]. intro query.
    unfold credited. cbn beta. rewrite balance_after_account_write by exact HdebitWF.
    destruct (String.eqb recipient query) eqn:HrecipientEq.
    + apply String.eqb_eq in HrecipientEq. subst query. rewrite HcreditBalance.
      unfold debited. cbn beta. rewrite balance_after_account_write by exact Hwf.
      destruct (String.eqb sender recipient) eqn:HsenderEq.
      × apply String.eqb_eq in HsenderEq. subst recipient. rewrite HdebitBalance. cbn beta. lia.
      × lia.
    + unfold debited. cbn beta. rewrite balance_after_account_write by exact Hwf.
      destruct (String.eqb sender query) eqn:HsenderEq.
      × apply String.eqb_eq in HsenderEq. subst query. rewrite HdebitBalance. cbn beta. lia.
      × lia.
Qed.

Lemma transfer_preserves_supply sender recipient amount s :
  balanceInvariant (S.t.world_state s) →
  0 ≤ U.to_z amount →
  let after := snd (@H.transfer_ether F sender recipient amount s) in
  balanceInvariant (S.t.world_state after) ∧
  totalBalance (S.t.world_state after) = totalBalance (S.t.world_state s).
Proof.
  intros Hinv Hamount.
  destruct (transfer_balance_effects sender recipient amount s Hinv Hamount) as [Hafter [Htotal _]].
  split; assumption.
Qed.

Lemma transfer_cannot_debit_other sender recipient amount s query :
  balanceInvariant (S.t.world_state s) →
  0 ≤ U.to_z amount → sender ≠ query →
  U.to_z (A.t.balance (readAccount (S.t.world_state s) query)) ≤
  U.to_z (A.t.balance (readAccount (S.t.world_state
    (snd (@H.transfer_ether F sender recipient amount s))) query)).
Proof.
  intros Hinv Hamount Hneq.
  destruct (transfer_balance_effects sender recipient amount s Hinv Hamount) as [_ [_ Hbalances]].
  cbn beta. rewrite Hbalances.
  assert (String.eqb sender query = false) as Heq by (apply String.eqb_neq; exact Hneq).
  rewrite Heq. destruct (fst (@H.transfer_ether F sender recipient amount s)),
    (String.eqb recipient query); lia.
Qed.

Context {Uunit : Basics.Unreachable unit}.

Local Lemma selfdestruct_world addr beneficiary s :
  S.t.world_state (snd (@H.selfdestruct F addr beneficiary s)) =
  let middle := snd (@H.transfer_ether F addr beneficiary
    (A.t.balance (readAccount (S.t.world_state s) addr)) s) in
  if Addr._Set.(OCamlSet.S.mem) addr (S.t.accounts_created_in_current_transaction middle)
  then writeAccount (S.t.world_state middle) addr
    (A.t.with_balance (@U.zero) (readAccount (S.t.world_state middle) addr))
  else S.t.world_state middle.
Proof.
  unfold H.selfdestruct. cbn -[H.transfer_ether Addr._Set W.account].
  match goal with |- context [H.transfer_ether ?from ?to ?value ?pre] ⇒
    destruct (H.transfer_ether from to value pre) as [ok middle] eqn:Htransfer end.
  cbn -[H.transfer_ether Addr._Set W.account].

  change (@H.transfer_ether F addr beneficiary
    (A.t.balance (readAccount (S.t.world_state s) addr)) s = (ok, middle)) in Htransfer.
  cbn beta in Htransfer. rewrite Htransfer.
  cbn -[Addr._Set W.account].
  destruct (Addr._Set.(OCamlSet.S.mem) addr (S.t.accounts_created_in_current_transaction middle)); reflexivity.
Qed.

Lemma selfdestruct_preserves_supply_bound addr beneficiary s :
  balanceInvariant (S.t.world_state s) →
  let after := snd (@H.selfdestruct F addr beneficiary s) in
  balanceInvariant (S.t.world_state after) ∧
  totalBalance (S.t.world_state after) ≤ totalBalance (S.t.world_state s).
Proof.
  intro Hinvariant. cbn zeta. rewrite selfdestruct_world.
  pose proof (@account_balance_bounded_by_supply (S.t.world_state s) addr
    (proj1 (proj2 Hinvariant))) as Haccount.
  pose proof (transfer_preserves_supply addr beneficiary
    (A.t.balance (readAccount (S.t.world_state s) addr)) s Hinvariant (proj1 Haccount))
    as [Hmiddle Htotal].
  set (middle := snd (@H.transfer_ether F addr beneficiary
    (A.t.balance (readAccount (S.t.world_state s) addr)) s)) in ×.
  cbn zeta.
  destruct (Addr._Set.(OCamlSet.S.mem) addr (S.t.accounts_created_in_current_transaction middle)).
  - pose proof (@clear_balance_preserves_invariant (S.t.world_state middle) addr Hmiddle)
      as [Hafter Hdecrease].
    split; [exact Hafter|]. rewrite <- Htotal. exact Hdecrease.
  - split; [exact Hmiddle|]. rewrite Htotal. reflexivity.
Qed.

Lemma selfdestruct_cannot_debit_other addr beneficiary s query :
  balanceInvariant (S.t.world_state s) → addr ≠ query →
  U.to_z (A.t.balance (readAccount (S.t.world_state s) query)) ≤
  U.to_z (A.t.balance (readAccount (S.t.world_state
    (snd (@H.selfdestruct F addr beneficiary s))) query)).
Proof.
  intros Hinvariant Hneq. cbn beta. rewrite selfdestruct_world.
  pose proof (@account_balance_bounded_by_supply (S.t.world_state s) addr
    (proj1 (proj2 Hinvariant))) as Haccount.
  pose proof (transfer_preserves_supply addr beneficiary
    (A.t.balance (readAccount (S.t.world_state s) addr)) s Hinvariant (proj1 Haccount))
    as [Hmiddle _].
  pose proof (transfer_cannot_debit_other addr beneficiary
    (A.t.balance (readAccount (S.t.world_state s) addr)) s query Hinvariant (proj1 Haccount) Hneq)
    as Hbalance.
  set (middle := snd (@H.transfer_ether F addr beneficiary
    (A.t.balance (readAccount (S.t.world_state s) addr)) s)) in ×.
  cbn zeta.
  destruct (Addr._Set.(OCamlSet.S.mem) addr (S.t.accounts_created_in_current_transaction middle)).
  - cbn beta. rewrite balance_after_account_write by exact (proj1 Hmiddle).
    assert (String.eqb addr query = false) as Heq by (apply String.eqb_neq; exact Hneq).
    rewrite Heq. exact Hbalance.
  - exact Hbalance.
Qed.

Context {Uint : Basics.Unreachable int}.
Context {U32 : Basics.Unreachable Byte_string.B32.(Byte_string.Fixed.Fixed_result.t)}.

Lemma storage_preserves_supply addr key value s :
  balanceInvariant (S.t.world_state s) →
  let after := snd (@H.set_storage F addr key value s) in
  balanceInvariant (S.t.world_state after) ∧
  totalBalance (S.t.world_state after) = totalBalance (S.t.world_state s).
Proof.
  intro Hinvariant. eapply account_write_preserves_supply; [exact Hinvariant|reflexivity].
Qed.

Lemma storage_preserves_balances addr key value s query :
  stringmaps.WellFormed (W.t.accounts (S.t.world_state s)) →
  U.to_z (A.t.balance (readAccount (S.t.world_state
    (snd (@H.set_storage F addr key value s))) query)) =
  U.to_z (A.t.balance (readAccount (S.t.world_state s) query)).
Proof.
  intro Hwf. eapply account_write_preserves_balances; [exact Hwf|reflexivity].
Qed.

Lemma transient_storage_preserves_world addr key value s :
  S.t.world_state (snd (@H.set_transient_storage F addr key value s)) = S.t.world_state s.
Proof. reflexivity. Qed.

Lemma log_preserves_world addr data topics s :
  S.t.world_state (snd (@H.emit_log F addr data topics s)) = S.t.world_state s.
Proof. reflexivity. Qed.

Lemma access_account_preserves_world addr s :
  S.t.world_state (snd (@H.access_account F addr s)) = S.t.world_state s.
Proof.
  unfold H.access_account. cbn.
  match goal with |- context [if ?b then _ else _] ⇒ destruct b end; reflexivity.
Qed.

Lemma access_storage_preserves_world addr key s :
  S.t.world_state (snd (@H.access_storage F addr key s)) = S.t.world_state s.
Proof.
  unfold H.access_storage. cbn.
  match goal with |- context [if ?b then _ else _] ⇒ destruct b end; reflexivity.
Qed.

End HostBalances.

Print Assumptions transfer_preserves_supply.
Print Assumptions selfdestruct_preserves_supply_bound.
Print Assumptions selfdestruct_cannot_debit_other.
Print Assumptions storage_preserves_supply.
Print Assumptions storage_preserves_balances.