Skip to main content

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