sui_core/checkpoints/
mod.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4pub(crate) mod causal_order;
5pub mod checkpoint_executor;
6mod checkpoint_output;
7mod metrics;
8
9use crate::accumulators::{self, AccumulatorSettlementTxBuilder};
10use crate::authority::AuthorityState;
11use crate::authority::epoch_start_configuration::EpochStartConfigTrait;
12use crate::authority_client::{AuthorityAPI, make_network_authority_clients_with_network_config};
13use crate::checkpoints::causal_order::CausalOrder;
14use crate::checkpoints::checkpoint_output::{CertifiedCheckpointOutput, CheckpointOutput};
15pub use crate::checkpoints::checkpoint_output::{
16    LogCheckpointOutput, SendCheckpointToStateSync, SubmitCheckpointToConsensus,
17};
18pub use crate::checkpoints::metrics::CheckpointMetrics;
19use crate::consensus_manager::ReplayWaiter;
20use crate::execution_cache::TransactionCacheRead;
21
22use crate::execution_scheduler::funds_withdraw_scheduler::FundsSettlement;
23use crate::global_state_hasher::GlobalStateHasher;
24use crate::stake_aggregator::{InsertResult, MultiStakeAggregator};
25use consensus_core::CommitRef;
26use diffy::create_patch;
27use itertools::Itertools;
28use mysten_common::ZipDebugEqIteratorExt;
29use mysten_common::random::get_rng;
30use mysten_common::sync::notify_read::{CHECKPOINT_BUILDER_NOTIFY_READ_TASK_NAME, NotifyRead};
31use mysten_common::{assert_reachable, debug_fatal, fatal, in_antithesis};
32use mysten_metrics::{MonitoredFutureExt, monitored_scope, spawn_monitored_task};
33use nonempty::NonEmpty;
34use parking_lot::Mutex;
35use pin_project_lite::pin_project;
36use serde::{Deserialize, Serialize};
37use sui_macros::fail_point_arg;
38use sui_network::default_mysten_network_config;
39use sui_types::SUI_ACCUMULATOR_ROOT_OBJECT_ID;
40use sui_types::base_types::{ConciseableName, SequenceNumber};
41use sui_types::executable_transaction::VerifiedExecutableTransaction;
42use sui_types::execution::ExecutionTimeObservationKey;
43use sui_types::messages_checkpoint::{
44    CheckpointArtifacts, CheckpointCommitment, VersionedFullCheckpointContents,
45};
46use sui_types::sui_system_state::epoch_start_sui_system_state::EpochStartSystemStateTrait;
47use tokio::sync::{mpsc, watch};
48use typed_store::rocks::{DBOptions, ReadWriteOptions, default_db_options};
49
50use crate::authority::authority_per_epoch_store::AuthorityPerEpochStore;
51use crate::authority::authority_store_pruner::PrunerWatermarks;
52use crate::consensus_handler::SequencedConsensusTransactionKey;
53use rand::seq::SliceRandom;
54use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
55use std::fs::File;
56use std::future::Future;
57use std::io::Write;
58use std::path::Path;
59use std::pin::Pin;
60use std::sync::Arc;
61use std::sync::Weak;
62use std::task::{Context, Poll};
63use std::time::{Duration, SystemTime};
64use sui_protocol_config::ProtocolVersion;
65use sui_types::base_types::{AuthorityName, EpochId, TransactionDigest};
66use sui_types::committee::StakeUnit;
67use sui_types::crypto::AuthorityStrongQuorumSignInfo;
68use sui_types::digests::{
69    CheckpointContentsDigest, CheckpointDigest, Digest, TransactionEffectsDigest,
70};
71use sui_types::effects::{TransactionEffects, TransactionEffectsAPI};
72use sui_types::error::{SuiErrorKind, SuiResult};
73use sui_types::gas::GasCostSummary;
74use sui_types::message_envelope::Message;
75use sui_types::messages_checkpoint::{
76    CertifiedCheckpointSummary, CheckpointContents, CheckpointResponseV2, CheckpointSequenceNumber,
77    CheckpointSignatureMessage, CheckpointSummary, CheckpointSummaryResponse, CheckpointTimestamp,
78    EndOfEpochData, FullCheckpointContents, TrustedCheckpoint, VerifiedCheckpoint,
79    VerifiedCheckpointContents,
80};
81use sui_types::messages_checkpoint::{CheckpointRequestV2, SignedCheckpointSummary};
82use sui_types::messages_consensus::ConsensusTransactionKey;
83use sui_types::signature::GenericSignature;
84use sui_types::sui_system_state::{SuiSystemState, SuiSystemStateTrait};
85use sui_types::transaction::{
86    TransactionDataAPI, TransactionKey, TransactionKind, VerifiedTransaction,
87};
88use tokio::sync::Notify;
89use tracing::{debug, error, info, instrument, trace, warn};
90use typed_store::DBMapUtils;
91use typed_store::Map;
92use typed_store::{
93    TypedStoreError,
94    rocks::{DBMap, MetricConf},
95};
96
97const TRANSACTION_FORK_DETECTED_KEY: u8 = 0;
98
99pub type CheckpointHeight = u64;
100
101pub struct EpochStats {
102    pub checkpoint_count: u64,
103    pub transaction_count: u64,
104    pub total_gas_reward: u64,
105}
106
107#[derive(Clone, Debug)]
108pub struct PendingCheckpointInfo {
109    pub timestamp_ms: CheckpointTimestamp,
110    pub last_of_epoch: bool,
111    // Computed in calculate_pending_checkpoint_height() from consensus round,
112    // there is no guarantee that this is increasing per checkpoint, because of checkpoint splitting.
113    pub checkpoint_height: CheckpointHeight,
114    // Consensus commit ref and rejected transactions digest which corresponds to this checkpoint.
115    pub consensus_commit_ref: CommitRef,
116    pub rejected_transactions_digest: Digest,
117    // Pre-assigned checkpoint sequence number from consensus handler.
118    // Only set when split_checkpoints_in_consensus_handler is enabled.
119    pub checkpoint_seq: Option<CheckpointSequenceNumber>,
120}
121
122#[derive(Clone, Debug)]
123pub struct PendingCheckpoint {
124    pub roots: Vec<TransactionKey>,
125    pub details: PendingCheckpointInfo,
126}
127
128#[derive(Clone, Debug, Default)]
129pub struct CheckpointRoots {
130    pub tx_roots: Vec<TransactionKey>,
131    pub settlement_root: Option<TransactionKey>,
132    pub height: CheckpointHeight,
133}
134
135/// PendingCheckpointV2 is merged and split in ConsensusHandler
136/// instead of CheckpointBuilder. It contains 1 or more
137/// CheckpointRoots which represents a group of transactions
138/// settled together.
139/// Usage of PendingCheckpointV2 is gated by split_checkpoints_in_consensus_handler
140/// We need to support dual implementations until this feature flag is removed.
141#[derive(Clone, Debug)]
142pub struct PendingCheckpointV2 {
143    pub roots: Vec<CheckpointRoots>,
144    pub details: PendingCheckpointInfo,
145}
146
147#[derive(Clone, Debug, Serialize, Deserialize)]
148pub struct BuilderCheckpointSummary {
149    pub summary: CheckpointSummary,
150    // Height at which this checkpoint summary was built. None for genesis checkpoint
151    pub checkpoint_height: Option<CheckpointHeight>,
152    pub position_in_commit: usize,
153}
154
155#[derive(DBMapUtils)]
156#[cfg_attr(tidehunter, tidehunter)]
157pub struct CheckpointStoreTables {
158    /// Maps checkpoint contents digest to checkpoint contents
159    pub(crate) checkpoint_content: DBMap<CheckpointContentsDigest, CheckpointContents>,
160
161    /// Maps checkpoint contents digest to checkpoint sequence number
162    pub(crate) checkpoint_sequence_by_contents_digest:
163        DBMap<CheckpointContentsDigest, CheckpointSequenceNumber>,
164
165    /// Stores entire checkpoint contents from state sync, indexed by sequence number, for
166    /// efficient reads of full checkpoints. Entries from this table are deleted after state
167    /// accumulation has completed.
168    #[default_options_override_fn = "full_checkpoint_content_table_default_config"]
169    // TODO: Once the switch to `full_checkpoint_content_v2` is fully active on mainnet,
170    // deprecate this table (and remove when possible).
171    full_checkpoint_content: DBMap<CheckpointSequenceNumber, FullCheckpointContents>,
172
173    /// Stores certified checkpoints
174    pub(crate) certified_checkpoints: DBMap<CheckpointSequenceNumber, TrustedCheckpoint>,
175    /// Map from checkpoint digest to certified checkpoint
176    pub(crate) checkpoint_by_digest: DBMap<CheckpointDigest, TrustedCheckpoint>,
177
178    /// Store locally computed checkpoint summaries so that we can detect forks and log useful
179    /// information. Can be pruned as soon as we verify that we are in agreement with the latest
180    /// certified checkpoint.
181    pub(crate) locally_computed_checkpoints: DBMap<CheckpointSequenceNumber, CheckpointSummary>,
182
183    /// A map from epoch ID to the sequence number of the last checkpoint in that epoch.
184    epoch_last_checkpoint_map: DBMap<EpochId, CheckpointSequenceNumber>,
185
186    /// Watermarks used to determine the highest verified, fully synced, and
187    /// fully executed checkpoints
188    pub(crate) watermarks: DBMap<CheckpointWatermark, (CheckpointSequenceNumber, CheckpointDigest)>,
189
190    /// Stores transaction fork detection information
191    pub(crate) transaction_fork_detected: DBMap<
192        u8,
193        (
194            TransactionDigest,
195            TransactionEffectsDigest,
196            TransactionEffectsDigest,
197        ),
198    >,
199    #[default_options_override_fn = "full_checkpoint_content_table_default_config"]
200    full_checkpoint_content_v2: DBMap<CheckpointSequenceNumber, VersionedFullCheckpointContents>,
201}
202
203fn full_checkpoint_content_table_default_config() -> DBOptions {
204    DBOptions {
205        options: default_db_options().options,
206        // We have seen potential data corruption issues in this table after forced shutdowns
207        // so we enable value hash logging to help with debugging.
208        // TODO: remove this once we have a better understanding of the root cause.
209        rw_options: ReadWriteOptions::default().set_log_value_hash(true),
210    }
211}
212
213impl CheckpointStoreTables {
214    #[cfg(not(tidehunter))]
215    pub fn new(path: &Path, metric_name: &'static str, _: Arc<PrunerWatermarks>) -> Self {
216        Self::open_tables_read_write(path.to_path_buf(), MetricConf::new(metric_name), None, None)
217    }
218
219    #[cfg(tidehunter)]
220    pub fn new(
221        path: &Path,
222        metric_name: &'static str,
223        pruner_watermarks: Arc<PrunerWatermarks>,
224    ) -> Self {
225        tracing::warn!("Checkpoint DB using tidehunter");
226        use crate::authority::authority_store_pruner::apply_relocation_filter;
227        use typed_store::tidehunter_util::{
228            Decision, KeySpaceConfig, KeyType, ThConfig, default_cells_per_mutex,
229            default_mutex_count, default_value_cache_size,
230        };
231        let mutexes = default_mutex_count();
232        let u64_sequence_key = KeyType::from_prefix_bits(6 * 8);
233        let override_dirty_keys_config = KeySpaceConfig::new()
234            .with_max_dirty_keys(16_000)
235            .with_value_cache_size(default_value_cache_size());
236        let config_u64 = ThConfig::new_with_config(
237            8,
238            mutexes,
239            u64_sequence_key,
240            override_dirty_keys_config.clone(),
241        );
242        let digest_config = ThConfig::new_with_rm_prefix(
243            32,
244            mutexes,
245            KeyType::uniform(default_cells_per_mutex()),
246            KeySpaceConfig::default(),
247            vec![0, 0, 0, 0, 0, 0, 0, 32],
248        );
249        let watermarks_config = KeySpaceConfig::new()
250            .with_value_cache_size(10)
251            .disable_unload();
252        let lru_config = KeySpaceConfig::new().with_value_cache_size(100);
253        let configs = vec![
254            (
255                "checkpoint_content",
256                digest_config.clone().with_config(
257                    KeySpaceConfig::new().with_relocation_filter(|_, _| Decision::Remove),
258                ),
259            ),
260            (
261                "checkpoint_sequence_by_contents_digest",
262                digest_config.clone().with_config(apply_relocation_filter(
263                    KeySpaceConfig::default(),
264                    pruner_watermarks.checkpoint_id.clone(),
265                    |sequence_number: CheckpointSequenceNumber| sequence_number,
266                    false,
267                )),
268            ),
269            (
270                "full_checkpoint_content",
271                config_u64.clone().with_config(apply_relocation_filter(
272                    override_dirty_keys_config.clone(),
273                    pruner_watermarks.checkpoint_id.clone(),
274                    |sequence_number: CheckpointSequenceNumber| sequence_number,
275                    true,
276                )),
277            ),
278            ("certified_checkpoints", config_u64.clone()),
279            (
280                "checkpoint_by_digest",
281                digest_config.clone().with_config(apply_relocation_filter(
282                    lru_config,
283                    pruner_watermarks.epoch_id.clone(),
284                    |checkpoint: TrustedCheckpoint| checkpoint.inner().epoch,
285                    false,
286                )),
287            ),
288            (
289                "locally_computed_checkpoints",
290                config_u64.clone().with_config(apply_relocation_filter(
291                    override_dirty_keys_config.clone(),
292                    pruner_watermarks.checkpoint_id.clone(),
293                    |checkpoint_id: CheckpointSequenceNumber| checkpoint_id,
294                    true,
295                )),
296            ),
297            ("epoch_last_checkpoint_map", config_u64.clone()),
298            (
299                "watermarks",
300                ThConfig::new_with_config(4, 1, KeyType::uniform(1), watermarks_config.clone()),
301            ),
302            (
303                "transaction_fork_detected",
304                ThConfig::new_with_config(
305                    1,
306                    1,
307                    KeyType::uniform(1),
308                    watermarks_config.with_relocation_filter(|_, _| Decision::Remove),
309                ),
310            ),
311            (
312                "full_checkpoint_content_v2",
313                config_u64.clone().with_config(apply_relocation_filter(
314                    override_dirty_keys_config.clone(),
315                    pruner_watermarks.checkpoint_id.clone(),
316                    |sequence_number: CheckpointSequenceNumber| sequence_number,
317                    true,
318                )),
319            ),
320        ];
321        Self::open_tables_read_write(
322            path.to_path_buf(),
323            MetricConf::new(metric_name),
324            configs
325                .into_iter()
326                .map(|(cf, config)| (cf.to_string(), config))
327                .collect(),
328        )
329    }
330
331    #[cfg(not(tidehunter))]
332    pub fn open_readonly(path: &Path) -> CheckpointStoreTablesReadOnly {
333        Self::get_read_only_handle(
334            path.to_path_buf(),
335            None,
336            None,
337            MetricConf::new("checkpoint_readonly"),
338        )
339    }
340
341    #[cfg(tidehunter)]
342    pub fn open_readonly(path: &Path) -> Self {
343        Self::new(path, "checkpoint", Arc::new(PrunerWatermarks::default()))
344    }
345}
346
347pub struct CheckpointStore {
348    pub(crate) tables: CheckpointStoreTables,
349    synced_checkpoint_notify_read: NotifyRead<CheckpointSequenceNumber, VerifiedCheckpoint>,
350    executed_checkpoint_notify_read: NotifyRead<CheckpointSequenceNumber, VerifiedCheckpoint>,
351}
352
353impl CheckpointStore {
354    pub fn new(path: &Path, pruner_watermarks: Arc<PrunerWatermarks>) -> Arc<Self> {
355        let tables = CheckpointStoreTables::new(path, "checkpoint", pruner_watermarks);
356        Arc::new(Self {
357            tables,
358            synced_checkpoint_notify_read: NotifyRead::new(),
359            executed_checkpoint_notify_read: NotifyRead::new(),
360        })
361    }
362
363    pub fn new_for_tests() -> Arc<Self> {
364        let ckpt_dir = mysten_common::tempdir().unwrap();
365        CheckpointStore::new(ckpt_dir.path(), Arc::new(PrunerWatermarks::default()))
366    }
367
368    pub fn new_for_db_checkpoint_handler(path: &Path) -> Arc<Self> {
369        let tables = CheckpointStoreTables::new(
370            path,
371            "db_checkpoint",
372            Arc::new(PrunerWatermarks::default()),
373        );
374        Arc::new(Self {
375            tables,
376            synced_checkpoint_notify_read: NotifyRead::new(),
377            executed_checkpoint_notify_read: NotifyRead::new(),
378        })
379    }
380
381    #[cfg(not(tidehunter))]
382    pub fn open_readonly(path: &Path) -> CheckpointStoreTablesReadOnly {
383        CheckpointStoreTables::open_readonly(path)
384    }
385
386    #[cfg(tidehunter)]
387    pub fn open_readonly(path: &Path) -> CheckpointStoreTables {
388        CheckpointStoreTables::open_readonly(path)
389    }
390
391    #[instrument(level = "info", skip_all)]
392    pub fn insert_genesis_checkpoint(
393        &self,
394        checkpoint: VerifiedCheckpoint,
395        contents: CheckpointContents,
396        epoch_store: &AuthorityPerEpochStore,
397    ) {
398        assert_eq!(
399            checkpoint.epoch(),
400            0,
401            "can't call insert_genesis_checkpoint with a checkpoint not in epoch 0"
402        );
403        assert_eq!(
404            *checkpoint.sequence_number(),
405            0,
406            "can't call insert_genesis_checkpoint with a checkpoint that doesn't have a sequence number of 0"
407        );
408
409        // Only insert the genesis checkpoint if the DB is empty and doesn't have it already
410        match self.get_checkpoint_by_sequence_number(0).unwrap() {
411            Some(existing_checkpoint) => {
412                assert_eq!(existing_checkpoint.digest(), checkpoint.digest())
413            }
414            None => {
415                if epoch_store.epoch() == checkpoint.epoch {
416                    epoch_store
417                        .put_genesis_checkpoint_in_builder(checkpoint.data(), &contents)
418                        .unwrap();
419                } else {
420                    debug!(
421                        validator_epoch =% epoch_store.epoch(),
422                        genesis_epoch =% checkpoint.epoch(),
423                        "Not inserting checkpoint builder data for genesis checkpoint",
424                    );
425                }
426                self.insert_checkpoint_contents(contents).unwrap();
427                self.insert_verified_checkpoint(&checkpoint).unwrap();
428                self.update_highest_synced_checkpoint(&checkpoint).unwrap();
429            }
430        }
431    }
432
433    pub fn get_checkpoint_by_digest(
434        &self,
435        digest: &CheckpointDigest,
436    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
437        self.tables
438            .checkpoint_by_digest
439            .get(digest)
440            .map(|maybe_checkpoint| maybe_checkpoint.map(|c| c.into()))
441    }
442
443    pub fn get_checkpoint_by_sequence_number(
444        &self,
445        sequence_number: CheckpointSequenceNumber,
446    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
447        self.tables
448            .certified_checkpoints
449            .get(&sequence_number)
450            .map(|maybe_checkpoint| maybe_checkpoint.map(|c| c.into()))
451    }
452
453    pub fn get_locally_computed_checkpoint(
454        &self,
455        sequence_number: CheckpointSequenceNumber,
456    ) -> Result<Option<CheckpointSummary>, TypedStoreError> {
457        self.tables
458            .locally_computed_checkpoints
459            .get(&sequence_number)
460    }
461
462    pub fn multi_get_locally_computed_checkpoints(
463        &self,
464        sequence_numbers: &[CheckpointSequenceNumber],
465    ) -> Result<Vec<Option<CheckpointSummary>>, TypedStoreError> {
466        let checkpoints = self
467            .tables
468            .locally_computed_checkpoints
469            .multi_get(sequence_numbers)?;
470
471        Ok(checkpoints)
472    }
473
474    pub fn get_sequence_number_by_contents_digest(
475        &self,
476        digest: &CheckpointContentsDigest,
477    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
478        self.tables
479            .checkpoint_sequence_by_contents_digest
480            .get(digest)
481    }
482
483    pub fn delete_contents_digest_sequence_number_mapping(
484        &self,
485        digest: &CheckpointContentsDigest,
486    ) -> Result<(), TypedStoreError> {
487        self.tables
488            .checkpoint_sequence_by_contents_digest
489            .remove(digest)
490    }
491
492    pub fn get_latest_certified_checkpoint(
493        &self,
494    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
495        Ok(self
496            .tables
497            .certified_checkpoints
498            .reversed_safe_iter_with_bounds(None, None)?
499            .next()
500            .transpose()?
501            .map(|(_, v)| v.into()))
502    }
503
504    pub fn get_latest_locally_computed_checkpoint(
505        &self,
506    ) -> Result<Option<CheckpointSummary>, TypedStoreError> {
507        Ok(self
508            .tables
509            .locally_computed_checkpoints
510            .reversed_safe_iter_with_bounds(None, None)?
511            .next()
512            .transpose()?
513            .map(|(_, v)| v))
514    }
515
516    pub fn multi_get_checkpoint_by_sequence_number(
517        &self,
518        sequence_numbers: &[CheckpointSequenceNumber],
519    ) -> Result<Vec<Option<VerifiedCheckpoint>>, TypedStoreError> {
520        let checkpoints = self
521            .tables
522            .certified_checkpoints
523            .multi_get(sequence_numbers)?
524            .into_iter()
525            .map(|maybe_checkpoint| maybe_checkpoint.map(|c| c.into()))
526            .collect();
527
528        Ok(checkpoints)
529    }
530
531    pub fn multi_get_checkpoint_content(
532        &self,
533        contents_digest: &[CheckpointContentsDigest],
534    ) -> Result<Vec<Option<CheckpointContents>>, TypedStoreError> {
535        self.tables.checkpoint_content.multi_get(contents_digest)
536    }
537
538    pub fn get_highest_verified_checkpoint(
539        &self,
540    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
541        let highest_verified = if let Some(highest_verified) = self
542            .tables
543            .watermarks
544            .get(&CheckpointWatermark::HighestVerified)?
545        {
546            highest_verified
547        } else {
548            return Ok(None);
549        };
550        self.get_checkpoint_by_digest(&highest_verified.1)
551    }
552
553    pub fn get_highest_synced_checkpoint(
554        &self,
555    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
556        let highest_synced = if let Some(highest_synced) = self
557            .tables
558            .watermarks
559            .get(&CheckpointWatermark::HighestSynced)?
560        {
561            highest_synced
562        } else {
563            return Ok(None);
564        };
565        self.get_checkpoint_by_digest(&highest_synced.1)
566    }
567
568    pub fn get_highest_synced_checkpoint_seq_number(
569        &self,
570    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
571        if let Some(highest_synced) = self
572            .tables
573            .watermarks
574            .get(&CheckpointWatermark::HighestSynced)?
575        {
576            Ok(Some(highest_synced.0))
577        } else {
578            Ok(None)
579        }
580    }
581
582    pub fn get_highest_executed_checkpoint_seq_number(
583        &self,
584    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
585        if let Some(highest_executed) = self
586            .tables
587            .watermarks
588            .get(&CheckpointWatermark::HighestExecuted)?
589        {
590            Ok(Some(highest_executed.0))
591        } else {
592            Ok(None)
593        }
594    }
595
596    pub fn get_highest_executed_checkpoint(
597        &self,
598    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
599        let highest_executed = if let Some(highest_executed) = self
600            .tables
601            .watermarks
602            .get(&CheckpointWatermark::HighestExecuted)?
603        {
604            highest_executed
605        } else {
606            return Ok(None);
607        };
608        self.get_checkpoint_by_digest(&highest_executed.1)
609    }
610
611    pub fn get_highest_pruned_checkpoint_seq_number(
612        &self,
613    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
614        self.tables
615            .watermarks
616            .get(&CheckpointWatermark::HighestPruned)
617            .map(|watermark| watermark.map(|w| w.0))
618    }
619
620    pub fn get_checkpoint_contents(
621        &self,
622        digest: &CheckpointContentsDigest,
623    ) -> Result<Option<CheckpointContents>, TypedStoreError> {
624        self.tables.checkpoint_content.get(digest)
625    }
626
627    pub fn get_full_checkpoint_contents_by_sequence_number(
628        &self,
629        seq: CheckpointSequenceNumber,
630    ) -> Result<Option<VersionedFullCheckpointContents>, TypedStoreError> {
631        self.tables.full_checkpoint_content_v2.get(&seq)
632    }
633
634    fn prune_local_summaries(&self) -> SuiResult {
635        if let Some((last_local_summary, _)) = self
636            .tables
637            .locally_computed_checkpoints
638            .reversed_safe_iter_with_bounds(None, None)?
639            .next()
640            .transpose()?
641        {
642            let mut batch = self.tables.locally_computed_checkpoints.batch();
643            batch.schedule_delete_range(
644                &self.tables.locally_computed_checkpoints,
645                &0,
646                &last_local_summary,
647            )?;
648            batch.write()?;
649            info!("Pruned local summaries up to {:?}", last_local_summary);
650        }
651        Ok(())
652    }
653
654    pub fn clear_locally_computed_checkpoints_from(
655        &self,
656        from_seq: CheckpointSequenceNumber,
657    ) -> SuiResult {
658        let keys: Vec<_> = self
659            .tables
660            .locally_computed_checkpoints
661            .safe_iter_with_bounds(Some(from_seq), None)
662            .map(|r| r.map(|(k, _)| k))
663            .collect::<Result<_, _>>()?;
664        if let Some(&last_local_summary) = keys.last() {
665            let mut batch = self.tables.locally_computed_checkpoints.batch();
666            batch
667                .delete_batch(&self.tables.locally_computed_checkpoints, keys.iter())
668                .expect("Failed to delete locally computed checkpoints");
669            batch
670                .write()
671                .expect("Failed to delete locally computed checkpoints");
672            warn!(
673                from_seq,
674                last_local_summary,
675                "Cleared locally_computed_checkpoints from {} (inclusive) through {} (inclusive)",
676                from_seq,
677                last_local_summary
678            );
679        }
680        Ok(())
681    }
682
683    fn check_for_checkpoint_fork(
684        &self,
685        local_checkpoint: &CheckpointSummary,
686        verified_checkpoint: &VerifiedCheckpoint,
687    ) {
688        if local_checkpoint != verified_checkpoint.data() {
689            let verified_contents = self
690                .get_checkpoint_contents(&verified_checkpoint.content_digest)
691                .map(|opt_contents| {
692                    opt_contents
693                        .map(|contents| format!("{:?}", contents))
694                        .unwrap_or_else(|| {
695                            format!(
696                                "Verified checkpoint contents not found, digest: {:?}",
697                                verified_checkpoint.content_digest,
698                            )
699                        })
700                })
701                .map_err(|e| {
702                    format!(
703                        "Failed to get verified checkpoint contents, digest: {:?} error: {:?}",
704                        verified_checkpoint.content_digest, e
705                    )
706                })
707                .unwrap_or_else(|err_msg| err_msg);
708
709            let local_contents = self
710                .get_checkpoint_contents(&local_checkpoint.content_digest)
711                .map(|opt_contents| {
712                    opt_contents
713                        .map(|contents| format!("{:?}", contents))
714                        .unwrap_or_else(|| {
715                            format!(
716                                "Local checkpoint contents not found, digest: {:?}",
717                                local_checkpoint.content_digest
718                            )
719                        })
720                })
721                .map_err(|e| {
722                    format!(
723                        "Failed to get local checkpoint contents, digest: {:?} error: {:?}",
724                        local_checkpoint.content_digest, e
725                    )
726                })
727                .unwrap_or_else(|err_msg| err_msg);
728
729            // checkpoint contents may be too large for panic message.
730            error!(
731                verified_checkpoint = ?verified_checkpoint.data(),
732                ?verified_contents,
733                ?local_checkpoint,
734                ?local_contents,
735                "Local checkpoint fork detected!",
736            );
737
738            // Record the fork in the database before crashing
739            if let Err(e) = self.record_checkpoint_fork_detected(
740                *local_checkpoint.sequence_number(),
741                local_checkpoint.digest(),
742            ) {
743                error!("Failed to record checkpoint fork in database: {:?}", e);
744            }
745
746            fail_point_arg!(
747                "kill_checkpoint_fork_node",
748                |checkpoint_overrides: std::sync::Arc<
749                    std::sync::Mutex<std::collections::BTreeMap<u64, String>>,
750                >| {
751                    #[cfg(msim)]
752                    {
753                        if let Ok(mut overrides) = checkpoint_overrides.lock() {
754                            overrides.insert(
755                                local_checkpoint.sequence_number,
756                                verified_checkpoint.digest().to_string(),
757                            );
758                        }
759                        tracing::error!(
760                            fatal = true,
761                            "Fork recovery test: killing node due to checkpoint fork for sequence number: {}, using verified digest: {}",
762                            local_checkpoint.sequence_number(),
763                            verified_checkpoint.digest()
764                        );
765                        sui_simulator::task::shutdown_current_node();
766                    }
767                }
768            );
769
770            fatal!(
771                "Local checkpoint fork detected for sequence number: {}",
772                local_checkpoint.sequence_number()
773            );
774        }
775    }
776
777    // Called by consensus (ConsensusAggregator).
778    // Different from `insert_verified_checkpoint`, it does not touch
779    // the highest_verified_checkpoint watermark such that state sync
780    // will have a chance to process this checkpoint and perform some
781    // state-sync only things.
782    pub fn insert_certified_checkpoint(
783        &self,
784        checkpoint: &VerifiedCheckpoint,
785    ) -> Result<(), TypedStoreError> {
786        debug!(
787            checkpoint_seq = checkpoint.sequence_number(),
788            "Inserting certified checkpoint",
789        );
790        let mut batch = self.tables.certified_checkpoints.batch();
791        batch
792            .insert_batch(
793                &self.tables.certified_checkpoints,
794                [(checkpoint.sequence_number(), checkpoint.serializable_ref())],
795            )?
796            .insert_batch(
797                &self.tables.checkpoint_by_digest,
798                [(checkpoint.digest(), checkpoint.serializable_ref())],
799            )?;
800        if checkpoint.next_epoch_committee().is_some() {
801            batch.insert_batch(
802                &self.tables.epoch_last_checkpoint_map,
803                [(&checkpoint.epoch(), checkpoint.sequence_number())],
804            )?;
805        }
806        batch.write()?;
807
808        if let Some(local_checkpoint) = self
809            .tables
810            .locally_computed_checkpoints
811            .get(checkpoint.sequence_number())?
812        {
813            self.check_for_checkpoint_fork(&local_checkpoint, checkpoint);
814        }
815
816        Ok(())
817    }
818
819    // Called by state sync, apart from inserting the checkpoint and updating
820    // related tables, it also bumps the highest_verified_checkpoint watermark.
821    #[instrument(level = "debug", skip_all)]
822    pub fn insert_verified_checkpoint(
823        &self,
824        checkpoint: &VerifiedCheckpoint,
825    ) -> Result<(), TypedStoreError> {
826        self.insert_certified_checkpoint(checkpoint)?;
827        self.update_highest_verified_checkpoint(checkpoint)
828    }
829
830    pub fn update_highest_verified_checkpoint(
831        &self,
832        checkpoint: &VerifiedCheckpoint,
833    ) -> Result<(), TypedStoreError> {
834        if Some(*checkpoint.sequence_number())
835            > self
836                .get_highest_verified_checkpoint()?
837                .map(|x| *x.sequence_number())
838        {
839            debug!(
840                checkpoint_seq = checkpoint.sequence_number(),
841                "Updating highest verified checkpoint",
842            );
843            self.tables.watermarks.insert(
844                &CheckpointWatermark::HighestVerified,
845                &(*checkpoint.sequence_number(), *checkpoint.digest()),
846            )?;
847        }
848
849        Ok(())
850    }
851
852    pub fn update_highest_synced_checkpoint(
853        &self,
854        checkpoint: &VerifiedCheckpoint,
855    ) -> Result<(), TypedStoreError> {
856        let seq = *checkpoint.sequence_number();
857        debug!(checkpoint_seq = seq, "Updating highest synced checkpoint",);
858        self.tables.watermarks.insert(
859            &CheckpointWatermark::HighestSynced,
860            &(seq, *checkpoint.digest()),
861        )?;
862        self.synced_checkpoint_notify_read.notify(&seq, checkpoint);
863        Ok(())
864    }
865
866    async fn notify_read_checkpoint_watermark<F>(
867        &self,
868        notify_read: &NotifyRead<CheckpointSequenceNumber, VerifiedCheckpoint>,
869        seq: CheckpointSequenceNumber,
870        get_watermark: F,
871    ) -> VerifiedCheckpoint
872    where
873        F: Fn() -> Option<CheckpointSequenceNumber>,
874    {
875        notify_read
876            .read("notify_read_checkpoint_watermark", &[seq], |seqs| {
877                let seq = seqs[0];
878                let Some(highest) = get_watermark() else {
879                    return vec![None];
880                };
881                if highest < seq {
882                    return vec![None];
883                }
884                let checkpoint = self
885                    .get_checkpoint_by_sequence_number(seq)
886                    .expect("db error")
887                    .expect("checkpoint not found");
888                vec![Some(checkpoint)]
889            })
890            .await
891            .into_iter()
892            .next()
893            .unwrap()
894    }
895
896    pub async fn notify_read_synced_checkpoint(
897        &self,
898        seq: CheckpointSequenceNumber,
899    ) -> VerifiedCheckpoint {
900        self.notify_read_checkpoint_watermark(&self.synced_checkpoint_notify_read, seq, || {
901            self.get_highest_synced_checkpoint_seq_number()
902                .expect("db error")
903        })
904        .await
905    }
906
907    pub async fn notify_read_executed_checkpoint(
908        &self,
909        seq: CheckpointSequenceNumber,
910    ) -> VerifiedCheckpoint {
911        self.notify_read_checkpoint_watermark(&self.executed_checkpoint_notify_read, seq, || {
912            self.get_highest_executed_checkpoint_seq_number()
913                .expect("db error")
914        })
915        .await
916    }
917
918    pub fn update_highest_executed_checkpoint(
919        &self,
920        checkpoint: &VerifiedCheckpoint,
921    ) -> Result<(), TypedStoreError> {
922        if let Some(seq_number) = self.get_highest_executed_checkpoint_seq_number()? {
923            if seq_number >= *checkpoint.sequence_number() {
924                return Ok(());
925            }
926            assert_eq!(
927                seq_number + 1,
928                *checkpoint.sequence_number(),
929                "Cannot update highest executed checkpoint to {} when current highest executed checkpoint is {}",
930                checkpoint.sequence_number(),
931                seq_number
932            );
933        }
934        let seq = *checkpoint.sequence_number();
935        debug!(checkpoint_seq = seq, "Updating highest executed checkpoint",);
936        self.tables.watermarks.insert(
937            &CheckpointWatermark::HighestExecuted,
938            &(seq, *checkpoint.digest()),
939        )?;
940        self.executed_checkpoint_notify_read
941            .notify(&seq, checkpoint);
942        Ok(())
943    }
944
945    pub fn update_highest_pruned_checkpoint(
946        &self,
947        checkpoint: &VerifiedCheckpoint,
948    ) -> Result<(), TypedStoreError> {
949        self.tables.watermarks.insert(
950            &CheckpointWatermark::HighestPruned,
951            &(*checkpoint.sequence_number(), *checkpoint.digest()),
952        )
953    }
954
955    /// Sets highest executed checkpoint to any value.
956    ///
957    /// WARNING: This method is very subtle and can corrupt the database if used incorrectly.
958    /// It should only be used in one-off cases or tests after fully understanding the risk.
959    pub fn set_highest_executed_checkpoint_subtle(
960        &self,
961        checkpoint: &VerifiedCheckpoint,
962    ) -> Result<(), TypedStoreError> {
963        self.tables.watermarks.insert(
964            &CheckpointWatermark::HighestExecuted,
965            &(*checkpoint.sequence_number(), *checkpoint.digest()),
966        )
967    }
968
969    pub fn insert_checkpoint_contents(
970        &self,
971        contents: CheckpointContents,
972    ) -> Result<(), TypedStoreError> {
973        debug!(
974            checkpoint_seq = ?contents.digest(),
975            "Inserting checkpoint contents",
976        );
977        self.tables
978            .checkpoint_content
979            .insert(contents.digest(), &contents)
980    }
981
982    pub fn insert_verified_checkpoint_contents(
983        &self,
984        checkpoint: &VerifiedCheckpoint,
985        full_contents: VerifiedCheckpointContents,
986    ) -> Result<(), TypedStoreError> {
987        let mut batch = self.tables.full_checkpoint_content_v2.batch();
988        batch.insert_batch(
989            &self.tables.checkpoint_sequence_by_contents_digest,
990            [(&checkpoint.content_digest, checkpoint.sequence_number())],
991        )?;
992        let full_contents = full_contents.into_inner();
993        batch.insert_batch(
994            &self.tables.full_checkpoint_content_v2,
995            [(checkpoint.sequence_number(), &full_contents)],
996        )?;
997
998        let contents = full_contents.into_checkpoint_contents();
999        assert_eq!(&checkpoint.content_digest, contents.digest());
1000
1001        batch.insert_batch(
1002            &self.tables.checkpoint_content,
1003            [(contents.digest(), &contents)],
1004        )?;
1005
1006        batch.write()
1007    }
1008
1009    pub fn delete_full_checkpoint_contents(
1010        &self,
1011        seq: CheckpointSequenceNumber,
1012    ) -> Result<(), TypedStoreError> {
1013        self.tables.full_checkpoint_content.remove(&seq)?;
1014        self.tables.full_checkpoint_content_v2.remove(&seq)
1015    }
1016
1017    pub fn get_epoch_last_checkpoint(
1018        &self,
1019        epoch_id: EpochId,
1020    ) -> SuiResult<Option<VerifiedCheckpoint>> {
1021        let seq = self.get_epoch_last_checkpoint_seq_number(epoch_id)?;
1022        let checkpoint = match seq {
1023            Some(seq) => self.get_checkpoint_by_sequence_number(seq)?,
1024            None => None,
1025        };
1026        Ok(checkpoint)
1027    }
1028
1029    pub fn get_epoch_last_checkpoint_seq_number(
1030        &self,
1031        epoch_id: EpochId,
1032    ) -> SuiResult<Option<CheckpointSequenceNumber>> {
1033        let seq = self.tables.epoch_last_checkpoint_map.get(&epoch_id)?;
1034        Ok(seq)
1035    }
1036
1037    pub fn insert_epoch_last_checkpoint(
1038        &self,
1039        epoch_id: EpochId,
1040        checkpoint: &VerifiedCheckpoint,
1041    ) -> SuiResult {
1042        self.tables
1043            .epoch_last_checkpoint_map
1044            .insert(&epoch_id, checkpoint.sequence_number())?;
1045        Ok(())
1046    }
1047
1048    pub fn get_epoch_state_commitments(
1049        &self,
1050        epoch: EpochId,
1051    ) -> SuiResult<Option<Vec<CheckpointCommitment>>> {
1052        let commitments = self.get_epoch_last_checkpoint(epoch)?.map(|checkpoint| {
1053            checkpoint
1054                .end_of_epoch_data
1055                .as_ref()
1056                .expect("Last checkpoint of epoch expected to have EndOfEpochData")
1057                .epoch_commitments
1058                .clone()
1059        });
1060        Ok(commitments)
1061    }
1062
1063    /// Given the epoch ID, and the last checkpoint of the epoch, derive a few statistics of the epoch.
1064    pub fn get_epoch_stats(
1065        &self,
1066        epoch: EpochId,
1067        last_checkpoint: &CheckpointSummary,
1068    ) -> Option<EpochStats> {
1069        let (first_checkpoint, prev_epoch_network_transactions) = if epoch == 0 {
1070            (0, 0)
1071        } else if let Ok(Some(checkpoint)) = self.get_epoch_last_checkpoint(epoch - 1) {
1072            (
1073                checkpoint.sequence_number + 1,
1074                checkpoint.network_total_transactions,
1075            )
1076        } else {
1077            return None;
1078        };
1079        Some(EpochStats {
1080            checkpoint_count: last_checkpoint.sequence_number - first_checkpoint + 1,
1081            transaction_count: last_checkpoint.network_total_transactions
1082                - prev_epoch_network_transactions,
1083            total_gas_reward: last_checkpoint
1084                .epoch_rolling_gas_cost_summary
1085                .computation_cost,
1086        })
1087    }
1088
1089    pub fn checkpoint_db(&self, path: &Path) -> SuiResult {
1090        // This checkpoints the entire db and not one column family
1091        self.tables
1092            .checkpoint_content
1093            .checkpoint_db(path)
1094            .map_err(Into::into)
1095    }
1096
1097    pub fn delete_highest_executed_checkpoint_test_only(&self) -> Result<(), TypedStoreError> {
1098        let mut wb = self.tables.watermarks.batch();
1099        wb.delete_batch(
1100            &self.tables.watermarks,
1101            std::iter::once(CheckpointWatermark::HighestExecuted),
1102        )?;
1103        wb.write()?;
1104        Ok(())
1105    }
1106
1107    pub fn reset_db_for_execution_since_genesis(&self) -> SuiResult {
1108        self.delete_highest_executed_checkpoint_test_only()?;
1109        Ok(())
1110    }
1111
1112    pub fn record_checkpoint_fork_detected(
1113        &self,
1114        checkpoint_seq: CheckpointSequenceNumber,
1115        checkpoint_digest: CheckpointDigest,
1116    ) -> Result<(), TypedStoreError> {
1117        info!(
1118            checkpoint_seq = checkpoint_seq,
1119            checkpoint_digest = ?checkpoint_digest,
1120            "Recording checkpoint fork detection in database"
1121        );
1122        self.tables.watermarks.insert(
1123            &CheckpointWatermark::CheckpointForkDetected,
1124            &(checkpoint_seq, checkpoint_digest),
1125        )
1126    }
1127
1128    pub fn get_checkpoint_fork_detected(
1129        &self,
1130    ) -> Result<Option<(CheckpointSequenceNumber, CheckpointDigest)>, TypedStoreError> {
1131        self.tables
1132            .watermarks
1133            .get(&CheckpointWatermark::CheckpointForkDetected)
1134    }
1135
1136    pub fn clear_checkpoint_fork_detected(&self) -> Result<(), TypedStoreError> {
1137        self.tables
1138            .watermarks
1139            .remove(&CheckpointWatermark::CheckpointForkDetected)
1140    }
1141
1142    pub fn record_transaction_fork_detected(
1143        &self,
1144        tx_digest: TransactionDigest,
1145        expected_effects_digest: TransactionEffectsDigest,
1146        actual_effects_digest: TransactionEffectsDigest,
1147    ) -> Result<(), TypedStoreError> {
1148        info!(
1149            tx_digest = ?tx_digest,
1150            expected_effects_digest = ?expected_effects_digest,
1151            actual_effects_digest = ?actual_effects_digest,
1152            "Recording transaction fork detection in database"
1153        );
1154        self.tables.transaction_fork_detected.insert(
1155            &TRANSACTION_FORK_DETECTED_KEY,
1156            &(tx_digest, expected_effects_digest, actual_effects_digest),
1157        )
1158    }
1159
1160    pub fn get_transaction_fork_detected(
1161        &self,
1162    ) -> Result<
1163        Option<(
1164            TransactionDigest,
1165            TransactionEffectsDigest,
1166            TransactionEffectsDigest,
1167        )>,
1168        TypedStoreError,
1169    > {
1170        self.tables
1171            .transaction_fork_detected
1172            .get(&TRANSACTION_FORK_DETECTED_KEY)
1173    }
1174
1175    pub fn clear_transaction_fork_detected(&self) -> Result<(), TypedStoreError> {
1176        self.tables
1177            .transaction_fork_detected
1178            .remove(&TRANSACTION_FORK_DETECTED_KEY)
1179    }
1180}
1181
1182#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
1183pub enum CheckpointWatermark {
1184    HighestVerified,
1185    HighestSynced,
1186    HighestExecuted,
1187    HighestPruned,
1188    CheckpointForkDetected,
1189}
1190
1191struct CheckpointStateHasher {
1192    epoch_store: Arc<AuthorityPerEpochStore>,
1193    hasher: Weak<GlobalStateHasher>,
1194    receive_from_builder: mpsc::Receiver<(CheckpointSequenceNumber, Vec<TransactionEffects>)>,
1195}
1196
1197impl CheckpointStateHasher {
1198    fn new(
1199        epoch_store: Arc<AuthorityPerEpochStore>,
1200        hasher: Weak<GlobalStateHasher>,
1201        receive_from_builder: mpsc::Receiver<(CheckpointSequenceNumber, Vec<TransactionEffects>)>,
1202    ) -> Self {
1203        Self {
1204            epoch_store,
1205            hasher,
1206            receive_from_builder,
1207        }
1208    }
1209
1210    async fn run(self) {
1211        let Self {
1212            epoch_store,
1213            hasher,
1214            mut receive_from_builder,
1215        } = self;
1216        while let Some((seq, effects)) = receive_from_builder.recv().await {
1217            let Some(hasher) = hasher.upgrade() else {
1218                info!("Object state hasher was dropped, stopping checkpoint accumulation");
1219                break;
1220            };
1221            hasher
1222                .accumulate_checkpoint(&effects, seq, &epoch_store)
1223                .expect("epoch ended while accumulating checkpoint");
1224        }
1225    }
1226}
1227
1228#[derive(Debug)]
1229pub enum CheckpointBuilderError {
1230    ChangeEpochTxAlreadyExecuted,
1231    SystemPackagesMissing,
1232    Retry(anyhow::Error),
1233}
1234
1235impl<SuiError: std::error::Error + Send + Sync + 'static> From<SuiError>
1236    for CheckpointBuilderError
1237{
1238    fn from(e: SuiError) -> Self {
1239        Self::Retry(e.into())
1240    }
1241}
1242
1243pub type CheckpointBuilderResult<T = ()> = Result<T, CheckpointBuilderError>;
1244
1245pub struct CheckpointBuilder {
1246    state: Arc<AuthorityState>,
1247    store: Arc<CheckpointStore>,
1248    epoch_store: Arc<AuthorityPerEpochStore>,
1249    notify: Arc<Notify>,
1250    notify_aggregator: Arc<Notify>,
1251    last_built: watch::Sender<CheckpointSequenceNumber>,
1252    effects_store: Arc<dyn TransactionCacheRead>,
1253    global_state_hasher: Weak<GlobalStateHasher>,
1254    send_to_hasher: mpsc::Sender<(CheckpointSequenceNumber, Vec<TransactionEffects>)>,
1255    output: Box<dyn CheckpointOutput>,
1256    metrics: Arc<CheckpointMetrics>,
1257    max_transactions_per_checkpoint: usize,
1258    max_checkpoint_size_bytes: usize,
1259}
1260
1261pub struct CheckpointAggregator {
1262    store: Arc<CheckpointStore>,
1263    epoch_store: Arc<AuthorityPerEpochStore>,
1264    notify: Arc<Notify>,
1265    receiver: mpsc::UnboundedReceiver<CheckpointSignatureMessage>,
1266    pending: BTreeMap<CheckpointSequenceNumber, Vec<CheckpointSignatureMessage>>,
1267    current: Option<CheckpointSignatureAggregator>,
1268    output: Box<dyn CertifiedCheckpointOutput>,
1269    state: Arc<AuthorityState>,
1270    metrics: Arc<CheckpointMetrics>,
1271}
1272
1273// This holds information to aggregate signatures for one checkpoint
1274pub struct CheckpointSignatureAggregator {
1275    summary: CheckpointSummary,
1276    digest: CheckpointDigest,
1277    /// Aggregates voting stake for each signed checkpoint proposal by authority
1278    signatures_by_digest: MultiStakeAggregator<CheckpointDigest, CheckpointSummary, true>,
1279    store: Arc<CheckpointStore>,
1280    state: Arc<AuthorityState>,
1281    metrics: Arc<CheckpointMetrics>,
1282}
1283
1284impl CheckpointBuilder {
1285    fn new(
1286        state: Arc<AuthorityState>,
1287        store: Arc<CheckpointStore>,
1288        epoch_store: Arc<AuthorityPerEpochStore>,
1289        notify: Arc<Notify>,
1290        effects_store: Arc<dyn TransactionCacheRead>,
1291        // for synchronous accumulation of end-of-epoch checkpoint
1292        global_state_hasher: Weak<GlobalStateHasher>,
1293        // for asynchronous/concurrent accumulation of regular checkpoints
1294        send_to_hasher: mpsc::Sender<(CheckpointSequenceNumber, Vec<TransactionEffects>)>,
1295        output: Box<dyn CheckpointOutput>,
1296        notify_aggregator: Arc<Notify>,
1297        last_built: watch::Sender<CheckpointSequenceNumber>,
1298        metrics: Arc<CheckpointMetrics>,
1299        max_transactions_per_checkpoint: usize,
1300        max_checkpoint_size_bytes: usize,
1301    ) -> Self {
1302        Self {
1303            state,
1304            store,
1305            epoch_store,
1306            notify,
1307            effects_store,
1308            global_state_hasher,
1309            send_to_hasher,
1310            output,
1311            notify_aggregator,
1312            last_built,
1313            metrics,
1314            max_transactions_per_checkpoint,
1315            max_checkpoint_size_bytes,
1316        }
1317    }
1318
1319    /// This function first waits for ConsensusCommitHandler to finish reprocessing
1320    /// commits that have been processed before the last restart, if consensus_replay_waiter
1321    /// is supplied. Then it starts building checkpoints in a loop.
1322    ///
1323    /// It is optional to pass in consensus_replay_waiter, to make it easier to attribute
1324    /// if slow recovery of previously built checkpoints is due to consensus replay or
1325    /// checkpoint building.
1326    async fn run(mut self, consensus_replay_waiter: Option<ReplayWaiter>) {
1327        if let Some(replay_waiter) = consensus_replay_waiter {
1328            info!("Waiting for consensus commits to replay ...");
1329            replay_waiter.wait_for_replay().await;
1330            info!("Consensus commits finished replaying");
1331        }
1332        info!("Starting CheckpointBuilder");
1333        loop {
1334            match self.maybe_build_checkpoints().await {
1335                Ok(()) => {}
1336                err @ Err(
1337                    CheckpointBuilderError::ChangeEpochTxAlreadyExecuted
1338                    | CheckpointBuilderError::SystemPackagesMissing,
1339                ) => {
1340                    info!("CheckpointBuilder stopping: {:?}", err);
1341                    return;
1342                }
1343                Err(CheckpointBuilderError::Retry(inner)) => {
1344                    let msg = format!("{:?}", inner);
1345                    debug_fatal!("Error while making checkpoint, will retry in 1s: {}", msg);
1346                    tokio::time::sleep(Duration::from_secs(1)).await;
1347                    self.metrics.checkpoint_errors.inc();
1348                    continue;
1349                }
1350            }
1351
1352            self.notify.notified().await;
1353        }
1354    }
1355
1356    async fn maybe_build_checkpoints(&mut self) -> CheckpointBuilderResult {
1357        if self
1358            .epoch_store
1359            .protocol_config()
1360            .split_checkpoints_in_consensus_handler()
1361        {
1362            self.maybe_build_checkpoints_v2().await
1363        } else {
1364            self.maybe_build_checkpoints_v1().await
1365        }
1366    }
1367
1368    async fn maybe_build_checkpoints_v1(&mut self) -> CheckpointBuilderResult {
1369        let _scope = monitored_scope("BuildCheckpoints");
1370
1371        // Collect info about the most recently built checkpoint.
1372        let summary = self
1373            .epoch_store
1374            .last_built_checkpoint_builder_summary()
1375            .expect("epoch should not have ended");
1376        let mut last_height = summary.clone().and_then(|s| s.checkpoint_height);
1377        let mut last_timestamp = summary.map(|s| s.summary.timestamp_ms);
1378
1379        let min_checkpoint_interval_ms = self
1380            .epoch_store
1381            .protocol_config()
1382            .min_checkpoint_interval_ms_as_option()
1383            .unwrap_or_default();
1384        let mut grouped_pending_checkpoints = Vec::new();
1385        let mut checkpoints_iter = self
1386            .epoch_store
1387            .get_pending_checkpoints(last_height)
1388            .expect("unexpected epoch store error")
1389            .into_iter()
1390            .peekable();
1391        while let Some((height, pending)) = checkpoints_iter.next() {
1392            // Group PendingCheckpoints until:
1393            // - minimum interval has elapsed ...
1394            let current_timestamp = pending.details().timestamp_ms;
1395            let can_build = match last_timestamp {
1396                    Some(last_timestamp) => {
1397                        current_timestamp >= last_timestamp + min_checkpoint_interval_ms
1398                    }
1399                    None => true,
1400                // - or, next PendingCheckpoint is last-of-epoch (since the last-of-epoch checkpoint
1401                //   should be written separately) ...
1402                } || checkpoints_iter
1403                    .peek()
1404                    .is_some_and(|(_, next_pending)| next_pending.details().last_of_epoch)
1405                // - or, we have reached end of epoch.
1406                    || pending.details().last_of_epoch;
1407            grouped_pending_checkpoints.push(pending);
1408            if !can_build {
1409                debug!(
1410                    checkpoint_commit_height = height,
1411                    ?last_timestamp,
1412                    ?current_timestamp,
1413                    "waiting for more PendingCheckpoints: minimum interval not yet elapsed"
1414                );
1415                continue;
1416            }
1417
1418            // Min interval has elapsed, we can now coalesce and build a checkpoint.
1419            last_height = Some(height);
1420            last_timestamp = Some(current_timestamp);
1421            debug!(
1422                checkpoint_commit_height_from = grouped_pending_checkpoints
1423                    .first()
1424                    .unwrap()
1425                    .details()
1426                    .checkpoint_height,
1427                checkpoint_commit_height_to = last_height,
1428                "Making checkpoint with commit height range"
1429            );
1430
1431            let seq = self
1432                .make_checkpoint(std::mem::take(&mut grouped_pending_checkpoints))
1433                .await?;
1434
1435            self.last_built.send_if_modified(|cur| {
1436                // when rebuilding checkpoints at startup, seq can be for an old checkpoint
1437                if seq > *cur {
1438                    *cur = seq;
1439                    true
1440                } else {
1441                    false
1442                }
1443            });
1444
1445            // ensure that the task can be cancelled at end of epoch, even if no other await yields
1446            // execution.
1447            tokio::task::yield_now().await;
1448        }
1449        debug!(
1450            "Waiting for more checkpoints from consensus after processing {last_height:?}; {} pending checkpoints left unprocessed until next interval",
1451            grouped_pending_checkpoints.len(),
1452        );
1453
1454        Ok(())
1455    }
1456
1457    async fn maybe_build_checkpoints_v2(&mut self) -> CheckpointBuilderResult {
1458        let _scope = monitored_scope("BuildCheckpoints");
1459
1460        // Collect info about the most recently built checkpoint.
1461        let last_height = self
1462            .epoch_store
1463            .last_built_checkpoint_builder_summary()
1464            .expect("epoch should not have ended")
1465            .and_then(|s| s.checkpoint_height);
1466
1467        for (height, pending) in self
1468            .epoch_store
1469            .get_pending_checkpoints_v2(last_height)
1470            .expect("unexpected epoch store error")
1471        {
1472            debug!(checkpoint_commit_height = height, "Making checkpoint");
1473
1474            let seq = self.make_checkpoint_v2(pending).await?;
1475
1476            self.last_built.send_if_modified(|cur| {
1477                // when rebuilding checkpoints at startup, seq can be for an old checkpoint
1478                if seq > *cur {
1479                    *cur = seq;
1480                    true
1481                } else {
1482                    false
1483                }
1484            });
1485
1486            // ensure that the task can be cancelled at end of epoch, even if no other await yields
1487            // execution.
1488            tokio::task::yield_now().await;
1489        }
1490
1491        Ok(())
1492    }
1493
1494    #[instrument(level = "debug", skip_all, fields(last_height = pendings.last().unwrap().details().checkpoint_height))]
1495    async fn make_checkpoint(
1496        &mut self,
1497        pendings: Vec<PendingCheckpoint>,
1498    ) -> CheckpointBuilderResult<CheckpointSequenceNumber> {
1499        let _scope = monitored_scope("CheckpointBuilder::make_checkpoint");
1500
1501        let pending_ckpt_str = pendings
1502            .iter()
1503            .map(|p| {
1504                format!(
1505                    "height={}, commit={}",
1506                    p.details().checkpoint_height,
1507                    p.details().consensus_commit_ref
1508                )
1509            })
1510            .join("; ");
1511
1512        let last_details = pendings.last().unwrap().details().clone();
1513
1514        // Stores the transactions that should be included in the checkpoint. Transactions will be recorded in the checkpoint
1515        // in this order.
1516        let highest_executed_sequence = self
1517            .store
1518            .get_highest_executed_checkpoint_seq_number()
1519            .expect("db error")
1520            .unwrap_or(0);
1521
1522        let (poll_count, result) = poll_count(self.resolve_checkpoint_transactions(pendings)).await;
1523        let (sorted_tx_effects_included_in_checkpoint, all_roots) = result?;
1524
1525        let new_checkpoints = self
1526            .create_checkpoints(
1527                sorted_tx_effects_included_in_checkpoint,
1528                &last_details,
1529                &all_roots,
1530            )
1531            .await?;
1532        let highest_sequence = *new_checkpoints.last().0.sequence_number();
1533        if highest_sequence <= highest_executed_sequence && poll_count > 1 {
1534            debug_fatal!(
1535                "resolve_checkpoint_transactions should be instantaneous when executed checkpoint is ahead of checkpoint builder"
1536            );
1537        }
1538
1539        let new_ckpt_str = new_checkpoints
1540            .iter()
1541            .map(|(ckpt, _)| format!("seq={}, digest={}", ckpt.sequence_number(), ckpt.digest()))
1542            .join("; ");
1543
1544        self.write_checkpoints(last_details.checkpoint_height, new_checkpoints)
1545            .await?;
1546        info!(
1547            "Made new checkpoint {} from pending checkpoint {}",
1548            new_ckpt_str, pending_ckpt_str
1549        );
1550
1551        Ok(highest_sequence)
1552    }
1553
1554    #[instrument(level = "debug", skip_all, fields(height = pending.details.checkpoint_height))]
1555    async fn make_checkpoint_v2(
1556        &mut self,
1557        pending: PendingCheckpointV2,
1558    ) -> CheckpointBuilderResult<CheckpointSequenceNumber> {
1559        let _scope = monitored_scope("CheckpointBuilder::make_checkpoint");
1560
1561        let details = pending.details.clone();
1562
1563        let highest_executed_sequence = self
1564            .store
1565            .get_highest_executed_checkpoint_seq_number()
1566            .expect("db error")
1567            .unwrap_or(0);
1568
1569        let (poll_count, result) =
1570            poll_count(self.resolve_checkpoint_transactions_v2(pending)).await;
1571        let (sorted_tx_effects_included_in_checkpoint, all_roots) = result?;
1572
1573        let new_checkpoints = self
1574            .create_checkpoints(
1575                sorted_tx_effects_included_in_checkpoint,
1576                &details,
1577                &all_roots,
1578            )
1579            .await?;
1580        assert_eq!(new_checkpoints.len(), 1, "Expected exactly one checkpoint");
1581        let sequence = *new_checkpoints.first().0.sequence_number();
1582        let digest = new_checkpoints.first().0.digest();
1583        if sequence <= highest_executed_sequence && poll_count > 1 {
1584            debug_fatal!(
1585                "resolve_checkpoint_transactions should be instantaneous when executed checkpoint is ahead of checkpoint builder"
1586            );
1587        }
1588
1589        self.write_checkpoints(details.checkpoint_height, new_checkpoints)
1590            .await?;
1591        info!(
1592            seq = sequence,
1593            %digest,
1594            height = details.checkpoint_height,
1595            commit = %details.consensus_commit_ref,
1596            "Made new checkpoint"
1597        );
1598
1599        Ok(sequence)
1600    }
1601
1602    async fn construct_and_execute_settlement_transactions(
1603        &self,
1604        sorted_tx_effects_included_in_checkpoint: &[TransactionEffects],
1605        checkpoint_height: CheckpointHeight,
1606        checkpoint_seq: CheckpointSequenceNumber,
1607        tx_index_offset: u64,
1608    ) -> (TransactionKey, Vec<TransactionEffects>) {
1609        let _scope =
1610            monitored_scope("CheckpointBuilder::construct_and_execute_settlement_transactions");
1611
1612        let tx_key =
1613            TransactionKey::AccumulatorSettlement(self.epoch_store.epoch(), checkpoint_height);
1614
1615        let epoch = self.epoch_store.epoch();
1616        let accumulator_root_obj_initial_shared_version = self
1617            .epoch_store
1618            .epoch_start_config()
1619            .accumulator_root_obj_initial_shared_version()
1620            .expect("accumulator root object must exist");
1621
1622        let builder = AccumulatorSettlementTxBuilder::new(
1623            Some(self.effects_store.as_ref()),
1624            sorted_tx_effects_included_in_checkpoint,
1625            checkpoint_seq,
1626            tx_index_offset,
1627        );
1628
1629        let funds_changes = builder.collect_funds_changes();
1630        let num_updates = builder.num_updates();
1631        let settlement_txns = builder.build_tx(
1632            self.epoch_store.protocol_config(),
1633            epoch,
1634            accumulator_root_obj_initial_shared_version,
1635            checkpoint_height,
1636            checkpoint_seq,
1637        );
1638
1639        let settlement_txns: Vec<_> = settlement_txns
1640            .into_iter()
1641            .map(|tx| {
1642                VerifiedExecutableTransaction::new_system(
1643                    VerifiedTransaction::new_system_transaction(tx),
1644                    self.epoch_store.epoch(),
1645                )
1646            })
1647            .collect();
1648
1649        let settlement_digests: Vec<_> = settlement_txns.iter().map(|tx| *tx.digest()).collect();
1650
1651        debug!(
1652            ?settlement_digests,
1653            ?tx_key,
1654            "created settlement transactions with {num_updates} updates"
1655        );
1656
1657        self.epoch_store
1658            .notify_settlement_transactions_ready(tx_key, settlement_txns);
1659
1660        let settlement_effects = wait_for_effects_with_retry(
1661            self.effects_store.as_ref(),
1662            "CheckpointBuilder::notify_read_settlement_effects",
1663            &settlement_digests,
1664            tx_key,
1665        )
1666        .await;
1667
1668        let barrier_tx = accumulators::build_accumulator_barrier_tx(
1669            epoch,
1670            accumulator_root_obj_initial_shared_version,
1671            checkpoint_height,
1672            &settlement_effects,
1673        );
1674
1675        let barrier_tx = VerifiedExecutableTransaction::new_system(
1676            VerifiedTransaction::new_system_transaction(barrier_tx),
1677            self.epoch_store.epoch(),
1678        );
1679        let barrier_digest = *barrier_tx.digest();
1680
1681        self.epoch_store
1682            .notify_barrier_transaction_ready(tx_key, barrier_tx);
1683
1684        let barrier_effects = wait_for_effects_with_retry(
1685            self.effects_store.as_ref(),
1686            "CheckpointBuilder::notify_read_barrier_effects",
1687            &[barrier_digest],
1688            tx_key,
1689        )
1690        .await;
1691
1692        let settlement_effects: Vec<_> = settlement_effects
1693            .into_iter()
1694            .chain(barrier_effects)
1695            .collect();
1696
1697        let mut next_accumulator_version = None;
1698        for fx in settlement_effects.iter() {
1699            assert!(
1700                fx.status().is_ok(),
1701                "settlement transaction cannot fail (digest: {:?}) {:#?}",
1702                fx.transaction_digest(),
1703                fx
1704            );
1705            if let Some(version) = fx
1706                .mutated()
1707                .iter()
1708                .find_map(|(oref, _)| (oref.0 == SUI_ACCUMULATOR_ROOT_OBJECT_ID).then_some(oref.1))
1709            {
1710                assert!(
1711                    next_accumulator_version.is_none(),
1712                    "Only one settlement transaction should mutate the accumulator root object"
1713                );
1714                next_accumulator_version = Some(version);
1715            }
1716        }
1717        let settlements = FundsSettlement {
1718            next_accumulator_version: next_accumulator_version
1719                .expect("Accumulator root object should be mutated in the settlement transactions"),
1720            funds_changes,
1721        };
1722
1723        self.state
1724            .execution_scheduler()
1725            .settle_address_funds(settlements);
1726
1727        (tx_key, settlement_effects)
1728    }
1729
1730    // Given the root transactions of a pending checkpoint, resolve the transactions should be included in
1731    // the checkpoint, and return them in the order they should be included in the checkpoint.
1732    // `effects_in_current_checkpoint` tracks the transactions that already exist in the current
1733    // checkpoint.
1734    #[instrument(level = "debug", skip_all)]
1735    async fn resolve_checkpoint_transactions(
1736        &self,
1737        pending_checkpoints: Vec<PendingCheckpoint>,
1738    ) -> SuiResult<(Vec<TransactionEffects>, HashSet<TransactionDigest>)> {
1739        let _scope = monitored_scope("CheckpointBuilder::resolve_checkpoint_transactions");
1740
1741        // Keeps track of the effects that are already included in the current checkpoint.
1742        // This is used when there are multiple pending checkpoints to create a single checkpoint
1743        // because in such scenarios, dependencies of a transaction may in earlier created checkpoints,
1744        // or in earlier pending checkpoints.
1745        let mut effects_in_current_checkpoint = BTreeSet::new();
1746
1747        let mut tx_effects = Vec::new();
1748        let mut tx_roots = HashSet::new();
1749
1750        for pending_checkpoint in pending_checkpoints.into_iter() {
1751            let mut pending = pending_checkpoint;
1752            debug!(
1753                checkpoint_commit_height = pending.details.checkpoint_height,
1754                "Resolving checkpoint transactions for pending checkpoint.",
1755            );
1756
1757            trace!(
1758                "roots for pending checkpoint {:?}: {:?}",
1759                pending.details.checkpoint_height, pending.roots,
1760            );
1761
1762            let settlement_root = if self.epoch_store.accumulators_enabled() {
1763                let Some(settlement_root @ TransactionKey::AccumulatorSettlement(..)) =
1764                    pending.roots.pop()
1765                else {
1766                    fatal!("No settlement root found");
1767                };
1768                Some(settlement_root)
1769            } else {
1770                None
1771            };
1772
1773            let roots = &pending.roots;
1774
1775            self.metrics
1776                .checkpoint_roots_count
1777                .inc_by(roots.len() as u64);
1778
1779            let root_digests = self
1780                .epoch_store
1781                .notify_read_tx_key_to_digest(roots)
1782                .in_monitored_scope("CheckpointNotifyDigests")
1783                .await?;
1784            let root_effects = self
1785                .effects_store
1786                .notify_read_executed_effects(
1787                    CHECKPOINT_BUILDER_NOTIFY_READ_TASK_NAME,
1788                    &root_digests,
1789                )
1790                .in_monitored_scope("CheckpointNotifyRead")
1791                .await;
1792
1793            assert!(
1794                self.epoch_store
1795                    .protocol_config()
1796                    .prepend_prologue_tx_in_consensus_commit_in_checkpoints()
1797            );
1798
1799            // If the roots contains consensus commit prologue transaction, we want to extract it,
1800            // and put it to the front of the checkpoint.
1801            let consensus_commit_prologue =
1802                self.extract_consensus_commit_prologue(&root_digests, &root_effects)?;
1803
1804            // Get the unincluded depdnencies of the consensus commit prologue. We should expect no
1805            // other dependencies that haven't been included in any previous checkpoints.
1806            if let Some((ccp_digest, ccp_effects)) = &consensus_commit_prologue {
1807                let unsorted_ccp = self.complete_checkpoint_effects(
1808                    vec![ccp_effects.clone()],
1809                    &mut effects_in_current_checkpoint,
1810                )?;
1811
1812                // No other dependencies of this consensus commit prologue that haven't been included
1813                // in any previous checkpoint.
1814                if unsorted_ccp.len() != 1 {
1815                    fatal!(
1816                        "Expected 1 consensus commit prologue, got {:?}",
1817                        unsorted_ccp
1818                            .iter()
1819                            .map(|e| e.transaction_digest())
1820                            .collect::<Vec<_>>()
1821                    );
1822                }
1823                assert_eq!(unsorted_ccp.len(), 1);
1824                assert_eq!(unsorted_ccp[0].transaction_digest(), ccp_digest);
1825            }
1826
1827            let unsorted =
1828                self.complete_checkpoint_effects(root_effects, &mut effects_in_current_checkpoint)?;
1829
1830            let _scope = monitored_scope("CheckpointBuilder::causal_sort");
1831            let mut sorted: Vec<TransactionEffects> = Vec::with_capacity(unsorted.len() + 1);
1832            if let Some((ccp_digest, ccp_effects)) = consensus_commit_prologue {
1833                if cfg!(debug_assertions) {
1834                    // When consensus_commit_prologue is extracted, it should not be included in the `unsorted`.
1835                    for tx in unsorted.iter() {
1836                        assert!(tx.transaction_digest() != &ccp_digest);
1837                    }
1838                }
1839                sorted.push(ccp_effects);
1840            }
1841            sorted.extend(CausalOrder::causal_sort(unsorted));
1842
1843            if let Some(settlement_root) = settlement_root {
1844                //TODO: this is an incorrect heuristic for checkpoint seq number
1845                //      due to checkpoint splitting, to be fixed separately
1846                let last_checkpoint =
1847                    Self::load_last_built_checkpoint_summary(&self.epoch_store, &self.store)?;
1848                let next_checkpoint_seq = last_checkpoint
1849                    .as_ref()
1850                    .map(|(seq, _)| *seq)
1851                    .unwrap_or_default()
1852                    + 1;
1853                let tx_index_offset = tx_effects.len() as u64;
1854
1855                let (tx_key, settlement_effects) = self
1856                    .construct_and_execute_settlement_transactions(
1857                        &sorted,
1858                        pending.details.checkpoint_height,
1859                        next_checkpoint_seq,
1860                        tx_index_offset,
1861                    )
1862                    .await;
1863                debug!(?tx_key, "executed settlement transactions");
1864
1865                assert_eq!(settlement_root, tx_key);
1866
1867                // Note: we do not need to add the settlement digests to `tx_roots` - `tx_roots`
1868                // should only include the digests of transactions that were originally roots in
1869                // the pending checkpoint. It is later used to identify transactions which were
1870                // added as dependencies, so that those transactions can be waited on using
1871                // `consensus_messages_processed_notify()`. System transactions (such as
1872                // settlements) are exempt from this already.
1873                //
1874                // However, we DO need to add them to `effects_in_current_checkpoint` so that
1875                // `complete_checkpoint_effects` won't pull them in again as dependencies when
1876                // processing later pending checkpoints in the same batch.
1877                effects_in_current_checkpoint
1878                    .extend(settlement_effects.iter().map(|e| *e.transaction_digest()));
1879                sorted.extend(settlement_effects);
1880            }
1881
1882            #[cfg(msim)]
1883            {
1884                // Check consensus commit prologue invariants in sim test.
1885                self.expensive_consensus_commit_prologue_invariants_check(&root_digests, &sorted);
1886            }
1887
1888            tx_effects.extend(sorted);
1889            tx_roots.extend(root_digests);
1890        }
1891
1892        Ok((tx_effects, tx_roots))
1893    }
1894
1895    // Given the root transactions of a pending checkpoint, resolve the transactions should be included in
1896    // the checkpoint, and return them in the order they should be included in the checkpoint.
1897    #[instrument(level = "debug", skip_all)]
1898    async fn resolve_checkpoint_transactions_v2(
1899        &self,
1900        pending: PendingCheckpointV2,
1901    ) -> SuiResult<(Vec<TransactionEffects>, HashSet<TransactionDigest>)> {
1902        let _scope = monitored_scope("CheckpointBuilder::resolve_checkpoint_transactions");
1903
1904        debug!(
1905            checkpoint_commit_height = pending.details.checkpoint_height,
1906            "Resolving checkpoint transactions for pending checkpoint.",
1907        );
1908
1909        trace!(
1910            "roots for pending checkpoint {:?}: {:?}",
1911            pending.details.checkpoint_height, pending.roots,
1912        );
1913
1914        assert!(
1915            self.epoch_store
1916                .protocol_config()
1917                .prepend_prologue_tx_in_consensus_commit_in_checkpoints()
1918        );
1919
1920        let mut all_effects: Vec<TransactionEffects> = Vec::new();
1921        let mut all_root_digests: Vec<TransactionDigest> = Vec::new();
1922
1923        for checkpoint_roots in &pending.roots {
1924            let tx_roots = &checkpoint_roots.tx_roots;
1925
1926            self.metrics
1927                .checkpoint_roots_count
1928                .inc_by(tx_roots.len() as u64);
1929
1930            let root_digests = self
1931                .epoch_store
1932                .notify_read_tx_key_to_digest(tx_roots)
1933                .in_monitored_scope("CheckpointNotifyDigests")
1934                .await?;
1935
1936            all_root_digests.extend(root_digests.iter().cloned());
1937
1938            let root_effects = self
1939                .effects_store
1940                .notify_read_executed_effects(
1941                    CHECKPOINT_BUILDER_NOTIFY_READ_TASK_NAME,
1942                    &root_digests,
1943                )
1944                .in_monitored_scope("CheckpointNotifyRead")
1945                .await;
1946            let consensus_commit_prologue =
1947                self.extract_consensus_commit_prologue(&root_digests, &root_effects)?;
1948
1949            let _scope = monitored_scope("CheckpointBuilder::causal_sort");
1950            let ccp_digest = consensus_commit_prologue.map(|(d, _)| d);
1951            let mut sorted = CausalOrder::causal_sort_with_ccp(root_effects, ccp_digest);
1952
1953            if let Some(settlement_key) = &checkpoint_roots.settlement_root {
1954                let checkpoint_seq = pending
1955                    .details
1956                    .checkpoint_seq
1957                    .expect("checkpoint_seq must be set");
1958                let tx_index_offset = all_effects.len() as u64;
1959                let effects = self
1960                    .resolve_settlement_effects(
1961                        *settlement_key,
1962                        &sorted,
1963                        checkpoint_roots.height,
1964                        checkpoint_seq,
1965                        tx_index_offset,
1966                    )
1967                    .await;
1968                sorted.extend(effects);
1969            }
1970
1971            #[cfg(msim)]
1972            {
1973                self.expensive_consensus_commit_prologue_invariants_check(&root_digests, &sorted);
1974            }
1975
1976            all_effects.extend(sorted);
1977        }
1978        Ok((all_effects, all_root_digests.into_iter().collect()))
1979    }
1980
1981    /// Constructs settlement transactions to compute their digests, then reads effects
1982    /// directly from the cache. If execution is ahead of the checkpoint builder, the
1983    /// effects are already cached and this returns instantly. Otherwise it waits for
1984    /// the execution scheduler's queue worker to execute them.
1985    async fn resolve_settlement_effects(
1986        &self,
1987        settlement_key: TransactionKey,
1988        sorted_root_effects: &[TransactionEffects],
1989        checkpoint_height: CheckpointHeight,
1990        checkpoint_seq: CheckpointSequenceNumber,
1991        tx_index_offset: u64,
1992    ) -> Vec<TransactionEffects> {
1993        let epoch = self.epoch_store.epoch();
1994        let accumulator_root_obj_initial_shared_version = self
1995            .epoch_store
1996            .epoch_start_config()
1997            .accumulator_root_obj_initial_shared_version()
1998            .expect("accumulator root object must exist");
1999
2000        let builder = AccumulatorSettlementTxBuilder::new(
2001            None,
2002            sorted_root_effects,
2003            checkpoint_seq,
2004            tx_index_offset,
2005        );
2006
2007        let settlement_digests: Vec<_> = builder
2008            .build_tx(
2009                self.epoch_store.protocol_config(),
2010                epoch,
2011                accumulator_root_obj_initial_shared_version,
2012                checkpoint_height,
2013                checkpoint_seq,
2014            )
2015            .into_iter()
2016            .map(|tx| *VerifiedTransaction::new_system_transaction(tx).digest())
2017            .collect();
2018
2019        debug!(
2020            ?settlement_digests,
2021            ?settlement_key,
2022            "fallback: reading settlement effects from cache"
2023        );
2024
2025        let settlement_effects = wait_for_effects_with_retry(
2026            self.effects_store.as_ref(),
2027            "CheckpointBuilder::fallback_settlement_effects",
2028            &settlement_digests,
2029            settlement_key,
2030        )
2031        .await;
2032
2033        let barrier_digest = *VerifiedTransaction::new_system_transaction(
2034            accumulators::build_accumulator_barrier_tx(
2035                epoch,
2036                accumulator_root_obj_initial_shared_version,
2037                checkpoint_height,
2038                &settlement_effects,
2039            ),
2040        )
2041        .digest();
2042
2043        let barrier_effects = wait_for_effects_with_retry(
2044            self.effects_store.as_ref(),
2045            "CheckpointBuilder::fallback_barrier_effects",
2046            &[barrier_digest],
2047            settlement_key,
2048        )
2049        .await;
2050
2051        settlement_effects
2052            .into_iter()
2053            .chain(barrier_effects)
2054            .collect()
2055    }
2056
2057    // Extracts the consensus commit prologue digest and effects from the root transactions.
2058    // The consensus commit prologue is expected to be the first transaction in the roots.
2059    fn extract_consensus_commit_prologue(
2060        &self,
2061        root_digests: &[TransactionDigest],
2062        root_effects: &[TransactionEffects],
2063    ) -> SuiResult<Option<(TransactionDigest, TransactionEffects)>> {
2064        let _scope = monitored_scope("CheckpointBuilder::extract_consensus_commit_prologue");
2065        if root_digests.is_empty() {
2066            return Ok(None);
2067        }
2068
2069        // Reads the first transaction in the roots, and checks whether it is a consensus commit
2070        // prologue transaction. The consensus commit prologue transaction should be the first
2071        // transaction in the roots written by the consensus handler.
2072        let first_tx = self
2073            .state
2074            .get_transaction_cache_reader()
2075            .get_transaction_block(&root_digests[0])
2076            .expect("Transaction block must exist");
2077
2078        Ok(first_tx
2079            .transaction_data()
2080            .is_consensus_commit_prologue()
2081            .then(|| {
2082                assert_eq!(first_tx.digest(), root_effects[0].transaction_digest());
2083                (*first_tx.digest(), root_effects[0].clone())
2084            }))
2085    }
2086
2087    #[instrument(level = "debug", skip_all)]
2088    async fn write_checkpoints(
2089        &mut self,
2090        height: CheckpointHeight,
2091        new_checkpoints: NonEmpty<(CheckpointSummary, CheckpointContents)>,
2092    ) -> SuiResult {
2093        let _scope = monitored_scope("CheckpointBuilder::write_checkpoints");
2094        let mut batch = self.store.tables.checkpoint_content.batch();
2095        let mut all_tx_digests =
2096            Vec::with_capacity(new_checkpoints.iter().map(|(_, c)| c.size()).sum());
2097
2098        for (summary, contents) in &new_checkpoints {
2099            debug!(
2100                checkpoint_commit_height = height,
2101                checkpoint_seq = summary.sequence_number,
2102                contents_digest = ?contents.digest(),
2103                "writing checkpoint",
2104            );
2105
2106            if let Some(previously_computed_summary) = self
2107                .store
2108                .tables
2109                .locally_computed_checkpoints
2110                .get(&summary.sequence_number)?
2111                && previously_computed_summary.digest() != summary.digest()
2112            {
2113                fatal!(
2114                    "Checkpoint {} was previously built with a different result: previously_computed_summary {:?} vs current_summary {:?}",
2115                    summary.sequence_number,
2116                    previously_computed_summary.digest(),
2117                    summary.digest()
2118                );
2119            }
2120
2121            all_tx_digests.extend(contents.iter().map(|digests| digests.transaction));
2122
2123            self.metrics
2124                .transactions_included_in_checkpoint
2125                .inc_by(contents.size() as u64);
2126            let sequence_number = summary.sequence_number;
2127            self.metrics
2128                .last_constructed_checkpoint
2129                .set(sequence_number as i64);
2130
2131            batch.insert_batch(
2132                &self.store.tables.checkpoint_content,
2133                [(contents.digest(), contents)],
2134            )?;
2135
2136            batch.insert_batch(
2137                &self.store.tables.locally_computed_checkpoints,
2138                [(sequence_number, summary)],
2139            )?;
2140        }
2141
2142        batch.write()?;
2143
2144        // Send all checkpoint sigs to consensus.
2145        for (summary, contents) in &new_checkpoints {
2146            self.output
2147                .checkpoint_created(summary, contents, &self.epoch_store, &self.store)
2148                .await?;
2149        }
2150
2151        for (local_checkpoint, _) in &new_checkpoints {
2152            if let Some(certified_checkpoint) = self
2153                .store
2154                .tables
2155                .certified_checkpoints
2156                .get(local_checkpoint.sequence_number())?
2157            {
2158                self.store
2159                    .check_for_checkpoint_fork(local_checkpoint, &certified_checkpoint.into());
2160            }
2161        }
2162
2163        self.notify_aggregator.notify_one();
2164        self.epoch_store
2165            .process_constructed_checkpoint(height, new_checkpoints);
2166        Ok(())
2167    }
2168
2169    #[allow(clippy::type_complexity)]
2170    fn split_checkpoint_chunks(
2171        &self,
2172        effects_and_transaction_sizes: Vec<(TransactionEffects, usize)>,
2173        signatures: Vec<Vec<(GenericSignature, Option<SequenceNumber>)>>,
2174    ) -> CheckpointBuilderResult<
2175        Vec<
2176            Vec<(
2177                TransactionEffects,
2178                Vec<(GenericSignature, Option<SequenceNumber>)>,
2179            )>,
2180        >,
2181    > {
2182        let _guard = monitored_scope("CheckpointBuilder::split_checkpoint_chunks");
2183
2184        // If splitting is done in consensus_handler, return everything as one chunk.
2185        if self
2186            .epoch_store
2187            .protocol_config()
2188            .split_checkpoints_in_consensus_handler()
2189        {
2190            let chunk: Vec<_> = effects_and_transaction_sizes
2191                .into_iter()
2192                .zip_debug_eq(signatures)
2193                .map(|((effects, _size), sigs)| (effects, sigs))
2194                .collect();
2195            return Ok(vec![chunk]);
2196        }
2197        let mut chunks = Vec::new();
2198        let mut chunk = Vec::new();
2199        let mut chunk_size: usize = 0;
2200        for ((effects, transaction_size), signatures) in effects_and_transaction_sizes
2201            .into_iter()
2202            .zip_debug_eq(signatures.into_iter())
2203        {
2204            // Roll over to a new chunk after either max count or max size is reached.
2205            // The size calculation here is intended to estimate the size of the
2206            // FullCheckpointContents struct. If this code is modified, that struct
2207            // should also be updated accordingly.
2208            let signatures_size = if self.epoch_store.protocol_config().address_aliases() {
2209                bcs::serialized_size(&signatures)?
2210            } else {
2211                let signatures: Vec<&GenericSignature> =
2212                    signatures.iter().map(|(s, _)| s).collect();
2213                bcs::serialized_size(&signatures)?
2214            };
2215            let size = transaction_size + bcs::serialized_size(&effects)? + signatures_size;
2216            if chunk.len() == self.max_transactions_per_checkpoint
2217                || (chunk_size + size) > self.max_checkpoint_size_bytes
2218            {
2219                if chunk.is_empty() {
2220                    // Always allow at least one tx in a checkpoint.
2221                    warn!(
2222                        "Size of single transaction ({size}) exceeds max checkpoint size ({}); allowing excessively large checkpoint to go through.",
2223                        self.max_checkpoint_size_bytes
2224                    );
2225                } else {
2226                    chunks.push(chunk);
2227                    chunk = Vec::new();
2228                    chunk_size = 0;
2229                }
2230            }
2231
2232            chunk.push((effects, signatures));
2233            chunk_size += size;
2234        }
2235
2236        if !chunk.is_empty() || chunks.is_empty() {
2237            // We intentionally create an empty checkpoint if there is no content provided
2238            // to make a 'heartbeat' checkpoint.
2239            // Important: if some conditions are added here later, we need to make sure we always
2240            // have at least one chunk if last_pending_of_epoch is set
2241            chunks.push(chunk);
2242            // Note: empty checkpoints are ok - they shouldn't happen at all on a network with even
2243            // modest load. Even if they do happen, it is still useful as it allows fullnodes to
2244            // distinguish between "no transactions have happened" and "i am not receiving new
2245            // checkpoints".
2246        }
2247        Ok(chunks)
2248    }
2249
2250    fn load_last_built_checkpoint_summary(
2251        epoch_store: &AuthorityPerEpochStore,
2252        store: &CheckpointStore,
2253    ) -> SuiResult<Option<(CheckpointSequenceNumber, CheckpointSummary)>> {
2254        let mut last_checkpoint = epoch_store.last_built_checkpoint_summary()?;
2255        if last_checkpoint.is_none() {
2256            let epoch = epoch_store.epoch();
2257            if epoch > 0 {
2258                let previous_epoch = epoch - 1;
2259                let last_verified = store.get_epoch_last_checkpoint(previous_epoch)?;
2260                last_checkpoint = last_verified.map(VerifiedCheckpoint::into_summary_and_sequence);
2261                if let Some((ref seq, _)) = last_checkpoint {
2262                    debug!(
2263                        "No checkpoints in builder DB, taking checkpoint from previous epoch with sequence {seq}"
2264                    );
2265                } else {
2266                    // This is some serious bug with when CheckpointBuilder started so surfacing it via panic
2267                    panic!("Can not find last checkpoint for previous epoch {previous_epoch}");
2268                }
2269            }
2270        }
2271        Ok(last_checkpoint)
2272    }
2273
2274    #[instrument(level = "debug", skip_all)]
2275    async fn create_checkpoints(
2276        &self,
2277        all_effects: Vec<TransactionEffects>,
2278        details: &PendingCheckpointInfo,
2279        all_roots: &HashSet<TransactionDigest>,
2280    ) -> CheckpointBuilderResult<NonEmpty<(CheckpointSummary, CheckpointContents)>> {
2281        let _scope = monitored_scope("CheckpointBuilder::create_checkpoints");
2282
2283        let total = all_effects.len();
2284        let mut last_checkpoint =
2285            Self::load_last_built_checkpoint_summary(&self.epoch_store, &self.store)?;
2286        let last_checkpoint_seq = last_checkpoint.as_ref().map(|(seq, _)| *seq);
2287        debug!(
2288            checkpoint_commit_height = details.checkpoint_height,
2289            next_checkpoint_seq = last_checkpoint_seq.unwrap_or_default() + 1,
2290            checkpoint_timestamp = details.timestamp_ms,
2291            "Creating checkpoint(s) for {} transactions",
2292            all_effects.len(),
2293        );
2294
2295        let all_digests: Vec<_> = all_effects
2296            .iter()
2297            .map(|effect| *effect.transaction_digest())
2298            .collect();
2299        let transactions_and_sizes = self
2300            .state
2301            .get_transaction_cache_reader()
2302            .get_transactions_and_serialized_sizes(&all_digests)?;
2303        let mut all_effects_and_transaction_sizes = Vec::with_capacity(all_effects.len());
2304        let mut transactions = Vec::with_capacity(all_effects.len());
2305        let mut transaction_keys = Vec::with_capacity(all_effects.len());
2306        let mut randomness_rounds = BTreeMap::new();
2307        {
2308            let _guard = monitored_scope("CheckpointBuilder::wait_for_transactions_sequenced");
2309            debug!(
2310                ?last_checkpoint_seq,
2311                "Waiting for {:?} certificates to appear in consensus",
2312                all_effects.len()
2313            );
2314
2315            for (effects, transaction_and_size) in all_effects
2316                .into_iter()
2317                .zip_debug_eq(transactions_and_sizes.into_iter())
2318            {
2319                let (transaction, size) = transaction_and_size
2320                    .unwrap_or_else(|| panic!("Could not find executed transaction {:?}", effects));
2321                match transaction.inner().transaction_data().kind() {
2322                    TransactionKind::ConsensusCommitPrologue(_)
2323                    | TransactionKind::ConsensusCommitPrologueV2(_)
2324                    | TransactionKind::ConsensusCommitPrologueV3(_)
2325                    | TransactionKind::ConsensusCommitPrologueV4(_)
2326                    | TransactionKind::AuthenticatorStateUpdate(_) => {
2327                        // ConsensusCommitPrologue and AuthenticatorStateUpdate are guaranteed to be
2328                        // processed before we reach here.
2329                    }
2330                    TransactionKind::ProgrammableSystemTransaction(_) => {
2331                        // settlement transactions are added by checkpoint builder
2332                    }
2333                    TransactionKind::ChangeEpoch(_)
2334                    | TransactionKind::Genesis(_)
2335                    | TransactionKind::EndOfEpochTransaction(_) => {
2336                        fatal!(
2337                            "unexpected transaction in checkpoint effects: {:?}",
2338                            transaction
2339                        );
2340                    }
2341                    TransactionKind::RandomnessStateUpdate(rsu) => {
2342                        randomness_rounds
2343                            .insert(*effects.transaction_digest(), rsu.randomness_round);
2344                    }
2345                    TransactionKind::ProgrammableTransaction(_) => {
2346                        // Only transactions that are not roots should be included in the call to
2347                        // `consensus_messages_processed_notify`. roots come directly from the consensus
2348                        // commit and so are known to be processed already.
2349                        let digest = *effects.transaction_digest();
2350                        if !all_roots.contains(&digest) {
2351                            transaction_keys.push(SequencedConsensusTransactionKey::External(
2352                                ConsensusTransactionKey::Certificate(digest),
2353                            ));
2354                        }
2355                    }
2356                }
2357                transactions.push(transaction);
2358                all_effects_and_transaction_sizes.push((effects, size));
2359            }
2360
2361            self.epoch_store
2362                .consensus_messages_processed_notify(transaction_keys)
2363                .await?;
2364        }
2365
2366        let signatures = self
2367            .epoch_store
2368            .user_signatures_for_checkpoint(&transactions, &all_digests);
2369        debug!(
2370            ?last_checkpoint_seq,
2371            "Received {} checkpoint user signatures from consensus",
2372            signatures.len()
2373        );
2374
2375        let mut end_of_epoch_observation_keys: Option<Vec<_>> = if details.last_of_epoch {
2376            Some(
2377                transactions
2378                    .iter()
2379                    .flat_map(|tx| {
2380                        if let TransactionKind::ProgrammableTransaction(ptb) =
2381                            tx.transaction_data().kind()
2382                        {
2383                            itertools::Either::Left(
2384                                ptb.commands
2385                                    .iter()
2386                                    .map(ExecutionTimeObservationKey::from_command),
2387                            )
2388                        } else {
2389                            itertools::Either::Right(std::iter::empty())
2390                        }
2391                    })
2392                    .collect(),
2393            )
2394        } else {
2395            None
2396        };
2397
2398        let chunks = self.split_checkpoint_chunks(all_effects_and_transaction_sizes, signatures)?;
2399        let chunks_count = chunks.len();
2400
2401        let mut checkpoints = Vec::with_capacity(chunks_count);
2402        debug!(
2403            ?last_checkpoint_seq,
2404            "Creating {} checkpoints with {} transactions", chunks_count, total,
2405        );
2406
2407        let epoch = self.epoch_store.epoch();
2408        for (index, transactions) in chunks.into_iter().enumerate() {
2409            let first_checkpoint_of_epoch = index == 0
2410                && last_checkpoint
2411                    .as_ref()
2412                    .map(|(_, c)| c.epoch != epoch)
2413                    .unwrap_or(true);
2414            if first_checkpoint_of_epoch {
2415                self.epoch_store
2416                    .record_epoch_first_checkpoint_creation_time_metric();
2417            }
2418            let last_checkpoint_of_epoch = details.last_of_epoch && index == chunks_count - 1;
2419
2420            let sequence_number = if let Some(preassigned_seq) = details.checkpoint_seq {
2421                preassigned_seq
2422            } else {
2423                last_checkpoint
2424                    .as_ref()
2425                    .map(|(_, c)| c.sequence_number + 1)
2426                    .unwrap_or_default()
2427            };
2428            let mut timestamp_ms = details.timestamp_ms;
2429            if let Some((_, last_checkpoint)) = &last_checkpoint
2430                && last_checkpoint.timestamp_ms > timestamp_ms
2431            {
2432                // First consensus commit of an epoch can have zero timestamp.
2433                debug!(
2434                    "Decrease of checkpoint timestamp, possibly due to epoch change. Sequence: {}, previous: {}, current: {}",
2435                    sequence_number, last_checkpoint.timestamp_ms, timestamp_ms,
2436                );
2437                if self
2438                    .epoch_store
2439                    .protocol_config()
2440                    .enforce_checkpoint_timestamp_monotonicity()
2441                {
2442                    timestamp_ms = last_checkpoint.timestamp_ms;
2443                }
2444            }
2445
2446            let (mut effects, mut signatures): (Vec<_>, Vec<_>) = transactions.into_iter().unzip();
2447            let epoch_rolling_gas_cost_summary =
2448                self.get_epoch_total_gas_cost(last_checkpoint.as_ref().map(|(_, c)| c), &effects);
2449
2450            let end_of_epoch_data = if last_checkpoint_of_epoch {
2451                let system_state_obj = self
2452                    .augment_epoch_last_checkpoint(
2453                        &epoch_rolling_gas_cost_summary,
2454                        timestamp_ms,
2455                        &mut effects,
2456                        &mut signatures,
2457                        sequence_number,
2458                        std::mem::take(&mut end_of_epoch_observation_keys).expect("end_of_epoch_observation_keys must be populated for the last checkpoint"),
2459                        last_checkpoint_seq.unwrap_or_default(),
2460                    )
2461                    .await?;
2462
2463                let committee = system_state_obj
2464                    .get_current_epoch_committee()
2465                    .committee()
2466                    .clone();
2467
2468                // This must happen after the call to augment_epoch_last_checkpoint,
2469                // otherwise we will not capture the change_epoch tx.
2470                let root_state_digest = {
2471                    let state_acc = self
2472                        .global_state_hasher
2473                        .upgrade()
2474                        .expect("No checkpoints should be getting built after local configuration");
2475                    let acc = state_acc.accumulate_checkpoint(
2476                        &effects,
2477                        sequence_number,
2478                        &self.epoch_store,
2479                    )?;
2480
2481                    state_acc
2482                        .wait_for_previous_running_root(&self.epoch_store, sequence_number)
2483                        .await?;
2484
2485                    state_acc.accumulate_running_root(
2486                        &self.epoch_store,
2487                        sequence_number,
2488                        Some(acc),
2489                    )?;
2490                    state_acc
2491                        .digest_epoch(self.epoch_store.clone(), sequence_number)
2492                        .await?
2493                };
2494                self.metrics.highest_accumulated_epoch.set(epoch as i64);
2495                info!("Epoch {epoch} root state hash digest: {root_state_digest:?}");
2496
2497                let epoch_commitments = if self
2498                    .epoch_store
2499                    .protocol_config()
2500                    .check_commit_root_state_digest_supported()
2501                {
2502                    vec![root_state_digest.into()]
2503                } else {
2504                    vec![]
2505                };
2506
2507                Some(EndOfEpochData {
2508                    next_epoch_committee: committee.voting_rights,
2509                    next_epoch_protocol_version: ProtocolVersion::new(
2510                        system_state_obj.protocol_version(),
2511                    ),
2512                    epoch_commitments,
2513                })
2514            } else {
2515                self.send_to_hasher
2516                    .send((sequence_number, effects.clone()))
2517                    .await?;
2518
2519                None
2520            };
2521            let contents = if self.epoch_store.protocol_config().address_aliases() {
2522                CheckpointContents::new_v2(&effects, signatures)
2523            } else {
2524                CheckpointContents::new_with_digests_and_signatures(
2525                    effects.iter().map(TransactionEffects::execution_digests),
2526                    signatures
2527                        .into_iter()
2528                        .map(|sigs| sigs.into_iter().map(|(s, _)| s).collect())
2529                        .collect(),
2530                )
2531            };
2532
2533            let num_txns = contents.size() as u64;
2534
2535            let network_total_transactions = last_checkpoint
2536                .as_ref()
2537                .map(|(_, c)| c.network_total_transactions + num_txns)
2538                .unwrap_or(num_txns);
2539
2540            let previous_digest = last_checkpoint.as_ref().map(|(_, c)| c.digest());
2541
2542            let matching_randomness_rounds: Vec<_> = effects
2543                .iter()
2544                .filter_map(|e| randomness_rounds.get(e.transaction_digest()))
2545                .copied()
2546                .collect();
2547
2548            let checkpoint_commitments = if self
2549                .epoch_store
2550                .protocol_config()
2551                .include_checkpoint_artifacts_digest_in_summary()
2552            {
2553                let artifacts = CheckpointArtifacts::from(&effects[..]);
2554                let artifacts_digest = artifacts.digest()?;
2555                vec![artifacts_digest.into()]
2556            } else {
2557                Default::default()
2558            };
2559
2560            let summary = CheckpointSummary::new(
2561                self.epoch_store.protocol_config(),
2562                epoch,
2563                sequence_number,
2564                network_total_transactions,
2565                &contents,
2566                previous_digest,
2567                epoch_rolling_gas_cost_summary,
2568                end_of_epoch_data,
2569                timestamp_ms,
2570                matching_randomness_rounds,
2571                checkpoint_commitments,
2572            );
2573            summary.report_checkpoint_age(
2574                &self.metrics.last_created_checkpoint_age,
2575                &self.metrics.last_created_checkpoint_age_ms,
2576            );
2577            if last_checkpoint_of_epoch {
2578                info!(
2579                    checkpoint_seq = sequence_number,
2580                    "creating last checkpoint of epoch {}", epoch
2581                );
2582                if let Some(stats) = self.store.get_epoch_stats(epoch, &summary) {
2583                    self.epoch_store
2584                        .report_epoch_metrics_at_last_checkpoint(stats);
2585                }
2586            }
2587            last_checkpoint = Some((sequence_number, summary.clone()));
2588            checkpoints.push((summary, contents));
2589        }
2590
2591        Ok(NonEmpty::from_vec(checkpoints).expect("at least one checkpoint"))
2592    }
2593
2594    fn get_epoch_total_gas_cost(
2595        &self,
2596        last_checkpoint: Option<&CheckpointSummary>,
2597        cur_checkpoint_effects: &[TransactionEffects],
2598    ) -> GasCostSummary {
2599        let (previous_epoch, previous_gas_costs) = last_checkpoint
2600            .map(|c| (c.epoch, c.epoch_rolling_gas_cost_summary.clone()))
2601            .unwrap_or_default();
2602        let current_gas_costs = GasCostSummary::new_from_txn_effects(cur_checkpoint_effects.iter());
2603        if previous_epoch == self.epoch_store.epoch() {
2604            // sum only when we are within the same epoch
2605            GasCostSummary::new(
2606                previous_gas_costs.computation_cost + current_gas_costs.computation_cost,
2607                previous_gas_costs.storage_cost + current_gas_costs.storage_cost,
2608                previous_gas_costs.storage_rebate + current_gas_costs.storage_rebate,
2609                previous_gas_costs.non_refundable_storage_fee
2610                    + current_gas_costs.non_refundable_storage_fee,
2611            )
2612        } else {
2613            current_gas_costs
2614        }
2615    }
2616
2617    #[instrument(level = "error", skip_all)]
2618    async fn augment_epoch_last_checkpoint(
2619        &self,
2620        epoch_total_gas_cost: &GasCostSummary,
2621        epoch_start_timestamp_ms: CheckpointTimestamp,
2622        checkpoint_effects: &mut Vec<TransactionEffects>,
2623        signatures: &mut Vec<Vec<(GenericSignature, Option<SequenceNumber>)>>,
2624        checkpoint: CheckpointSequenceNumber,
2625        end_of_epoch_observation_keys: Vec<ExecutionTimeObservationKey>,
2626        // This may be less than `checkpoint - 1` if the end-of-epoch PendingCheckpoint produced
2627        // >1 checkpoint.
2628        last_checkpoint: CheckpointSequenceNumber,
2629    ) -> CheckpointBuilderResult<SuiSystemState> {
2630        let (system_state, effects) = self
2631            .state
2632            .create_and_execute_advance_epoch_tx(
2633                &self.epoch_store,
2634                epoch_total_gas_cost,
2635                checkpoint,
2636                epoch_start_timestamp_ms,
2637                end_of_epoch_observation_keys,
2638                last_checkpoint,
2639            )
2640            .await?;
2641        checkpoint_effects.push(effects);
2642        signatures.push(vec![]);
2643        Ok(system_state)
2644    }
2645
2646    /// For the given roots return complete list of effects to include in checkpoint
2647    /// This list includes the roots and all their dependencies, which are not part of checkpoint already.
2648    /// Note that this function may be called multiple times to construct the checkpoint.
2649    /// `existing_tx_digests_in_checkpoint` is used to track the transactions that are already included in the checkpoint.
2650    /// Txs in `roots` that need to be included in the checkpoint will be added to `existing_tx_digests_in_checkpoint`
2651    /// after the call of this function.
2652    #[instrument(level = "debug", skip_all)]
2653    fn complete_checkpoint_effects(
2654        &self,
2655        mut roots: Vec<TransactionEffects>,
2656        existing_tx_digests_in_checkpoint: &mut BTreeSet<TransactionDigest>,
2657    ) -> SuiResult<Vec<TransactionEffects>> {
2658        let _scope = monitored_scope("CheckpointBuilder::complete_checkpoint_effects");
2659        let mut results = vec![];
2660        let mut seen = HashSet::new();
2661        loop {
2662            let mut pending = HashSet::new();
2663
2664            let transactions_included = self
2665                .epoch_store
2666                .builder_included_transactions_in_checkpoint(
2667                    roots.iter().map(|e| e.transaction_digest()),
2668                )?;
2669
2670            for (effect, tx_included) in roots
2671                .into_iter()
2672                .zip_debug_eq(transactions_included.into_iter())
2673            {
2674                let digest = effect.transaction_digest();
2675                // Unnecessary to read effects of a dependency if the effect is already processed.
2676                seen.insert(*digest);
2677
2678                // Skip roots that are already included in the checkpoint.
2679                if existing_tx_digests_in_checkpoint.contains(effect.transaction_digest()) {
2680                    continue;
2681                }
2682
2683                // Skip roots already included in checkpoints or roots from previous epochs
2684                if tx_included || effect.executed_epoch() < self.epoch_store.epoch() {
2685                    continue;
2686                }
2687
2688                let existing_effects = self
2689                    .epoch_store
2690                    .transactions_executed_in_cur_epoch(effect.dependencies())?;
2691
2692                for (dependency, effects_signature_exists) in effect
2693                    .dependencies()
2694                    .iter()
2695                    .zip_debug_eq(existing_effects.iter())
2696                {
2697                    // Skip here if dependency not executed in the current epoch.
2698                    // Note that the existence of an effects signature in the
2699                    // epoch store for the given digest indicates that the transaction
2700                    // was locally executed in the current epoch
2701                    if !effects_signature_exists {
2702                        continue;
2703                    }
2704                    if seen.insert(*dependency) {
2705                        pending.insert(*dependency);
2706                    }
2707                }
2708                results.push(effect);
2709            }
2710            if pending.is_empty() {
2711                break;
2712            }
2713            let pending = pending.into_iter().collect::<Vec<_>>();
2714            let effects = self.effects_store.multi_get_executed_effects(&pending);
2715            let effects = effects
2716                .into_iter()
2717                .zip_debug_eq(pending)
2718                .map(|(opt, digest)| match opt {
2719                    Some(x) => x,
2720                    None => panic!(
2721                        "Can not find effect for transaction {:?}, however transaction that depend on it was already executed",
2722                        digest
2723                    ),
2724                })
2725                .collect::<Vec<_>>();
2726            roots = effects;
2727        }
2728
2729        existing_tx_digests_in_checkpoint.extend(results.iter().map(|e| e.transaction_digest()));
2730        Ok(results)
2731    }
2732
2733    // Checks the invariants of the consensus commit prologue transactions in the checkpoint
2734    // in simtest.
2735    #[cfg(msim)]
2736    fn expensive_consensus_commit_prologue_invariants_check(
2737        &self,
2738        root_digests: &[TransactionDigest],
2739        sorted: &[TransactionEffects],
2740    ) {
2741        // Gets all the consensus commit prologue transactions from the roots.
2742        let root_txs = self
2743            .state
2744            .get_transaction_cache_reader()
2745            .multi_get_transaction_blocks(root_digests);
2746        let ccps = root_txs
2747            .iter()
2748            .filter_map(|tx| {
2749                if let Some(tx) = tx {
2750                    if tx.transaction_data().is_consensus_commit_prologue() {
2751                        Some(tx)
2752                    } else {
2753                        None
2754                    }
2755                } else {
2756                    None
2757                }
2758            })
2759            .collect::<Vec<_>>();
2760
2761        // There should be at most one consensus commit prologue transaction in the roots.
2762        assert!(ccps.len() <= 1);
2763
2764        // Get all the transactions in the checkpoint.
2765        let txs = self
2766            .state
2767            .get_transaction_cache_reader()
2768            .multi_get_transaction_blocks(
2769                &sorted
2770                    .iter()
2771                    .map(|tx| tx.transaction_digest().clone())
2772                    .collect::<Vec<_>>(),
2773            );
2774
2775        if ccps.len() == 0 {
2776            // If there is no consensus commit prologue transaction in the roots, then there should be no
2777            // consensus commit prologue transaction in the checkpoint.
2778            for tx in txs.iter() {
2779                if let Some(tx) = tx {
2780                    assert!(!tx.transaction_data().is_consensus_commit_prologue());
2781                }
2782            }
2783        } else {
2784            // If there is one consensus commit prologue, it must be the first one in the checkpoint.
2785            assert!(
2786                txs[0]
2787                    .as_ref()
2788                    .unwrap()
2789                    .transaction_data()
2790                    .is_consensus_commit_prologue()
2791            );
2792
2793            assert_eq!(ccps[0].digest(), txs[0].as_ref().unwrap().digest());
2794
2795            for tx in txs.iter().skip(1) {
2796                if let Some(tx) = tx {
2797                    assert!(!tx.transaction_data().is_consensus_commit_prologue());
2798                }
2799            }
2800        }
2801    }
2802}
2803
2804async fn wait_for_effects_with_retry(
2805    effects_store: &dyn TransactionCacheRead,
2806    task_name: &'static str,
2807    digests: &[TransactionDigest],
2808    tx_key: TransactionKey,
2809) -> Vec<TransactionEffects> {
2810    let delay = if in_antithesis() {
2811        // antithesis has aggressive thread pausing, 5 seconds causes false positives
2812        15
2813    } else {
2814        5
2815    };
2816    loop {
2817        match tokio::time::timeout(Duration::from_secs(delay), async {
2818            effects_store
2819                .notify_read_executed_effects(task_name, digests)
2820                .await
2821        })
2822        .await
2823        {
2824            Ok(effects) => break effects,
2825            Err(_) => {
2826                debug_fatal!(
2827                    "Timeout waiting for transactions to be executed {:?}, retrying...",
2828                    tx_key
2829                );
2830            }
2831        }
2832    }
2833}
2834
2835impl CheckpointAggregator {
2836    fn new(
2837        tables: Arc<CheckpointStore>,
2838        epoch_store: Arc<AuthorityPerEpochStore>,
2839        notify: Arc<Notify>,
2840        receiver: mpsc::UnboundedReceiver<CheckpointSignatureMessage>,
2841        output: Box<dyn CertifiedCheckpointOutput>,
2842        state: Arc<AuthorityState>,
2843        metrics: Arc<CheckpointMetrics>,
2844    ) -> Self {
2845        Self {
2846            store: tables,
2847            epoch_store,
2848            notify,
2849            receiver,
2850            pending: BTreeMap::new(),
2851            current: None,
2852            output,
2853            state,
2854            metrics,
2855        }
2856    }
2857
2858    async fn run(mut self) {
2859        info!("Starting CheckpointAggregator");
2860        loop {
2861            // Drain all signatures that arrived since the last iteration into the pending buffer
2862            while let Ok(sig) = self.receiver.try_recv() {
2863                self.pending
2864                    .entry(sig.summary.sequence_number)
2865                    .or_default()
2866                    .push(sig);
2867            }
2868
2869            if let Err(e) = self.run_and_notify().await {
2870                error!(
2871                    "Error while aggregating checkpoint, will retry in 1s: {:?}",
2872                    e
2873                );
2874                self.metrics.checkpoint_errors.inc();
2875                tokio::time::sleep(Duration::from_secs(1)).await;
2876                continue;
2877            }
2878
2879            tokio::select! {
2880                Some(sig) = self.receiver.recv() => {
2881                    self.pending
2882                        .entry(sig.summary.sequence_number)
2883                        .or_default()
2884                        .push(sig);
2885                }
2886                _ = self.notify.notified() => {}
2887                _ = tokio::time::sleep(Duration::from_secs(1)) => {}
2888            }
2889        }
2890    }
2891
2892    async fn run_and_notify(&mut self) -> SuiResult {
2893        let summaries = self.run_inner()?;
2894        for summary in summaries {
2895            self.output.certified_checkpoint_created(&summary).await?;
2896        }
2897        Ok(())
2898    }
2899
2900    fn run_inner(&mut self) -> SuiResult<Vec<CertifiedCheckpointSummary>> {
2901        let _scope = monitored_scope("CheckpointAggregator");
2902        let mut result = vec![];
2903        'outer: loop {
2904            let next_to_certify = self.next_checkpoint_to_certify()?;
2905            // Discard buffered signatures for checkpoints already certified
2906            // (e.g. certified via StateSync before local aggregation completed).
2907            self.pending.retain(|&seq, _| seq >= next_to_certify);
2908            let current = if let Some(current) = &mut self.current {
2909                // It's possible that the checkpoint was already certified by
2910                // the rest of the network and we've already received the
2911                // certified checkpoint via StateSync. In this case, we reset
2912                // the current signature aggregator to the next checkpoint to
2913                // be certified
2914                if current.summary.sequence_number < next_to_certify {
2915                    assert_reachable!("skip checkpoint certification");
2916                    self.current = None;
2917                    continue;
2918                }
2919                current
2920            } else {
2921                let Some(summary) = self
2922                    .epoch_store
2923                    .get_built_checkpoint_summary(next_to_certify)?
2924                else {
2925                    return Ok(result);
2926                };
2927                self.current = Some(CheckpointSignatureAggregator {
2928                    digest: summary.digest(),
2929                    summary,
2930                    signatures_by_digest: MultiStakeAggregator::new(
2931                        self.epoch_store.committee().clone(),
2932                    ),
2933                    store: self.store.clone(),
2934                    state: self.state.clone(),
2935                    metrics: self.metrics.clone(),
2936                });
2937                self.current.as_mut().unwrap()
2938            };
2939
2940            let seq = current.summary.sequence_number;
2941            let sigs = self.pending.remove(&seq).unwrap_or_default();
2942            if sigs.is_empty() {
2943                trace!(
2944                    checkpoint_seq =? seq,
2945                    "Not enough checkpoint signatures",
2946                );
2947                return Ok(result);
2948            }
2949            for data in sigs {
2950                trace!(
2951                    checkpoint_seq = seq,
2952                    "Processing signature for checkpoint (digest: {:?}) from {:?}",
2953                    current.summary.digest(),
2954                    data.summary.auth_sig().authority.concise()
2955                );
2956                self.metrics
2957                    .checkpoint_participation
2958                    .with_label_values(&[&format!(
2959                        "{:?}",
2960                        data.summary.auth_sig().authority.concise()
2961                    )])
2962                    .inc();
2963                if let Ok(auth_signature) = current.try_aggregate(data) {
2964                    debug!(
2965                        checkpoint_seq = seq,
2966                        "Successfully aggregated signatures for checkpoint (digest: {:?})",
2967                        current.summary.digest(),
2968                    );
2969                    let summary = VerifiedCheckpoint::new_unchecked(
2970                        CertifiedCheckpointSummary::new_from_data_and_sig(
2971                            current.summary.clone(),
2972                            auth_signature,
2973                        ),
2974                    );
2975
2976                    self.store.insert_certified_checkpoint(&summary)?;
2977                    self.metrics.last_certified_checkpoint.set(seq as i64);
2978                    current.summary.report_checkpoint_age(
2979                        &self.metrics.last_certified_checkpoint_age,
2980                        &self.metrics.last_certified_checkpoint_age_ms,
2981                    );
2982                    result.push(summary.into_inner());
2983                    self.current = None;
2984                    continue 'outer;
2985                }
2986            }
2987            break;
2988        }
2989        Ok(result)
2990    }
2991
2992    fn next_checkpoint_to_certify(&self) -> SuiResult<CheckpointSequenceNumber> {
2993        Ok(self
2994            .store
2995            .tables
2996            .certified_checkpoints
2997            .reversed_safe_iter_with_bounds(None, None)?
2998            .next()
2999            .transpose()?
3000            .map(|(seq, _)| seq + 1)
3001            .unwrap_or_default())
3002    }
3003}
3004
3005impl CheckpointSignatureAggregator {
3006    #[allow(clippy::result_unit_err)]
3007    pub fn try_aggregate(
3008        &mut self,
3009        data: CheckpointSignatureMessage,
3010    ) -> Result<AuthorityStrongQuorumSignInfo, ()> {
3011        let their_digest = *data.summary.digest();
3012        let (_, signature) = data.summary.into_data_and_sig();
3013        let author = signature.authority;
3014        let envelope =
3015            SignedCheckpointSummary::new_from_data_and_sig(self.summary.clone(), signature);
3016        match self.signatures_by_digest.insert(their_digest, envelope) {
3017            // ignore repeated signatures
3018            InsertResult::Failed { error }
3019                if matches!(
3020                    error.as_inner(),
3021                    SuiErrorKind::StakeAggregatorRepeatedSigner {
3022                        conflicting_sig: false,
3023                        ..
3024                    },
3025                ) =>
3026            {
3027                Err(())
3028            }
3029            InsertResult::Failed { error } => {
3030                warn!(
3031                    checkpoint_seq = self.summary.sequence_number,
3032                    "Failed to aggregate new signature from validator {:?}: {:?}",
3033                    author.concise(),
3034                    error
3035                );
3036                self.check_for_split_brain();
3037                Err(())
3038            }
3039            InsertResult::QuorumReached(cert) => {
3040                // It is not guaranteed that signature.authority == narwhal_cert.author, but we do verify
3041                // the signature so we know that the author signed the message at some point.
3042                if their_digest != self.digest {
3043                    self.metrics.remote_checkpoint_forks.inc();
3044                    warn!(
3045                        checkpoint_seq = self.summary.sequence_number,
3046                        "Validator {:?} has mismatching checkpoint digest {}, we have digest {}",
3047                        author.concise(),
3048                        their_digest,
3049                        self.digest
3050                    );
3051                    return Err(());
3052                }
3053                Ok(cert)
3054            }
3055            InsertResult::NotEnoughVotes {
3056                bad_votes: _,
3057                bad_authorities: _,
3058            } => {
3059                self.check_for_split_brain();
3060                Err(())
3061            }
3062        }
3063    }
3064
3065    /// Check if there is a split brain condition in checkpoint signature aggregation, defined
3066    /// as any state wherein it is no longer possible to achieve quorum on a checkpoint proposal,
3067    /// irrespective of the outcome of any outstanding votes.
3068    fn check_for_split_brain(&self) {
3069        debug!(
3070            checkpoint_seq = self.summary.sequence_number,
3071            "Checking for split brain condition"
3072        );
3073        if self.signatures_by_digest.quorum_unreachable() {
3074            // TODO: at this point we should immediately halt processing
3075            // of new transaction certificates to avoid building on top of
3076            // forked output
3077            // self.halt_all_execution();
3078
3079            let all_unique_values = self.signatures_by_digest.get_all_unique_values();
3080            let digests_by_stake_messages = all_unique_values
3081                .iter()
3082                .sorted_by_key(|(_, (_, stake))| -(*stake as i64))
3083                .map(|(digest, (_authorities, total_stake))| {
3084                    format!("{:?} (total stake: {})", digest, total_stake)
3085                })
3086                .collect::<Vec<String>>();
3087            fail_point_arg!("kill_split_brain_node", |(
3088                checkpoint_overrides,
3089                forked_authorities,
3090            ): (
3091                std::sync::Arc<std::sync::Mutex<std::collections::BTreeMap<u64, String>>>,
3092                std::sync::Arc<std::sync::Mutex<std::collections::HashSet<AuthorityName>>>,
3093            )| {
3094                #[cfg(msim)]
3095                {
3096                    if let (Ok(mut overrides), Ok(forked_authorities_set)) =
3097                        (checkpoint_overrides.lock(), forked_authorities.lock())
3098                    {
3099                        // Find the digest produced by non-forked authorities
3100                        let correct_digest = all_unique_values
3101                            .iter()
3102                            .find(|(_, (authorities, _))| {
3103                                // Check if any authority that produced this digest is NOT in the forked set
3104                                authorities
3105                                    .iter()
3106                                    .any(|auth| !forked_authorities_set.contains(auth))
3107                            })
3108                            .map(|(digest, _)| digest.to_string())
3109                            .unwrap_or_else(|| {
3110                                // Fallback: use the digest with the highest stake
3111                                all_unique_values
3112                                    .iter()
3113                                    .max_by_key(|(_, (_, stake))| *stake)
3114                                    .map(|(digest, _)| digest.to_string())
3115                                    .unwrap_or_else(|| self.digest.to_string())
3116                            });
3117
3118                        overrides.insert(self.summary.sequence_number, correct_digest.clone());
3119
3120                        tracing::error!(
3121                            fatal = true,
3122                            "Fork recovery test: detected split-brain for sequence number: {}, using digest: {}",
3123                            self.summary.sequence_number,
3124                            correct_digest
3125                        );
3126                    }
3127                }
3128            });
3129
3130            debug_fatal!(
3131                "Split brain detected in checkpoint signature aggregation for checkpoint {:?}. Remaining stake: {:?}, Digests by stake: {:?}",
3132                self.summary.sequence_number,
3133                self.signatures_by_digest.uncommitted_stake(),
3134                digests_by_stake_messages
3135            );
3136            self.metrics.split_brain_checkpoint_forks.inc();
3137
3138            let all_unique_values = self.signatures_by_digest.get_all_unique_values();
3139            let local_summary = self.summary.clone();
3140            let state = self.state.clone();
3141            let tables = self.store.clone();
3142
3143            tokio::spawn(async move {
3144                diagnose_split_brain(all_unique_values, local_summary, state, tables).await;
3145            });
3146        }
3147    }
3148}
3149
3150/// Create data dump containing relevant data for diagnosing cause of the
3151/// split brain by querying one disagreeing validator for full checkpoint contents.
3152/// To minimize peer chatter, we only query one validator at random from each
3153/// disagreeing faction, as all honest validators that participated in this round may
3154/// inevitably run the same process.
3155async fn diagnose_split_brain(
3156    all_unique_values: BTreeMap<CheckpointDigest, (Vec<AuthorityName>, StakeUnit)>,
3157    local_summary: CheckpointSummary,
3158    state: Arc<AuthorityState>,
3159    tables: Arc<CheckpointStore>,
3160) {
3161    debug!(
3162        checkpoint_seq = local_summary.sequence_number,
3163        "Running split brain diagnostics..."
3164    );
3165    let time = SystemTime::now();
3166    // collect one random disagreeing validator per differing digest
3167    let digest_to_validator = all_unique_values
3168        .iter()
3169        .filter_map(|(digest, (validators, _))| {
3170            if *digest != local_summary.digest() {
3171                let random_validator = validators.choose(&mut get_rng()).unwrap();
3172                Some((*digest, *random_validator))
3173            } else {
3174                None
3175            }
3176        })
3177        .collect::<HashMap<_, _>>();
3178    if digest_to_validator.is_empty() {
3179        panic!(
3180            "Given split brain condition, there should be at \
3181                least one validator that disagrees with local signature"
3182        );
3183    }
3184
3185    let epoch_store = state.load_epoch_store_one_call_per_task();
3186    let committee = epoch_store
3187        .epoch_start_state()
3188        .get_sui_committee_with_network_metadata();
3189    let network_config = default_mysten_network_config();
3190    let network_clients =
3191        make_network_authority_clients_with_network_config(&committee, &network_config);
3192
3193    // Query all disagreeing validators
3194    let response_futures = digest_to_validator
3195        .values()
3196        .cloned()
3197        .map(|validator| {
3198            let client = network_clients
3199                .get(&validator)
3200                .expect("Failed to get network client");
3201            let request = CheckpointRequestV2 {
3202                sequence_number: Some(local_summary.sequence_number),
3203                request_content: true,
3204                certified: false,
3205            };
3206            client.handle_checkpoint_v2(request)
3207        })
3208        .collect::<Vec<_>>();
3209
3210    let digest_name_pair = digest_to_validator.iter();
3211    let response_data = futures::future::join_all(response_futures)
3212        .await
3213        .into_iter()
3214        .zip_debug_eq(digest_name_pair)
3215        .filter_map(|(response, (digest, name))| match response {
3216            Ok(response) => match response {
3217                CheckpointResponseV2 {
3218                    checkpoint: Some(CheckpointSummaryResponse::Pending(summary)),
3219                    contents: Some(contents),
3220                } => Some((*name, *digest, summary, contents)),
3221                CheckpointResponseV2 {
3222                    checkpoint: Some(CheckpointSummaryResponse::Certified(_)),
3223                    contents: _,
3224                } => {
3225                    panic!("Expected pending checkpoint, but got certified checkpoint");
3226                }
3227                CheckpointResponseV2 {
3228                    checkpoint: None,
3229                    contents: _,
3230                } => {
3231                    error!(
3232                        "Summary for checkpoint {:?} not found on validator {:?}",
3233                        local_summary.sequence_number, name
3234                    );
3235                    None
3236                }
3237                CheckpointResponseV2 {
3238                    checkpoint: _,
3239                    contents: None,
3240                } => {
3241                    error!(
3242                        "Contents for checkpoint {:?} not found on validator {:?}",
3243                        local_summary.sequence_number, name
3244                    );
3245                    None
3246                }
3247            },
3248            Err(e) => {
3249                error!(
3250                    "Failed to get checkpoint contents from validator for fork diagnostics: {:?}",
3251                    e
3252                );
3253                None
3254            }
3255        })
3256        .collect::<Vec<_>>();
3257
3258    let local_checkpoint_contents = tables
3259        .get_checkpoint_contents(&local_summary.content_digest)
3260        .unwrap_or_else(|_| {
3261            panic!(
3262                "Could not find checkpoint contents for digest {:?}",
3263                local_summary.digest()
3264            )
3265        })
3266        .unwrap_or_else(|| {
3267            panic!(
3268                "Could not find local full checkpoint contents for checkpoint {:?}, digest {:?}",
3269                local_summary.sequence_number,
3270                local_summary.digest()
3271            )
3272        });
3273    let local_contents_text = format!("{local_checkpoint_contents:?}");
3274
3275    let local_summary_text = format!("{local_summary:?}");
3276    let local_validator = state.name.concise();
3277    let diff_patches = response_data
3278        .iter()
3279        .map(|(name, other_digest, other_summary, contents)| {
3280            let other_contents_text = format!("{contents:?}");
3281            let other_summary_text = format!("{other_summary:?}");
3282            let (local_transactions, local_effects): (Vec<_>, Vec<_>) = local_checkpoint_contents
3283                .enumerate_transactions(&local_summary)
3284                .map(|(_, exec_digest)| (exec_digest.transaction, exec_digest.effects))
3285                .unzip();
3286            let (other_transactions, other_effects): (Vec<_>, Vec<_>) = contents
3287                .enumerate_transactions(other_summary)
3288                .map(|(_, exec_digest)| (exec_digest.transaction, exec_digest.effects))
3289                .unzip();
3290            let summary_patch = create_patch(&local_summary_text, &other_summary_text);
3291            let contents_patch = create_patch(&local_contents_text, &other_contents_text);
3292            let local_transactions_text = format!("{local_transactions:#?}");
3293            let other_transactions_text = format!("{other_transactions:#?}");
3294            let transactions_patch =
3295                create_patch(&local_transactions_text, &other_transactions_text);
3296            let local_effects_text = format!("{local_effects:#?}");
3297            let other_effects_text = format!("{other_effects:#?}");
3298            let effects_patch = create_patch(&local_effects_text, &other_effects_text);
3299            let seq_number = local_summary.sequence_number;
3300            let local_digest = local_summary.digest();
3301            let other_validator = name.concise();
3302            format!(
3303                "Checkpoint: {seq_number:?}\n\
3304                Local validator (original): {local_validator:?}, digest: {local_digest:?}\n\
3305                Other validator (modified): {other_validator:?}, digest: {other_digest:?}\n\n\
3306                Summary Diff: \n{summary_patch}\n\n\
3307                Contents Diff: \n{contents_patch}\n\n\
3308                Transactions Diff: \n{transactions_patch}\n\n\
3309                Effects Diff: \n{effects_patch}",
3310            )
3311        })
3312        .collect::<Vec<_>>()
3313        .join("\n\n\n");
3314
3315    let header = format!(
3316        "Checkpoint Fork Dump - Authority {local_validator:?}: \n\
3317        Datetime: {:?}",
3318        time
3319    );
3320    let fork_logs_text = format!("{header}\n\n{diff_patches}\n\n");
3321    let path = tempfile::tempdir()
3322        .expect("Failed to create tempdir")
3323        .keep()
3324        .join(Path::new("checkpoint_fork_dump.txt"));
3325    let mut file = File::create(path).unwrap();
3326    write!(file, "{}", fork_logs_text).unwrap();
3327    debug!("{}", fork_logs_text);
3328}
3329
3330pub trait CheckpointServiceNotify {
3331    fn notify_checkpoint_signature(&self, info: &CheckpointSignatureMessage) -> SuiResult;
3332
3333    fn notify_checkpoint(&self) -> SuiResult;
3334}
3335
3336#[allow(clippy::large_enum_variant)]
3337enum CheckpointServiceState {
3338    Unstarted(
3339        (
3340            CheckpointBuilder,
3341            CheckpointAggregator,
3342            CheckpointStateHasher,
3343        ),
3344    ),
3345    Started,
3346}
3347
3348impl CheckpointServiceState {
3349    fn take_unstarted(
3350        &mut self,
3351    ) -> (
3352        CheckpointBuilder,
3353        CheckpointAggregator,
3354        CheckpointStateHasher,
3355    ) {
3356        let mut state = CheckpointServiceState::Started;
3357        std::mem::swap(self, &mut state);
3358
3359        match state {
3360            CheckpointServiceState::Unstarted((builder, aggregator, hasher)) => {
3361                (builder, aggregator, hasher)
3362            }
3363            CheckpointServiceState::Started => panic!("CheckpointServiceState is already started"),
3364        }
3365    }
3366}
3367
3368pub struct CheckpointService {
3369    tables: Arc<CheckpointStore>,
3370    notify_builder: Arc<Notify>,
3371    signature_sender: mpsc::UnboundedSender<CheckpointSignatureMessage>,
3372    // A notification for the current highest built sequence number.
3373    highest_currently_built_seq_tx: watch::Sender<CheckpointSequenceNumber>,
3374    // The highest sequence number that had already been built at the time CheckpointService
3375    // was constructed
3376    highest_previously_built_seq: CheckpointSequenceNumber,
3377    metrics: Arc<CheckpointMetrics>,
3378    state: Mutex<CheckpointServiceState>,
3379}
3380
3381impl CheckpointService {
3382    /// Constructs a new CheckpointService in an un-started state.
3383    // The signature channel is unbounded because notify_checkpoint_signature is called from a
3384    // sync context (consensus_validator.rs implements a sync external trait) and cannot block.
3385    // The channel is consumed by a single async aggregator task that drains it continuously, so
3386    // unbounded growth is not a concern in practice.
3387    #[allow(clippy::disallowed_methods)]
3388    pub fn build(
3389        state: Arc<AuthorityState>,
3390        checkpoint_store: Arc<CheckpointStore>,
3391        epoch_store: Arc<AuthorityPerEpochStore>,
3392        effects_store: Arc<dyn TransactionCacheRead>,
3393        global_state_hasher: Weak<GlobalStateHasher>,
3394        checkpoint_output: Box<dyn CheckpointOutput>,
3395        certified_checkpoint_output: Box<dyn CertifiedCheckpointOutput>,
3396        metrics: Arc<CheckpointMetrics>,
3397        max_transactions_per_checkpoint: usize,
3398        max_checkpoint_size_bytes: usize,
3399    ) -> Arc<Self> {
3400        info!(
3401            "Starting checkpoint service with {max_transactions_per_checkpoint} max_transactions_per_checkpoint and {max_checkpoint_size_bytes} max_checkpoint_size_bytes"
3402        );
3403        let notify_builder = Arc::new(Notify::new());
3404        let notify_aggregator = Arc::new(Notify::new());
3405
3406        // We may have built higher checkpoint numbers before restarting.
3407        let highest_previously_built_seq = checkpoint_store
3408            .get_latest_locally_computed_checkpoint()
3409            .expect("failed to get latest locally computed checkpoint")
3410            .map(|s| s.sequence_number)
3411            .unwrap_or(0);
3412
3413        let highest_currently_built_seq =
3414            CheckpointBuilder::load_last_built_checkpoint_summary(&epoch_store, &checkpoint_store)
3415                .expect("epoch should not have ended")
3416                .map(|(seq, _)| seq)
3417                .unwrap_or(0);
3418
3419        let (highest_currently_built_seq_tx, _) = watch::channel(highest_currently_built_seq);
3420
3421        let (signature_sender, signature_receiver) = mpsc::unbounded_channel();
3422
3423        let aggregator = CheckpointAggregator::new(
3424            checkpoint_store.clone(),
3425            epoch_store.clone(),
3426            notify_aggregator.clone(),
3427            signature_receiver,
3428            certified_checkpoint_output,
3429            state.clone(),
3430            metrics.clone(),
3431        );
3432
3433        let (send_to_hasher, receive_from_builder) = mpsc::channel(16);
3434
3435        let ckpt_state_hasher = CheckpointStateHasher::new(
3436            epoch_store.clone(),
3437            global_state_hasher.clone(),
3438            receive_from_builder,
3439        );
3440
3441        let builder = CheckpointBuilder::new(
3442            state.clone(),
3443            checkpoint_store.clone(),
3444            epoch_store.clone(),
3445            notify_builder.clone(),
3446            effects_store,
3447            global_state_hasher,
3448            send_to_hasher,
3449            checkpoint_output,
3450            notify_aggregator.clone(),
3451            highest_currently_built_seq_tx.clone(),
3452            metrics.clone(),
3453            max_transactions_per_checkpoint,
3454            max_checkpoint_size_bytes,
3455        );
3456
3457        Arc::new(Self {
3458            tables: checkpoint_store,
3459            notify_builder,
3460            signature_sender,
3461            highest_currently_built_seq_tx,
3462            highest_previously_built_seq,
3463            metrics,
3464            state: Mutex::new(CheckpointServiceState::Unstarted((
3465                builder,
3466                aggregator,
3467                ckpt_state_hasher,
3468            ))),
3469        })
3470    }
3471
3472    /// Starts the CheckpointService.
3473    ///
3474    /// This function blocks until the CheckpointBuilder re-builds all checkpoints that had
3475    /// been built before the most recent restart. You can think of this as a WAL replay
3476    /// operation. Upon startup, we may have a number of consensus commits and resulting
3477    /// checkpoints that were built but not committed to disk. We want to reprocess the
3478    /// commits and rebuild the checkpoints before starting normal operation.
3479    pub async fn spawn(
3480        &self,
3481        epoch_store: Arc<AuthorityPerEpochStore>,
3482        consensus_replay_waiter: Option<ReplayWaiter>,
3483    ) {
3484        let (builder, aggregator, state_hasher) = self.state.lock().take_unstarted();
3485
3486        // Clean up state hashes computed after the last built checkpoint
3487        // This prevents ECMH divergence after fork recovery restarts
3488
3489        // Note: there is a rare crash recovery edge case where we write the builder
3490        // summary, but crash before we can bump the highest executed checkpoint.
3491        // If we committed the builder summary, it was certified and unforked, so there
3492        // is no need to clear that state hash. If we do clear it, then checkpoint executor
3493        // will wait forever for checkpoint builder to produce the state hash, which will
3494        // never happen.
3495        let last_persisted_builder_seq = epoch_store
3496            .last_persisted_checkpoint_builder_summary()
3497            .expect("epoch should not have ended")
3498            .map(|s| s.summary.sequence_number);
3499
3500        let last_executed_seq = self
3501            .tables
3502            .get_highest_executed_checkpoint()
3503            .expect("Failed to get highest executed checkpoint")
3504            .map(|checkpoint| *checkpoint.sequence_number());
3505
3506        if let Some(last_committed_seq) = last_persisted_builder_seq.max(last_executed_seq) {
3507            if let Err(e) = builder
3508                .epoch_store
3509                .clear_state_hashes_after_checkpoint(last_committed_seq)
3510            {
3511                error!(
3512                    "Failed to clear state hashes after checkpoint {}: {:?}",
3513                    last_committed_seq, e
3514                );
3515            } else {
3516                info!(
3517                    "Cleared state hashes after checkpoint {} to ensure consistent ECMH computation",
3518                    last_committed_seq
3519                );
3520            }
3521        }
3522
3523        let (builder_finished_tx, builder_finished_rx) = tokio::sync::oneshot::channel();
3524
3525        let state_hasher_task = spawn_monitored_task!(state_hasher.run());
3526        let aggregator_task = spawn_monitored_task!(aggregator.run());
3527
3528        spawn_monitored_task!(async move {
3529            epoch_store
3530                .within_alive_epoch(async move {
3531                    builder.run(consensus_replay_waiter).await;
3532                    builder_finished_tx.send(()).ok();
3533                })
3534                .await
3535                .ok();
3536
3537            // state hasher will terminate as soon as it has finished processing all messages from builder
3538            state_hasher_task
3539                .await
3540                .expect("state hasher should exit normally");
3541
3542            // builder must shut down before aggregator and state_hasher, since it sends
3543            // messages to them
3544            aggregator_task.abort();
3545            aggregator_task.await.ok();
3546        });
3547
3548        // If this times out, the validator may still start up. The worst that can
3549        // happen is that we will crash later on instead of immediately. The eventual
3550        // crash would occur because we may be missing transactions that are below the
3551        // highest_synced_checkpoint watermark, which can cause a crash in
3552        // `CheckpointExecutor::extract_randomness_rounds`.
3553        if tokio::time::timeout(Duration::from_secs(120), async move {
3554            tokio::select! {
3555                _ = builder_finished_rx => { debug!("CheckpointBuilder finished"); }
3556                _ = self.wait_for_rebuilt_checkpoints() => (),
3557            }
3558        })
3559        .await
3560        .is_err()
3561        {
3562            debug_fatal!("Timed out waiting for checkpoints to be rebuilt");
3563        }
3564    }
3565}
3566
3567impl CheckpointService {
3568    /// Waits until all checkpoints had been built before the node restarted
3569    /// are rebuilt. This is required to preserve the invariant that all checkpoints
3570    /// (and their transactions) below the highest_synced_checkpoint watermark are
3571    /// available. Once the checkpoints are constructed, we can be sure that the
3572    /// transactions have also been executed.
3573    pub async fn wait_for_rebuilt_checkpoints(&self) {
3574        let highest_previously_built_seq = self.highest_previously_built_seq;
3575        let mut rx = self.highest_currently_built_seq_tx.subscribe();
3576        let mut highest_currently_built_seq = *rx.borrow_and_update();
3577        info!(
3578            "Waiting for checkpoints to be rebuilt, previously built seq: {highest_previously_built_seq}, currently built seq: {highest_currently_built_seq}"
3579        );
3580        loop {
3581            if highest_currently_built_seq >= highest_previously_built_seq {
3582                info!("Checkpoint rebuild complete");
3583                break;
3584            }
3585            rx.changed().await.unwrap();
3586            highest_currently_built_seq = *rx.borrow_and_update();
3587        }
3588    }
3589
3590    #[cfg(test)]
3591    fn write_and_notify_checkpoint_for_testing(
3592        &self,
3593        epoch_store: &AuthorityPerEpochStore,
3594        checkpoint: PendingCheckpoint,
3595    ) -> SuiResult {
3596        use crate::authority::authority_per_epoch_store::consensus_quarantine::ConsensusCommitOutput;
3597
3598        let mut output = ConsensusCommitOutput::new(0);
3599        epoch_store.write_pending_checkpoint(&mut output, &checkpoint)?;
3600        output.set_default_commit_stats_for_testing();
3601        epoch_store.push_consensus_output_for_tests(output);
3602        self.notify_checkpoint()?;
3603        Ok(())
3604    }
3605}
3606
3607impl CheckpointServiceNotify for CheckpointService {
3608    fn notify_checkpoint_signature(&self, info: &CheckpointSignatureMessage) -> SuiResult {
3609        let sequence = info.summary.sequence_number;
3610        let signer = info.summary.auth_sig().authority.concise();
3611
3612        if let Some(highest_verified_checkpoint) = self
3613            .tables
3614            .get_highest_verified_checkpoint()?
3615            .map(|x| *x.sequence_number())
3616            && sequence <= highest_verified_checkpoint
3617        {
3618            trace!(
3619                checkpoint_seq = sequence,
3620                "Ignore checkpoint signature from {} - already certified", signer,
3621            );
3622            self.metrics
3623                .last_ignored_checkpoint_signature_received
3624                .set(sequence as i64);
3625            return Ok(());
3626        }
3627        trace!(
3628            checkpoint_seq = sequence,
3629            "Received checkpoint signature, digest {} from {}",
3630            info.summary.digest(),
3631            signer,
3632        );
3633        self.metrics
3634            .last_received_checkpoint_signatures
3635            .with_label_values(&[&signer.to_string()])
3636            .set(sequence as i64);
3637        self.signature_sender.send(info.clone()).ok();
3638        Ok(())
3639    }
3640
3641    fn notify_checkpoint(&self) -> SuiResult {
3642        self.notify_builder.notify_one();
3643        Ok(())
3644    }
3645}
3646
3647// test helper
3648pub struct CheckpointServiceNoop {}
3649impl CheckpointServiceNotify for CheckpointServiceNoop {
3650    fn notify_checkpoint_signature(&self, _: &CheckpointSignatureMessage) -> SuiResult {
3651        Ok(())
3652    }
3653
3654    fn notify_checkpoint(&self) -> SuiResult {
3655        Ok(())
3656    }
3657}
3658
3659impl PendingCheckpoint {
3660    pub fn height(&self) -> CheckpointHeight {
3661        self.details.checkpoint_height
3662    }
3663
3664    pub fn roots(&self) -> &Vec<TransactionKey> {
3665        &self.roots
3666    }
3667
3668    pub fn details(&self) -> &PendingCheckpointInfo {
3669        &self.details
3670    }
3671}
3672
3673impl PendingCheckpointV2 {
3674    pub fn height(&self) -> CheckpointHeight {
3675        self.details.checkpoint_height
3676    }
3677
3678    pub(crate) fn num_roots(&self) -> usize {
3679        self.roots.iter().map(|r| r.tx_roots.len()).sum()
3680    }
3681}
3682
3683pin_project! {
3684    pub struct PollCounter<Fut> {
3685        #[pin]
3686        future: Fut,
3687        count: usize,
3688    }
3689}
3690
3691impl<Fut> PollCounter<Fut> {
3692    pub fn new(future: Fut) -> Self {
3693        Self { future, count: 0 }
3694    }
3695
3696    pub fn count(&self) -> usize {
3697        self.count
3698    }
3699}
3700
3701impl<Fut: Future> Future for PollCounter<Fut> {
3702    type Output = (usize, Fut::Output);
3703
3704    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3705        let this = self.project();
3706        *this.count += 1;
3707        match this.future.poll(cx) {
3708            Poll::Ready(output) => Poll::Ready((*this.count, output)),
3709            Poll::Pending => Poll::Pending,
3710        }
3711    }
3712}
3713
3714fn poll_count<Fut>(future: Fut) -> PollCounter<Fut> {
3715    PollCounter::new(future)
3716}
3717
3718#[cfg(test)]
3719mod tests {
3720    use super::*;
3721    use crate::authority::test_authority_builder::TestAuthorityBuilder;
3722    use fastcrypto_zkp::bn254::zk_login::{JWK, JwkId};
3723    use futures::FutureExt as _;
3724    use futures::future::BoxFuture;
3725    use std::collections::HashMap;
3726    use std::ops::Deref;
3727    use sui_macros::sim_test;
3728    use sui_protocol_config::{Chain, ProtocolConfig};
3729    use sui_types::accumulator_event::AccumulatorEvent;
3730    use sui_types::authenticator_state::ActiveJwk;
3731    use sui_types::base_types::{SequenceNumber, TransactionEffectsDigest};
3732    use sui_types::crypto::Signature;
3733    use sui_types::effects::{TransactionEffects, TransactionEvents};
3734    use sui_types::messages_checkpoint::SignedCheckpointSummary;
3735    use sui_types::transaction::VerifiedTransaction;
3736    use tokio::sync::mpsc;
3737
3738    #[tokio::test]
3739    async fn test_clear_locally_computed_checkpoints_from_deletes_inclusive_range() {
3740        let store = CheckpointStore::new_for_tests();
3741        let protocol = sui_protocol_config::ProtocolConfig::get_for_max_version_UNSAFE();
3742        for seq in 70u64..=80u64 {
3743            let contents =
3744                sui_types::messages_checkpoint::CheckpointContents::new_with_digests_only_for_tests(
3745                    [sui_types::base_types::ExecutionDigests::new(
3746                        sui_types::digests::TransactionDigest::random(),
3747                        sui_types::digests::TransactionEffectsDigest::ZERO,
3748                    )],
3749                );
3750            let summary = sui_types::messages_checkpoint::CheckpointSummary::new(
3751                &protocol,
3752                0,
3753                seq,
3754                0,
3755                &contents,
3756                None,
3757                sui_types::gas::GasCostSummary::default(),
3758                None,
3759                0,
3760                Vec::new(),
3761                Vec::new(),
3762            );
3763            store
3764                .tables
3765                .locally_computed_checkpoints
3766                .insert(&seq, &summary)
3767                .unwrap();
3768        }
3769
3770        store
3771            .clear_locally_computed_checkpoints_from(76)
3772            .expect("clear should succeed");
3773
3774        // Explicit boundary checks: 75 must remain, 76 must be deleted
3775        assert!(
3776            store
3777                .tables
3778                .locally_computed_checkpoints
3779                .get(&75)
3780                .unwrap()
3781                .is_some()
3782        );
3783        assert!(
3784            store
3785                .tables
3786                .locally_computed_checkpoints
3787                .get(&76)
3788                .unwrap()
3789                .is_none()
3790        );
3791
3792        for seq in 70u64..76u64 {
3793            assert!(
3794                store
3795                    .tables
3796                    .locally_computed_checkpoints
3797                    .get(&seq)
3798                    .unwrap()
3799                    .is_some()
3800            );
3801        }
3802        for seq in 76u64..=80u64 {
3803            assert!(
3804                store
3805                    .tables
3806                    .locally_computed_checkpoints
3807                    .get(&seq)
3808                    .unwrap()
3809                    .is_none()
3810            );
3811        }
3812    }
3813
3814    #[tokio::test]
3815    async fn test_fork_detection_storage() {
3816        let store = CheckpointStore::new_for_tests();
3817        // checkpoint fork
3818        let seq_num = 42;
3819        let digest = CheckpointDigest::random();
3820
3821        assert!(store.get_checkpoint_fork_detected().unwrap().is_none());
3822
3823        store
3824            .record_checkpoint_fork_detected(seq_num, digest)
3825            .unwrap();
3826
3827        let retrieved = store.get_checkpoint_fork_detected().unwrap();
3828        assert!(retrieved.is_some());
3829        let (retrieved_seq, retrieved_digest) = retrieved.unwrap();
3830        assert_eq!(retrieved_seq, seq_num);
3831        assert_eq!(retrieved_digest, digest);
3832
3833        store.clear_checkpoint_fork_detected().unwrap();
3834        assert!(store.get_checkpoint_fork_detected().unwrap().is_none());
3835
3836        // txn fork
3837        let tx_digest = TransactionDigest::random();
3838        let expected_effects = TransactionEffectsDigest::random();
3839        let actual_effects = TransactionEffectsDigest::random();
3840
3841        assert!(store.get_transaction_fork_detected().unwrap().is_none());
3842
3843        store
3844            .record_transaction_fork_detected(tx_digest, expected_effects, actual_effects)
3845            .unwrap();
3846
3847        let retrieved = store.get_transaction_fork_detected().unwrap();
3848        assert!(retrieved.is_some());
3849        let (retrieved_tx, retrieved_expected, retrieved_actual) = retrieved.unwrap();
3850        assert_eq!(retrieved_tx, tx_digest);
3851        assert_eq!(retrieved_expected, expected_effects);
3852        assert_eq!(retrieved_actual, actual_effects);
3853
3854        store.clear_transaction_fork_detected().unwrap();
3855        assert!(store.get_transaction_fork_detected().unwrap().is_none());
3856    }
3857
3858    #[sim_test]
3859    pub async fn checkpoint_builder_test() {
3860        telemetry_subscribers::init_for_testing();
3861
3862        let mut protocol_config =
3863            ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
3864        protocol_config.disable_accumulators_for_testing();
3865        protocol_config.set_split_checkpoints_in_consensus_handler_for_testing(false);
3866        protocol_config.set_min_checkpoint_interval_ms_for_testing(100);
3867        let state = TestAuthorityBuilder::new()
3868            .with_protocol_config(protocol_config)
3869            .build()
3870            .await;
3871
3872        let dummy_tx = VerifiedTransaction::new_authenticator_state_update(
3873            0,
3874            0,
3875            vec![],
3876            SequenceNumber::new(),
3877        );
3878
3879        let jwks = {
3880            let mut jwks = Vec::new();
3881            while bcs::to_bytes(&jwks).unwrap().len() < 40_000 {
3882                jwks.push(ActiveJwk {
3883                    jwk_id: JwkId::new(
3884                        "https://accounts.google.com".to_string(),
3885                        "1234567890".to_string(),
3886                    ),
3887                    jwk: JWK {
3888                        kty: "RSA".to_string(),
3889                        e: "AQAB".to_string(),
3890                        n: "1234567890".to_string(),
3891                        alg: "RS256".to_string(),
3892                    },
3893                    epoch: 0,
3894                });
3895            }
3896            jwks
3897        };
3898
3899        let dummy_tx_with_data =
3900            VerifiedTransaction::new_authenticator_state_update(0, 1, jwks, SequenceNumber::new());
3901
3902        for i in 0..15 {
3903            state
3904                .database_for_testing()
3905                .perpetual_tables
3906                .transactions
3907                .insert(&d(i), dummy_tx.serializable_ref())
3908                .unwrap();
3909        }
3910        for i in 15..20 {
3911            state
3912                .database_for_testing()
3913                .perpetual_tables
3914                .transactions
3915                .insert(&d(i), dummy_tx_with_data.serializable_ref())
3916                .unwrap();
3917        }
3918
3919        let mut store = HashMap::<TransactionDigest, TransactionEffects>::new();
3920        commit_cert_for_test(
3921            &mut store,
3922            state.clone(),
3923            d(1),
3924            vec![d(2), d(3)],
3925            GasCostSummary::new(11, 12, 11, 1),
3926        );
3927        commit_cert_for_test(
3928            &mut store,
3929            state.clone(),
3930            d(2),
3931            vec![d(3), d(4)],
3932            GasCostSummary::new(21, 22, 21, 1),
3933        );
3934        commit_cert_for_test(
3935            &mut store,
3936            state.clone(),
3937            d(3),
3938            vec![],
3939            GasCostSummary::new(31, 32, 31, 1),
3940        );
3941        commit_cert_for_test(
3942            &mut store,
3943            state.clone(),
3944            d(4),
3945            vec![],
3946            GasCostSummary::new(41, 42, 41, 1),
3947        );
3948        for i in [5, 6, 7, 10, 11, 12, 13] {
3949            commit_cert_for_test(
3950                &mut store,
3951                state.clone(),
3952                d(i),
3953                vec![],
3954                GasCostSummary::new(41, 42, 41, 1),
3955            );
3956        }
3957        for i in [15, 16, 17] {
3958            commit_cert_for_test(
3959                &mut store,
3960                state.clone(),
3961                d(i),
3962                vec![],
3963                GasCostSummary::new(51, 52, 51, 1),
3964            );
3965        }
3966        let all_digests: Vec<_> = store.keys().copied().collect();
3967        for digest in all_digests {
3968            let signature = Signature::Ed25519SuiSignature(Default::default()).into();
3969            state
3970                .epoch_store_for_testing()
3971                .test_insert_user_signature(digest, vec![(signature, None)]);
3972        }
3973
3974        let (output, mut result) = mpsc::channel::<(CheckpointContents, CheckpointSummary)>(10);
3975        let (certified_output, mut certified_result) =
3976            mpsc::channel::<CertifiedCheckpointSummary>(10);
3977        let store = Arc::new(store);
3978
3979        let ckpt_dir = tempfile::tempdir().unwrap();
3980        let checkpoint_store =
3981            CheckpointStore::new(ckpt_dir.path(), Arc::new(PrunerWatermarks::default()));
3982        let epoch_store = state.epoch_store_for_testing();
3983
3984        let global_state_hasher = Arc::new(GlobalStateHasher::new_for_tests(
3985            state.get_global_state_hash_store().clone(),
3986        ));
3987
3988        let checkpoint_service = CheckpointService::build(
3989            state.clone(),
3990            checkpoint_store,
3991            epoch_store.clone(),
3992            store,
3993            Arc::downgrade(&global_state_hasher),
3994            Box::new(output),
3995            Box::new(certified_output),
3996            CheckpointMetrics::new_for_tests(),
3997            3,
3998            100_000,
3999        );
4000        checkpoint_service.spawn(epoch_store.clone(), None).await;
4001
4002        checkpoint_service
4003            .write_and_notify_checkpoint_for_testing(&epoch_store, p(0, vec![4], 0))
4004            .unwrap();
4005        checkpoint_service
4006            .write_and_notify_checkpoint_for_testing(&epoch_store, p(1, vec![1, 3], 2000))
4007            .unwrap();
4008        checkpoint_service
4009            .write_and_notify_checkpoint_for_testing(&epoch_store, p(2, vec![10, 11, 12, 13], 3000))
4010            .unwrap();
4011        checkpoint_service
4012            .write_and_notify_checkpoint_for_testing(&epoch_store, p(3, vec![15, 16, 17], 4000))
4013            .unwrap();
4014        checkpoint_service
4015            .write_and_notify_checkpoint_for_testing(&epoch_store, p(4, vec![5], 4001))
4016            .unwrap();
4017        checkpoint_service
4018            .write_and_notify_checkpoint_for_testing(&epoch_store, p(5, vec![6], 5000))
4019            .unwrap();
4020
4021        let (c1c, c1s) = result.recv().await.unwrap();
4022        let (c2c, c2s) = result.recv().await.unwrap();
4023
4024        let c1t = c1c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4025        let c2t = c2c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4026        assert_eq!(c1t, vec![d(4)]);
4027        assert_eq!(c1s.previous_digest, None);
4028        assert_eq!(c1s.sequence_number, 0);
4029        assert_eq!(
4030            c1s.epoch_rolling_gas_cost_summary,
4031            GasCostSummary::new(41, 42, 41, 1)
4032        );
4033
4034        assert_eq!(c2t, vec![d(3), d(2), d(1)]);
4035        assert_eq!(c2s.previous_digest, Some(c1s.digest()));
4036        assert_eq!(c2s.sequence_number, 1);
4037        assert_eq!(
4038            c2s.epoch_rolling_gas_cost_summary,
4039            GasCostSummary::new(104, 108, 104, 4)
4040        );
4041
4042        // Pending at index 2 had 4 transactions, and we configured 3 transactions max.
4043        // Verify that we split into 2 checkpoints.
4044        let (c3c, c3s) = result.recv().await.unwrap();
4045        let c3t = c3c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4046        let (c4c, c4s) = result.recv().await.unwrap();
4047        let c4t = c4c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4048        assert_eq!(c3s.sequence_number, 2);
4049        assert_eq!(c3s.previous_digest, Some(c2s.digest()));
4050        assert_eq!(c4s.sequence_number, 3);
4051        assert_eq!(c4s.previous_digest, Some(c3s.digest()));
4052        assert_eq!(c3t, vec![d(10), d(11), d(12)]);
4053        assert_eq!(c4t, vec![d(13)]);
4054
4055        // Pending at index 3 had 3 transactions of 40K size, and we configured 100K max.
4056        // Verify that we split into 2 checkpoints.
4057        let (c5c, c5s) = result.recv().await.unwrap();
4058        let c5t = c5c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4059        let (c6c, c6s) = result.recv().await.unwrap();
4060        let c6t = c6c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4061        assert_eq!(c5s.sequence_number, 4);
4062        assert_eq!(c5s.previous_digest, Some(c4s.digest()));
4063        assert_eq!(c6s.sequence_number, 5);
4064        assert_eq!(c6s.previous_digest, Some(c5s.digest()));
4065        assert_eq!(c5t, vec![d(15), d(16)]);
4066        assert_eq!(c6t, vec![d(17)]);
4067
4068        // Pending at index 4 was too soon after the prior one and should be coalesced into
4069        // the next one.
4070        let (c7c, c7s) = result.recv().await.unwrap();
4071        let c7t = c7c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4072        assert_eq!(c7t, vec![d(5), d(6)]);
4073        assert_eq!(c7s.previous_digest, Some(c6s.digest()));
4074        assert_eq!(c7s.sequence_number, 6);
4075
4076        let c1ss = SignedCheckpointSummary::new(c1s.epoch, c1s, state.secret.deref(), state.name);
4077        let c2ss = SignedCheckpointSummary::new(c2s.epoch, c2s, state.secret.deref(), state.name);
4078
4079        checkpoint_service
4080            .notify_checkpoint_signature(&CheckpointSignatureMessage { summary: c2ss })
4081            .unwrap();
4082        checkpoint_service
4083            .notify_checkpoint_signature(&CheckpointSignatureMessage { summary: c1ss })
4084            .unwrap();
4085
4086        let c1sc = certified_result.recv().await.unwrap();
4087        let c2sc = certified_result.recv().await.unwrap();
4088        assert_eq!(c1sc.sequence_number, 0);
4089        assert_eq!(c2sc.sequence_number, 1);
4090    }
4091
4092    impl TransactionCacheRead for HashMap<TransactionDigest, TransactionEffects> {
4093        fn notify_read_executed_effects_may_fail(
4094            &self,
4095            _: &str,
4096            digests: &[TransactionDigest],
4097        ) -> BoxFuture<'_, SuiResult<Vec<TransactionEffects>>> {
4098            std::future::ready(Ok(digests
4099                .iter()
4100                .map(|d| self.get(d).expect("effects not found").clone())
4101                .collect()))
4102            .boxed()
4103        }
4104
4105        fn notify_read_executed_effects_digests(
4106            &self,
4107            _: &str,
4108            digests: &[TransactionDigest],
4109        ) -> BoxFuture<'_, Vec<TransactionEffectsDigest>> {
4110            std::future::ready(
4111                digests
4112                    .iter()
4113                    .map(|d| {
4114                        self.get(d)
4115                            .map(|fx| fx.digest())
4116                            .expect("effects not found")
4117                    })
4118                    .collect(),
4119            )
4120            .boxed()
4121        }
4122
4123        fn multi_get_executed_effects(
4124            &self,
4125            digests: &[TransactionDigest],
4126        ) -> Vec<Option<TransactionEffects>> {
4127            digests.iter().map(|d| self.get(d).cloned()).collect()
4128        }
4129
4130        // Unimplemented methods - its unfortunate to have this big blob of useless code, but it wasn't
4131        // worth it to keep EffectsNotifyRead around just for these tests, as it caused a ton of
4132        // complication in non-test code. (e.g. had to implement EFfectsNotifyRead for all
4133        // ExecutionCacheRead implementors).
4134
4135        fn multi_get_transaction_blocks(
4136            &self,
4137            _: &[TransactionDigest],
4138        ) -> Vec<Option<Arc<VerifiedTransaction>>> {
4139            unimplemented!()
4140        }
4141
4142        fn multi_get_executed_effects_digests(
4143            &self,
4144            _: &[TransactionDigest],
4145        ) -> Vec<Option<TransactionEffectsDigest>> {
4146            unimplemented!()
4147        }
4148
4149        fn multi_get_effects(
4150            &self,
4151            _: &[TransactionEffectsDigest],
4152        ) -> Vec<Option<TransactionEffects>> {
4153            unimplemented!()
4154        }
4155
4156        fn multi_get_events(&self, _: &[TransactionDigest]) -> Vec<Option<TransactionEvents>> {
4157            unimplemented!()
4158        }
4159
4160        fn take_accumulator_events(&self, _: &TransactionDigest) -> Option<Vec<AccumulatorEvent>> {
4161            unimplemented!()
4162        }
4163
4164        fn get_unchanged_loaded_runtime_objects(
4165            &self,
4166            _digest: &TransactionDigest,
4167        ) -> Option<Vec<sui_types::storage::ObjectKey>> {
4168            unimplemented!()
4169        }
4170
4171        fn transaction_executed_in_last_epoch(&self, _: &TransactionDigest, _: EpochId) -> bool {
4172            unimplemented!()
4173        }
4174    }
4175
4176    #[async_trait::async_trait]
4177    impl CheckpointOutput for mpsc::Sender<(CheckpointContents, CheckpointSummary)> {
4178        async fn checkpoint_created(
4179            &self,
4180            summary: &CheckpointSummary,
4181            contents: &CheckpointContents,
4182            _epoch_store: &Arc<AuthorityPerEpochStore>,
4183            _checkpoint_store: &Arc<CheckpointStore>,
4184        ) -> SuiResult {
4185            self.try_send((contents.clone(), summary.clone())).unwrap();
4186            Ok(())
4187        }
4188    }
4189
4190    #[async_trait::async_trait]
4191    impl CertifiedCheckpointOutput for mpsc::Sender<CertifiedCheckpointSummary> {
4192        async fn certified_checkpoint_created(
4193            &self,
4194            summary: &CertifiedCheckpointSummary,
4195        ) -> SuiResult {
4196            self.try_send(summary.clone()).unwrap();
4197            Ok(())
4198        }
4199    }
4200
4201    fn p(i: u64, t: Vec<u8>, timestamp_ms: u64) -> PendingCheckpoint {
4202        PendingCheckpoint {
4203            roots: t
4204                .into_iter()
4205                .map(|t| TransactionKey::Digest(d(t)))
4206                .collect(),
4207            details: PendingCheckpointInfo {
4208                timestamp_ms,
4209                last_of_epoch: false,
4210                checkpoint_height: i,
4211                consensus_commit_ref: CommitRef::default(),
4212                rejected_transactions_digest: Digest::default(),
4213                checkpoint_seq: None,
4214            },
4215        }
4216    }
4217
4218    fn d(i: u8) -> TransactionDigest {
4219        let mut bytes: [u8; 32] = Default::default();
4220        bytes[0] = i;
4221        TransactionDigest::new(bytes)
4222    }
4223
4224    fn e(
4225        transaction_digest: TransactionDigest,
4226        dependencies: Vec<TransactionDigest>,
4227        gas_used: GasCostSummary,
4228    ) -> TransactionEffects {
4229        let mut effects = TransactionEffects::default();
4230        *effects.transaction_digest_mut_for_testing() = transaction_digest;
4231        *effects.dependencies_mut_for_testing() = dependencies;
4232        *effects.gas_cost_summary_mut_for_testing() = gas_used;
4233        effects
4234    }
4235
4236    fn commit_cert_for_test(
4237        store: &mut HashMap<TransactionDigest, TransactionEffects>,
4238        state: Arc<AuthorityState>,
4239        digest: TransactionDigest,
4240        dependencies: Vec<TransactionDigest>,
4241        gas_used: GasCostSummary,
4242    ) {
4243        let epoch_store = state.epoch_store_for_testing();
4244        let effects = e(digest, dependencies, gas_used);
4245        store.insert(digest, effects.clone());
4246        epoch_store.insert_executed_in_epoch(&digest);
4247    }
4248}