Library SetcodeConcrete.consensuscorrectnessproofs

Proofs of the SETCODE consensus guarantees

The entry page defines setcodeConsensusCorrect. This file proves that exact proposition and retains the previous match-on-result formulation, with an equivalence proof. No premise or execution behavior is changed.
Require Export SetcodeConcrete.consensuscorrectness.
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 Export SetcodeConcrete.consensusresources SetcodeConcrete.rechecking.
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.consensusresourcesproofs SetcodeConcrete.miscblockproofs
  SetcodeConcrete.transactionbudget SetcodeConcrete.blockbudget
  SetcodeConcrete.windowbudget.
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 check_blocks_app {F : E.FArgs} snapshot previous prefix suffix :
  checkBlocks snapshot previous (prefix ++ suffix) =
    match checkBlocks snapshot previous prefix with
    | Some middle ⇒ checkBlocks snapshot middle suffix
    | None ⇒ None
    end.
Proof.
  revert previous. induction prefix as [|block prefix IH]; intro previous; [reflexivity|].
  cbn [app checkBlocks].
  match goal with |- context [checkTransactions ?s ?h ?p ?txs] ⇒
    destruct (checkTransactions s h p txs) as [next|]
  end; [apply IH|reflexivity].
Qed.

Lemma consensus_accepts_prefix {F : E.FArgs} snapshot height past rest :
  consensusAccepts snapshot height (past ++ rest) →
  consensusAccepts snapshot height past.
Proof.
  intros [next Hcheck]. rewrite check_blocks_app in Hcheck.
  destruct (checkBlocks snapshot (initialAdmission snapshot height) past)
    as [middle|] eqn:Hpast; [∃ middle; exact Hpast|discriminate Hcheck].
Qed.

Lemma window_transactions_app past rest :
  windowTransactions (past ++ rest) =
    windowTransactions past ++ windowTransactions rest.
Proof.
  unfold windowTransactions.
  rewrite map_app, concat_app.
  reflexivity.
Qed.

Lemma blocks_avoid_sender_creation_prefix {F : E.FArgs} senders verify world past rest :
  blocksAvoidSenderCreation senders verify world (past ++ rest) →
  blocksAvoidSenderCreation senders verify world past.
Proof.
  revert world. induction past as [|block past IH]; intros world Hcreation; [exact I|].
  destruct Hcreation as [Hhead Htail].
  split; [exact Hhead|].
  intros post Hrun. exact (IH post (Htail post Hrun)).
Qed.

Lemma blocks_avoid_sender_creation_suffix {F : E.FArgs} senders verify world past rest post :
  blocksAvoidSenderCreation senders verify world (past ++ rest) →
  Result.List.fold_leftM (E.process_block verify) world past = inl post →
  blocksAvoidSenderCreation senders verify post rest.
Proof.
  revert world. induction past as [|block past IH]; intros world Hcreation Hrun.
  - injection Hrun as <-. exact Hcreation.
  - destruct Hcreation as [_ Htail].
    change (match E.process_block verify world block with
      | inl after ⇒ Result.List.fold_leftM (E.process_block verify) after past
      | inr err ⇒ inr err
      end = inl post) in Hrun.
    destruct (E.process_block verify world block) as [after|err] eqn:Hstep;
      [|discriminate Hrun].
    exact (IH after (Htail after eq_refl) Hrun).
Qed.

Lemma process_blocks_app {F : E.FArgs} verify world past rest :
  Result.List.fold_leftM (E.process_block verify) world (past ++ rest) =
    match Result.List.fold_leftM (E.process_block verify) world past with
    | inl middle ⇒ Result.List.fold_leftM (E.process_block verify) middle rest
    | inr err ⇒ inr err
    end.
Proof.
  revert world. induction past as [|block past IH]; intro world; [reflexivity|].
  change (Result.List.fold_leftM (E.process_block verify) world ((block :: past) ++ rest))
    with (match E.process_block verify world block with
          | inl next ⇒ Result.List.fold_leftM (E.process_block verify) next (past ++ rest)
          | inr err ⇒ inr err
          end).
  change (Result.List.fold_leftM (E.process_block verify) world (block :: past))
    with (match E.process_block verify world block with
          | inl next ⇒ Result.List.fold_leftM (E.process_block verify) next past
          | inr err ⇒ inr err
          end).
  destruct (E.process_block verify world block) as [next|err]; [apply IH|reflexivity].
Qed.

Lemma resource_window_conditions_prefix {F : E.FArgs} senders snapshot past rest :
  ResourceWindowConditions senders snapshot (past ++ rest) →
  ResourceWindowConditions senders snapshot past.
Proof.
  intros [Hinputs Hbal Hfmt Hsupply Hsys [Hhalf HnonceBudget] HnotNative Hsenders].
  apply Forall_app in Hinputs as [HpastInputs HrestInputs].
  rewrite window_credits_app in Hsupply.
  pose proof (window_credits_nonnegative rest HrestInputs) as HrestCredits.
  rewrite window_nonce_budget_app in HnonceBudget.
  pose proof (window_nonce_budget_nonnegative rest) as HrestNonce.
  rewrite window_transactions_app in Hsenders.
  apply Forall_app in Hsenders as [HpastSenders _].
  constructor; try assumption; [lia|].
  constructor; [exact Hhalf|lia].
Qed.

Lemma setcode_window_conditions_prefix {F : E.FArgs} senders until verify snapshot past rest :
  SetcodeWindowConditions senders until verify snapshot (past ++ rest) →
  SetcodeWindowConditions senders until verify snapshot past.
Proof.
  intros [Hres Hcfg Hcnt Helig Hsigs Hheights Hcreation].
  rewrite window_transactions_app in Hsigs.
  apply Forall_app in Hsigs as [HpastSigs _].
  apply Forall_app in Hheights as [HpastHeights _].
  constructor; try assumption.
  - exact (resource_window_conditions_prefix senders snapshot past rest Hres).
  - exact (blocks_avoid_sender_creation_prefix senders verify snapshot past rest Hcreation).
Qed.

Section Consensus.
Context {F : E.FArgs}.
Context (cold warm access write reserve : N).

Whole-window transaction-validation safety for any verify flag, without requiring miscBlockChecks.
Definition setcodeWindowValidationSafety : Prop :=
  ∀ snapshot senders until verify height blocks,
    ResourceProtocolConditions cold warm access write reserve →
    SetcodeWindowConditions senders until verify snapshot blocks →
    consensusAccepts snapshot height blocks →
    ∀ details,
      Result.List.fold_leftM (E.process_block verify) snapshot blocks ≠
        inr (Execution.Error.Invalid_transaction details).

Theorem consensus_window_validates : setcodeWindowValidationSafety.
Proof.
  intros snapshot senders until verify height blocks Hprotocol Hwindow Hadmit details.
  destruct Hprotocol as [Hrevision Hcold Hwarm Hhash Hsha Hg1 Hg2 Hchain].
  destruct Hwindow as [[Hinputs Hbal Hfmt Hsupply Hsys Hnonces HnotNative Hsenders]
    Hcfg Hcnt Helig Hsigs Hheights Hcreation].
  exact (consensus_window_no_transaction_error cold warm access write reserve
    Hrevision Hcold Hwarm Hhash Hsha Hg1 Hg2 Hchain
    verify snapshot height blocks senders until details
    HnotNative Hsys Hbal Hfmt Hcfg Hcnt Helig Hnonces Hinputs
    Hsigs Hsenders Hheights Hcreation Hsupply Hadmit).
Qed.

Theorem consensus_prefix_retains_backing snapshot senders until verify height past rest :
  ResourceProtocolConditions cold warm access write reserve →
  SetcodeWindowConditions senders until verify snapshot (past ++ rest) →
  consensusAccepts snapshot height (past ++ rest) →
  match Result.List.fold_leftM (E.process_block verify) snapshot past with
  | inl post ⇒
      RemainingWindowInvariant senders until verify snapshot height past rest post
  | inr (Execution.Error.Invalid_transaction _) ⇒ False
  | inr (Execution.Error.Invalid_block _) ⇒ True
  end.
Proof.
  intros Hprotocol Hwindow Hadmit.
  pose proof (setcode_window_conditions_prefix senders until verify snapshot past rest Hwindow)
    as HpastWindow.
  pose proof (consensus_accepts_prefix snapshot height past rest Hadmit) as HpastAdmit.
  pose proof (consensus_preserves_resource_bounds cold warm access write reserve
    snapshot senders verify height past rest Hprotocol
    (window_resources _ _ _ _ _ Hwindow) Hadmit) as HresBounds.
  destruct (Result.List.fold_leftM (E.process_block verify) snapshot past)
    as [post|[blockErr|txDetails]] eqn:Hrun.
  - constructor.
    + exact HresBounds.
    + destruct Hadmit as [next Hcheck].
      rewrite check_blocks_app in Hcheck.
      destruct (checkBlocks snapshot (initialAdmission snapshot height) past)
        as [middle|] eqn:HcheckPast; [|discriminate Hcheck].
      ∃ middle, next.
      split; [reflexivity|split; [exact Hcheck|]].
      destruct Hprotocol as [Hrevision Hcold Hwarm Hhash Hsha Hg1 Hg2 Hchain].
      destruct HpastWindow as [[Hinputs Hbal Hfmt Hsupply Hsys _ HnotNative Hsenders]
        Hcfg Hcnt Helig Hsigs Hheights Hcreation].
      pose proof (initial_window_budget_backing snapshot height senders until
        Hsys Hbal Hfmt Hcfg Hcnt Helig) as HinitBacking.
      pose proof (checked_blocks_window_budget_backing cold warm access write reserve
        Hrevision Hcold Hwarm Hhash Hsha Hg1 Hg2 Hchain verify snapshot
        (initialAdmission snapshot height) middle snapshot past senders until
        HnotNative Hsys (proj2 (proj2 (proj2 Hcfg))) Hinputs Hsigs Hsenders
        Hheights Hcreation Hsupply HinitBacking HcheckPast) as HpastBacking.
      rewrite Hrun in HpastBacking.
      exact (proj1 HpastBacking).
    + exact (blocks_avoid_sender_creation_suffix senders verify snapshot past rest post
        (window_creation _ _ _ _ _ Hwindow) Hrun).
  - exact I.
  - exact (consensus_window_validates snapshot senders until verify height past
      Hprotocol HpastWindow HpastAdmit txDetails Hrun).
Qed.

Main SETCODE prefix execution theorem: under ResourceProtocolConditions, SetcodeWindowConditions, miscBlockChecks and consensusAccepts for past ++ rest, executing past with verify = false cannot fail with either Invalid_transaction or Invalid_block, and returns a state post satisfying RemainingWindowInvariant and miscBlockChecks post rest = true.
Definition setcodeConsensusCorrectMatch : Prop :=
  ∀ snapshot senders until height past rest,
    ResourceProtocolConditions cold warm access write reserve →
    SetcodeWindowConditions senders until false snapshot (past ++ rest) →
    miscBlockChecks snapshot (past ++ rest) = true →
    consensusAccepts snapshot height (past ++ rest) →
    match Result.List.fold_leftM (E.process_block false) snapshot past with
    | inl post ⇒
        RemainingWindowInvariant senders until false snapshot height past rest post ∧
        miscBlockChecks post rest = true
    | inr (Execution.Error.Invalid_transaction _) ⇒ False
    | inr (Execution.Error.Invalid_block _) ⇒ False
    end.

Theorem setcode_consensus_correct_match : setcodeConsensusCorrectMatch.
Proof.
  intros snapshot senders until height past rest Hprotocol Hwindow Hmisc Hadmit.
  pose proof (consensus_prefix_retains_backing snapshot senders until false height past rest
    Hprotocol Hwindow Hadmit) as Hbacking.
  pose proof (misc_checks_prefix_execution cold warm access write reserve snapshot past rest
    (resource_revision _ _ _ _ _ Hprotocol) Hmisc) as HmiscStep.
  destruct (Result.List.fold_leftM (E.process_block false) snapshot past)
    as [post|[blockErr|txDetails]].
  - exact (conj Hbacking HmiscStep).
  - exact HmiscStep.
  - exact Hbacking.
Qed.

The existential statement on the entry page is logically equivalent to the previous statement that excludes both error constructors.
Lemma setcode_consensus_correct_equiv :
  setcodeConsensusCorrect cold warm access write reserve ↔ setcodeConsensusCorrectMatch.
Proof.
  unfold setcodeConsensusCorrect, setcodeConsensusCorrectMatch, executeBlocks.
  split; intros H snapshot senders until height past rest Hp Hw Hm Ha;
    specialize (H snapshot senders until height past rest Hp Hw Hm Ha).
  - destruct H as [post [Hrun Hpost]]. rewrite Hrun. exact Hpost.
  - destruct (Result.List.fold_leftM (E.process_block false) snapshot past)
      as [post|[blockErr|txDetails]] eqn:Hrun.
    + ∃ post. split; [reflexivity|exact H].
    + contradiction.
    + contradiction.
Qed.

Theorem setcode_consensus_correct :
  setcodeConsensusCorrect cold warm access write reserve.
Proof.
  apply (proj2 setcode_consensus_correct_equiv).
  exact setcode_consensus_correct_match.
Qed.

Whole-window successful execution corollary: an admitted SETCODE window passing miscBlockChecks executes to a concrete post-state post without any block or transaction-validation error.
Corollary setcode_consensus_window_executes snapshot senders until height blocks :
  ResourceProtocolConditions cold warm access write reserve →
  SetcodeWindowConditions senders until false snapshot blocks →
  miscBlockChecks snapshot blocks = true →
  consensusAccepts snapshot height blocks →
  ∃ post,
    Result.List.fold_leftM (E.process_block false) snapshot blocks = inl post ∧
    RemainingWindowInvariant senders until false snapshot height blocks [] post.
Proof.
  intros Hprotocol Hwindow Hmisc Hadmit.
  pose proof (setcode_consensus_correct snapshot senders until height blocks []) as Hmain.
  rewrite app_nil_r in Hmain.
  destruct (Hmain Hprotocol Hwindow Hmisc Hadmit) as [post [Hrun [Hinv _]]].
  ∃ post. exact (conj Hrun Hinv).
Qed.

Suffix execution from an already-reached prefix state post: even when a sender adopts regular code during past (causing fresh admission from post to reject rest by regular_sender_prevents_fresh_admission), retaining the original admission guarantees that rest executes from post without error.
Corollary setcode_suffix_executes_from_prefix snapshot senders until height past rest post :
  ResourceProtocolConditions cold warm access write reserve →
  SetcodeWindowConditions senders until false snapshot (past ++ rest) →
  miscBlockChecks snapshot (past ++ rest) = true →
  consensusAccepts snapshot height (past ++ rest) →
  Result.List.fold_leftM (E.process_block false) snapshot past = inl post →
  ∃ final,
    Result.List.fold_leftM (E.process_block false) post rest = inl final ∧
    RemainingWindowInvariant senders until false snapshot height (past ++ rest) [] final.
Proof.
  intros Hprotocol Hwindow Hmisc Hadmit HpastRun.
  destruct (setcode_consensus_window_executes snapshot senders until height (past ++ rest)
    Hprotocol Hwindow Hmisc Hadmit) as [final [HfullRun Hinv]].
  rewrite process_blocks_app, HpastRun in HfullRun.
  ∃ final. exact (conj HfullRun Hinv).
Qed.
End Consensus.

Print Assumptions consensus_window_validates.
Print Assumptions consensus_prefix_retains_backing.
Print Assumptions setcode_consensus_correct.
Print Assumptions setcode_consensus_window_executes.
Print Assumptions setcode_suffix_executes_from_prefix.