Library QedkConcrete.stakingsystem

Concrete Monad system-transaction validity, execution, and frame properties

Monad system transactions (Chain.Monad.system_sender) dispatch staking syscalls (syscall_snapshot, syscall_on_epoch_change, syscall_reward) via Execution.Make.process_monad_system_transaction. Unlike assuming VM execution success, this module characterizes the exact calldata and staking storage conditions under which each syscall succeeds and proves that consensus-accepted system transactions both validate and execute without reverting.
From Stdlib Require Import List String ZArith NArith Bool Lia Wellfounded.
From stdpp Require Import decidable numbers strings.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Import MonadVM.Execution MonadVM.Contract MonadVM.Staking MonadVM.State.
Require Import MonadVM.Contract._Type MonadVM.Contract.Storage.
Require Import QedkConcrete.stringmaps QedkConcrete.worldaccounts
  QedkConcrete.authorizationnonces QedkConcrete.authorizationcode
  QedkConcrete.publictransaction QedkConcrete.transactionchecks
  QedkConcrete.transactionchecksproofs QedkConcrete.storagepreservation
  QedkConcrete.stakingaccounting QedkConcrete.precompilesframe
  QedkConcrete.transactionchecked.
Set Default Goal Selector "!".
#[local] Hint Extern 100 (Basics.Unreachable _) ⇒
  (apply Opaque.legacy_witness; Opaque.opaque_inhabit 64%nat) : typeclass_instances.
Import ListNotations.
Local Open Scope Z_scope.

Module E := Execution.Make.
Module B := State.BlockState.
Module TS := State.TransactionState.
Module W := State.WorldState.
Module A := Chain.Ethereum.Account.
Module T := Chain.Ethereum.Transaction.
Module U := Numeric.U256.
Module CT := Contract._Type.
Module CS := Contract.Storage.Make.
Module C := Contract.Make.
Module St := MonadVM.Staking.

Local Existing Instance St.Contract_fargs.
Local Instance staking_storage_fargs_sys : CS.FArgs :=
  MonadVM.Contract.Make.Storage_fargs (_fargs := St.Contract_fargs).

Local Abbreviation readAccount world addr :=
  (State.op_pointcaretlparenrparen world (@W.account None addr)).
Local Abbreviation writeAccount keep world addr value :=
  (State.op_pointcaretlparenrparenltminus world (@W.account (Some keep) addr) value).

Four-byte ABI selectors for the three Monad staking syscalls.
World-level staking storage reader matching St.M.op_exclamationdollar.
Definition readStakingLoc {a : Set}
    (fallback : a × CT.Input_view.t) (loc : CS.Loc.t a) (world : W.t) : a :=
  fst (Result.get_ok fallback
    (CT.dec (CS.Loc.Impl.t.typ loc)
      (CT.Input_view.of_storage
        (A.t.storage (readAccount world St.staking_address))
        (CS.Loc.Impl.t.offset loc)))).

World-level mirror of get_this_epoch_view.
World-level mirror of creditStakingAccount in syscall_reward.
Exact execution preconditions for syscall_snapshot.
Exact execution preconditions for syscall_on_epoch_change.
Definition validEpochChangeSyscall (world : W.t) (tx : T.t) : Prop :=
  4 ≤ Byte_string.Bytes.length (T.data tx) ∧
  syscallSelector (T.data tx) = epochChangeSelector ∧
  T.value tx = U.zero ∧
  ∃ next_epoch next_next_epoch,
    CT.dec_bytes None (CT.tuple (CT.tup1 St.Epoch.t_value)) (syscallArgs (T.data tx)) =
      inl next_epoch ∧
    St.Epoch.op_plus next_epoch 1 = inl next_next_epoch ∧
    St.Epoch.op_lteq next_epoch
      (readStakingLoc
        (St._rocq_fallback_get_epoch_0 (A := CT.Address.t) (B := CT.U256.t))
        St.Variables.epoch world) = false.

Exact execution preconditions for syscall_reward.
Definition validRewardSyscall (world : W.t) (tx : T.t) : Prop :=
  4 ≤ Byte_string.Bytes.length (T.data tx) ∧
  syscallSelector (T.data tx) = rewardSelector ∧
  syscallSelector (T.data tx) ≠ snapshotSelector ∧
  syscallSelector (T.data tx) ≠ epochChangeSelector ∧
  ∃ block_author val_id commission auth_rewards del_reward val_execution',
    CT.dec_bytes None (CT.tuple (CT.tup1 CT.Address.t_value)) (syscallArgs (T.data tx)) =
      inl block_author ∧
    readStakingLoc
      (St._rocq_fallback_syscall_reward_2 (A := CT.Address.t))
      (St.Variables.val_id block_author) world = Some val_id ∧
    let epoch_view := readThisEpochView world val_id in
    CT.U256.op_eq epoch_view.(St.Consensus_view.t.stake) CT.U256.zero = false ∧
    St.Pure_result.op_letdollar
      (CT.U256.Checked.op_star (T.value tx) epoch_view.(St.Consensus_view.t.commission))
      (fun product ⇒ CT.U256.Checked.op_div product St.mon) = inl commission ∧
    let credited := creditStakingWorld (T.value tx) world in
    let val_execution :=
      readStakingLoc
        (St._rocq_fallback_add_validator_2 (A := CT.Address.t))
        (St.Variables.val_execution val_id) credited in
    let auth_address :=
      val_execution.(St.Val_execution.t.address_flags).(St.Address_flags.t.auth_address) in
    let auth_del :=
      readStakingLoc
        (St._rocq_fallback_undelegate_3 (A := CT.Address.t))
        (St.Variables.delegator (val_id, auth_address)) credited in
    CT.U256.Checked.op_plus auth_del.(St.Delegator.t.rewards) commission = inl auth_rewards ∧
    CT.U256.Checked.op_minus (T.value tx) commission = inl del_reward ∧
    St.apply_reward val_execution del_reward epoch_view.(St.Consensus_view.t.stake) =
      inl val_execution'.

A Monad system transaction invokes one of the three staking syscalls on a staking state satisfying that syscall's arithmetic and epoch invariants.
Definition validStakingSyscall (world : W.t) (tx : T.t) : Prop :=
  validSnapshotSyscall world tx ∨
  validEpochChangeSyscall world tx ∨
  validRewardSyscall world tx.

Section InfallibleCombinators.

Definition contractM_ok {A : Set} (m : St.M.t A) : Prop :=
  ∀ s, ∃ x s', m s = (inl x, s').

Lemma contractM_ok_return {A : Set} (v : A) :
  contractM_ok (St.M._return v).
Proof.
  intro s. ∃ v, s. reflexivity.
Qed.

Lemma contractM_ok_letdollar {A B : Set} (m : St.M.t A) (f : A → St.M.t B) :
  contractM_ok m →
  (∀ x, contractM_ok (f x)) →
  contractM_ok (St.M.op_letdollar m f).
Proof.
  intros Hm Hf s.
  destruct (Hm s) as [x [s1 Hms]].
  destruct (Hf x s1) as [y [s2 Hfs]].
  ∃ y, s2.
  change (match m s with
          | (inl a, st) ⇒ f a st
          | (inr err, st) ⇒ (inr err, st)
          end = (inl y, s2)).
  rewrite Hms. exact Hfs.
Qed.

Lemma contractM_ok_lift {A : Set} (m : TS.M.(Monad.State.State_result.t) A) :
  contractM_ok (St.M.lift m).
Proof.
  intro s.
  destruct (m s) as [x s1] eqn:Hms.
  ∃ x, s1.
  change ((let '(v, st) := m s in (@inl A St.Error.t v, st)) = (inl x, s1)).
  rewrite Hms. reflexivity.
Qed.

Lemma contractM_ok_exclamationdollar {A : Set} fallback (loc : CS.Loc.t A) :
  contractM_ok (St.M.op_exclamationdollar fallback loc).
Proof.
  intro s.
  ∃ (Lens.t.get (CS.Loc.lens fallback loc) s), s.
  reflexivity.
Qed.

Lemma contractM_ok_op_eq {A : Set} fallback (loc : CS.Loc.t A) (v : A) :
  contractM_ok (St.M.op___eq fallback loc v).
Proof.
  intro s.
  ∃ tt, (Lens.t.set (CS.Loc.lens fallback loc) v s).
  reflexivity.
Qed.

Lemma contractM_ok_update_field {A : Set} (lens : Lens.t TS.t A) (f : A → A) :
  contractM_ok (St.M.update_field lens f).
Proof.
  intro s.
  ∃ tt, (Lens.t.set lens (f (Lens.t.get lens s)) s).
  reflexivity.
Qed.

Lemma contractM_ok_emit_event {A B : Set}
    (ev : Contract.Abi.Event.t A B) (x : A) (y : B) :
  contractM_ok (St.M.emit_event ev x y).
Proof.
  intro s.
  ∃ tt, (TS.t.with_logs
    (Contract.Abi.Event.to_log ev St.staking_address x y :: TS.t.logs s) s).
  reflexivity.
Qed.

Lemma contractM_ok_iterM {A : Set} (f : A → St.M.t unit) (xs : list A) :
  (∀ x, contractM_ok (f x)) →
  contractM_ok (St.M.List.iterM f xs).
Proof.
  intro Hf.
  induction xs as [|x rest IH]; cbn [St.M.List.iterM].
  - apply contractM_ok_return.
  - apply contractM_ok_letdollar; [apply Hf | intros _; exact IH].
Qed.

Lemma contractM_ok_clear_valset {a : Set}
    (val_ids : CS.Array.t St.Val_id.t)
    (validators : CS.Mapping.t St.Val_id.t a) :
  contractM_ok (St.clear_valset val_ids validators).
Proof.
  unfold St.clear_valset.
  apply contractM_ok_letdollar; [apply contractM_ok_lift | intros _; apply contractM_ok_lift].
Qed.

Lemma readStakingLoc_matches_state {a : Set}
    (fallback : a × CT.Input_view.t) (loc : CS.Loc.t a) (world : W.t) (s : TS.t) :
  A.t.storage (readAccount (TS.t.world_state s) St.staking_address) =
    A.t.storage (readAccount world St.staking_address) →
  St.M.op_exclamationdollar fallback loc s = (inl (readStakingLoc fallback loc world), s).
Proof.
  intro Hstor.
  destruct loc as [typ kind offset].
  unfold readStakingLoc; cbn [CS.Loc.Impl.t.typ CS.Loc.Impl.t.offset].
  change ((@inl a St.Error.t
    (fst (Result.get_ok fallback
      (CT.dec typ
        (CT.Input_view.of_storage
          (A.t.storage (readAccount (TS.t.world_state s) St.staking_address))
          offset)))), s) =
    (inl
      (fst (Result.get_ok fallback
        (CT.dec typ
          (CT.Input_view.of_storage
            (A.t.storage (readAccount world St.staking_address))
            offset)))), s)).
  do 6 f_equal. exact Hstor.
Qed.

Lemma letdollar_step {A B : Set} (m : St.M.t A) (f : A → St.M.t B)
    (v : A) (s s1 : TS.t) :
  m s = (inl v, s1) →
  St.M.op_letdollar m f s = f v s1.
Proof.
  intro Hm.
  change (match m s with (inl a, st) ⇒ f a st | (inr e, st) ⇒ (inr e, st) end = f v s1).
  rewrite Hm. reflexivity.
Qed.

Lemma checked_arith_inl_step {A : Set}
    (r : A + MonadVM.Numeric.arithmetic_error) (v : A) (s : TS.t) :
  r = inl v →
  St.M.checked_arith r s = (inl v, s).
Proof.
  intros →. reflexivity.
Qed.

Lemma when_false_step (cond : bool) (fail : St.M.t unit) (s : TS.t) :
  cond = false →
  St.M.when_ cond fail s = (inl tt, s).
Proof.
  intros →. reflexivity.
Qed.

Lemma get_this_epoch_view_matches_world (world : W.t) (val_id : St.Val_id.t) (s : TS.t) :
  A.t.storage (readAccount (TS.t.world_state s) St.staking_address) =
    A.t.storage (readAccount world St.staking_address) →
  St.get_this_epoch_view val_id s = (inl (readThisEpochView world val_id), s).
Proof.
  intro Hstor.
  unfold St.get_this_epoch_view, readThisEpochView.
  change (match St.M.op_exclamationdollar St._rocq_fallback_get_this_epoch_valset_1
                  St.Variables.in_epoch_delay_period s with
          | (inl in_delay, s1) ⇒
              let view :=
                if in_delay then St.Variables.snapshot_view else St.Variables.consensus_view in
              St.M.op_exclamationdollar St._rocq_fallback_get_this_epoch_view_0 (view val_id) s1
          | (inr err, s1) ⇒ (inr err, s1)
          end =
          (inl
            (let in_delay :=
               readStakingLoc St._rocq_fallback_get_this_epoch_valset_1
                 St.Variables.in_epoch_delay_period world in
             let view :=
               if in_delay then St.Variables.snapshot_view else St.Variables.consensus_view in
             readStakingLoc St._rocq_fallback_get_this_epoch_view_0 (view val_id) world), s)).
  rewrite (readStakingLoc_matches_state St._rocq_fallback_get_this_epoch_valset_1
    St.Variables.in_epoch_delay_period world s Hstor).
  set (in_delay := readStakingLoc St._rocq_fallback_get_this_epoch_valset_1
    St.Variables.in_epoch_delay_period world).
  set (view := if in_delay then St.Variables.snapshot_view else St.Variables.consensus_view).
  exact (readStakingLoc_matches_state St._rocq_fallback_get_this_epoch_view_0 (view val_id) world s Hstor).
Qed.

Lemma syscall_snapshot_succeeds fb0 (sender : CT.Address.t) (value : CT.U256.t)
    (world : W.t) (s : TS.t) :
  A.t.storage (readAccount (TS.t.world_state s) St.staking_address) =
    A.t.storage (readAccount world St.staking_address) →
  readStakingLoc
    (St._rocq_fallback_get_epoch_1 (A := CT.Address.t) (B := CT.U256.t))
    St.Variables.in_epoch_delay_period world = false →
  ∃ s', St.syscall_snapshot fb0 sender value tt s = (inl tt, s').
Proof.
  intros Hstor Hdelay.
  unfold St.syscall_snapshot.
  cbn beta iota zeta.
  match goal with
  | |- ∃ s', St.M.op_letdollar ?m1 (fun d ⇒ St.M.op_letdollar (St.M.when_ d ?fail) ?rest) s = _ ⇒
      assert (Htail : contractM_ok (rest tt))
  end.
  { apply contractM_ok_letdollar; [apply contractM_ok_clear_valset | intros _].
    apply contractM_ok_letdollar.
    { apply contractM_ok_letdollar; [apply contractM_ok_lift | intro consensus].
      apply contractM_ok_letdollar; [apply contractM_ok_lift | intros _].
      apply contractM_ok_iterM; intro vid.
      apply contractM_ok_letdollar; [apply contractM_ok_exclamationdollar | intro cv].
      apply contractM_ok_op_eq. }
    intros _.
    apply contractM_ok_letdollar; [apply contractM_ok_clear_valset | intros _].
    apply contractM_ok_letdollar.
    { apply contractM_ok_letdollar; [apply contractM_ok_exclamationdollar | intro len].
      cbn beta iota zeta.
      match goal with
      | |- contractM_ok (Fix ?wf ?P ?body ?init) ⇒
          apply (fix_dep_preserves _ wf P body (fun _ m ⇒ contractM_ok m))
      end.
      intros [[i_value candidates] removals] recur IH.
      cbn beta iota zeta.
      match goal with
      | |- contractM_ok (_ (eq_refl ?g1)) ⇒
          generalize (eq_refl g1); generalize g1 at 2 3
      end.
      intros [] Hguard1; cbn beta iota zeta.
      - apply contractM_ok_return.
      - apply contractM_ok_letdollar; [apply contractM_ok_exclamationdollar | intro vid].
        apply contractM_ok_letdollar; [apply contractM_ok_exclamationdollar | intro ve].
        match goal with
        | |- contractM_ok (_ (eq_refl ?g2)) ⇒
            generalize (eq_refl g2); generalize g2 at 2 3
        end.
        intros [] Hguard2; cbn beta iota zeta; apply IH. }
    intros [candidates removals].
    apply contractM_ok_letdollar.
    { cbn zeta.
      apply contractM_ok_iterM; intros [vid ve].
      destruct ve.
      apply contractM_ok_letdollar; [apply contractM_ok_lift | intros _].
      apply contractM_ok_op_eq. }
    intros _.
    apply contractM_ok_letdollar.
    { apply contractM_ok_iterM; intro idx.
      cbn zeta.
      apply contractM_ok_letdollar; [apply contractM_ok_exclamationdollar | intro id_rem].
      apply contractM_ok_letdollar; [apply contractM_ok_exclamationdollar | intro bitset].
      apply contractM_ok_letdollar; [apply contractM_ok_op_eq | intros _].
      apply contractM_ok_letdollar; [apply contractM_ok_lift | intro swapped].
      apply contractM_ok_op_eq. }
    intros _.
    apply contractM_ok_op_eq. }
  destruct (Htail s) as [[] [s' Hs']].
  ∃ s'.
  match goal with
  | |- St.M.op_letdollar ?m1 ?f s = _ ⇒
      change (match m1 s with (inl a, st) ⇒ f a st | (inr err, st) ⇒ (inr err, st) end = (inl tt, s'))
  end.
  rewrite (readStakingLoc_matches_state
    (St._rocq_fallback_get_epoch_1 (A := CT.Address.t) (B := CT.U256.t))
    St.Variables.in_epoch_delay_period world s Hstor).
  rewrite Hdelay.
  exact Hs'.
Qed.

Lemma syscall_on_epoch_change_succeeds fb0 (sender : CT.Address.t) (value : CT.U256.t)
    (next_epoch next_next_epoch : St.Epoch.t) (world : W.t) (s : TS.t) :
  A.t.storage (readAccount (TS.t.world_state s) St.staking_address) =
    A.t.storage (readAccount world St.staking_address) →
  St.Epoch.op_plus next_epoch 1 = inl next_next_epoch →
  St.Epoch.op_lteq next_epoch
    (readStakingLoc
      (St._rocq_fallback_get_epoch_0 (A := CT.Address.t) (B := CT.U256.t))
      St.Variables.epoch world) = false →
  ∃ s', St.syscall_on_epoch_change fb0 sender value next_epoch s = (inl tt, s').
Proof.
  intros Hstor Hplus Hlt.
  unfold St.syscall_on_epoch_change.
  cbn beta iota zeta.
  set (last_epoch := readStakingLoc
    (St._rocq_fallback_get_epoch_0 (A := CT.Address.t) (B := CT.U256.t))
    St.Variables.epoch world) in ×.
  match goal with
  | |- ∃ s',
        St.M.op_letdollar _ (fun nne ⇒
          St.M.op_letdollar _ (fun le ⇒
            St.M.op_letdollar (St.M.when_ _ _) (fun u ⇒ @?rest nne le u))) s = _ ⇒
      assert (Htail : contractM_ok (rest next_next_epoch last_epoch tt))
  end.
  { cbn beta iota zeta.
    apply contractM_ok_letdollar.
    { unfold St.emit_epoch_changed_event.
      destruct last_epoch, next_epoch.
      apply contractM_ok_emit_event. }
    intros _.
    apply contractM_ok_letdollar; [apply contractM_ok_lift | intro valset].
    apply contractM_ok_letdollar.
    { apply contractM_ok_iterM; intro vid.
      apply contractM_ok_letdollar; [apply contractM_ok_exclamationdollar | intro validator].
      apply contractM_ok_letdollar; [apply contractM_ok_update_field | intros _].
      apply contractM_ok_letdollar; [apply contractM_ok_update_field | intros _].
      apply contractM_ok_return. }
    intros _.
    apply contractM_ok_letdollar; [apply contractM_ok_op_eq | intros _].
    apply contractM_ok_op_eq. }
  destruct (Htail s) as [[] [s' Hs']].
  ∃ s'.
  erewrite letdollar_step; [| exact (checked_arith_inl_step _ _ s Hplus)].
  cbn beta.
  erewrite letdollar_step; [| exact (readStakingLoc_matches_state
    (St._rocq_fallback_get_epoch_0 (A := CT.Address.t) (B := CT.U256.t))
    St.Variables.epoch world s Hstor)].
  cbn beta.
  fold last_epoch.
  erewrite letdollar_step; [| exact (when_false_step _ _ s Hlt)].
  exact Hs'.
Qed.

Lemma syscall_reward_succeeds (sender : CT.Address.t) (value : CT.U256.t)
    (block_author : CT.Address.t) (val_id : St.Val_id.t)
    (commission auth_rewards del_reward : CT.U256.t)
    (val_execution' : St.Val_execution.t)
    (world : W.t) (s : TS.t) :
  WellFormed (W.t.accounts world) →
  WellFormed (W.t.accounts (TS.t.world_state s)) →
  readAccount (TS.t.world_state s) St.staking_address = readAccount world St.staking_address →
  readStakingLoc
    (St._rocq_fallback_syscall_reward_2 (A := CT.Address.t))
    (St.Variables.val_id block_author) world = Some val_id →
  let epoch_view := readThisEpochView world val_id in
  CT.U256.op_eq epoch_view.(St.Consensus_view.t.stake) CT.U256.zero = false →
  St.Pure_result.op_letdollar
    (CT.U256.Checked.op_star value epoch_view.(St.Consensus_view.t.commission))
    (fun product ⇒ CT.U256.Checked.op_div product St.mon) = inl commission →
  let credited := creditStakingWorld value world in
  let val_execution :=
    readStakingLoc
      (St._rocq_fallback_add_validator_2 (A := CT.Address.t))
      (St.Variables.val_execution val_id) credited in
  let auth_address :=
    val_execution.(St.Val_execution.t.address_flags).(St.Address_flags.t.auth_address) in
  let auth_del :=
    readStakingLoc
      (St._rocq_fallback_undelegate_3 (A := CT.Address.t))
      (St.Variables.delegator (val_id, auth_address)) credited in
  CT.U256.Checked.op_plus auth_del.(St.Delegator.t.rewards) commission = inl auth_rewards →
  CT.U256.Checked.op_minus value commission = inl del_reward →
  St.apply_reward val_execution del_reward epoch_view.(St.Consensus_view.t.stake) =
    inl val_execution' →
  ∃ s', St.syscall_reward sender value block_author s = (inl tt, s').
Proof.
  intros Hwf_w Hwf_s Hacc Hvid epoch_view Hstake Hcomm credited val_execution auth_address
    auth_del Hauth_plus Hdel_minus Happly.
  assert (Hstor0 : A.t.storage (readAccount (TS.t.world_state s) St.staking_address) =
    A.t.storage (readAccount world St.staking_address)) by congruence.
  set (s_cred := creditStakingAccount value s).
  assert (Hstor_cred : A.t.storage (readAccount (TS.t.world_state s_cred) St.staking_address) =
    A.t.storage (readAccount credited St.staking_address)).
  { unfold s_cred, creditStakingAccount, credited, creditStakingWorld.
    cbn [TS.t.world_state TS.t.with_world_state].
    rewrite (account_read_after_write false (TS.t.world_state s) St.staking_address _
      St.staking_address Hwf_s).
    rewrite (account_read_after_write false world St.staking_address _
      St.staking_address Hwf_w).
    rewrite Hacc. reflexivity. }
  unfold St.syscall_reward.
  cbn beta iota zeta.
  assert (Hvid_step :
    St.M.op_gtgteq
      (St.M.op_exclamationdollar (St._rocq_fallback_syscall_reward_2 (A := CT.Address.t))
        (St.Variables.val_id block_author))
      (St.M.Option.or_fail St.Error.Not_in_validator_set) s = (inl val_id, s)).
  { change (match St.M.op_exclamationdollar (St._rocq_fallback_syscall_reward_2 (A := CT.Address.t))
                    (St.Variables.val_id block_author) s with
            | (inl opt, s1) ⇒ St.M.Option.or_fail St.Error.Not_in_validator_set opt s1
            | (inr err, s1) ⇒ (inr err, s1)
            end = (inl val_id, s)).
    rewrite (readStakingLoc_matches_state
      (St._rocq_fallback_syscall_reward_2 (A := CT.Address.t))
      (St.Variables.val_id block_author) world s Hstor0).
    rewrite Hvid. reflexivity. }
  assert (Hview_step := get_this_epoch_view_matches_world world val_id s Hstor0).
  fold epoch_view in Hview_step.
  assert (Hcred_step :
    St.M.update_field (Lens.Infix.op_pipeminusminus St.staking_account A.balance)
      (fun b_value : U.t ⇒ CT.U256.op_plus b_value value) s = (inl tt, s_cred)).
  { reflexivity. }
  assert (Hve_step := readStakingLoc_matches_state
    (St._rocq_fallback_add_validator_2 (A := CT.Address.t))
    (St.Variables.val_execution val_id) credited s_cred Hstor_cred).
  fold val_execution in Hve_step.
  assert (Hdel_step := readStakingLoc_matches_state
    (St._rocq_fallback_undelegate_3 (A := CT.Address.t))
    (St.Variables.delegator (val_id, auth_address)) credited s_cred Hstor_cred).
  fold auth_del in Hdel_step.
  destruct (contractM_ok_op_eq
    (St._rocq_fallback_undelegate_3 (A := CT.Address.t))
    (St.Variables.delegator (val_id, auth_address))
    (St.Delegator.t.with_rewards auth_rewards auth_del) s_cred)
    as [[] [s_del Hset_del]].
  assert (Htail : contractM_ok
    (St.M.op_letdollar
      (St.M.op___eq (St._rocq_fallback_add_validator_2 (A := CT.Address.t))
        (St.Variables.val_execution val_id) val_execution')
      (fun _ ⇒
        St.M.op_letdollar
          (St.emit_validator_rewarded_event val_id Chain.Monad.system_sender del_reward)
          (fun _ ⇒
            St.M.op___eq (St._rocq_fallback_add_validator_1 (A := CT.Address.t))
              St.Variables.proposer_val_id val_id)))).
  { apply contractM_ok_letdollar; [apply contractM_ok_op_eq | intros _].
    apply contractM_ok_letdollar.
    { unfold St.emit_validator_rewarded_event.
      destruct val_id.
      apply contractM_ok_letdollar; [apply contractM_ok_exclamationdollar | intros []].
      apply contractM_ok_emit_event. }
    intros _.
    apply contractM_ok_op_eq. }
  destruct (Htail s_del) as [[] [s' Hs']].
  ∃ s'.
  erewrite letdollar_step; [| exact Hvid_step]. cbn beta.
  erewrite letdollar_step; [| exact Hview_step]. cbn beta.
  erewrite letdollar_step; [| exact (when_false_step _ _ s Hstake)]. cbn beta.
  erewrite letdollar_step; [| exact Hcred_step]. cbn beta.
  erewrite letdollar_step; [| exact (checked_arith_inl_step _ _ s_cred Hcomm)]. cbn beta.
  erewrite letdollar_step; [| exact Hve_step]. cbn beta.
  fold auth_address.
  erewrite letdollar_step; [| exact Hdel_step]. cbn beta.
  erewrite letdollar_step; [| exact (checked_arith_inl_step _ _ s_cred Hauth_plus)]. cbn beta.
  erewrite letdollar_step; [| exact Hset_del]. cbn beta.
  erewrite letdollar_step; [| exact (checked_arith_inl_step _ _ s_del Hdel_minus)]. cbn beta.
  erewrite letdollar_step; [| exact (checked_arith_inl_step _ _ s_del Happly)]. cbn beta.
  exact Hs'.
Qed.

End InfallibleCombinators.

Section DispatchAndFrame.
Context {F : E.FArgs}.

Lemma send_pack_make_succeeds {i o : Set}
    (name : string) (payable_opt : option bool)
    (input_tup : CT.tup i) (output_typ : CT.typ o)
    (abi_fn : St.Function.abi_fn i o)
    (inputs : i) (out : o)
    (msg : Evmc.Message.t) (s s' : TS.t) :
  Evmc.Message.t.gas msg = Gas.to_int64 Gas.zero →
  (payable_opt = Some true ∨ Evmc.Message.t.value msg = U.zero) →
  CT.dec_bytes None (CT.tuple input_tup) (Evmc.Message.t.input_data msg) = inl inputs →
  abi_fn (Evmc.Message.t.sender msg) (Evmc.Message.t.value msg) inputs s = (inl out, s') →
  Evmc.Result.StatusCode.is_success
    (Evmc.Result.t.status_code
      (fst (C.Function.send_message (_fargs := St.Contract_fargs)
        (St.Function._pack (St.Function.make name payable_opt input_tup output_typ Gas.zero abi_fn))
        msg s))) = true.
Proof.
  intros Hgas Hpay Hdec Habi.
  destruct payable_opt as [payable|];
    change (C.Function.send_message (_fargs := St.Contract_fargs)
      (St.Function._pack ?fn) msg s)
      with (C.Function.send_impl (_fargs := St.Contract_fargs) fn msg s);
    unfold C.Function.send_impl;
    change (C.Function.impl.gas_cost (St.Function.make name _ input_tup output_typ Gas.zero abi_fn))
      with Gas.zero;
    rewrite Hgas;
    change (Gas.op_lt (Gas.of_uint64 (Gas.to_int64 Gas.zero)) Gas.zero) with false;
    (replace (andb (CT.U256.op_ltgt (Evmc.Message.t.value msg) CT.U256.zero)
        (negb (C.Function.impl.payable
          (St.Function.make name _ input_tup output_typ Gas.zero abi_fn))))
      with false
      by (symmetry;
          destruct Hpay as [Hsome | Hval0];
          [ inversion Hsome; subst; apply Bool.andb_false_r
          | rewrite Hval0; try destruct payable; reflexivity ]));
    change (C.Function.impl.impl (St.Function.make name _ input_tup output_typ Gas.zero abi_fn))
      with (C.Function.Abi (_fargs := St.Contract_fargs) (i := i) (o := o) abi_fn);
    change (Contract.Abi.Signature.Impl.t.input
      (C.Function.impl.signature (St.Function.make name _ input_tup output_typ Gas.zero abi_fn)))
      with input_tup;
    rewrite Hdec;
    cbn;
    rewrite Habi; reflexivity.
Qed.

Lemma staking_syscalls_succeeds fb0 (world : W.t) (tx : T.t) (msg : Evmc.Message.t) (s : TS.t) :
  WellFormed (W.t.accounts world) →
  WellFormed (W.t.accounts (TS.t.world_state s)) →
  readAccount (TS.t.world_state s) St.staking_address = readAccount world St.staking_address →
  Evmc.Message.t.gas msg = Gas.to_int64 Gas.zero →
  Evmc.Message.t.input_data msg = T.data tx →
  Evmc.Message.t.value msg = T.value tx →
  validStakingSyscall world tx →
  Evmc.Result.StatusCode.is_success
    (Evmc.Result.t.status_code (fst (St.staking_syscalls fb0 msg s))) = true.
Proof.
  intros Hwf_w Hwf_s Hacc Hgas Hdata Hval Hvalid.
  assert (Hstor0 : A.t.storage (readAccount (TS.t.world_state s) St.staking_address) =
    A.t.storage (readAccount world St.staking_address)) by congruence.
  unfold St.staking_syscalls.
  change (St.Contract.(C.Make_result.dispatch)
    (St.Contract.(C.Make_result.make) ?fns ?fb) msg)
    with (C.dispatch (_fargs := St.Contract_fargs)
      (C.make (_fargs := St.Contract_fargs) fns fb) msg).
  unfold C.dispatch, C.make, C.Dispatch_table, C.Dispatch_table.module, C.Dispatch_table.make.
  cbn [C.Dispatch_table.Dispatch_table_signature.make
       C.Dispatch_table.t.functions C.Dispatch_table.t.fallback].
  rewrite Hdata.
  set (fn_rew := St.Function._pack St.syscall_reward_function).
  set (fn_snap := St.Function._pack (St.syscall_snapshot_function fb0)).
  set (fn_ep := St.Function._pack (St.syscall_on_epoch_change_function fb0)).
  assert (Hsel_rew : fn_rew.(C.Function.t.selector) = rewardSelector) by reflexivity.
  assert (Hsel_snap : fn_snap.(C.Function.t.selector) = snapshotSelector) by reflexivity.
  assert (Hsel_ep : fn_ep.(C.Function.t.selector) = epochChangeSelector) by reflexivity.
  change (Contract.Abi.Selector.(Byte_string.Fixed.Fixed_result.Map).(Byte_string.Fixed.Map.Map_signature.find_opt)
    (Contract.Abi.Selector.(Byte_string.Fixed.Fixed_result.sub) (T.data tx) 0)
    (Contract.Abi.Selector.(Byte_string.Fixed.Fixed_result.Map).(Byte_string.Fixed.Map.Map_signature.of_list)
      (OCamlList.map (fun fn : C.Function.t (_fargs := St.Contract_fargs) ⇒ (fn.(C.Function.t.selector), fn))
        [fn_rew; fn_snap; fn_ep])))
    with (OCamlMap.Make.find_opt stringOrder (syscallSelector (T.data tx))
      (OCamlMap.Make.add stringOrder fn_ep.(C.Function.t.selector) fn_ep
        (OCamlMap.Make.add stringOrder fn_snap.(C.Function.t.selector) fn_snap
          (OCamlMap.Make.add stringOrder fn_rew.(C.Function.t.selector) fn_rew nil)))).
  rewrite Hsel_rew, Hsel_snap, Hsel_ep.
  assert (Hmap1 : WellFormed (OCamlMap.Make.add stringOrder rewardSelector fn_rew nil))
    by (apply add_wellformed, empty_wellformed).
  assert (Hmap2 : WellFormed
    (OCamlMap.Make.add stringOrder snapshotSelector fn_snap
      (OCamlMap.Make.add stringOrder rewardSelector fn_rew nil)))
    by (apply add_wellformed, Hmap1).
  change ((MonadVM.String.sub (C._rocq_fallback_dispatch_0 (_fargs := St.Contract_fargs)))
    (T.data tx) 4 (OCamlInt.sub (MonadVM.String.length (T.data tx)) 4))
    with (syscallArgs (T.data tx)).
  destruct Hvalid as [Hsnap | [Hep | Hrew]].
  - destruct Hsnap as [Hlen [Hsel [Hne_ep [Hval0 [Hdec Hdelay]]]]].
    replace (Z.ltb (Byte_string.Bytes.length (T.data tx)) 4) with false
      by (symmetry; apply Z.ltb_ge; exact Hlen).
    rewrite Hsel.
    rewrite (find_add_other _ epochChangeSelector snapshotSelector fn_ep Hmap2)
      by (intro Heq; apply Hne_ep; congruence).
    rewrite (find_add_same _ snapshotSelector fn_snap Hmap1).
    destruct (syscall_snapshot_succeeds fb0 (Evmc.Message.t.sender msg)
      (Evmc.Message.t.value msg) world s Hstor0 Hdelay) as [s' Hs'].
    unfold fn_snap, St.syscall_snapshot_function.
    eapply send_pack_make_succeeds;
      cbn [Evmc.Message.t.gas Evmc.Message.t.value Evmc.Message.t.sender
           Evmc.Message.t.input_data Evmc.Message.t.with_input_data];
      [exact Hgas | right; rewrite Hval; exact Hval0 | exact Hdec | exact Hs'].
  - destruct Hep as [Hlen [Hsel [Hval0 [next_ep [next_next_ep [Hdec [Hplus Hlt]]]]]]].
    replace (Z.ltb (Byte_string.Bytes.length (T.data tx)) 4) with false
      by (symmetry; apply Z.ltb_ge; exact Hlen).
    rewrite Hsel.
    rewrite (find_add_same _ epochChangeSelector fn_ep Hmap2).
    destruct (syscall_on_epoch_change_succeeds fb0 (Evmc.Message.t.sender msg)
      (Evmc.Message.t.value msg) next_ep next_next_ep world s Hstor0 Hplus Hlt) as [s' Hs'].
    unfold fn_ep, St.syscall_on_epoch_change_function.
    eapply send_pack_make_succeeds;
      cbn [Evmc.Message.t.gas Evmc.Message.t.value Evmc.Message.t.sender
           Evmc.Message.t.input_data Evmc.Message.t.with_input_data];
      [exact Hgas | right; rewrite Hval; exact Hval0 | exact Hdec | exact Hs'].
  - destruct Hrew as [Hlen [Hsel [Hne_snap [Hne_ep
      [block_author [val_id [commission [auth_rewards [del_reward [ve'
      [Hdec [Hvid [Hstake [Hcomm [Hauth_plus [Hdel_minus Happly]]]]]]]]]]]]]]]].
    replace (Z.ltb (Byte_string.Bytes.length (T.data tx)) 4) with false
      by (symmetry; apply Z.ltb_ge; exact Hlen).
    rewrite Hsel.
    rewrite (find_add_other _ epochChangeSelector rewardSelector fn_ep Hmap2)
      by (intro Heq; apply Hne_ep; congruence).
    rewrite (find_add_other _ snapshotSelector rewardSelector fn_snap Hmap1)
      by (intro Heq; apply Hne_snap; congruence).
    rewrite (find_add_same nil rewardSelector fn_rew empty_wellformed).
    destruct (syscall_reward_succeeds (Evmc.Message.t.sender msg) (T.value tx)
      block_author val_id commission auth_rewards del_reward ve' world s
      Hwf_w Hwf_s Hacc Hvid Hstake Hcomm Hauth_plus Hdel_minus Happly) as [s' Hs'].
    unfold fn_rew, St.syscall_reward_function.
    eapply send_pack_make_succeeds;
      cbn [Evmc.Message.t.gas Evmc.Message.t.value Evmc.Message.t.sender
           Evmc.Message.t.input_data Evmc.Message.t.with_input_data];
      [exact Hgas | left; reflexivity | exact Hdec | rewrite Hval; exact Hs'].
Qed.

Lemma find_singleton_same {A : Set} k (v : A) :
  Chain.Ethereum.Address.Map.find_opt k
    (Chain.Ethereum.Address.Map.of_list ((k, v) :: nil)) = Some v.
Proof.
  exact (find_add_same nil k v empty_wellformed).
Qed.

Every Monad system transaction that passes systemTransactionChecks and satisfies validStakingSyscall validates and executes without error.
Theorem system_transaction_validates_and_executes block tx :
  WellFormed (W.t.accounts (B.t.world_state block)) →
  systemTransactionChecks tx
    (A.t.nonce (readAccount (B.t.world_state block) Chain.Monad.system_sender)) = true →
  @A.is_smart_contract (readAccount (B.t.world_state block) Chain.Monad.system_sender) = false →
  validStakingSyscall (B.t.world_state block) tx →
  ∃ post, @E.process_monad_system_transaction F block tx = inl post.
Proof.
  intros Hwf Hchecks Hcode Hvalid_sys.
  pose proof (@system_transaction_checks_validate F block tx Hchecks Hcode) as Hval_tx.
  assert (Hto : ∃ txImpl, tx = T.Legacy txImpl ∧
    txImpl.(T.legacy_tx.to_) = Some St.staking_address).
  { unfold systemTransactionChecks in Hchecks.
    repeat rewrite Bool.andb_true_iff in Hchecks.
    destruct Hchecks as [[[[Hto _] _] _] _].
    destruct tx as [txImpl| | |]; [|discriminate Hto..].
    destruct (txImpl.(T.legacy_tx.to_)) as [to_|] eqn:Hto_opt; [|discriminate Hto].
    apply bool_decide_eq_true_1 in Hto; subst to_.
    ∃ txImpl; split; [reflexivity | exact Hto_opt]. }
  unfold E.process_monad_system_transaction.
  rewrite Hval_tx.
  change (@Result.op_letdollar) with
    (fun (A Error C : Set) (first : A + Error) (next : A → C + Error) ⇒
      match first with inl value ⇒ next value | inr error ⇒ inr error end).
  change (@Result._return) with (fun (A Error : Set) (value : A) ⇒ @inl A Error value).
  change (@Result.when_) with (fun (Error : Set) (condition : bool) (failure : unit + Error) ⇒
    if condition then failure else inl tt).
  cbn beta iota zeta.
  match goal with
  | |- context [@TS.initialize_access_sets tx ?s ?precompiles] ⇒
      set (beforeVm := @TS.initialize_access_sets tx s precompiles)
  end.
  set (w0 := B.t.world_state block).
  set (updated := A.t.with_nonce
    (Numeric.U64.op_plus (A.t.nonce (readAccount w0 Chain.Monad.system_sender)) Numeric.U64.one)
    (readAccount w0 Chain.Monad.system_sender)).
  assert (Hwf_before : WellFormed (W.t.accounts (TS.t.world_state beforeVm))).
  { change (TS.t.world_state beforeVm) with
      (writeAccount false w0 Chain.Monad.system_sender updated).
    exact (@account_write_wellformed false w0 Chain.Monad.system_sender updated Hwf). }
  assert (Hacc_before :
    readAccount (TS.t.world_state beforeVm) St.staking_address = readAccount w0 St.staking_address).
  { change (TS.t.world_state beforeVm) with
      (writeAccount false w0 Chain.Monad.system_sender updated).
    rewrite (account_read_after_write false w0 Chain.Monad.system_sender updated
      St.staking_address Hwf).
    assert (Hneq_sys_st : String.eqb Chain.Monad.system_sender St.staking_address = false)
      by (vm_compute; reflexivity).
    rewrite Hneq_sys_st. reflexivity. }
  set (msg := @E.prepare_message F Chain.Monad.system_sender Gas.zero tx
    (TS.t.world_state beforeVm)).
  assert (Hmsg_props :
    Evmc.Message.t.kind msg = Evmc.Message.CallKind.Call ∧
    Evmc.Message.t.recipient msg = St.staking_address ∧
    Evmc.Message.t.gas msg = Gas.to_int64 Gas.zero ∧
    Evmc.Message.t.input_data msg = T.data tx ∧
    Evmc.Message.t.value msg = T.value tx).
  { destruct Hto as [txImpl [-> Hto_opt]].
    unfold msg, E.prepare_message, T.call_or_create_value, T.data, T.value.
    destruct txImpl; cbn in Hto_opt |- *; subst to_.
    repeat split; reflexivity. }
  destruct Hmsg_props as [Hkind [Hrecip [Hgas [Hdata Hval]]]].
  assert (Hcall_ok :
    Evmc.Result.StatusCode.is_success
      (Evmc.Result.t.status_code
        (fst (@E.Host.call_from_monad_system_transaction F msg beforeVm))) = true).
  { unfold E.Host.call_from_monad_system_transaction.
    cbv beta iota zeta delta [E.Instantiation Host.Instantiate.functor
      Host.Instantiate.Instantiate_result.Host Host.Instantiate.Host
      Host.Make.functor Host.Make.Make_result.call_from_monad_system_transaction
      Host.Make.call_from_monad_system_transaction].
    unfold Host.Make.call_impl, Host.Make.process_syscall.
    rewrite Hkind, Hrecip.
    cbn -[Chain.Ethereum.Address.Map.find_opt Chain.Ethereum.Address.Map.of_list
      MonadVM.Staking.staking_syscalls St.staking_address].
    match goal with
    | |- context [@Chain.Ethereum.Address.Map.find_opt ?T St.staking_address ?endpoints] ⇒
      destruct (@Chain.Ethereum.Address.Map.find_opt T St.staking_address endpoints)
        as [precompile|] eqn:Hfind
    end.
    2: { unfold Precompiles.Make.syscall_endpoints in Hfind.
         rewrite find_singleton_same in Hfind. discriminate Hfind. }
    apply find_singleton_value in Hfind as [_ ->].
    match goal with
    | |- context [St.staking_syscalls ?fb0 msg beforeVm] ⇒
      pose proof (staking_syscalls_succeeds
        fb0 w0 tx msg beforeVm Hwf Hwf_before Hacc_before Hgas Hdata Hval Hvalid_sys) as Hsys_ok;
      destruct (St.staking_syscalls fb0 msg beforeVm) as [res s1] eqn:Hsys
    end.
    cbn [fst] in Hsys_ok.
    cbn; unfold Monad.Make_Monad.when_; cbn.
    rewrite Hsys_ok; cbn.
    exact Hsys_ok. }
  fold msg.
  destruct (@E.Host.call_from_monad_system_transaction F msg beforeVm) as [result afterVm].
  cbn [fst] in Hcall_ok.
  rewrite Hcall_ok; cbn [negb].
  eexists; reflexivity.
Qed.

Frame properties of any succeeding Monad system transaction.
Theorem process_monad_system_transaction_frame block tx post :
  WellFormed (W.t.accounts (B.t.world_state block)) →
  @E.process_monad_system_transaction F block tx = inl post →
  WellFormed (W.t.accounts (B.t.world_state post)) ∧
  W.t.history (B.t.world_state post) = W.t.history (B.t.world_state block) ∧
  W.t.next_emptying_transaction_block (B.t.world_state post) =
    W.t.next_emptying_transaction_block (B.t.world_state block) ∧
  B.t.current_block post = B.t.current_block block ∧
  (∀ query,
    A.t.code (readAccount (B.t.world_state post) query) =
      A.t.code (readAccount (B.t.world_state block) query)) ∧
  (∀ query,
    @A.is_smart_contract (readAccount (B.t.world_state post) query) =
      @A.is_smart_contract (readAccount (B.t.world_state block) query)) ∧
  (∀ query,
    A.t.nonce (readAccount (B.t.world_state post) query) =
      if String.eqb Chain.Monad.system_sender query
      then @Numeric.U64.op_plus
             (A.t.nonce (readAccount (B.t.world_state block) query))
             (@Numeric.U64.one)
      else A.t.nonce (readAccount (B.t.world_state block) query)) ∧
  (∀ query,
    St.staking_address ≠ query →
    U.to_z (A.t.balance (readAccount (B.t.world_state post) query)) =
      U.to_z (A.t.balance (readAccount (B.t.world_state block) query))) ∧
  (∀ query,
    St.staking_address ≠ query →
    Chain.Monad.system_sender ≠ query →
    A.t.balance (readAccount (B.t.world_state post) query) =
      A.t.balance (readAccount (B.t.world_state block) query) ∧
    A.t.storage (readAccount (B.t.world_state post) query) =
      A.t.storage (readAccount (B.t.world_state block) query)).
Proof.
  intros Hwf Hrun.
  pose proof (@process_monad_system_transaction_current_block F block tx post Hrun) as Hblk.
  unfold E.process_monad_system_transaction in Hrun.
  destruct (@E.validate_monad_system_transaction F block tx Chain.Monad.system_sender)
    as [[]|err] eqn:Hvalid; [|discriminate Hrun].
  change (@Result.op_letdollar) with
    (fun (A Error C : Set) (r : A + Error) (f : A → C + Error) ⇒
      match r with inl value ⇒ f value | inr error ⇒ inr error end) in Hrun.
  cbn beta iota zeta in Hrun.
  match type of Hrun with
  | context [@TS.initialize_access_sets tx ?s ?precompiles] ⇒
      set (beforeVm := @TS.initialize_access_sets tx s precompiles) in ×
  end.
  set (w0 := B.t.world_state block).
  set (sender := Chain.Monad.system_sender).
  set (updated := A.t.with_nonce
    (Numeric.U64.op_plus (A.t.nonce (readAccount w0 sender)) Numeric.U64.one)
    (readAccount w0 sender)).
  assert (Hbefore_world :
    TS.t.world_state beforeVm = writeAccount false w0 sender updated) by reflexivity.
  assert (Hwf_before : WellFormed (W.t.accounts (TS.t.world_state beforeVm))).
  { rewrite Hbefore_world. exact (@account_write_wellformed false w0 sender updated Hwf). }
  assert (Hhist_before : W.t.history (TS.t.world_state beforeVm) = W.t.history w0)
    by reflexivity.
  assert (Hcounters_before :
    W.t.next_emptying_transaction_block (TS.t.world_state beforeVm) =
      W.t.next_emptying_transaction_block w0) by reflexivity.
  assert (Hcode_before : ∀ query,
    A.t.code (readAccount (TS.t.world_state beforeVm) query) =
      A.t.code (readAccount w0 query)).
  { intro query. rewrite Hbefore_world.
    eapply eq_trans; [apply code_after_account_write, Hwf |].
    destruct (String.eqb sender query) eqn:Heq.
    - apply String.eqb_eq in Heq; subst query. reflexivity.
    - reflexivity. }
  assert (Hnonce_before : ∀ query,
    A.t.nonce (readAccount (TS.t.world_state beforeVm) query) =
      if String.eqb sender query
      then Numeric.U64.op_plus (A.t.nonce (readAccount w0 query)) Numeric.U64.one
      else A.t.nonce (readAccount w0 query)).
  { intro query. rewrite Hbefore_world.
    eapply eq_trans; [apply nonce_after_account_write, Hwf |].
    destruct (String.eqb sender query) eqn:Heq.
    - apply String.eqb_eq in Heq; subst query. reflexivity.
    - reflexivity. }
  assert (Hbal_before : ∀ query,
    U.to_z (A.t.balance (readAccount (TS.t.world_state beforeVm) query)) =
      U.to_z (A.t.balance (readAccount w0 query))).
  { intro query. rewrite Hbefore_world.
    eapply eq_trans; [apply balance_after_account_write, Hwf |].
    destruct (String.eqb sender query) eqn:Heq.
    - apply String.eqb_eq in Heq; subst query. reflexivity.
    - reflexivity. }
  assert (Hother_before : ∀ query,
    sender ≠ query →
    readAccount (TS.t.world_state beforeVm) query = readAccount w0 query).
  { intros query Hne. rewrite Hbefore_world.
    eapply eq_trans; [apply account_read_after_write, Hwf |].
    apply String.eqb_neq in Hne; rewrite Hne. reflexivity. }
  match type of Hrun with
  | context [E.Host.call_from_monad_system_transaction ?message beforeVm] ⇒
      set (msg := message) in *;
      destruct (@validate_monad_system_transaction_is_call F block tx sender Hvalid
        Gas.zero (TS.t.world_state beforeVm)) as [Hkind _];
      change (Evmc.Message.t.kind msg = Evmc.Message.CallKind.Call) in Hkind;
      pose proof (@call_from_monad_system_transaction_state_cases F msg beforeVm Hkind) as Hcases;
      destruct (E.Host.call_from_monad_system_transaction msg beforeVm) as [result afterVm]
  end.
  cbn [snd] in Hcases.
  unfold Result.when_ in Hrun.
  destruct (negb (Evmc.Result.StatusCode.is_success (Evmc.Result.t.status_code result)));
    [discriminate Hrun |].
  injection Hrun as <-.
  change (B.t.world_state (E.append_transaction_receipt
    (B.t.with_world_state (TS.t.world_state afterVm) block) tx result afterVm))
    with (TS.t.world_state afterVm).
  assert (Hafter_frame :
    WellFormed (W.t.accounts (TS.t.world_state afterVm)) ∧
    W.t.history (TS.t.world_state afterVm) = W.t.history (TS.t.world_state beforeVm) ∧
    W.t.next_emptying_transaction_block (TS.t.world_state afterVm) =
      W.t.next_emptying_transaction_block (TS.t.world_state beforeVm) ∧
    ∀ query,
      A.t.nonce (readAccount (TS.t.world_state afterVm) query) =
        A.t.nonce (readAccount (TS.t.world_state beforeVm) query) ∧
      A.t.code (readAccount (TS.t.world_state afterVm) query) =
        A.t.code (readAccount (TS.t.world_state beforeVm) query) ∧
      (St.staking_address ≠ query →
        A.t.balance (readAccount (TS.t.world_state afterVm) query) =
          A.t.balance (readAccount (TS.t.world_state beforeVm) query) ∧
        A.t.storage (readAccount (TS.t.world_state afterVm) query) =
          A.t.storage (readAccount (TS.t.world_state beforeVm) query))).
  { destruct Hcases as [-> | [fb0 ->]].
    - refine (conj Hwf_before (conj eq_refl (conj eq_refl _))).
      intro query; repeat split; reflexivity.
    - destruct (staking_syscalls_uframe fb0 msg beforeVm) as [Huf | Huf].
      + destruct Huf as [Hctx [_ [Hacc_uf _]]].
        destruct Hctx as [_ [_ [_ [_ [_ [_ [_ [_ [_ [_ [_ [Hh Hc]]]]]]]]]]]].
        destruct (Hacc_uf Hwf_before) as [Hwf_after Hq].
        refine (conj Hwf_after (conj Hh (conj Hc _))).
        intro query.
        destruct (Hq query) as [Hbal [Hnonce [Hcode Hstor]]].
        refine (conj Hnonce (conj Hcode _)).
        intro Hne; exact (conj Hbal (Hstor Hne)).
      + pose proof (creditStakingAccount_fields (Evmc.Message.t.value msg) beforeVm)
          as [Hctx1 [_ [_ Hacc1]]].
        destruct Hctx1 as [_ [_ [_ [_ [_ [_ [_ [_ [_ [_ [_ [Hh1 Hc1]]]]]]]]]]]].
        destruct (Hacc1 Hwf_before) as [Hwf_cred Hq1].
        destruct Huf as [Hctx2 [_ [Hacc2 _]]].
        destruct Hctx2 as [_ [_ [_ [_ [_ [_ [_ [_ [_ [_ [_ [Hh2 Hc2]]]]]]]]]]]].
        destruct (Hacc2 Hwf_cred) as [Hwf_after Hq2].
        refine (conj Hwf_after (conj (eq_trans Hh2 Hh1) (conj (eq_trans Hc2 Hc1) _))).
        intro query.
        destruct (Hq1 query) as [Hnonce1 [Hcode1 Hother1]].
        destruct (Hq2 query) as [Hbal2 [Hnonce2 [Hcode2 Hstor2]]].
        refine (conj (eq_trans Hnonce2 Hnonce1) (conj (eq_trans Hcode2 Hcode1) _)).
        intro Hne.
        destruct (Hother1 Hne) as [Hbal1 Hstor1].
        exact (conj (eq_trans Hbal2 Hbal1) (eq_trans (Hstor2 Hne) Hstor1)). }
  destruct Hafter_frame as [Hwf_after [Hh_after [Hc_after Hq_after]]].
  refine (conj Hwf_after
    (conj (eq_trans Hh_after Hhist_before)
    (conj (eq_trans Hc_after Hcounters_before)
    (conj Hblk _)))).
  split.
  - intro query. rewrite (proj1 (proj2 (Hq_after query))). exact (Hcode_before query).
  - split.
    + intro query.
      pose proof (eq_trans (proj1 (proj2 (Hq_after query))) (Hcode_before query)) as Hcode_eq.
      destruct (readAccount (TS.t.world_state afterVm) query), (readAccount w0 query).
      cbn in Hcode_eq. subst. reflexivity.
    + split.
      × intro query. rewrite (proj1 (Hq_after query)). exact (Hnonce_before query).
      × split.
        -- intros query Hne.
           rewrite (proj1 (proj2 (proj2 (Hq_after query)) Hne)).
           exact (Hbal_before query).
        -- intros query Hne_st Hne_sys.
           destruct (proj2 (proj2 (Hq_after query)) Hne_st) as [Hbal_a Hstor_a].
           rewrite Hbal_a, Hstor_a, (Hother_before query Hne_sys).
           split; reflexivity.
Qed.

Dispatching a transaction whose recovered sender is Chain.Monad.system_sender and which passes systemTransactionChecks takes the system-transaction path.
Lemma system_sender_dispatch_eq tx expectedNonce :
  transactionSender tx = Some Chain.Monad.system_sender →
  systemTransactionChecks tx expectedNonce = true →
  @E.sender_kind_value F tx = Some E.System ∧
  @E.is_system_transaction F tx = true ∧
  ∀ block,
    @E.dispatch_transaction F block tx = @E.process_monad_system_transaction F block tx.
Proof.
  intros Hsender Hchecks.
  unfold systemTransactionChecks in Hchecks.
  repeat rewrite Bool.andb_true_iff in Hchecks.
  destruct Hchecks as [[[[Hto _] _] _] _].
  destruct tx as [txImpl| | |]; [|discriminate Hto..].
  unfold E.dispatch_transaction, E.is_system_transaction, E.sender_kind_value.
  cbn [T.chain_id].
  fold (transactionSender (T.Legacy txImpl)).
  rewrite Hsender.
  assert (Heq : Chain.Ethereum.Address.op_eq Chain.Monad.system_sender Chain.Monad.system_sender = true)
    by (vm_compute; reflexivity).
  rewrite Heq.
  repeat split; reflexivity.
Qed.

Dispatching a transaction whose recovered sender is not Chain.Monad.system_sender and which passes transactionChecks takes the EOA user-transaction path.
Lemma user_sender_dispatch_eq header tx sender expectedNonce :
  transactionSender tx = Some sender →
  sender ≠ Chain.Monad.system_sender →
  transactionChecks header tx expectedNonce = true →
  @E.sender_kind_value F tx = Some (E.EOA sender) ∧
  @E.is_system_transaction F tx = false ∧
  ∀ block,
    @E.dispatch_transaction F block tx = @E.process_transaction F block tx.
Proof.
  intros Hsender Hne Hchecks.
  rewrite transaction_checks_native in Hchecks.
  repeat rewrite Bool.andb_true_iff in Hchecks.
  destruct Hchecks as [[[[[[[[Hchain _] _] _] _] _] _] _] _].
  apply Bool.negb_true_iff in Hchain.
  assert (Heq : Chain.Ethereum.Address.op_eq sender Chain.Monad.system_sender = false).
  { change (Z.eqb (OCamlString.compare sender Chain.Monad.system_sender) 0 = false).
    destruct (Z.eqb_spec (OCamlString.compare sender Chain.Monad.system_sender) 0) as [Hz|];
      [|reflexivity].
    exfalso; apply Hne, reservecheck.address_compare_eq, Hz. }
  unfold E.dispatch_transaction, E.is_system_transaction, E.sender_kind_value.
  fold (transactionSender tx).
  destruct (T.chain_id tx) as [cid|];
    cbn beta iota zeta in Hchain |- *;
    try rewrite Hchain;
    rewrite Hsender, Heq;
    repeat split; reflexivity.
Qed.

End DispatchAndFrame.