Library QedkConcrete.blockhistoryprojection

Block-boundary preservation of consensus history

System calls and withdrawals do not consume signer nonces or reset emptying counters. Their effects must still be proved: neither operation passes through the transaction reserve check.
From Stdlib Require Import List String ZArith Lia Bool.
Require Import RocqOfOCaml.RocqOfOCaml.
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.transactionhistoryprojection QedkConcrete.systemnonces
  QedkConcrete.systemmessages QedkConcrete.blockpersistentcode
  QedkConcrete.supply QedkConcrete.systemcode QedkConcrete.hashwords
  QedkConcrete.hostaccountformat QedkConcrete.wordrange
  QedkConcrete.reservewrites QedkConcrete.transactionformat
  QedkConcrete.worldaccounts QedkConcrete.transactionfees
  QedkConcrete.authorizationnonces.
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 prefix := (@transactionPrefix F).
Local Abbreviation vmInput := (@transactionVmInput F).
Local Abbreviation callFromEoa := (@E.Host.call_from_eoa F).
Local Abbreviation processTransaction := (@E.process_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 recoveredAuthority := (@Chain.Ethereum.Transaction.Authorization.authority).

Local Abbreviation blockNumber := (fun block ⇒ Chain.Ethereum.Block.Header.t.number
  (Chain.Ethereum.Block.t.header (B.t.current_block block))).
Local Abbreviation emptying := (@Reserve_balance.is_emptying_tx).

Local Abbreviation systemMessage := (@E.process_system_message F).

Theorem system_message_history snapshot history signers until block addr data :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  keccak256OutputSize → wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  headerWords (Chain.Ethereum.Block.t.header (B.t.current_block block)) →
  OCamlString.length data < 2^62 →
  balanceInvariant (B.t.world_state block) → worldFormat (B.t.world_state block) →
  callFreeBytes (A.t.code (readAccount (B.t.world_state block) addr)) = true →
  (∀ a, List.In a signers → a ≠ native) →
  HistoryMatches snapshot history (B.t.world_state block) signers until →
  HistoryMatches snapshot history (B.t.world_state (snd (systemMessage block addr data))) signers until.
Proof.
  intros Hrevision Hhash Hchain Hheader Hdata Hbalance Hformat Hcode Hnative Hhistory.
  destruct (@system_message_call_free F
    block addr data Hrevision Hhash Hchain Hheader Hdata
    Hbalance Hformat Hcode) as [HpostBalance [_ [Hcodes _]]].
  pose proof (proj2 (@system_message_activity_history F
    block addr data Hrevision)) as Hcounters.
  constructor.
  - exact (proj1 HpostBalance).
  - rewrite Hcounters. exact (history_counters_wf _ _ _ _ _ Hhistory).
  - intros a Ha. etransitivity.
    + apply (@executionreserve.contract_test_same_code). exact (Hcodes a).
    + exact (history_noncontract _ _ _ _ _ Hhistory a Ha).
  - intros a Ha. etransitivity.
    + exact (@system_message_nonce F
        block addr data a (Hnative a Ha)
        Hrevision Hhash Hchain Hheader Hdata Hbalance Hformat Hcode).
    + exact (history_nonce_agreement _ _ _ _ _ Hhistory a Ha).
  - intros a Ha HnotSys future Hfuture. transitivity (@emptyingEligible (B.t.world_state block) a future).
    + unfold emptyingEligible. cbv beta. rewrite Hcodes.
      rewrite (read_counter_same_map _ _ a Hcounters). reflexivity.
    + exact (history_emptying_agreement _ _ _ _ _ Hhistory a Ha HnotSys future Hfuture).
Qed.

Lemma withdrawal_history snapshot history signers until block withdrawal :
  HistoryMatches snapshot history (B.t.world_state block) signers until →
  HistoryMatches snapshot history (B.t.world_state (@E.process_withdrawal F block withdrawal)) signers until.
Proof.
  intro Hhistory.
  pose proof (history_accounts_wf _ _ _ _ _ Hhistory) as Hmap.
  constructor.
  - unfold E.process_withdrawal. apply stringmaps.update_wellformed. exact Hmap.
  - exact (history_counters_wf _ _ _ _ _ Hhistory).
  - intros a Ha. etransitivity.
    + apply (@executionreserve.contract_test_same_code).
      exact (proj2 (@withdrawal_code F block withdrawal a Hmap)).
    + exact (history_noncontract _ _ _ _ _ Hhistory a Ha).
  - intros a Ha. etransitivity.
    + unfold E.process_withdrawal. apply balance_write_preserves_nonce. exact Hmap.
    + exact (history_nonce_agreement _ _ _ _ _ Hhistory a Ha).
  - intros a Ha HnotSys future Hfuture. transitivity (@emptyingEligible (B.t.world_state block) a future).
    + unfold emptyingEligible. cbv beta.
      rewrite (proj2 (@withdrawal_code F block withdrawal a Hmap)). reflexivity.
    + exact (history_emptying_agreement _ _ _ _ _ Hhistory a Ha HnotSys future Hfuture).
Qed.

Lemma withdrawals_history snapshot history signers until block withdrawals :
  HistoryMatches snapshot history (B.t.world_state block) signers until →
  HistoryMatches snapshot history (B.t.world_state
    (Result.List.fold_left (@E.process_withdrawal F) block withdrawals)) signers until.
Proof.
  revert block. induction withdrawals as [|withdrawal withdrawals IH]; intros block Hhistory.
  - exact Hhistory.
  - change (HistoryMatches snapshot history (B.t.world_state
      (Result.List.fold_left (@E.process_withdrawal F) (@E.process_withdrawal F block withdrawal)
        withdrawals)) signers until).
    apply IH, withdrawal_history. exact Hhistory.
Qed.
Local Abbreviation activate := (@Reserve_balance.activate_precompile).

Lemma activate_history snapshot history signers until world :
  (∀ a, List.In a signers → a ≠ native) →
  HistoryMatches snapshot history world signers until →
  HistoryMatches snapshot history (activate world) signers until.
Proof.
  intros Hnative Hhistory.
  pose proof (history_accounts_wf _ _ _ _ _ Hhistory) as Hmap.
  assert (Hcode : ∀ a, A.t.code (readAccount (activate world) a) = A.t.code (readAccount world a)).
  { intro a. eapply hostcode.account_write_same_code; [exact Hmap|reflexivity]. }
  constructor.
  - apply account_write_wellformed. exact Hmap.
  - exact (history_counters_wf _ _ _ _ _ Hhistory).
  - intros a Ha. etransitivity.
    + apply (@executionreserve.contract_test_same_code). exact (Hcode a).
    + exact (history_noncontract _ _ _ _ _ Hhistory a Ha).
  - intros a Ha. transitivity (A.t.nonce (readAccount world a)).
    + change (A.t.nonce (State.op_pointcaretlparenrparen
        (activate world) (@W.account None a)) = A.t.nonce (readAccount world a)).
      change (A.t.nonce (readAccount (State.op_pointcaretlparenrparenltminus world
        (@W.account (Some false) native)
        (A.t.with_nonce (Numeric.U64.max (A.t.nonce (readAccount world native))
          (@Numeric.U64.one)) (readAccount world native))) a) =
        A.t.nonce (readAccount world a)).
      cbv beta.
      rewrite nonce_after_account_write by exact Hmap.
      fold native.
      destruct (String.eqb native a) eqn:Heq; [|reflexivity].
      apply String.eqb_eq in Heq. exfalso. exact (Hnative a Ha (eq_sym Heq)).
    + exact (history_nonce_agreement _ _ _ _ _ Hhistory a Ha).
  - intros a Ha HnotSys future Hfuture. transitivity (@emptyingEligible world a future).
    + unfold emptyingEligible. cbv beta. rewrite Hcode. reflexivity.
    + exact (history_emptying_agreement _ _ _ _ _ Hhistory a Ha HnotSys future Hfuture).
Qed.
Context {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}
  {UBlock : Basics.Unreachable Chain.Ethereum.Block.t}.
Local Abbreviation processBlock := (@E.process_block F).

Lemma dispatch_transaction_inl_process_transaction state tx next :
  @E.sender_kind_value F tx ≠ Some E.System →
  @E.dispatch_transaction F state tx = inl next →
  @E.process_transaction F state tx = inl next.
Proof.
  intros HnotSys Hrun.
  destruct (@dispatch_transaction_cases F state tx next Hrun)
    as [[_ [_ Hproc]] | [Hsys _]].
  - exact Hproc.
  - contradiction (HnotSys Hsys).
Qed.

Lemma dispatched_transactions_inl_process_transactions start txs after :
  Forall (fun tx ⇒ @E.sender_kind_value F tx ≠ Some E.System) txs →
  Result.List.fold_leftM (@E.dispatch_transaction F) start txs = inl after →
  Result.List.fold_leftM (@E.process_transaction F) start txs = inl after.
Proof.
  intro Htxs. revert start.
  induction Htxs as [|tx txs HnotSys Htxs IH]; intros start Hrun.
  - exact Hrun.
  - change (Result.op_letdollar (@E.dispatch_transaction F start tx)
      (fun next ⇒ Result.List.fold_leftM (@E.dispatch_transaction F) next txs) = inl after) in Hrun.
    destruct (@E.dispatch_transaction F start tx) as [next|error] eqn:Hstep;
      [|discriminate Hrun].
    change (Result.op_letdollar (@E.process_transaction F start tx)
      (fun next ⇒ Result.List.fold_leftM (@E.process_transaction F) next txs) = inl after).
    rewrite (dispatch_transaction_inl_process_transaction start tx next HnotSys Hstep).
    exact (IH next Hrun).
Qed.

The scan crosses the actual block boundary, including native-account activation, both prescribed system calls and withdrawals. No history or nonce correctness is required of intermediate transaction states.
Theorem process_block_history_projection snapshot history signers until verify world block post :
  (@E.Params F).(Execution.Make_Params_signature.revision) = Support.Variants.Revision.Eleven →
  keccak256OutputSize → wordRange (Support.UintN.to_z (Chain.Monad.PARAMS.chain_id params)) →
  headerWords (Chain.Ethereum.Block.t.header block) →
  OCamlString.length (Chain.Ethereum.Block.Header.t.parent_beacon_block_root
    (Chain.Ethereum.Block.t.header block)) = 32 →
  balanceInvariant world → worldFormat world → @prescribedSystemCode F world →
  HistoryMatches snapshot history world signers until →
  (∀ a, List.In a signers → @A.is_smart_contract (readAccount snapshot a) = false) →
  (∀ a, List.In a signers → a ≠ native) →
  Forall (fun tx ⇒
    Forall (fun auth ⇒ OCamlString.length (T.Authorization.t.address auth) = 20)
      (T.authorization_list tx)) (Chain.Ethereum.Block.t.transactions block) →
  (∀ before tx validation a,
    List.In tx (Chain.Ethereum.Block.t.transactions block) → List.In a signers →
    @E.validate_transaction F before tx = inl validation →
    @A.is_smart_contract (readAccount (B.t.world_state before) a) = false →
    let '(msg, entry) := vmInput before tx validation in
    ¬ List.In a (S.t.accounts_created_in_current_transaction (snd (callFromEoa tx msg entry)))) →
  (until < Chain.Ethereum.Block.Header.t.number (Chain.Ethereum.Block.t.header block) + 3)%N →
  processBlock verify world block = inl post →
  ∃ after, scanHistory snapshot history (Chain.Ethereum.Block.t.transactions block) = Some after ∧
    HistoryMatches snapshot after post signers until.
Proof.
  intros Hrevision Hhash Hchain Hheader Hroot Hbalance Hformat Hsystem Hhistory
    Hsnapshot Hnative Hinputs Hsafe Htime Hrun.
  unfold E.process_block in Hrun. rewrite Hrevision 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.
  destruct (@E.validate_block F world block) as [[]|error]; [|discriminate Hrun].
  cbn beta iota zeta in Hrun.
  match type of Hrun with context [B.make ?w block] ⇒ set (initial := B.make w block) in × end.
  assert (HinitialHistory : HistoryMatches snapshot history (B.t.world_state initial) signers until).
  { apply activate_history; assumption. }
  assert (HinitialFormat : worldFormat (B.t.world_state initial)).
  { apply activate_preserves_format. exact Hformat. }
  assert (HinitialBalance : balanceInvariant (B.t.world_state initial)).
  { exact (proj1 (activate_preserves_supply world Hbalance)). }
  assert (HinitialSystem : @prescribedSystemCode F (B.t.world_state initial)).
  { destruct Hsystem as [Hbeacon HhistoryCode]. split; etransitivity;
      first [eapply hostcode.account_write_same_code;
        [exact (history_accounts_wf _ _ _ _ _ Hhistory)|reflexivity] | eassumption]. }
  match type of Hrun with context [E.process_system_message initial ?systemAddr ?systemData] ⇒
    assert (Hdata : OCamlString.length systemData < 2^62) by
      (change (OCamlString.length (Chain.Ethereum.Block.Header.t.parent_beacon_block_root
        (Chain.Ethereum.Block.t.header block)) < 2^62); rewrite Hroot; lia);
    assert (Hfree : callFreeBytes (A.t.code (readAccount (B.t.world_state initial) systemAddr)) = true) by
      (rewrite (proj1 HinitialSystem); apply beaconRootsCode_call_free);
    pose proof (system_message_history snapshot history signers until initial systemAddr systemData
      Hrevision Hhash Hchain Hheader Hdata HinitialBalance HinitialFormat Hfree Hnative HinitialHistory)
      as HbeaconHistory;
    pose proof (@system_message_call_free F
      initial systemAddr systemData Hrevision Hhash Hchain Hheader Hdata
      HinitialBalance HinitialFormat Hfree) as Hbeacon;
    pose proof (system_message_preserves_format initial systemAddr systemData Hrevision HinitialFormat) as HbeaconFormat;
    pose proof (@system_message_current_block F
      initial systemAddr systemData) as HbeaconBlock;
    destruct (E.process_system_message initial systemAddr systemData) as [beaconResult afterBeacon]
  end.
  cbn beta iota zeta delta [snd] in HbeaconHistory, Hbeacon, HbeaconFormat, HbeaconBlock, Hrun.
  destruct Hbeacon as [HbeaconBalance [_ [HbeaconCodes _]]].
  clear Hfree Hdata.
  assert (HbeaconHeader : headerWords (Chain.Ethereum.Block.t.header (B.t.current_block afterBeacon))).
  { rewrite HbeaconBlock. exact Hheader. }
  match type of Hrun with context [E.process_system_message afterBeacon ?systemAddr ?systemData] ⇒
    assert (Hdata : OCamlString.length systemData < 2^62) by
      (lazymatch systemData with ?toBytes ?hash ⇒ change (OCamlString.length hash < 2^62) end;
        rewrite (block_hash_length Hhash); lia);
    assert (Hfree : callFreeBytes (A.t.code (readAccount (B.t.world_state afterBeacon) systemAddr)) = true) by
      (rewrite HbeaconCodes, (proj2 HinitialSystem); apply historyStorageCode_call_free);
    pose proof (system_message_history snapshot history signers until afterBeacon systemAddr systemData
      Hrevision Hhash Hchain HbeaconHeader Hdata HbeaconBalance HbeaconFormat Hfree Hnative HbeaconHistory)
      as HhistoryHistory;
    pose proof (@system_message_current_block F
      afterBeacon systemAddr systemData) as HhistoryBlock;
    destruct (E.process_system_message afterBeacon systemAddr systemData) as [historyResult afterHistory]
  end.
  cbn beta iota zeta delta [snd] in HhistoryHistory, HhistoryBlock, Hrun.
  match type of Hrun with context [Result.List.fold_leftM ?step afterHistory ?txs] ⇒
    destruct (Result.List.fold_leftM step afterHistory txs) as [afterTransactions|error] eqn:Htransactions
  end.
  2: discriminate Hrun.
  assert (HtransactionTime : (until < blockNumber afterHistory + 3)%N).
  { cbv beta. rewrite HhistoryBlock, HbeaconBlock. exact Htime. }
  destruct (@dispatched_transactions_history_projection F
    snapshot signers until
    (Chain.Ethereum.Block.t.transactions block) Hrevision Hsnapshot Hnative Hinputs Hsafe
    history afterHistory afterTransactions HhistoryHistory HtransactionTime Htransactions)
    as [after [Hscan Hafter]].
  pose proof (withdrawals_history snapshot after signers until afterTransactions
    (Chain.Ethereum.Block.t.withdrawals block) Hafter) as Hwithdrawals.
  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.
  2: discriminate Hrun.
  match type of Hrun with context [if verify then ?check else _] ⇒
    destruct verify; [destruct check as [[]|error]; [|discriminate Hrun]|]
  end.
  all: injection Hrun as <-; ∃ after; split; [exact Hscan|].
  all: destruct Hwithdrawals; constructor; assumption.
Qed.
End Execution.