Skip to main content

iota_core/checkpoints/checkpoint_executor/
mod.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5//! CheckpointExecutor is a Node component that executes all checkpoints for the
6//! given epoch. It acts as a Consumer to StateSync
7//! for newly synced checkpoints, taking these checkpoints and
8//! scheduling and monitoring their execution. Its primary goal is to allow
9//! for catching up to the current checkpoint sequence number of the network
10//! as quickly as possible so that a newly joined, or recovering Node can
11//! participate in a timely manner. To that end, CheckpointExecutor attempts
12//! to saturate the CPU with executor tasks (one per checkpoint), each of which
13//! handle scheduling and awaiting checkpoint transaction execution.
14//!
15//! CheckpointExecutor is made recoverable in the event of Node shutdown by way
16//! of a watermark, highest_executed_checkpoint, which is guaranteed to be
17//! updated sequentially in order, despite checkpoints themselves potentially
18//! being executed nonsequentially and in parallel. CheckpointExecutor
19//! parallelizes checkpoints of the same epoch as much as possible.
20//! CheckpointExecutor enforces the invariant that if `run` returns
21//! successfully, we have reached the end of epoch. This allows us to use it as
22//! a signal for reconfig.
23
24use std::{
25    collections::BTreeSet,
26    future::Future,
27    sync::{
28        Arc,
29        atomic::{AtomicBool, Ordering},
30    },
31    time::Instant,
32};
33
34use futures::{StreamExt, TryStreamExt};
35use iota_common::{debug_fatal, fatal};
36use iota_config::node::{CheckpointExecutorConfig, RunWithRange};
37use iota_macros::{fail_point, fail_point_async};
38use iota_sdk_types::{
39    CheckpointContents, CheckpointSummary, RandomnessRound, TransactionDigest, TransactionEffects,
40    TransactionEffectsDigest, TransactionKind,
41};
42use iota_types::{
43    attestation::{AttestationRecord, AttestationTotals, AttestationVerdict},
44    base_types::{AuthorityName, ExecutionData},
45    committee::{Committee, EpochId},
46    effects::TransactionEffectsAPI,
47    executable_transaction::VerifiedExecutableTransaction,
48    full_checkpoint_content::CheckpointData,
49    global_state_hash::GlobalStateHash,
50    messages_checkpoint::{
51        CheckpointContentsExt, CheckpointSequenceNumber, CheckpointSummaryExt,
52        CheckpointVersionSpecificData, FullCheckpointContents, VerifiedCheckpoint,
53    },
54    transaction::{SenderSignedTransactionAPI, TransactionAPI, VerifiedTransaction},
55};
56use parking_lot::Mutex;
57use tap::{TapFallible, TapOptional};
58use tokio::task::JoinError;
59use tracing::{debug, info, instrument, warn};
60
61use crate::{
62    authority::{
63        AuthorityState, ExecutionEnv, attestation::attestors_taking_whole_score,
64        authority_per_epoch_store::AuthorityPerEpochStore, backpressure::BackpressureManager,
65        shared_object_version_manager::gas_object_cancellation_version_from_effects,
66    },
67    checkpoint_progress_tracker::CheckpointProgressTracker,
68    checkpoints::CheckpointStore,
69    execution_cache::{ObjectCacheRead, TransactionCacheRead},
70    execution_scheduler::{
71        ExecutionSchedulerAPI, ExecutionSchedulerWrapper, transaction_manager::AttestationSource,
72    },
73    global_state_hasher::GlobalStateHasher,
74};
75
76mod data_ingestion_handler;
77pub mod metrics;
78pub(crate) mod utils;
79
80#[cfg(test)]
81pub(crate) mod tests;
82
83use data_ingestion_handler::{
84    load_checkpoint_data, load_epoch_boundary_data, store_checkpoint_locally,
85};
86use metrics::CheckpointExecutorMetrics;
87use utils::*;
88
89type CheckpointDataSender = Box<dyn Fn(&CheckpointData) + Send + Sync>;
90
91#[derive(PartialEq, Eq, Debug)]
92pub enum StopReason {
93    EpochComplete,
94    RunWithRangeCondition,
95    /// The tokio runtime is shutting down and cancelled checkpoint execution
96    /// work.
97    RuntimeShutdown,
98}
99
100pub(crate) struct CheckpointExecutionData {
101    pub checkpoint: VerifiedCheckpoint,
102    pub checkpoint_contents: CheckpointContents,
103    pub tx_digests: Vec<TransactionDigest>,
104    pub fx_digests: Vec<TransactionEffectsDigest>,
105    /// Parsed once from the summary.
106    pub version_specific_data: Option<CheckpointVersionSpecificData>,
107}
108
109impl CheckpointExecutionData {
110    /// The records the summary certifies, one slot per transaction in contents
111    /// order; `None` where the attestation was valid or there was none.
112    ///
113    /// # Panics
114    ///
115    /// If a certified entry lies outside the checkpoint, which a certified
116    /// checkpoint cannot do without a protocol bug.
117    fn certified_attestations(&self) -> Vec<Option<AttestationRecord>> {
118        let mut records = vec![None; self.tx_digests.len()];
119        if let Some(CheckpointVersionSpecificData::V2(data)) = &self.version_specific_data {
120            for entry in &data.attestation_entries {
121                let slot = records
122                    .get_mut(entry.position as usize)
123                    .expect("a certified entry position is within the checkpoint");
124                *slot = Some(entry.record);
125            }
126        }
127        records
128    }
129
130    /// Whether the summary certifies a refuted record. Only such a record
131    /// changes the epoch's totals.
132    fn certifies_refuted_record(&self) -> bool {
133        self.version_specific_data.as_ref().is_some_and(|data| {
134            data.attestation_entries()
135                .iter()
136                .any(|entry| matches!(entry.record.verdict, AttestationVerdict::Refuted { .. }))
137        })
138    }
139}
140
141pub(crate) struct CheckpointTransactionData {
142    pub transactions: Vec<VerifiedExecutableTransaction>,
143    pub effects: Vec<TransactionEffects>,
144}
145
146pub(crate) struct CheckpointExecutionState {
147    pub data: CheckpointExecutionData,
148    state_hash: Option<GlobalStateHash>,
149    full_data: Option<CheckpointData>,
150}
151
152impl CheckpointExecutionState {
153    pub fn new(data: CheckpointExecutionData) -> Self {
154        Self {
155            data,
156            state_hash: None,
157            full_data: None,
158        }
159    }
160
161    pub fn new_with_global_state_hash(
162        data: CheckpointExecutionData,
163        hash: GlobalStateHash,
164    ) -> Self {
165        Self {
166            data,
167            state_hash: Some(hash),
168            full_data: None,
169        }
170    }
171}
172
173macro_rules! finish_stage {
174    ($handle:expr, $stage:ident) => {
175        $handle.finish_stage(PipelineStage::$stage).await;
176    };
177}
178
179pub struct CheckpointExecutor {
180    epoch_store: Arc<AuthorityPerEpochStore>,
181    state: Arc<AuthorityState>,
182    checkpoint_store: Arc<CheckpointStore>,
183    object_cache_reader: Arc<dyn ObjectCacheRead>,
184    transaction_cache_reader: Arc<dyn TransactionCacheRead>,
185    execution_scheduler: Arc<ExecutionSchedulerWrapper>,
186    global_state_hasher: Arc<GlobalStateHasher>,
187    backpressure_manager: Arc<BackpressureManager>,
188    config: CheckpointExecutorConfig,
189    metrics: Arc<CheckpointExecutorMetrics>,
190    tps_estimator: Mutex<TPSEstimator>,
191    checkpoint_progress_tracker: Option<Arc<CheckpointProgressTracker>>,
192    data_sender: Option<CheckpointDataSender>,
193    /// The next synced checkpoint whose randomness has not been forwarded
194    /// yet; `CheckpointSequenceNumber::MAX` once every synced checkpoint of
195    /// this epoch has been.
196    next_randomness_to_forward: Mutex<CheckpointSequenceNumber>,
197    /// Whether this executor has executed a checkpoint yet.
198    executed_any_checkpoint: AtomicBool,
199}
200
201impl CheckpointExecutor {
202    pub fn new(
203        epoch_store: Arc<AuthorityPerEpochStore>,
204        checkpoint_store: Arc<CheckpointStore>,
205        state: Arc<AuthorityState>,
206        global_state_hasher: Arc<GlobalStateHasher>,
207        backpressure_manager: Arc<BackpressureManager>,
208        config: CheckpointExecutorConfig,
209        metrics: Arc<CheckpointExecutorMetrics>,
210        data_sender: Option<CheckpointDataSender>,
211        checkpoint_progress_tracker: Option<Arc<CheckpointProgressTracker>>,
212    ) -> Self {
213        Self {
214            epoch_store,
215            state: state.clone(),
216            checkpoint_store,
217            object_cache_reader: state.get_object_cache_reader().clone(),
218            transaction_cache_reader: state.get_transaction_cache_reader().clone(),
219            execution_scheduler: state.execution_scheduler().clone(),
220            global_state_hasher,
221            backpressure_manager,
222            config,
223            metrics,
224            tps_estimator: Mutex::new(TPSEstimator::default()),
225            checkpoint_progress_tracker,
226            data_sender,
227            next_randomness_to_forward: Mutex::new(0),
228            executed_any_checkpoint: AtomicBool::new(false),
229        }
230    }
231
232    pub fn new_for_tests(
233        epoch_store: Arc<AuthorityPerEpochStore>,
234        checkpoint_store: Arc<CheckpointStore>,
235        state: Arc<AuthorityState>,
236        global_state_hasher: Arc<GlobalStateHasher>,
237    ) -> Self {
238        Self::new(
239            epoch_store,
240            checkpoint_store.clone(),
241            state,
242            global_state_hasher,
243            BackpressureManager::new_from_checkpoint_store(&checkpoint_store),
244            Default::default(),
245            CheckpointExecutorMetrics::new_for_tests(),
246            None, // No callback for data
247            None, // No progress tracker for tests
248        )
249    }
250
251    // Gets the next checkpoint to schedule for execution. If the epoch is already
252    // completed, returns None.
253    fn get_next_to_schedule(&self) -> Option<CheckpointSequenceNumber> {
254        // Decide the first checkpoint to schedule for execution.
255        // If we haven't executed anything in the past, we schedule checkpoint 0.
256        // Otherwise we schedule the one after highest executed.
257        let highest_executed = self
258            .checkpoint_store
259            .get_highest_executed_checkpoint()
260            .unwrap();
261
262        if let Some(highest_executed) = &highest_executed {
263            if self.epoch_store.epoch() == highest_executed.epoch()
264                && highest_executed.is_last_checkpoint_of_epoch()
265            {
266                // We can arrive at this point if we bump the highest_executed_checkpoint
267                // watermark, and then crash before completing reconfiguration.
268                info!(seq = ?highest_executed.sequence_number, "final checkpoint of epoch has already been executed");
269                return None;
270            }
271        }
272
273        Some(
274            highest_executed
275                .as_ref()
276                .map(|c| c.sequence_number() + 1)
277                .unwrap_or_else(|| {
278                    // TODO this invariant may no longer hold once we introduce snapshots
279                    assert_eq!(self.epoch_store.epoch(), 0);
280                    // we need to execute the genesis checkpoint
281                    0
282                }),
283        )
284    }
285
286    /// Execute all checkpoints for the current epoch, ensuring that the node
287    /// has not forked, and return when finished.
288    /// If `run_with_range` is set, execution will stop early.
289    #[instrument(level = "error", skip_all, fields(epoch = ?self.epoch_store.epoch()))]
290    pub async fn run_epoch(self, run_with_range: Option<RunWithRange>) -> StopReason {
291        let _metrics_scope = iota_metrics::monitored_scope("CheckpointExecutor::run_epoch");
292        info!(?run_with_range, "CheckpointExecutor::run_epoch");
293        debug!(
294            "Checkpoint executor running for epoch {:?}",
295            self.epoch_store.epoch(),
296        );
297
298        // check if we want to run this epoch based on RunWithRange condition value
299        // we want to be inclusive of the defined RunWithRangeEpoch::Epoch
300        // i.e Epoch(N) means we will execute epoch N and stop when reaching N+1
301        if run_with_range.is_some_and(|rwr| rwr.is_epoch_gt(self.epoch_store.epoch())) {
302            info!("RunWithRange condition satisfied at {:?}", run_with_range,);
303            return StopReason::RunWithRangeCondition;
304        };
305
306        self.metrics
307            .checkpoint_exec_epoch
308            .set(self.epoch_store.epoch() as i64);
309        // The totals start empty in every epoch, and the hostnames are those
310        // of the epoch's committee.
311        self.metrics.attestation_certified_totals.reset();
312
313        let Some(next_to_schedule) = self.get_next_to_schedule() else {
314            return StopReason::EpochComplete;
315        };
316        self.seed_cut_off_attestors();
317
318        let this = Arc::new(self);
319
320        let concurrency = std::env::var("IOTA_CHECKPOINT_EXECUTION_MAX_CONCURRENCY")
321            .ok()
322            .and_then(|s| s.parse().ok())
323            .unwrap_or(this.config.checkpoint_execution_max_concurrency);
324
325        let pipeline_stages = PipelineStages::new(
326            next_to_schedule,
327            this.metrics.clone(),
328            this.checkpoint_progress_tracker.clone(),
329        );
330
331        let final_checkpoint_executed = stream_synced_checkpoints(
332            this.checkpoint_store.clone(),
333            next_to_schedule,
334            run_with_range.and_then(|rwr| rwr.into_checkpoint_bound()),
335        )
336        // Checkpoint loading and execution is parallelized: each
337        // checkpoint's task loads its transaction data before awaiting
338        // admission to the ordered pipeline stages.
339        .map(|checkpoint| {
340            let this = this.clone();
341            let pipeline_stages = pipeline_stages.clone();
342            async move {
343                let seq = checkpoint.sequence_number();
344                let pipeline_handle = async move { pipeline_stages.handle(seq).await };
345                tokio::spawn(this.execute_checkpoint(checkpoint, pipeline_handle))
346                    .await
347                    .and_then(|result| result)
348            }
349        })
350        .buffered(concurrency)
351        // Take the last value from the stream to determine if we completed the epoch
352        .try_fold(false, |state, is_final_checkpoint| async move {
353            assert!(!state, "Cannot execute checkpoint after epoch end");
354            Ok(is_final_checkpoint)
355        })
356        .await;
357
358        match final_checkpoint_executed {
359            Ok(true) => StopReason::EpochComplete,
360            Ok(false) => StopReason::RunWithRangeCondition,
361            Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
362            // Tasks are only cancelled when the runtime shuts down.
363            Err(e) => {
364                info!("Checkpoint execution cancelled by runtime shutdown: {e}");
365                StopReason::RuntimeShutdown
366            }
367        }
368    }
369}
370
371impl CheckpointExecutor {
372    /// Load all data for a checkpoint, ensure all transactions are executed,
373    /// and check for forks.
374    #[instrument(level = "debug", skip_all, fields(seq = ?checkpoint.sequence_number()))]
375    async fn execute_checkpoint(
376        self: Arc<Self>,
377        checkpoint: VerifiedCheckpoint,
378        pipeline_handle: impl Future<Output = PipelineHandle> + Send,
379    ) -> Result<bool /* is final checkpoint */, JoinError> {
380        debug!("executing checkpoint");
381        let sequence_number = checkpoint.sequence_number;
382        let is_last_checkpoint_of_epoch = checkpoint.is_last_checkpoint_of_epoch();
383
384        checkpoint.report_checkpoint_age(&self.metrics.checkpoint_contents_age);
385        self.backpressure_manager
386            .update_highest_certified_checkpoint(sequence_number);
387
388        // Load the transaction data before awaiting admission to the
389        // pipeline: it reads only state-sync-written data (contents,
390        // transactions, and expected effects), so it can run in parallel
391        // across the buffered checkpoints instead of inside the ordered
392        // ExecuteTransactions stage. The clone is needed because the
393        // locally-built-checkpoint path below wants the checkpoint too.
394        let loaded = (self.state.is_fullnode(&self.epoch_store) || is_last_checkpoint_of_epoch)
395            .then(|| {
396                let _scope = iota_metrics::monitored_scope(
397                    "CheckpointExecutor::load_checkpoint_transactions",
398                );
399                self.load_checkpoint_transactions(checkpoint.clone())
400            });
401
402        let mut pipeline_handle = pipeline_handle.await;
403
404        if is_last_checkpoint_of_epoch && sequence_number > 0 {
405            let _wait_for_previous_checkpoints_guard =
406                iota_metrics::monitored_scope("CheckpointExecutor::wait_for_previous_checkpoints");
407
408            info!(
409                "Reached end of epoch checkpoint, waiting for all previous checkpoints to be executed"
410            );
411            self.checkpoint_store
412                .notify_read_executed_checkpoint(sequence_number - 1)
413                .await;
414        }
415
416        // A committee validator that has not built the last checkpoint itself
417        // executes it from synced data like the checkpoints before, so it
418        // switches first.
419        if is_last_checkpoint_of_epoch
420            && self.epoch_store.pcool_bookkeeping_enabled()
421            && self
422                .checkpoint_store
423                .get_locally_computed_checkpoint(sequence_number)
424                .expect("db error")
425                .is_none()
426        {
427            self.epoch_store.start_executing_synced_checkpoints().await;
428        }
429
430        // The last checkpoint is executed from synced data even when this node
431        // built it, which schedules every transaction in it not executed yet.
432        // The epoch's last checkpoint is already known here, so the call below
433        // does not wait for the consensus handler: unless the handler has
434        // executed every transaction in it, the call switches this node to
435        // executing synced checkpoints.
436        if let Some((_, tx_data)) = loaded
437            .as_ref()
438            .filter(|_| is_last_checkpoint_of_epoch && self.epoch_store.pcool_bookkeeping_enabled())
439        {
440            let digests: Vec<_> = tx_data
441                .transactions
442                .iter()
443                .filter(|tx| !tx.transaction().is_end_of_epoch_tx())
444                .map(|tx| *tx.digest())
445                .collect();
446            self.wait_for_handler_execution(&checkpoint, &digests).await;
447        }
448
449        let _parallel_step_guard =
450            iota_metrics::monitored_scope("CheckpointExecutor::parallel_step");
451
452        // Note: only `execute_transactions_from_synced_checkpoint` has end-of-epoch
453        // logic. It is also the only branch that stages index updates, so a
454        // divergence here would stamp the watermark over unstaged checkpoints.
455        let exec_start = Instant::now();
456        let ckpt_state = match loaded {
457            Some((ckpt_state, tx_data)) => {
458                self.execute_transactions_from_synced_checkpoint(
459                    ckpt_state,
460                    tx_data,
461                    &mut pipeline_handle,
462                )
463                .await
464            }
465            None => {
466                self.verify_locally_built_checkpoint(checkpoint, &mut pipeline_handle)
467                    .await
468            }
469        };
470
471        let tps = self.tps_estimator.lock().update(
472            Instant::now(),
473            ckpt_state.data.checkpoint.network_total_transactions,
474        );
475        self.metrics.checkpoint_exec_sync_tps.set(tps as i64);
476
477        self.backpressure_manager
478            .update_highest_executed_checkpoint(ckpt_state.data.checkpoint.sequence_number());
479
480        let is_final_checkpoint = ckpt_state.data.checkpoint.is_last_checkpoint_of_epoch();
481
482        let seq = ckpt_state.data.checkpoint.sequence_number;
483
484        let batch = self.state.get_cache_commit().build_db_batch(
485            self.epoch_store.epoch(),
486            seq,
487            &ckpt_state.data.tx_digests,
488        );
489
490        // Before the outputs, so no durable object lacks its bookkeeping. In
491        // this stage, so the write overlaps the output writes of earlier
492        // checkpoints and still runs in checkpoint order. A transaction whose
493        // outputs are already durable is not in `batch` and needs nothing:
494        // its bookkeeping was written before them.
495        let batch = if self.epoch_store.pcool_bookkeeping_enabled() {
496            tokio::task::spawn_blocking({
497                let this = self.clone();
498                move || {
499                    this.epoch_store
500                        .persist_checkpoint_bookkeeping(
501                            batch.0.iter().map(|outputs| &outputs.effects),
502                        )
503                        .expect(
504                            "the epoch tables should accept the checkpoint's bookkeeping batch",
505                        );
506                    batch
507                }
508            })
509            .await?
510        } else {
511            batch
512        };
513
514        finish_stage!(pipeline_handle, BuildDbBatch);
515
516        let (ckpt_state, written_outputs) = tokio::task::spawn_blocking({
517            let this = self.clone();
518            move || {
519                // Commit all transaction effects to disk
520                let cache_commit = this.state.get_cache_commit();
521                debug!(?seq, "committing checkpoint transactions to disk");
522                let written_outputs = cache_commit
523                    .write_transaction_outputs_batch(batch, &ckpt_state.data.tx_digests);
524                fail_point!("crash-after-checkpoint-outputs-commit");
525                (ckpt_state, written_outputs)
526            }
527        })
528        .await?;
529
530        finish_stage!(pipeline_handle, CommitTransactionOutputs);
531
532        // In this stage, so the flush overlaps the next checkpoint's write.
533        // It relies on the stage running in checkpoint order, after this
534        // checkpoint's write.
535        tokio::task::spawn_blocking({
536            let this = self.clone();
537            move || {
538                this.state
539                    .get_cache_commit()
540                    .flush_committed_transaction_outputs(
541                        this.epoch_store.epoch(),
542                        &written_outputs,
543                    );
544            }
545        })
546        .await?;
547
548        self.epoch_store
549            .handle_finalized_checkpoint(&ckpt_state.data.checkpoint, &ckpt_state.data.tx_digests)
550            .expect("cannot fail");
551
552        let randomness_rounds = self.extract_randomness_rounds(
553            &ckpt_state.data.checkpoint,
554            &ckpt_state.data.checkpoint_contents,
555        );
556
557        // Once the checkpoint is finalized, we know that any randomness contained in
558        // this checkpoint has been successfully included in a checkpoint
559        // certified by quorum of validators. (RandomnessManager/
560        // RandomnessReporter is only present on validators.)
561        if let Some(randomness_reporter) = self.epoch_store.randomness_reporter() {
562            for round in randomness_rounds {
563                debug!(
564                    ?round,
565                    "notifying RandomnessReporter that randomness update was executed in checkpoint"
566                );
567                randomness_reporter
568                    .notify_randomness_in_checkpoint(round)
569                    .expect("epoch cannot have ended");
570            }
571        }
572
573        finish_stage!(pipeline_handle, FinalizeCheckpoint);
574
575        if self.state.rpc_indexes_store.is_some() {
576            // The commit writes RocksDB and takes the caches' owner locks.
577            tokio::task::spawn_blocking({
578                let this = self.clone();
579                move || this.commit_index_updates(seq)
580            })
581            .await?;
582        }
583
584        finish_stage!(pipeline_handle, UpdateRpcIndex);
585
586        self.global_state_hasher
587            .accumulate_running_root(&self.epoch_store, seq, ckpt_state.state_hash)
588            .expect("Failed to accumulate running root");
589
590        if is_final_checkpoint {
591            self.checkpoint_store
592                .insert_epoch_last_checkpoint(self.epoch_store.epoch(), &ckpt_state.data.checkpoint)
593                .expect("Failed to insert epoch last checkpoint");
594
595            self.global_state_hasher
596                .accumulate_epoch(self.epoch_store.clone(), seq)
597                .expect("Accumulating epoch cannot fail");
598
599            self.checkpoint_store
600                .prune_local_summaries()
601                .tap_err(|e| debug_fatal!("Failed to prune local summaries: {}", e))
602                .ok();
603        }
604
605        fail_point!("crash");
606
607        // Before the watermark, so whoever sees the checkpoint executed also sees
608        // the attestors it cuts off.
609        if ckpt_state.data.certifies_refuted_record() {
610            self.store_cut_off_attestors(ckpt_state.data.version_specific_data.as_ref());
611        }
612
613        // Keep this after the index commit: `wait_for_checkpoint_inclusion`
614        // reads this bump as "the checkpoint is indexed".
615        self.bump_highest_executed_checkpoint(&ckpt_state.data.checkpoint);
616        self.report_certified_attestation_totals(&ckpt_state.data);
617        self.state
618            .record_executed_for_object_retention(ckpt_state.data.checkpoint.sequence_number());
619
620        self.broadcast_checkpoint(&ckpt_state.data, ckpt_state.full_data.as_ref());
621
622        finish_stage!(pipeline_handle, BumpHighestExecutedCheckpoint);
623
624        if let Some(tracker) = &self.checkpoint_progress_tracker {
625            tracker.add_execution_time(exec_start.elapsed());
626        }
627
628        // Important: code after the last pipeline stage is finished can run out of
629        // checkpoint order.
630
631        Ok(is_final_checkpoint)
632    }
633
634    // On validators, checkpoints have often already been constructed locally, in
635    // which case we can skip many steps of the checkpoint execution process.
636    #[instrument(level = "info", skip_all)]
637    async fn verify_locally_built_checkpoint(
638        &self,
639        checkpoint: VerifiedCheckpoint,
640        pipeline_handle: &mut PipelineHandle,
641    ) -> CheckpointExecutionState {
642        assert!(
643            !checkpoint.is_last_checkpoint_of_epoch(),
644            "only fullnode path has end-of-epoch logic"
645        );
646
647        let sequence_number = checkpoint.sequence_number;
648        let Some(locally_built_checkpoint) =
649            self.wait_for_locally_built_checkpoint(&checkpoint).await
650        else {
651            let (ckpt_state, tx_data) = self.load_checkpoint_transactions(checkpoint);
652            return self
653                .execute_transactions_from_synced_checkpoint(ckpt_state, tx_data, pipeline_handle)
654                .await;
655        };
656        fail_point_async!("execute-locally-built-checkpoint");
657
658        self.metrics.checkpoint_executor_validator_path.inc();
659
660        // Check for fork
661        assert_checkpoint_not_forked(
662            &locally_built_checkpoint,
663            &checkpoint,
664            &self.checkpoint_store,
665        );
666
667        let checkpoint_contents = self
668            .checkpoint_store
669            .get_checkpoint_contents(&checkpoint.contents_digest)
670            .expect("db error")
671            .expect("checkpoint contents not found");
672
673        let (tx_digests, fx_digests): (Vec<_>, Vec<_>) = checkpoint_contents
674            .iter()
675            .map(|digests| (digests.transaction, digests.effects))
676            .unzip();
677
678        let state_hash = if self.epoch_store.pcool_bookkeeping_enabled() {
679            if !self
680                .wait_for_handler_execution(&checkpoint, &tx_digests)
681                .await
682            {
683                let (ckpt_state, tx_data) = self.load_checkpoint_transactions(checkpoint);
684                return self
685                    .execute_transactions_from_synced_checkpoint(
686                        ckpt_state,
687                        tx_data,
688                        pipeline_handle,
689                    )
690                    .await;
691            }
692            // Every transaction of the checkpoint has executed here, so hash
693            // its effects now instead of waiting for the builder's hash. The
694            // builder saves a checkpoint's hash a moment after its summary, so
695            // a crash can leave the summary without it, and after the restart
696            // the builder rebuilds the checkpoint only once the consensus
697            // replay is done. The replay waits on this executor, through the
698            // handler's wait for fully executed commits, so waiting here for
699            // the builder could wait forever.
700            let effects: Vec<_> = self
701                .transaction_cache_reader
702                .multi_get_executed_effects(&tx_digests)
703                .into_iter()
704                .zip(&tx_digests)
705                .zip(&fx_digests)
706                .map(|((effects, tx_digest), expected_fx_digest)| {
707                    let effects = effects
708                        .expect("every transaction of a checkpoint this node built has executed");
709                    assert_not_forked(
710                        &checkpoint,
711                        tx_digest,
712                        expected_fx_digest,
713                        &effects.digest(),
714                        &*self.transaction_cache_reader,
715                    );
716                    effects
717                })
718                .collect();
719            self.global_state_hasher
720                .accumulate_checkpoint(&effects, sequence_number, &self.epoch_store)
721                .expect("epoch cannot have ended")
722        } else {
723            // Checkpoint builder triggers accumulation of the checkpoint, so
724            // this is guaranteed to finish.
725            let _metrics_scope =
726                iota_metrics::monitored_scope("CheckpointExecutor::notify_read_state_hash");
727            self.epoch_store
728                .notify_read_checkpoint_state_hasher(&[sequence_number])
729                .await
730                .unwrap()
731                .pop()
732                .unwrap()
733        };
734
735        pipeline_handle
736            .skip_to(PipelineStage::FinalizeTransactions)
737            .await;
738
739        // Currently this code only runs on validators, where this method call does
740        // nothing. But in the future, fullnodes may follow the consensus dag
741        // and build their own checkpoints.
742        self.insert_finalized_transactions(&tx_digests, sequence_number, checkpoint.timestamp_ms);
743
744        pipeline_handle.skip_to(PipelineStage::BuildDbBatch).await;
745
746        let version_specific_data = self.parse_version_specific_data(&checkpoint);
747        CheckpointExecutionState::new_with_global_state_hash(
748            CheckpointExecutionData {
749                checkpoint,
750                checkpoint_contents,
751                tx_digests,
752                fx_digests,
753                version_specific_data,
754            },
755            state_hash,
756        )
757    }
758
759    /// Returns this node's own summary of `checkpoint`, waiting for the
760    /// checkpoint builder if needed. Returns `None` when the caller should
761    /// execute the synced checkpoint instead: always without
762    /// `enable_pcool_flow`; with it, for the genesis
763    /// checkpoint, and for any checkpoint once the certified last checkpoint of this epoch
764    /// is known, because peers then stop serving this epoch's consensus
765    /// commits. In that last case it first switches this node to executing
766    /// synced checkpoints for the rest of the epoch, which stops the consensus
767    /// handler and the checkpoint builder. Once switched, it returns `None`
768    /// for every checkpoint, built locally or not.
769    async fn wait_for_locally_built_checkpoint(
770        &self,
771        checkpoint: &VerifiedCheckpoint,
772    ) -> Option<CheckpointSummary> {
773        let seq = checkpoint.sequence_number;
774        let skip_synced_execution = self.epoch_store.protocol_config().enable_pcool_flow();
775        // Once switched, the builder no longer runs, so the state hash of a
776        // checkpoint it built may never be computed; the synced path computes
777        // it.
778        if skip_synced_execution && self.epoch_store.is_executing_synced_checkpoints() {
779            return None;
780        }
781        if let Some(summary) = self
782            .checkpoint_store
783            .get_locally_computed_checkpoint(seq)
784            .expect("db error")
785        {
786            return Some(summary);
787        }
788        if seq == 0 || !skip_synced_execution {
789            return None;
790        }
791        let epoch = self.epoch_store.epoch();
792        if self
793            .checkpoint_store
794            .get_epoch_last_checkpoint_seq_number(epoch)
795            .expect("db error")
796            .is_some()
797        {
798            self.epoch_store.start_executing_synced_checkpoints().await;
799            return None;
800        }
801        let _backpressure_guard = self.backpressure_manager.wait_for_local_build();
802        // The builder resolves every randomness round of a build before it
803        // writes any chunk of it, so the round this checkpoint waits for may
804        // only appear in a later synced chunk. Forward from all of them, each
805        // once per epoch.
806        let mut next_to_forward = (*self.next_randomness_to_forward.lock()).max(seq);
807        loop {
808            let highest_synced = self
809                .checkpoint_store
810                .get_highest_synced_checkpoint_seq_number()
811                .expect("db error")
812                .unwrap_or_default();
813            while next_to_forward <= highest_synced {
814                let synced = self
815                    .checkpoint_store
816                    .get_checkpoint_by_sequence_number(next_to_forward)
817                    .expect("db error")
818                    .expect("synced checkpoint should be in the store");
819                if synced.epoch() != epoch {
820                    next_to_forward = CheckpointSequenceNumber::MAX;
821                    break;
822                }
823                self.forward_randomness_from_checkpoint(synced);
824                next_to_forward += 1;
825                tokio::task::yield_now().await;
826            }
827            *self.next_randomness_to_forward.lock() = next_to_forward;
828            tokio::select! {
829                summary = self.checkpoint_store.notify_read_locally_computed_checkpoint(seq) => return Some(summary),
830                _ = self.checkpoint_store.notify_read_epoch_last_checkpoint_seq_number(epoch) => {
831                    self.epoch_store.start_executing_synced_checkpoints().await;
832                    return None;
833                }
834                _ = self.checkpoint_store.notify_read_synced_checkpoint(next_to_forward), if next_to_forward != CheckpointSequenceNumber::MAX => {}
835            }
836        }
837    }
838
839    /// Waits until every transaction in `digests`, all of `checkpoint`, has
840    /// executed, and returns `true`. Returns `false` once this node executes
841    /// synced checkpoints for the rest of the epoch instead, switching first
842    /// when the certified last checkpoint of the epoch becomes known.
843    ///
844    /// Called only on a committee validator keeping the P-COOL flow's
845    /// bookkeeping, which writes a transaction's handler rows only when the
846    /// consensus handler has assigned its commit. Until the switch only the
847    /// handler schedules these transactions, so they execute with their rows.
848    /// Normally they have executed before this node built the checkpoint. A
849    /// checkpoint built before a restart is the exception: its outputs were
850    /// only in memory, and the handler executes them again only once it
851    /// replays their commits.
852    async fn wait_for_handler_execution(
853        &self,
854        checkpoint: &VerifiedCheckpoint,
855        digests: &[TransactionDigest],
856    ) -> bool {
857        if self.epoch_store.is_executing_synced_checkpoints() {
858            return false;
859        }
860        // The transactions of a checkpoint execute in its epoch, so only that
861        // epoch's records are read.
862        if self
863            .transaction_cache_reader
864            .multi_get_executed_effects_digests_in_epoch(checkpoint.epoch(), digests)
865            .iter()
866            .all(Option::is_some)
867        {
868            return true;
869        }
870        let _backpressure_guard = self.backpressure_manager.wait_for_local_build();
871        // Peers drop their partial signatures for a round they completed, so
872        // the handler may get this checkpoint's randomness only from here.
873        self.forward_randomness_from_synced_contents(checkpoint);
874        let epoch = self.epoch_store.epoch();
875        tokio::select! {
876            biased;
877            _ = self.epoch_store.wait_for_synced_checkpoint_execution() => false,
878            _ = self.checkpoint_store.notify_read_epoch_last_checkpoint_seq_number(epoch) => {
879                self.epoch_store.start_executing_synced_checkpoints().await;
880                false
881            }
882            _ = self.transaction_cache_reader.notify_read_executed_effects_digests(
883                "CheckpointExecutor::wait_for_handler_execution",
884                digests,
885            ) => true,
886        }
887    }
888
889    /// [`Self::forward_randomness_from_checkpoint`] when state sync stored the
890    /// checkpoint's full contents; does nothing otherwise, since the
891    /// transactions of a checkpoint this node built may not be stored.
892    fn forward_randomness_from_synced_contents(&self, checkpoint: &VerifiedCheckpoint) {
893        let Some(reporter) = self.epoch_store.randomness_reporter() else {
894            return;
895        };
896        let Some(full_contents) = self
897            .checkpoint_store
898            .get_full_checkpoint_contents_by_sequence_number(checkpoint.sequence_number)
899        else {
900            return;
901        };
902        for execution_data in full_contents.iter() {
903            if let TransactionKind::RandomnessStateUpdate(rsu) =
904                execution_data.transaction.transaction().kind()
905            {
906                reporter
907                    .forward_randomness_from_checkpoint(rsu.randomness_round, &rsu.random_bytes);
908            }
909        }
910    }
911
912    fn forward_randomness_from_checkpoint(&self, checkpoint: VerifiedCheckpoint) {
913        let Some(reporter) = self.epoch_store.randomness_reporter() else {
914            return;
915        };
916        let contents = self
917            .checkpoint_store
918            .get_checkpoint_contents(&checkpoint.contents_digest)
919            .expect("db error")
920            .expect("checkpoint contents not found");
921        if self
922            .extract_randomness_rounds(&checkpoint, &contents)
923            .is_empty()
924        {
925            return;
926        }
927        let (_, tx_data) = self.load_checkpoint_transactions(checkpoint);
928        for tx in &tx_data.transactions {
929            if let TransactionKind::RandomnessStateUpdate(rsu) = tx.transaction().kind() {
930                reporter
931                    .forward_randomness_from_checkpoint(rsu.randomness_round, &rsu.random_bytes);
932            }
933        }
934    }
935
936    #[instrument(level = "info", skip_all)]
937    async fn execute_transactions_from_synced_checkpoint(
938        &self,
939        mut ckpt_state: CheckpointExecutionState,
940        tx_data: CheckpointTransactionData,
941        pipeline_handle: &mut PipelineHandle,
942    ) -> CheckpointExecutionState {
943        let sequence_number = ckpt_state.data.checkpoint.sequence_number;
944
945        let (unexecuted_tx_digests, unexecuted_expected_fx_digests) = {
946            let _scope = iota_metrics::monitored_scope("CheckpointExecutor::execute_transactions");
947            self.schedule_transaction_execution(&ckpt_state, &tx_data)
948        };
949
950        finish_stage!(pipeline_handle, ExecuteTransactions);
951
952        {
953            let actual_fx_digests = self
954                .transaction_cache_reader
955                .notify_read_executed_effects_digests(
956                    "CheckpointExecutor::notify_read_executed_effects_digests",
957                    &unexecuted_tx_digests,
958                )
959                .await;
960
961            // A transaction scheduled here can also be scheduled from consensus,
962            // and whichever enqueue arrives second is dropped along with its
963            // environment — so the expected digest passed above may never have
964            // reached execution. Compare here, where the checkpoint's digests are
965            // known, so a fork is caught regardless of which enqueue won.
966            for (tx_digest, expected, actual) in itertools::izip!(
967                unexecuted_tx_digests.iter(),
968                unexecuted_expected_fx_digests.iter(),
969                actual_fx_digests.iter()
970            ) {
971                assert_not_forked(
972                    &ckpt_state.data.checkpoint,
973                    tx_digest,
974                    expected,
975                    actual,
976                    &*self.transaction_cache_reader,
977                );
978            }
979        }
980
981        finish_stage!(pipeline_handle, WaitForTransactions);
982
983        if ckpt_state.data.checkpoint.is_last_checkpoint_of_epoch() {
984            self.execute_change_epoch_tx(&tx_data).await;
985        }
986
987        let _scope = iota_metrics::monitored_scope("CheckpointExecutor::finalize_checkpoint");
988
989        if self.state.is_fullnode(&self.epoch_store) {
990            self.state.congestion_tracker.process_checkpoint_effects(
991                &*self.transaction_cache_reader,
992                &ckpt_state.data.checkpoint,
993                &tx_data.effects,
994            );
995        }
996
997        self.insert_finalized_transactions(
998            &ckpt_state.data.tx_digests,
999            sequence_number,
1000            ckpt_state.data.checkpoint.timestamp_ms,
1001        );
1002
1003        // The early versions of the hasher (prior to effectsv2) rely on db
1004        // state, so we must wait until all transactions have been executed
1005        // before accumulating the checkpoint.
1006        ckpt_state.state_hash = Some(
1007            self.global_state_hasher
1008                .accumulate_checkpoint(&tx_data.effects, sequence_number, &self.epoch_store)
1009                .expect("epoch cannot have ended"),
1010        );
1011
1012        finish_stage!(pipeline_handle, FinalizeTransactions);
1013
1014        ckpt_state.full_data = self.process_checkpoint_data(&ckpt_state.data, &tx_data);
1015
1016        finish_stage!(pipeline_handle, ProcessCheckpointData);
1017
1018        ckpt_state
1019    }
1020
1021    fn checkpoint_data_enabled(&self) -> bool {
1022        self.state.rpc_indexes_store.is_some()
1023            || self.config.data_ingestion_dir.is_some()
1024            || self.data_sender.is_some()
1025    }
1026
1027    fn insert_finalized_transactions(
1028        &self,
1029        tx_digests: &[TransactionDigest],
1030        sequence_number: CheckpointSequenceNumber,
1031        timestamp_ms: u64,
1032    ) {
1033        self.epoch_store
1034            .insert_finalized_transactions(tx_digests, sequence_number, timestamp_ms)
1035            .expect("failed to insert finalized transactions");
1036
1037        if self.state.is_fullnode(&self.epoch_store) {
1038            // TODO remove once we no longer need to support this table for read RPC
1039            self.state
1040                .get_checkpoint_cache()
1041                .insert_finalized_transactions_perpetual_checkpoints(
1042                    tx_digests,
1043                    self.epoch_store.epoch(),
1044                    sequence_number,
1045                );
1046        }
1047    }
1048
1049    #[instrument(level = "info", skip_all)]
1050    fn process_checkpoint_data(
1051        &self,
1052        ckpt_data: &CheckpointExecutionData,
1053        tx_data: &CheckpointTransactionData,
1054    ) -> Option<CheckpointData> {
1055        let is_checkpoint_data_enabled = self.checkpoint_data_enabled();
1056        let is_last_checkpoint_of_epoch = ckpt_data.checkpoint.is_last_checkpoint_of_epoch();
1057        if !is_checkpoint_data_enabled && !is_last_checkpoint_of_epoch {
1058            return None;
1059        }
1060
1061        if !is_checkpoint_data_enabled {
1062            // With no checkpoint data consumer, the `epoch_info` row is the only
1063            // user of this data, and it reads just the epoch-change transaction,
1064            // so the other transactions are not loaded.
1065            let boundary_data = load_epoch_boundary_data(
1066                ckpt_data,
1067                tx_data,
1068                self.state.get_object_store(),
1069                self.state.get_historic_objects(),
1070                &*self.transaction_cache_reader,
1071            )
1072            .expect("failed to load epoch boundary data");
1073            self.checkpoint_store
1074                .index_epoch_boundary(&boundary_data)
1075                .expect("failed to persist epoch info at boundary");
1076            return None;
1077        }
1078
1079        let checkpoint_data = load_checkpoint_data(
1080            ckpt_data,
1081            tx_data,
1082            self.state.get_object_store(),
1083            self.state.get_historic_objects(),
1084            &*self.transaction_cache_reader,
1085        )
1086        .expect("failed to load checkpoint data");
1087
1088        if is_last_checkpoint_of_epoch {
1089            self.checkpoint_store
1090                .index_epoch_boundary(&checkpoint_data)
1091                .expect("failed to persist epoch info at boundary");
1092        }
1093
1094        // The RPC indexes accumulate non-idempotent state, so each update must
1095        // land exactly once. The transaction outputs are not durable yet, so
1096        // the writes are only staged here and committed, in checkpoint order,
1097        // after `FinalizeCheckpoint` via `commit_index_updates`.
1098        if let Some(rpc_indexes_store) = &self.state.rpc_indexes_store {
1099            rpc_indexes_store
1100                .index_checkpoint(&checkpoint_data)
1101                .expect("failed to stage the RPC index update");
1102        }
1103
1104        if let Some(path) = &self.config.data_ingestion_dir {
1105            store_checkpoint_locally(path, &checkpoint_data)
1106                .expect("failed to store checkpoint locally");
1107        }
1108
1109        Some(checkpoint_data)
1110    }
1111
1112    // Load all required transaction and effects data for the checkpoint.
1113    #[instrument(level = "info", skip_all)]
1114    fn load_checkpoint_transactions(
1115        &self,
1116        checkpoint: VerifiedCheckpoint,
1117    ) -> (CheckpointExecutionState, CheckpointTransactionData) {
1118        let seq = checkpoint.sequence_number;
1119        let epoch = checkpoint.epoch;
1120
1121        let checkpoint_contents = self
1122            .checkpoint_store
1123            .get_checkpoint_contents(&checkpoint.contents_digest)
1124            .expect("db error")
1125            .expect("checkpoint contents not found");
1126        let version_specific_data = self.parse_version_specific_data(&checkpoint);
1127
1128        // attempt to load full checkpoint contents in bulk
1129        if let Some(full_contents) = self
1130            .checkpoint_store
1131            .get_full_checkpoint_contents_by_sequence_number(seq)
1132            .tap_some(|_| debug!("loaded full checkpoint contents in bulk for sequence {seq}"))
1133        {
1134            let num_txns = full_contents.size();
1135            let mut tx_digests = Vec::with_capacity(num_txns);
1136            let mut transactions = Vec::with_capacity(num_txns);
1137            let mut effects = Vec::with_capacity(num_txns);
1138            let mut fx_digests = Vec::with_capacity(num_txns);
1139
1140            full_contents
1141                .iter()
1142                .zip(checkpoint_contents.iter())
1143                .for_each(|(execution_data, digests)| {
1144                    let tx_digest = digests.transaction;
1145                    let fx_digest = digests.effects;
1146                    debug_assert_eq!(tx_digest, *execution_data.transaction.digest());
1147                    debug_assert_eq!(fx_digest, execution_data.effects.digest());
1148
1149                    tx_digests.push(tx_digest);
1150                    transactions.push(VerifiedExecutableTransaction::new_from_checkpoint(
1151                        VerifiedTransaction::new_unchecked(execution_data.transaction.clone()),
1152                        epoch,
1153                        seq,
1154                    ));
1155                    effects.push(execution_data.effects.clone());
1156                    fx_digests.push(fx_digest);
1157                });
1158
1159            (
1160                CheckpointExecutionState::new(CheckpointExecutionData {
1161                    checkpoint,
1162                    checkpoint_contents,
1163                    tx_digests,
1164                    fx_digests,
1165                    version_specific_data,
1166                }),
1167                CheckpointTransactionData {
1168                    transactions,
1169                    effects,
1170                },
1171            )
1172        } else {
1173            // load items one-by-one
1174
1175            let digests = checkpoint_contents.transactions();
1176
1177            let (tx_digests, fx_digests): (Vec<_>, Vec<_>) =
1178                digests.iter().map(|d| (d.transaction, d.effects)).unzip();
1179            let verified_transactions: Vec<VerifiedTransaction> = self
1180                .transaction_cache_reader
1181                .multi_get_transaction_blocks(&tx_digests)
1182                .into_iter()
1183                .enumerate()
1184                .map(|(i, tx)| {
1185                    let tx = tx
1186                        .unwrap_or_else(|| fatal!("transaction not found for {:?}", tx_digests[i]));
1187                    Arc::try_unwrap(tx).unwrap_or_else(|tx| (*tx).clone())
1188                })
1189                .collect();
1190            let effects: Vec<TransactionEffects> = self
1191                .transaction_cache_reader
1192                .multi_get_effects(&fx_digests)
1193                .into_iter()
1194                .enumerate()
1195                .map(|(i, effect)| {
1196                    effect.unwrap_or_else(|| {
1197                        fatal!("checkpoint effect not found for {:?}", digests[i])
1198                    })
1199                })
1200                .collect();
1201
1202            // Reached when the contents were not already cached: a fullnode
1203            // syncing from a peer, or a node catching up. Cache the assembled
1204            // contents so this node can in turn serve state-sync peers without
1205            // reconstruction. (Validators' locally built checkpoints are cached
1206            // by the checkpoint builder and take the bulk path above instead.)
1207            //
1208            // The assembly clones every transaction and effect, so skip it
1209            // when the cache wouldn't retain the entry (see `should_cache`).
1210            if self
1211                .checkpoint_store
1212                .should_cache_full_checkpoint_contents(seq)
1213            {
1214                let execution_data = verified_transactions
1215                    .iter()
1216                    .zip(effects.iter())
1217                    .map(|(tx, fx)| ExecutionData::new(tx.clone().into_inner(), fx.clone()));
1218                let full_contents = FullCheckpointContents::from_contents_and_local_execution_data(
1219                    checkpoint_contents.clone(),
1220                    execution_data,
1221                )
1222                // Both were loaded for this checkpoint's own contents above,
1223                // one transaction and one effects entry per digest.
1224                .expect("checkpoint has one executed transaction per pinned signature set");
1225                self.checkpoint_store.cache_full_checkpoint_contents(
1226                    seq,
1227                    checkpoint.contents_digest,
1228                    full_contents,
1229                );
1230            }
1231
1232            let transactions = verified_transactions
1233                .into_iter()
1234                .map(|tx| VerifiedExecutableTransaction::new_from_checkpoint(tx, epoch, seq))
1235                .collect();
1236
1237            (
1238                CheckpointExecutionState::new(CheckpointExecutionData {
1239                    checkpoint,
1240                    checkpoint_contents,
1241                    tx_digests,
1242                    fx_digests,
1243                    version_specific_data,
1244                }),
1245                CheckpointTransactionData {
1246                    transactions,
1247                    effects,
1248                },
1249            )
1250        }
1251    }
1252
1253    /// Compares the records this node recorded for the already-executed
1254    /// transactions with the certified ones.
1255    fn check_executed_attestation_records(
1256        &self,
1257        epoch: EpochId,
1258        tx_digests: &[TransactionDigest],
1259        executed_fx_digests: &[Option<TransactionEffectsDigest>],
1260        certified_attestations: &[Option<AttestationRecord>],
1261    ) {
1262        // Without attestation no transaction has a record to read.
1263        if !self
1264            .epoch_store
1265            .protocol_config()
1266            .enable_validator_attestation()
1267        {
1268            return;
1269        }
1270        let (digests, certified): (Vec<_>, Vec<_>) =
1271            itertools::izip!(tx_digests, executed_fx_digests, certified_attestations)
1272                .filter_map(|(digest, executed, record)| executed.map(|_| (*digest, *record)))
1273                .unzip();
1274        if digests.is_empty() {
1275            return;
1276        }
1277        let local = self
1278            .transaction_cache_reader
1279            .multi_get_attestation_records_in_epoch(epoch, &digests);
1280        for (digest, certified, local) in itertools::izip!(digests, certified, local) {
1281            if attestation_record_differs(local, certified) {
1282                self.metrics
1283                    .checkpoint_exec_attestation_verdict_mismatches
1284                    .inc();
1285                warn!(
1286                    ?digest,
1287                    ?local,
1288                    ?certified,
1289                    "locally recorded attestation verdict differs from the certified one"
1290                );
1291            }
1292        }
1293    }
1294
1295    /// Enqueues the checkpoint's not-yet-executed transactions, and returns
1296    /// their digests together with the effects digest the checkpoint expects
1297    /// for each, so the caller can check for a fork once they execute.
1298    #[instrument(level = "info", skip_all)]
1299    fn schedule_transaction_execution(
1300        &self,
1301        ckpt_state: &CheckpointExecutionState,
1302        tx_data: &CheckpointTransactionData,
1303    ) -> (Vec<TransactionDigest>, Vec<TransactionEffectsDigest>) {
1304        // Which transactions have already been executed must be read here, in
1305        // the ordered pipeline stage, and not when the checkpoint data is
1306        // loaded: execution progresses in between, and a stale answer would
1307        // skip the fork check for a transaction that executed since loading.
1308        let executed_fx_digests = self
1309            .transaction_cache_reader
1310            .multi_get_executed_effects_digests_in_epoch(
1311                ckpt_state.data.checkpoint.epoch(),
1312                &ckpt_state.data.tx_digests,
1313            );
1314        let certified_attestations = ckpt_state.data.certified_attestations();
1315        self.check_executed_attestation_records(
1316            ckpt_state.data.checkpoint.epoch(),
1317            &ckpt_state.data.tx_digests,
1318            &executed_fx_digests,
1319            &certified_attestations,
1320        );
1321
1322        // Find unexecuted transactions and their expected effects digests
1323        let (unexecuted_tx_digests, unexecuted_expected_fx_digests, unexecuted_txns): (
1324            Vec<_>,
1325            Vec<_>,
1326            Vec<_>,
1327        ) = itertools::multiunzip(
1328            itertools::izip!(
1329                tx_data.transactions.iter(),
1330                ckpt_state.data.tx_digests.iter(),
1331                ckpt_state.data.fx_digests.iter(),
1332                tx_data.effects.iter(),
1333                executed_fx_digests.iter(),
1334                certified_attestations.iter().copied()
1335            )
1336            .filter_map(
1337                |(txn, tx_digest, expected_fx_digest, effects, executed_fx_digest, record)| {
1338                    if let Some(executed_fx_digest) = executed_fx_digest {
1339                        assert_not_forked(
1340                            &ckpt_state.data.checkpoint,
1341                            tx_digest,
1342                            expected_fx_digest,
1343                            executed_fx_digest,
1344                            &*self.transaction_cache_reader,
1345                        );
1346                        None
1347                    } else if txn.transaction().is_end_of_epoch_tx() {
1348                        None
1349                    } else {
1350                        // A transaction without shared inputs normally needs no version
1351                        // assignments, but one cancelled for congestion carries its
1352                        // cancellation version on the gas object, which re-execution
1353                        // must reproduce.
1354                        let assigned_versions = if txn.contains_shared_object()
1355                            || gas_object_cancellation_version_from_effects(effects).is_some()
1356                        {
1357                            self.epoch_store
1358                                .acquire_shared_version_assignments_from_effects(
1359                                    txn,
1360                                    effects,
1361                                    &*self.object_cache_reader,
1362                                )
1363                                .expect("failed to initialize shared object versions from effects")
1364                        } else {
1365                            Default::default()
1366                        };
1367
1368                        let env = ExecutionEnv::new()
1369                            .with_assigned_versions(assigned_versions)
1370                            .with_expected_effects_digest(*expected_fx_digest)
1371                            .with_attestation(AttestationSource::Certified(record));
1372
1373                        Some((tx_digest, *expected_fx_digest, (txn.clone(), env)))
1374                    }
1375                },
1376            ),
1377        );
1378
1379        // Enqueue unexecuted transactions with their expected effects digests
1380        self.execution_scheduler
1381            .enqueue_transactions(unexecuted_txns, &self.epoch_store);
1382
1383        (unexecuted_tx_digests, unexecuted_expected_fx_digests)
1384    }
1385
1386    // Execute the change epoch txn
1387    #[instrument(level = "error", skip_all)]
1388    async fn execute_change_epoch_tx(&self, tx_data: &CheckpointTransactionData) {
1389        let change_epoch_tx = tx_data.transactions.last().unwrap();
1390        let change_epoch_fx = tx_data.effects.last().unwrap();
1391        assert_eq!(
1392            change_epoch_tx.digest(),
1393            change_epoch_fx.transaction_digest()
1394        );
1395        assert!(
1396            change_epoch_tx.transaction().is_end_of_epoch_tx(),
1397            "final txn must be an end of epoch txn"
1398        );
1399
1400        // Ordinarily we would assert that the change epoch txn has not been executed
1401        // yet. However, during crash recovery, it is possible that we already
1402        // passed this point and the txn has been executed. You can uncomment
1403        // this assert if you are debugging a problem related to reconfig. If
1404        // you hit this assert and it is not because of crash-recovery,
1405        // it may indicate a bug in the checkpoint executor.
1406        //
1407        //     if self
1408        //         .transaction_cache_reader
1409        //         .get_executed_effects(change_epoch_tx.digest())
1410        //         .is_some()
1411        //     {
1412        //         fatal!(
1413        //             "end of epoch txn must not have been executed: {:?}",
1414        //             change_epoch_tx.digest()
1415        //         );
1416        //     }
1417
1418        let assigned_versions = self
1419            .epoch_store
1420            .acquire_shared_version_assignments_from_effects(
1421                change_epoch_tx,
1422                change_epoch_fx,
1423                self.object_cache_reader.as_ref(),
1424            )
1425            .expect("failed to initialize shared object versions for the change epoch transaction");
1426
1427        info!(
1428            "scheduling change epoch txn with digest: {:?}, expected effects digest: {:?}, \
1429            assigned versions: {:?}",
1430            change_epoch_tx.digest(),
1431            change_epoch_fx.digest(),
1432            assigned_versions
1433        );
1434        self.execution_scheduler.enqueue_transactions(
1435            vec![(
1436                change_epoch_tx.clone(),
1437                ExecutionEnv::new()
1438                    .with_assigned_versions(assigned_versions)
1439                    .with_expected_effects_digest(change_epoch_fx.digest()),
1440            )],
1441            &self.epoch_store,
1442        );
1443
1444        self.transaction_cache_reader
1445            .notify_read_executed_effects_digests(
1446                "CheckpointExecutor::notify_read_advance_epoch_tx",
1447                &[*change_epoch_tx.digest()],
1448            )
1449            .await;
1450    }
1451
1452    // Increment the highest executed checkpoint watermark
1453    #[instrument(level = "debug", skip_all)]
1454    fn bump_highest_executed_checkpoint(&self, checkpoint: &VerifiedCheckpoint) {
1455        // Ensure that we are not skipping checkpoints at any point
1456        let seq = checkpoint.sequence_number();
1457        debug!("Bumping highest_executed_checkpoint watermark to {seq:?}");
1458        if let Some(prev_highest) = self
1459            .checkpoint_store
1460            .get_highest_executed_checkpoint_seq_number()
1461            .unwrap()
1462        {
1463            assert_eq!(prev_highest + 1, seq);
1464        } else {
1465            assert_eq!(seq, 0);
1466        }
1467        fail_point!("highest-executed-checkpoint");
1468
1469        self.checkpoint_store
1470            .update_highest_executed_checkpoint(checkpoint)
1471            .unwrap();
1472        self.metrics.last_executed_checkpoint.set(seq as i64);
1473        // The executor runs from the end of the previous epoch after an epoch
1474        // change, so its first checkpoint is the first of the epoch.
1475        if !self.executed_any_checkpoint.swap(true, Ordering::Relaxed) {
1476            self.epoch_store.metrics.record_epoch_change_stage_now(
1477                self.epoch_store.epoch(),
1478                "first_checkpoint_executed",
1479            );
1480        }
1481
1482        self.metrics
1483            .last_executed_checkpoint_timestamp_ms
1484            .set(checkpoint.timestamp_ms as i64);
1485        checkpoint.report_checkpoint_age(&self.metrics.last_executed_checkpoint_age);
1486    }
1487
1488    /// Sets `attestation_certified_totals` to the attestation totals that the
1489    /// checkpoint of `data` certifies.
1490    fn report_certified_attestation_totals(&self, data: &CheckpointExecutionData) {
1491        let Some(totals) = data
1492            .version_specific_data
1493            .as_ref()
1494            .and_then(CheckpointVersionSpecificData::attestation_totals)
1495        else {
1496            return;
1497        };
1498        for (&attestor, &units_squared) in &totals.refuted_units_squared {
1499            let hostname = self
1500                .epoch_store
1501                .hostname_by_authority_index(u32::from(attestor));
1502            if let Some(hostname) = hostname {
1503                self.metrics
1504                    .attestation_certified_totals
1505                    .with_label_values(&[hostname])
1506                    .set(i64::try_from(units_squared).unwrap_or(i64::MAX));
1507            }
1508        }
1509    }
1510
1511    /// Send the finished checkpoint to the checkpoint data channel, if set.
1512    fn broadcast_checkpoint(
1513        &self,
1514        checkpoint_exec_data: &CheckpointExecutionData,
1515        checkpoint_data: Option<&CheckpointData>,
1516    ) {
1517        if let Some(data_sender) = &self.data_sender {
1518            let loaded;
1519            let checkpoint_data = match checkpoint_data {
1520                Some(data) => data,
1521                None => {
1522                    // Rare: a data channel without `checkpoint_data_enabled`.
1523                    let (_, tx_data) =
1524                        self.load_checkpoint_transactions(checkpoint_exec_data.checkpoint.clone());
1525                    loaded = load_checkpoint_data(
1526                        checkpoint_exec_data,
1527                        &tx_data,
1528                        self.state.get_object_store(),
1529                        self.state.get_historic_objects(),
1530                        self.transaction_cache_reader.as_ref(),
1531                    )
1532                    .expect("Failed to load full CheckpointData");
1533                    &loaded
1534                }
1535            };
1536            data_sender(checkpoint_data);
1537        }
1538
1539        debug!(
1540            "[Fullnode] Full CheckpointData is available: seq={}",
1541            checkpoint_exec_data.checkpoint.sequence_number()
1542        );
1543    }
1544
1545    /// If configured, commit the pending index updates for the checkpoint.
1546    #[instrument(level = "info", skip_all)]
1547    fn commit_index_updates(&self, sequence_number: CheckpointSequenceNumber) {
1548        if let Some(rpc_indexes_store) = &self.state.rpc_indexes_store {
1549            rpc_indexes_store
1550                .commit_update_for_checkpoint(sequence_number)
1551                .expect("failed to update the RPC indexes");
1552        }
1553    }
1554
1555    fn parse_version_specific_data(
1556        &self,
1557        checkpoint: &VerifiedCheckpoint,
1558    ) -> Option<CheckpointVersionSpecificData> {
1559        checkpoint
1560            .parse_version_specific_data(self.epoch_store.protocol_config())
1561            .expect("unable to get version_specific_data")
1562    }
1563
1564    /// Stores on the epoch store the attestors that the epoch's totals in
1565    /// `data` cut off. Does nothing when the cutoff is off.
1566    fn store_cut_off_attestors(&self, data: Option<&CheckpointVersionSpecificData>) {
1567        let Some(max_refuted_units_squared) = self
1568            .epoch_store
1569            .protocol_config()
1570            .attestation_max_refuted_units_squared_as_option()
1571        else {
1572            return;
1573        };
1574        let Some(totals) = data.and_then(|data| data.attestation_totals()) else {
1575            return;
1576        };
1577        self.epoch_store.set_cut_off_attestors(cut_off_attestors(
1578            totals,
1579            max_refuted_units_squared,
1580            self.epoch_store.committee(),
1581        ));
1582    }
1583
1584    /// Stores the cut-off attestors as of the highest executed checkpoint, so
1585    /// a node restarted during the epoch does not start without them. Does
1586    /// nothing when no checkpoint of this epoch has executed yet.
1587    ///
1588    /// # Panics
1589    ///
1590    /// If the checkpoint store cannot be read, or the checkpoint's
1591    /// `version_specific_data` does not decode.
1592    fn seed_cut_off_attestors(&self) {
1593        let highest_executed = self
1594            .checkpoint_store
1595            .get_highest_executed_checkpoint()
1596            .expect("db error");
1597        // Checked before parsing: an earlier epoch's summary may not parse
1598        // under this epoch's protocol config.
1599        if let Some(checkpoint) =
1600            highest_executed.filter(|checkpoint| checkpoint.epoch() == self.epoch_store.epoch())
1601        {
1602            self.store_cut_off_attestors(self.parse_version_specific_data(&checkpoint).as_ref());
1603        }
1604    }
1605
1606    // Extract randomness rounds from the checkpoint version-specific data (if
1607    // available). Otherwise, extract randomness rounds from the first
1608    // transaction in the checkpoint
1609    #[instrument(level = "debug", skip_all)]
1610    fn extract_randomness_rounds(
1611        &self,
1612        checkpoint: &VerifiedCheckpoint,
1613        checkpoint_contents: &CheckpointContents,
1614    ) -> Vec<RandomnessRound> {
1615        if let Some(version_specific_data) = self.parse_version_specific_data(checkpoint) {
1616            // With version-specific data, randomness rounds are stored in checkpoint
1617            // summary.
1618            version_specific_data.randomness_rounds().to_vec()
1619        } else {
1620            // Before version-specific data, checkpoint batching must be disabled. In this
1621            // case, randomness state update tx must be first if it exists,
1622            // because all other transactions in a checkpoint that includes a
1623            // randomness state update are causally dependent on it.
1624            assert_eq!(
1625                0,
1626                self.epoch_store
1627                    .protocol_config()
1628                    .min_checkpoint_interval_ms_as_option()
1629                    .unwrap_or_default(),
1630            );
1631            if let Some(first_digest) = checkpoint_contents.transactions().first() {
1632                let maybe_randomness_tx = self.transaction_cache_reader.get_transaction_block(&first_digest.transaction)
1633                .unwrap_or_else(||
1634                    fatal!(
1635                        "state-sync should have ensured that transaction with digests {first_digest:?} exists for checkpoint: {}",
1636                        checkpoint.sequence_number()
1637                    )
1638                );
1639                if let TransactionKind::RandomnessStateUpdate(rsu) =
1640                    maybe_randomness_tx.data().transaction().kind()
1641                {
1642                    vec![rsu.randomness_round]
1643                } else {
1644                    Vec::new()
1645                }
1646            } else {
1647                Vec::new()
1648            }
1649        }
1650    }
1651}
1652
1653/// Whether the record a node stored for an executed transaction disagrees
1654/// with the certified one. Only records other than `Valid` are certified, so
1655/// a valid local record matches no certified one.
1656fn attestation_record_differs(
1657    local: Option<AttestationRecord>,
1658    certified: Option<AttestationRecord>,
1659) -> bool {
1660    local.filter(|record| !record.verdict.is_valid()) != certified
1661}
1662
1663/// The committee members whose `totals` take their whole score.
1664fn cut_off_attestors(
1665    totals: &AttestationTotals,
1666    max_refuted_units_squared: u64,
1667    committee: &Committee,
1668) -> BTreeSet<AuthorityName> {
1669    attestors_taking_whole_score(totals, max_refuted_units_squared)
1670        .into_iter()
1671        .filter_map(|attestor| committee.authority_by_index(u32::from(attestor)).copied())
1672        .collect()
1673}