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