Library QedkConcrete.consensusadvance

The remaining blocks stay acceptable when execution catches up

Supporting proof for consensuscorrectness.consensusCorrect, which combines this result with transaction-validation safety. This file restarts consensus with the actual post-prefix accounts, configuration and history, rather than carrying the old snapshot.
From Stdlib Require Import List String ZArith Lia Bool.
Require Import RocqOfOCaml.RocqOfOCaml.
Require Export QedkConcrete.consensusrequirements.
Require Import MonadVM.Execution QedkConcrete.consensushistory
  QedkConcrete.consensushistoryproofs
  QedkConcrete.transactionnonces QedkConcrete.authorizationnonces
  QedkConcrete.transactionstage QedkConcrete.transactioncode
  QedkConcrete.transactionhistory QedkConcrete.authorizationcode
  QedkConcrete.transactionpersistentcode QedkConcrete.transactionchecked
  QedkConcrete.publictransaction QedkConcrete.protectedstorageboundary.
Require Import QedkConcrete.consensuswindow QedkConcrete.consensuswindowproofs
  QedkConcrete.consensusbudget QedkConcrete.transactionbudget
  QedkConcrete.transactionhistoryprojection QedkConcrete.supply
  QedkConcrete.assemblychecked QedkConcrete.hashwords QedkConcrete.wordrange
  QedkConcrete.hostaccountformat.
Require Import QedkConcrete.consensustransaction QedkConcrete.consensusbacking
  QedkConcrete.transactionformat.
Require Import QedkConcrete.blocktransactionentry QedkConcrete.consensusprefix
  QedkConcrete.blockpersistentcode QedkConcrete.consensusboundaries QedkConcrete.credits.
Require Import QedkConcrete.consensusblock QedkConcrete.prefixdecisions
  QedkConcrete.blockprefixstorage QedkConcrete.blocknumbers
  QedkConcrete.reservewindowtrace QedkConcrete.hoststoragewords.
Require Import QedkConcrete.precompileoutputs QedkConcrete.dispatchoutputs.
Require Import QedkConcrete.reservehash.
Require Import QedkConcrete.consensusblocks QedkConcrete.consensusrebase
  QedkConcrete.blockreservewindow.
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 S := State.TransactionState.
Module B := State.BlockState.
Module W := State.WorldState.
Module A := Chain.Ethereum.Account.
Module T := Chain.Ethereum.Transaction.
Module Addr := Chain.Ethereum.Address.

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

Local Abbreviation args := (@E.Instantiation_fargs F).
Local Abbreviation params := args.(Host.Instantiate.ChainParams).

Context {UI0 : Basics.Unreachable Support.UintN.Impl.t}
  {UB : Basics.Unreachable Bloom.t}
  {U8 : Basics.Unreachable Byte_string.B8.(Byte_string.Fixed.Fixed_result.t)}.

Local Abbreviation processTransaction := (@E.process_transaction F).
Local Abbreviation dispatchTransaction := (@E.dispatch_transaction F).
Local Abbreviation readAccount := (fun world addr ⇒ State.op_pointcaretlparenrparen
  world (@W.account None addr)).

Local Abbreviation native := (@Reserve_balance.precompile_address).
Local Abbreviation staking := (@MonadVM.Staking.staking_address).
Local Abbreviation systemSender := (@Chain.Monad.system_sender).

Local Abbreviation configured := (@Reserve_balance.user_reserve_balance).

Context {UBlock : Basics.Unreachable Chain.Ethereum.Block.t}
  {UTries : Basics.Unreachable (OCamlIarray.t Mpt.Trie.t)}
  {UChar : Basics.Unreachable OCamlChar.t} {UWorld : Basics.Unreachable W.t}
  {UTrie : Basics.Unreachable Mpt.Trie.t} {UNibbles : Basics.Unreachable Mpt.Nibbles.t}.
Local Abbreviation processBlock := (@E.process_block F).
Local Abbreviation blockEntry := (@blockTransactionEntry F).
Local Abbreviation height := (fun block ⇒ Chain.Ethereum.Block.Header.t.number
  (Chain.Ethereum.Block.t.header block)).

Local Abbreviation creationWindow := (@windowAvoidsSignerCreation F).
Local Abbreviation creationWindowPrefix := (@window_creation_safe_prefix F).
Local Abbreviation stakingWindow := (@windowValidStakingSyscalls F).
Local Abbreviation windowInduction := (@window_induction_under_configuration_agreement F UI0 UB U8).

Local Abbreviation blockInputs := (@consensusrequirements.blockInputs F).
Local Abbreviation txCredits := (fun txs ⇒ Lists.List.fold_right
  (fun tx subtotal ⇒ @systemTxCredit F tx + subtotal) 0 txs).
Local Abbreviation blockCredits := (fun block ⇒
  txCredits (Chain.Ethereum.Block.t.transactions block) +
  Lists.List.fold_right (fun wd subtotal ⇒ withdrawalWei wd + subtotal) 0
    (Chain.Ethereum.Block.t.withdrawals block)).
Local Abbreviation windowCredits := (@consensusconditions.windowCredits F).

Lemma ordered_block_numbers_prefix before after :
  orderedBlockNumbers (before ++ after) → orderedBlockNumbers before.
Proof.
  intros Horder prefix block suffix Hsplit.
  apply (Horder prefix block (suffix ++ after)). rewrite Hsplit, <- app_assoc. reflexivity.
Qed.

Lemma input_signature_exclusions signers until blocks :
  (∀ a, List.In a signers → a ≠ native) →
  Forall (blockInputs signers until) blocks →
  Forall (fun block ⇒ Forall (fun tx ⇒ @signaturesAvoidAddress F tx native)
    (Chain.Ethereum.Block.t.transactions block)) blocks.
Proof.
  intros Hnative Hinputs. eapply Forall_impl; [|exact Hinputs].
  intros block [_ [_ [_ [Htxs _]]]]. eapply Forall_impl; [|exact Htxs].
  intros tx [_ [_ [Hauth Hsender]]]. split.
  - intro Heq. exact (Hnative native (Hsender native Heq) eq_refl).
  - exact Hauth.
Qed.

Lemma ordered_window_configuration snapshot signers until verify blocks :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  worldFormat snapshot → balanceInvariant snapshot →
  A.t.code (readAccount snapshot native) = Byte_string.Bytes.empty →
  stringmaps.WellFormed (A.t.storage (readAccount snapshot native)) →
  (∀ a, List.In a signers → a ≠ native) →
  Forall (blockInputs signers until) blocks → orderedBlockNumbers blocks →
  ∀ before block after reached,
    blocks = before ++ block :: after →
    Result.List.fold_leftM (processBlock verify) snapshot before = inl reached →
    ∀ first last state,
      Chain.Ethereum.Block.t.transactions block = first ++ last →
      Result.List.fold_leftM dispatchTransaction (blockEntry reached block) first = inl state →
      ∀ a, List.In a signers → configured (B.t.world_state state) (height block) a =
        configured snapshot (height block) a.
Proof using F UChar UNibbles.
  intros Hrevision Hformat Hbalance Hcode Hstorage Hnative Hinputs Horder
    before block after reached Hsplit Hrun first last state Htxsplit Hprefix a Ha.
  pose proof (input_signature_exclusions signers until blocks Hnative Hinputs) as Hsignatures.
  rewrite Hsplit, Forall_app in Hsignatures. destruct Hsignatures as [Hbefore Hrest].
  pose proof (Forall_inv Hrest) as Htxs. cbv beta in Htxs.
  rewrite Htxsplit, Forall_app in Htxs.
  assert (Hcurrent : List.In block blocks).
  { rewrite Hsplit. apply in_or_app. right. left. reflexivity. }
  pose proof (proj1 (Forall_forall _ _) Hinputs block Hcurrent) as HcurrentInput.
  destruct HcurrentInput as [_ [_ [HcurrentTime _]]].
  assert (Htimes : Forall (fun b ⇒ (height b ≤ height block < height b + 3)%N) before).
  { pose proof (Horder before block after Hsplit) as Hordered.
    apply Forall_forall. intros b Hb.
    pose proof (proj1 (Forall_forall _ _) Hordered b Hb) as Hle.
    assert (Hin : List.In b blocks) by (rewrite Hsplit; apply in_or_app; left; exact Hb).
    pose proof (proj1 (Forall_forall _ _) Hinputs b Hin) as [_ [_ [Htime _]]]. cbv beta in Hle. lia. }
  exact (@window_prefix_configuration F UChar UNibbles
    verify before snapshot reached block first state a (height block) Hrevision (proj1 Hbalance)
    Hcode Hstorage (@read_account_storage_words snapshot native
      (proj1 (proj1 (world_format_components snapshot) Hformat)))
    Hbefore (proj1 Htxs) Htimes ltac:(lia) Hrun Hprefix).
Qed.

Section ApprovedCofactorOrders.
Hypothesis bls_g1_cofactor_order : @blsmapbounds.blsG1CofactorOrder .
Hypothesis bls_g2_cofactor_order : @blsmapbounds.blsG2CofactorOrder .

After a successfully executed prefix, restart the checker using that post-state. The suffix is proved accepted; it is not an input hypothesis. Empty blocks, configuration decreases, and delegated senders are allowed. Only transaction senders need the non-contract and creation exclusions; other authorization signers are not added to the protected list. Block-header/root errors remain possible; transaction-validation errors are excluded by the combined main theorem.
Theorem consensus_snapshot_advancement
    snapshot signers until verify past first rest initialHeight next post :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  keccak256OutputSize → sha256OutputSize →
  wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  worldFormat snapshot →
  (∀ a, List.In a signers → @A.is_smart_contract (readAccount snapshot a) = false) →
  (∀ a, List.In a signers → a ≠ native ∧ a ≠ staking) →
  Forall (blockInputs signers until) (past ++ first :: rest) →
  creationWindow signers verify snapshot (past ++ first :: rest) →
  stakingWindow verify snapshot (past ++ first :: rest) →
  balanceInvariant snapshot →
  stringmaps.WellFormed (W.t.next_emptying_transaction_block snapshot) →
  @prescribedSystemCode F snapshot →
  A.t.code (readAccount snapshot native) = Byte_string.Bytes.empty →
  stringmaps.WellFormed (A.t.storage (readAccount snapshot native)) →
  totalBalance snapshot + windowCredits (past ++ first :: rest) < 2^256 →
  checkBlocks snapshot (initialConsensusState snapshot initialHeight) (past ++ first :: rest) = Some next →
  orderedBlockNumbers (past ++ first :: rest) →
  Result.List.fold_leftM (processBlock verify) snapshot past = inl post →
  (∃ remaining,
    checkBlocks post (initialConsensusState post (height first)) (first :: rest) = Some remaining) ∧
  (∀ a, List.In a signers → @A.is_smart_contract (readAccount post a) = false) ∧
  balanceInvariant post ∧ worldFormat post ∧ @prescribedSystemCode F post ∧
  stringmaps.WellFormed (W.t.next_emptying_transaction_block post) ∧
  A.t.code (readAccount post native) = Byte_string.Bytes.empty ∧
  stringmaps.WellFormed (A.t.storage (readAccount post native)) ∧
  totalBalance post + windowCredits (first :: rest) < 2^256 ∧
  creationWindow signers verify post (first :: rest) ∧
  stakingWindow verify post (first :: rest).
Proof using All.
  intros Hrevision Hhash Hsha Hchain Hformat Hsnapshot Hnative Hinputs Hsafe Hstaking
    Hbalance Hcounters Hsystem Hcode Hstorage Hsupply Hcheck Horder Hrun.
  pose proof (@native_output_bounds_from_bls_maps args Hrevision Hsha
    (@bls_map_output_bounds_from_cofactor_orders args bls_g1_cofactor_order bls_g2_cofactor_order))
    as Houtputs.
  rewrite Forall_app in Hinputs. destruct Hinputs as [Hpast Hrest].
  rewrite check_blocks_app in Hcheck.
  destruct (checkBlocks snapshot (initialConsensusState snapshot initialHeight) past)
    as [middle|] eqn:HpastCheck; [|discriminate].
  pose proof (creationWindowPrefix signers verify snapshot past (first :: rest) Hsafe)
    as HpastSafe.
  assert (HpastSupply : totalBalance snapshot + windowCredits past < 2^256).
  { rewrite window_credits_app in Hsupply.
    pose proof (input_window_credits_nonnegative signers until _ Hrest). lia. }
  pose proof (ordered_window_configuration snapshot signers until verify past Hrevision Hformat
    Hbalance Hcode Hstorage (fun a Ha ⇒ proj1 (Hnative a Ha)) Hpast
    (ordered_block_numbers_prefix _ _ Horder)) as Hconfig.
  assert (Hinitial : BudgetBacking snapshot (initialConsensusState snapshot initialHeight)
    snapshot signers initialHeight until).
  { constructor.
    - apply initial_history_matches; [exact (proj1 Hbalance)|exact Hcounters|exact Hsnapshot].
    - intros a _. exact (@initial_budget_backed
        snapshot initialHeight Hbalance Hformat a).
    - intros; lia. }
  pose proof (windowInduction snapshot signers until verify past snapshot
    Hrevision Hhash Houtputs Hchain Hformat Hsnapshot Hnative Hpast HpastSafe
    _ middle initialHeight Hbalance Hformat Hsystem Hinitial HpastSupply Hconfig HpastCheck)
    as Hpreserved.
  rewrite Hrun in Hpreserved.
  destruct Hpreserved as [finalHeight [Hbacked [HpostBalance [HpostFormat [HpostSystem Htotal]]]]].
  pose proof (input_signature_exclusions signers until past
    (fun a Ha ⇒ proj1 (Hnative a Ha)) Hpast) as Hsignatures.
  destruct (@process_blocks_reserve_trace F
    verify past Hrevision Hsignatures snapshot post (proj1 Hbalance) Hcode Hrun)
    as [trace [Hheights [Htrace [_ HpostCode]]]].
  assert (HpostConfig : ∀ block, List.In block (first :: rest) → ∀ a,
    configured post (height block) a = configured snapshot (height block) a).
  { intros block Hin a.
    apply in_split in Hin as [before [after Hsplit]].
    pose proof (Horder (past ++ before) block after
      ltac:(rewrite <- app_assoc, <- Hsplit; reflexivity)) as Hprior.
    rewrite Forall_app in Hprior. destruct Hprior as [Hprior _].
    assert (Htarget : (height block ≤ until)%N).
    { pose proof (proj1 (Forall_forall _ _) Hrest block
        ltac:(rewrite Hsplit; apply in_or_app; right; left; reflexivity))
        as [_ [_ [Ht _]]]. lia. }
    assert (Htimes : Forall (fun step ⇒ (fst step ≤ height block < fst step + 3)%N) trace).
    { apply (proj1 (Forall_map fst (fun n ⇒ (n ≤ height block < n + 3)%N) trace)).
      change (Forall (fun n ⇒ (n ≤ height block < n + 3)%N) (Lists.List.map fst trace)).
      rewrite Hheights. apply (proj2 (Forall_map height _ past)).
      apply Forall_forall. intros b Hb.
      pose proof (proj1 (Forall_forall _ _) Hprior b Hb) as Hle.
      pose proof (proj1 (Forall_forall _ _) Hpast b Hb) as [_ [_ [Ht _]]].
      cbv beta in Hle. lia. }
    pose proof (reserve_trace_threshold_any_account _ _ _ a (height block) Hstorage
      (@read_account_storage_words snapshot native
        (proj1 (proj1 (world_format_components snapshot) Hformat))) Htrace Htimes) as Heq.
    unfold Reserve_balance.user_reserve_balance. f_equal. exact Heq. }
  split.
  - eapply backed_suffix_rechecks; [exact Hbacked|exact Hsnapshot| |exact Hcheck].
    apply Forall_forall. intros block Hin.
    pose proof (proj1 (Forall_forall _ _) Hrest block Hin) as [_ [_ [Ht [Htxs _]]]].
    split; [lia|]. split.
    + eapply Forall_impl; [|exact Htxs]. intros tx [_ [_ [Hauth Hsender]]]. auto.
    + intros a _. symmetry. exact (HpostConfig block Hin a).
  - split; [exact (history_noncontract _ _ _ _ _ (backing_history _ _ _ _ _ _ Hbacked))|].
    split; [exact HpostBalance|]. split; [exact HpostFormat|]. split; [exact HpostSystem|].
    split; [exact (history_counters_wf _ _ _ _ _ (backing_history _ _ _ _ _ _ Hbacked))|].
    split; [exact HpostCode|]. split.
    + exact (proj1 (reserve_trace_representation _ _ _ Hstorage
        (@read_account_storage_words snapshot native
          (proj1 (proj1 (world_format_components snapshot) Hformat))) Htrace)).
    + split.
      × rewrite window_credits_app in Hsupply. lia.
      × split.
        -- intros before block after reached Hsplit Hprefix.
           apply (Hsafe (past ++ before) block after reached).
           ++ rewrite <- app_assoc, <- Hsplit. reflexivity.
           ++ rewrite result_fold_leftM_app, Hrun. exact Hprefix.
        -- intros before block after reached Hsplit Hprefix.
           apply (Hstaking (past ++ before) block after reached).
           ++ rewrite <- app_assoc, <- Hsplit. reflexivity.
           ++ rewrite result_fold_leftM_app, Hrun. exact Hprefix.
Qed.
End ApprovedCofactorOrders.
End Execution.