Library SetcodeConcrete.windowbudget

Whole-window reserve budget induction and transaction-validation safety

Inducts BlockBudgetBacking across an arbitrary list of admitted blocks in a 3-block consensus window. Because E.validate_block enforces consecutive block numbers against the head of W.t.history whenever transaction processing is reached, the height interval from .. until automatically advances with each finalized block without requiring a separate block-ordering assumption. Combining exclusion of Insufficient_balance with consensus_only_fee_validation_error proves that an admitted SETCODE window cannot fail with any Invalid_transaction error.
From Stdlib Require Import List String NArith ZArith Bool Lia.
Require Import RocqOfOCaml.RocqOfOCaml MonadVM.Execution.
Require Import QedkConcrete.worldaccounts QedkConcrete.validation
  QedkConcrete.publictransaction QedkConcrete.reservecheck
  QedkConcrete.reservestorage QedkConcrete.reserveencoding
  QedkConcrete.hoststoragewords QedkConcrete.hostaccountformat
  QedkConcrete.hashwords QedkConcrete.precompileoutputs
  QedkConcrete.blsmapbounds QedkConcrete.nativeinputs
  QedkConcrete.supply QedkConcrete.wordrange QedkConcrete.credits
  QedkConcrete.protectedstorage QedkConcrete.protectedstoragenative
  QedkConcrete.protectedstorageboundarycore QedkConcrete.blockentry
  QedkConcrete.transactionchecks.
Require Import SetcodeConcrete.consensuschecks SetcodeConcrete.reserve
  SetcodeConcrete.nonceagreement SetcodeConcrete.nonceagreementsequence
  SetcodeConcrete.activityagreement SetcodeConcrete.emptyingagreement
  SetcodeConcrete.blockcode SetcodeConcrete.blockconfig
  SetcodeConcrete.windowconfig SetcodeConcrete.blocknonceagreement
  SetcodeConcrete.blockactivityagreement SetcodeConcrete.blockemptyingagreement
  SetcodeConcrete.blocksupply SetcodeConcrete.windowsupply
  SetcodeConcrete.nativeoutputs SetcodeConcrete.windownonce
  SetcodeConcrete.windownonceagreement SetcodeConcrete.noncebudget
  SetcodeConcrete.consensusnonce SetcodeConcrete.consensusvalidation
  SetcodeConcrete.miscblockproofs SetcodeConcrete.transactionbudget
  SetcodeConcrete.blockbudget.
Import ListNotations.
Set Default Goal Selector "!".
Local Open Scope Z_scope.
#[local] Hint Extern 100 (Basics.Unreachable _) ⇒
  (apply Opaque.legacy_witness; Opaque.opaque_inhabit 64%nat) : typeclass_instances.

Module E := Execution.Make.
Module B := State.BlockState.
Module W := consensuschecks.W.
Module A := consensuschecks.A.
Module T := consensuschecks.T.
Module Addr := consensuschecks.Addr.
Module Block := consensuschecks.Block.
Local Abbreviation native := Reserve_balance.precompile_address.
Local Abbreviation accountAt := consensuschecks.accountAt.

Lemma validate_block_parent_number {F : E.FArgs} world parent history block :
  W.t.history world = parent :: history →
  E.validate_block world block = inl tt →
  Block.Header.t.number (Block.t.header block) =
    (Block.Header.t.number (Block.t.header parent) + 1)%N.
Proof.
  intros Hhist Hvalid.
  unfold E.validate_block in Hvalid.
  rewrite Hhist in Hvalid.
  change (@Result.List.hd) with
    (fun (A : Set) (fallback : A) (xs : list A) ⇒
      match xs with [] ⇒ fallback | x :: _ ⇒ x end) in Hvalid.
  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 Hvalid.
  change (@Result.when_) with
    (fun (Error : Set) (condition : bool) (failure : unit + Error) ⇒
      if condition then failure else inl tt) in Hvalid.
  cbn beta iota zeta in Hvalid.
  match type of Hvalid with context [if ?cond then _ else _] ⇒
    destruct cond eqn:Hcond end; [discriminate Hvalid|].
  change (negb (N.eqb (Block.Header.t.number (Block.t.header block))
    (Block.Header.t.number (Block.t.header parent) + 1)) = false) in Hcond.
  apply Bool.negb_false_iff, N.eqb_eq in Hcond.
  exact Hcond.
Qed.

Lemma processed_block_history_head {F : E.FArgs} cold warm access write reserve
    verify world block post :
  E.Params.(Execution.Make_Params_signature.revision) =
    Support.Variants.Revision.Setcode (cold, warm, access, write, reserve) →
  E.process_block verify world block = inl post →
  ∃ parent history,
    W.t.history post = parent :: history ∧
    Block.Header.t.number (Block.t.header parent) =
      Block.Header.t.number (Block.t.header block).
Proof.
  intros Hrevision Hrun.
  pose proof (processed_block_valid_header verify world block post Hrun) as Hvalid.
  unfold E.process_block in Hrun.
  rewrite Hrevision, Hvalid in Hrun.
  change (@Result.op_letdollar) with
    (fun (A B C : Set) (r : A + B) (f : A → C + B) ⇒
      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 [Result.List.fold_leftM ?step ?entry ?txs] ⇒
    change entry with (blockTransactionEntry world block) in Hrun end.
  destruct (Result.List.fold_leftM E.process_transaction
    (blockTransactionEntry world block) (Block.t.transactions block))
    as [afterTransactions|err] eqn:Htxs; [|discriminate Hrun].
  cbn beta iota zeta in Hrun.
  match type of Hrun with context [E.validate_block ?w ?b] ⇒
    destruct (E.validate_block w b) as [[]|error] end; [|discriminate Hrun].
  set (afterWithdrawals := Result.List.fold_left E.process_withdrawal
    afterTransactions (Block.t.withdrawals block)) in ×.
  assert (Hpost : post = W.t.with_history
    (B.finalize_current_block afterWithdrawals :: W.t.history world)
    (B.t.world_state afterWithdrawals)).
  { destruct verify.
    - match type of Hrun with context [match ?chk with inl _ ⇒ _ | inr _ ⇒ _ end] ⇒
        destruct chk as [[]|error] end; [|discriminate Hrun].
      injection Hrun as <-. reflexivity.
    - injection Hrun as <-. reflexivity. }
  ∃ (B.finalize_current_block afterWithdrawals), (W.t.history world).
  rewrite Hpost. split; [reflexivity|].
  change (Block.Header.t.number (Block.t.header (B.t.current_block afterWithdrawals)) =
    Block.Header.t.number (Block.t.header block)).
  unfold afterWithdrawals.
  rewrite withdrawals_current_block, (transactions_current_block _ _ _ Htxs),
    block_entry_current.
  reflexivity.
Qed.

Relate original consensus state previous to actual execution world at a block boundary. snapshot remains the original designated state; senders contains all transaction senders, and until is the upper height of the admitted window.
Result: there is a lower block height from, either 0 (initial bound) or the successor of the actual last executed block. BlockBudgetBacking holds through until: remaining budgets are covered by actual balances, unmigrated nonces match prediction, and configuration/activity facts needed by the next block's checks hold. This is proved after execution, not assumed as part of initial admission.
Definition WindowBudgetBacking {F : E.FArgs} (snapshot : W.t) (previous : AdmissionState)
    (world : W.t) (senders : list Addr.t) (until : N) : Prop :=
  ∃ from : N,
    (from = 0%N ∨ ∃ parent history,
      W.t.history world = parent :: history ∧
      (Block.Header.t.number (Block.t.header parent) + 1 = from)%N) ∧
    BlockBudgetBacking snapshot previous world senders from until.

Lemma window_budget_backing_from_valid_header {F : E.FArgs} snapshot previous
    world block senders until :
  WindowBudgetBacking snapshot previous world senders until →
  E.validate_block world block = inl tt →
  BlockBudgetBacking snapshot previous world senders
    (Block.Header.t.number (Block.t.header block)) until.
Proof.
  intros [from [Hparent Hbacking]] Hvalid.
  eapply block_budget_backing_weaken_from; [|exact Hbacking].
  destruct Hparent as [->|[parent [history [Hhist Hnum]]]].
  - apply N.le_0_l.
  - pose proof (validate_block_parent_number world parent history block Hhist Hvalid).
    lia.
Qed.

Theorem initial_block_budget_backing {F : E.FArgs} snapshot height senders from until :
  prescribedSystemCode snapshot →
  balanceInvariant snapshot →
  worldFormat snapshot →
  configStorageWellFormed snapshot →
  stringmaps.WellFormed (W.t.next_emptying_transaction_block snapshot) →
  (∀ a, In a senders → A.is_smart_contract (accountAt snapshot a) = false) →
  BlockBudgetBacking snapshot (initialAdmission snapshot height) snapshot senders from until.
Proof.
  intros Hsys Hbal Hfmt HcfgWf Hcounters Helig.
  constructor.
  - exact Hsys.
  - exact Hbal.
  - exact Hfmt.
  - exact HcfgWf.
  - exact (initial_nonce_agreement snapshot senders (proj1 Hbal) Helig).
  - exact (initial_activity_agreement snapshot until Hcounters).
  - exact (initial_empty_code_agreement snapshot senders).
  - intros target a _. reflexivity.
  - intros a _. cbn [initialAdmission admissionBudgets].
    pose proof (account_balance_bounded_by_supply snapshot a (proj1 (proj2 Hbal))) as HbalRange.
    pose proof (reserve_at_nonnegative snapshot height a (proj2 (proj2 (proj2 HcfgWf)))) as HresNonneg.
    change (0 ≤ balanceAt snapshot a ≤ totalBalance snapshot) in HbalRange.
    lia.
  - intros a _ _ Hempty. split; [exact Hempty|lia].
  - intros a Ha. right. left. exact (Helig a Ha).
Qed.

Theorem initial_window_budget_backing {F : E.FArgs} snapshot height senders until :
  prescribedSystemCode snapshot →
  balanceInvariant snapshot →
  worldFormat snapshot →
  configStorageWellFormed snapshot →
  stringmaps.WellFormed (W.t.next_emptying_transaction_block snapshot) →
  (∀ a, In a senders → A.is_smart_contract (accountAt snapshot a) = false) →
  WindowBudgetBacking snapshot (initialAdmission snapshot height) snapshot senders until.
Proof.
  intros Hsys Hbal Hfmt HcfgWf Hcounters Helig.
  ∃ 0%N. split; [left; reflexivity|].
  exact (initial_block_budget_backing snapshot height senders 0%N until
    Hsys Hbal Hfmt HcfgWf Hcounters Helig).
Qed.

Section Execution.
Context {F : E.FArgs}.
Context (cold warm access write reserve : N).
Context (Hrevision : E.Params.(Execution.Make_Params_signature.revision) =
  Support.Variants.Revision.Setcode (cold, warm, access, write, reserve)).
Context (Hcold : (0 < cold)%N) (Hwarm : (0 < warm)%N).
Context (Hhash : keccak256OutputSize) (Hsha : sha256OutputSize).
Context (Hg1 : blsG1CofactorOrder) (Hg2 : blsG2CofactorOrder).
Context (Hchain : wordRange (Support.UintN.to_z E.Params.(Execution.Make_Params_signature.chain_id))).

Theorem checked_blocks_window_budget_backing verify snapshot previous next
    world blocks senders until :
  (∀ a, In a senders → a ≠ native) →
  prescribedSystemCode snapshot →
  storageWords (A.t.storage (accountAt snapshot native)) →
  Forall BlockSupplyInputs blocks →
  Forall (fun tx ⇒ signaturesAvoidAddress tx native) (windowTransactions blocks) →
  Forall (fun tx ⇒ ∀ a,
    T.sender E.Params.(Execution.Make_Params_signature.chain_id) tx = Some a → In a senders)
    (windowTransactions blocks) →
  Forall (fun block ⇒
    (Block.Header.t.number (Block.t.header block) ≤ until <
      Block.Header.t.number (Block.t.header block) + 3)%N) blocks →
  blocksAvoidSenderCreation senders verify world blocks →
  totalBalance world + windowCredits blocks < 2^256 →
  WindowBudgetBacking snapshot previous world senders until →
  checkBlocks snapshot previous blocks = Some next →
  match Result.List.fold_leftM (E.process_block verify) world blocks with
  | inl post ⇒
      WindowBudgetBacking snapshot next post senders until ∧
      totalBalance post ≤ totalBalance world + windowCredits blocks
  | inr (Execution.Error.Invalid_transaction details) ⇒
      ∀ fee,
        Execution.Error.t.Invalid_transaction.reason details ≠
          Execution.Error.Insufficient_balance fee
  | inr (Execution.Error.Invalid_block _) ⇒ True
  end.
Proof using F Hchain Hcold Hg1 Hg2 Hhash Hrevision Hsha Hwarm access cold reserve warm write.
  intros HnotNative HsnapSystem HsnapWords Hinputs.
  pose proof (@setcode_native_output_bounds (@E.Instantiation_fargs F)
    (cold,warm,access,write,reserve) Hrevision Hsha Hg1 Hg2) as Hnative.
  revert previous world.
  induction Hinputs as [|block rest HblockInputs HrestInputs IH];
    intros previous world Hsigs Hsenders Hheights Hcreation Hsupply Hbacking Hcheck.
  - cbn [checkBlocks] in Hcheck. injection Hcheck as <-.
    cbn [Result.List.fold_leftM windowCredits Stdlib.Lists.List.fold_right].
    split; [exact Hbacking|lia].
  - change (windowTransactions (block :: rest)) with
      (Block.t.transactions block ++ windowTransactions rest) in Hsigs, Hsenders.
    apply Forall_app in Hsigs as [HblockSigs HrestSigs].
    apply Forall_app in Hsenders as [HblockSenders HrestSenders].
    inversion Hheights as [|? ? [HleUntil HltDelay] HrestHeights]; subst.
    destruct HblockInputs as [Hheader Hroot HtxBounds Hwithdrawals].
    assert (HblockTxs : Forall (fun tx ⇒
      transactionValueAndDataBounds tx ∧
      Forall (fun auth ⇒ OCamlString.length (T.Authorization.t.address auth) = 20)
        (T.authorization_list tx) ∧
      signaturesAvoidAddress tx native ∧
      (∀ a, T.sender E.Params.(Execution.Make_Params_signature.chain_id) tx = Some a →
        In a senders)) (Block.t.transactions block)).
    { clear -HtxBounds HblockSigs HblockSenders.
      induction (Block.t.transactions block) as [|tx txs IHtx]; [constructor|].
      inversion HtxBounds as [|? ? [Hv Hw] HtxBounds']; subst.
      inversion HblockSigs as [|? ? Hs HblockSigs']; subst.
      inversion HblockSenders as [|? ? Ha HblockSenders']; subst.
      constructor; [exact (conj Hv (conj Hw (conj Hs Ha)))|].
      exact (IHtx HtxBounds' HblockSigs' HblockSenders'). }
    cbn [checkBlocks] in Hcheck.
    match type of Hcheck with context [checkTransactions ?s ?h ?p ?txs] ⇒
      set (capped := p) in *;
      destruct (checkTransactions s h capped txs) as [middle|] eqn:Htxs end; [|discriminate Hcheck].
    destruct Hcreation as [HblockCreation HrestCreation].
    change (windowCredits (block :: rest)) with
      (blockCredits block + windowCredits rest) in Hsupply |- ×.
    pose proof (window_credits_nonnegative rest HrestInputs) as HrestCreditsNonneg.
    change (Result.List.fold_leftM (E.process_block verify) world (block :: rest)) with
      (match E.process_block verify world block with
       | inl after ⇒ Result.List.fold_leftM (E.process_block verify) after rest
       | inr err ⇒ inr err
       end).
    destruct (E.process_block verify world block) as [after|[blockErr|txDetails]] eqn:Hrun.
    + pose proof (processed_block_valid_header verify world block after Hrun) as Hvalid.
      pose proof (window_budget_backing_from_valid_header snapshot previous
        world block senders until Hbacking Hvalid) as HblockBacking.
      destruct (checked_block_budget_backing cold warm access write reserve
        Hrevision Hcold Hwarm Hhash Hnative verify snapshot previous middle
        world block after senders (Block.Header.t.number (Block.t.header block)) until
        Hchain Hheader Hroot HnotNative HsnapSystem HsnapWords HblockTxs Hwithdrawals
        ltac:(unfold blockCredits in Hsupply; lia) HblockCreation
        (N.le_refl _) HleUntil HltDelay HblockBacking Htxs Hrun)
        as [HafterBlockBacking HafterTotal].
      pose proof (processed_block_history_head cold warm access write reserve
        verify world block after Hrevision Hrun) as [parent [history [Hhist Hnum]]].
      assert (HafterWindowBacking : WindowBudgetBacking snapshot middle after senders until).
      { ∃ (Block.Header.t.number (Block.t.header block) + 1)%N.
        split; [|exact HafterBlockBacking].
        right. ∃ parent, history. split; [exact Hhist|lia]. }
      change (totalBalance after ≤ totalBalance world + blockCredits block) in HafterTotal.
      pose proof (IH middle after HrestSigs HrestSenders HrestHeights
        (HrestCreation after eq_refl) ltac:(lia) HafterWindowBacking Hcheck) as Htail.
      destruct (Result.List.fold_leftM (E.process_block verify) after rest)
        as [post|[blockErr|txDetails]]; [|exact I|exact Htail].
      destruct Htail as [HpostBacking HpostTotal].
      split; [exact HpostBacking|lia].
    + exact I.
    + cbn. intro fee.
      pose proof (transaction_error_has_valid_block_header verify world block txDetails Hrun) as Hvalid.
      pose proof (window_budget_backing_from_valid_header snapshot previous
        world block senders until Hbacking Hvalid) as HblockBacking.
      exact (checked_block_no_insufficient_balance cold warm access write reserve
        Hrevision Hcold Hwarm Hhash Hnative verify snapshot previous middle
        world block senders (Block.Header.t.number (Block.t.header block)) until
        txDetails fee Hchain Hheader Hroot HnotNative HsnapSystem HsnapWords
        HblockTxs HblockCreation (N.le_refl _) HleUntil HltDelay HblockBacking Htxs Hrun).
Qed.

Theorem consensus_window_no_transaction_error verify snapshot height blocks senders until details :
  (∀ a, In a senders → a ≠ native) →
  prescribedSystemCode snapshot →
  balanceInvariant snapshot →
  worldFormat snapshot →
  configStorageWellFormed snapshot →
  stringmaps.WellFormed (W.t.next_emptying_transaction_block snapshot) →
  (∀ a, In a senders → A.is_smart_contract (accountAt snapshot a) = false) →
  InitialNonceBounds senders snapshot blocks →
  Forall BlockSupplyInputs blocks →
  Forall (fun tx ⇒ signaturesAvoidAddress tx native) (windowTransactions blocks) →
  Forall (fun tx ⇒ ∀ a,
    T.sender E.Params.(Execution.Make_Params_signature.chain_id) tx = Some a → In a senders)
    (windowTransactions blocks) →
  Forall (fun block ⇒
    (Block.Header.t.number (Block.t.header block) ≤ until <
      Block.Header.t.number (Block.t.header block) + 3)%N) blocks →
  blocksAvoidSenderCreation senders verify snapshot blocks →
  totalBalance snapshot + windowCredits blocks < 2^256 →
  consensusAccepts snapshot height blocks →
  Result.List.fold_leftM (E.process_block verify) snapshot blocks ≠
    inr (Execution.Error.Invalid_transaction details).
Proof using F Hchain Hcold Hg1 Hg2 Hhash Hrevision Hsha Hwarm access cold reserve warm write.
  intros HnotNative Hsys Hbal Hfmt HcfgWf Hcounters Helig Hnonces Hinputs
    Hsigs Hsenders Hheights Hcreation Hsupply Hadmit Hrun.
  assert (Hwidth : Forall (fun block ⇒ Forall (fun tx ⇒ Forall
    (fun auth ⇒ OCamlString.length (T.Authorization.t.address auth) = 20)
    (T.authorization_list tx)) (Block.t.transactions block)) blocks).
  { eapply Forall_impl; [|exact Hinputs].
    intros block Hblk. eapply Forall_impl; [|exact (supply_transactions _ Hblk)].
    intros tx [_ Hw]. exact Hw. }
  destruct (consensus_only_fee_validation_error cold warm access write reserve
    Hrevision Hcold Hwarm verify snapshot height blocks senders details
    HnotNative Hwidth Hsenders Hsys Helig Hnonces Hcreation Hadmit Hrun)
    as [fee Hfee].
  destruct Hadmit as [next Hcheck].
  pose proof (initial_window_budget_backing snapshot height senders until
    Hsys Hbal Hfmt HcfgWf Hcounters Helig) as HinitBacking.
  pose proof (checked_blocks_window_budget_backing verify snapshot
    (initialAdmission snapshot height) next snapshot blocks senders until
    HnotNative Hsys (proj2 (proj2 (proj2 HcfgWf))) Hinputs Hsigs Hsenders
    Hheights Hcreation Hsupply HinitBacking Hcheck) as HnoFee.
  rewrite Hrun in HnoFee.
  exact (HnoFee fee Hfee).
Qed.
End Execution.

Print Assumptions initial_window_budget_backing.
Print Assumptions checked_blocks_window_budget_backing.
Print Assumptions consensus_window_no_transaction_error.