Skip to main content

iota_core/checkpoints/
mod.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5mod causal_order;
6pub mod checkpoint_executor;
7mod checkpoint_output;
8mod epoch_info;
9mod full_checkpoint_contents_cache;
10pub mod historic_checkpoints;
11mod metrics;
12
13use std::{
14    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
15    fs::File,
16    future::Future,
17    io::Write,
18    path::Path,
19    pin::Pin,
20    sync::{Arc, OnceLock, Weak},
21    task::{Context, Poll},
22    time::{Duration, SystemTime},
23};
24
25use diffy::create_patch;
26use iota_common::{
27    debug_fatal, fatal,
28    random::get_rng,
29    sync::notify_read::{CHECKPOINT_BUILDER_NOTIFY_READ_TASK_NAME, NotifyRead},
30};
31use iota_macros::{fail_point, fail_point_async};
32use iota_metrics::{MonitoredFutureExt, monitored_future, monitored_scope};
33use iota_network::default_iota_network_config;
34use iota_sdk_types::{
35    CheckpointCommitment, CheckpointContents, CheckpointContentsDigest, CheckpointDigest,
36    CheckpointSummary, EndOfEpochData, GasCostSummary, TransactionDigest, TransactionEffects,
37    TransactionKind, UserSignature,
38};
39use iota_types::{
40    attestation::{AttestationEntry, AttestationRecord, AttestationTotals},
41    base_types::{AuthorityName, ConciseableName, EpochId, ExecutionData},
42    committee::StakeUnit,
43    crypto::AuthorityStrongQuorumSignInfo,
44    effects::{TransactionEffectsAPI, TransactionEffectsExt},
45    error::{IotaError, IotaResult},
46    event::SystemEpochInfoEvent,
47    iota_system_state::{
48        IotaSystemState, IotaSystemStateTrait,
49        epoch_start_iota_system_state::EpochStartSystemStateTrait,
50    },
51    messages_checkpoint::{
52        CertifiedCheckpointSummary, CheckpointContentsExt, CheckpointRequest, CheckpointResponse,
53        CheckpointSequenceNumber, CheckpointSignatureMessage, CheckpointSummaryExt,
54        CheckpointSummaryResponse, CheckpointTimestamp, FullCheckpointContents, TrustedCheckpoint,
55        VerifiedCheckpoint, VerifiedCheckpointContents,
56    },
57    messages_consensus::ConsensusTransactionKey,
58    storage::EpochInfoV2,
59    transaction::{TransactionAPI, TransactionEnvelope, TransactionKey},
60};
61use itertools::Itertools;
62use nonempty::NonEmpty;
63use once_cell::sync::Lazy;
64use parking_lot::Mutex;
65use pin_project_lite::pin_project;
66use rand::seq::IndexedRandom;
67use serde::{Deserialize, Serialize};
68use tokio::{
69    sync::{Notify, mpsc, watch},
70    task::JoinSet,
71    time::timeout,
72};
73use tracing::{debug, error, info, instrument, trace, warn};
74use typed_store::{
75    DBMapUtils, Map, TypedStoreError,
76    database::drop_tolerant_write_options,
77    rocks::{DBMap, DBMapTableConfigMap, DBOptions, MetricConf, default_db_options},
78};
79
80pub use crate::checkpoints::{
81    checkpoint_output::{
82        LogCheckpointOutput, SendCheckpointToStateSync, SubmitCheckpointToConsensus,
83    },
84    full_checkpoint_contents_cache::{
85        FullCheckpointContentsCache, FullCheckpointContentsCacheMetrics,
86    },
87    metrics::CheckpointMetrics,
88};
89use crate::{
90    authority::{
91        AuthorityState,
92        attestation::apply_fault_penalties,
93        authority_per_epoch_store::{AuthorityPerEpochStore, scorer::MAX_SCORE},
94        historic_ledger::HistoricLedger,
95    },
96    authority_client::{
97        make_network_authority_clients_with_network_config, validator_peer::ValidatorPeerAPI,
98    },
99    checkpoints::{
100        causal_order::CausalOrder,
101        checkpoint_output::{CertifiedCheckpointOutput, CheckpointOutput},
102        historic_checkpoints::HistoricCheckpoints,
103    },
104    consensus_handler::SequencedConsensusTransactionKey,
105    consensus_manager::ReplayWaiter,
106    epoch_buckets::historic_root,
107    execution_cache::TransactionCacheRead,
108    global_state_hasher::GlobalStateHasher,
109    stake_aggregator::{InsertResult, MultiStakeAggregator},
110};
111
112pub type CheckpointHeight = u64;
113
114/// Digest of checkpoint contents with no transactions. The empty checkpoints
115/// of one epoch share one `checkpoint_content` row in that epoch's bucket,
116/// which every bucket holds from its creation on.
117pub(crate) static EMPTY_CHECKPOINT_CONTENTS_DIGEST: Lazy<CheckpointContentsDigest> =
118    Lazy::new(|| empty_checkpoint_contents().digest());
119
120pub(crate) fn empty_checkpoint_contents() -> CheckpointContents {
121    CheckpointContents::new_with_digests_and_signatures([], Vec::new())
122}
123
124pub struct EpochStats {
125    pub checkpoint_count: u64,
126    pub transaction_count: u64,
127    pub total_gas_reward: u64,
128}
129
130#[derive(Clone, Debug, Serialize, Deserialize)]
131pub struct PendingCheckpointInfo {
132    pub timestamp_ms: CheckpointTimestamp,
133    pub last_of_epoch: bool,
134    pub checkpoint_height: CheckpointHeight,
135}
136
137#[derive(Clone, Debug, Serialize, Deserialize)]
138pub enum PendingCheckpoint {
139    // This is an enum for future upgradability, though at the moment there is only one variant.
140    V1(PendingCheckpointContentsV1),
141}
142
143#[derive(Clone, Debug, Serialize, Deserialize)]
144pub struct PendingCheckpointContentsV1 {
145    pub roots: Vec<TransactionKey>,
146    pub details: PendingCheckpointInfo,
147}
148
149impl PendingCheckpoint {
150    pub fn as_v1(&self) -> &PendingCheckpointContentsV1 {
151        match self {
152            PendingCheckpoint::V1(contents) => contents,
153        }
154    }
155
156    pub fn into_v1(self) -> PendingCheckpointContentsV1 {
157        match self {
158            PendingCheckpoint::V1(contents) => contents,
159        }
160    }
161
162    pub fn roots(&self) -> &Vec<TransactionKey> {
163        &self.as_v1().roots
164    }
165
166    pub fn details(&self) -> &PendingCheckpointInfo {
167        &self.as_v1().details
168    }
169
170    pub fn height(&self) -> CheckpointHeight {
171        self.details().checkpoint_height
172    }
173}
174
175#[derive(Clone, Debug, Serialize, Deserialize)]
176pub struct BuilderCheckpointSummary {
177    pub summary: CheckpointSummary,
178    // Height at which this checkpoint summary was built. None for genesis checkpoint
179    pub checkpoint_height: Option<CheckpointHeight>,
180    pub position_in_commit: usize,
181}
182
183#[derive(DBMapUtils)]
184pub struct CheckpointStoreTables {
185    /// Certified checkpoint summaries, keyed by sequence number.
186    ///
187    /// Intentionally never pruned: only these summaries carry a certified
188    /// `contents_digest` for a checkpoint that does not close an epoch, which
189    /// is what an inclusion proof is checked against.
190    pub(crate) certified_checkpoints: DBMap<CheckpointSequenceNumber, TrustedCheckpoint>,
191
192    /// Store locally computed checkpoint summaries so that we can detect forks
193    /// and log useful information. Can be pruned as soon as we verify that
194    /// we are in agreement with the latest certified checkpoint.
195    pub(crate) locally_computed_checkpoints: DBMap<CheckpointSequenceNumber, CheckpointSummary>,
196
197    /// A map from epoch ID to the sequence number of the last checkpoint in
198    /// that epoch.
199    ///
200    /// Written at certification time, before the boundary executes, so it
201    /// records the closing sequence number independently of the later-finalized
202    /// `epoch_info` row. Never pruned.
203    epoch_last_checkpoint_map: DBMap<EpochId, CheckpointSequenceNumber>,
204
205    /// Per-epoch verified data (start-of-epoch identity plus its close-of-epoch
206    /// proof bundle ([`EpochInfoV2`])) keyed by epoch ID. Populated at every
207    /// epoch boundary by the checkpoint executor and seeded from a formal
208    /// snapshot's `EPOCH_INFO` on restore.
209    ///
210    /// Intentionally not pruned: callers (the snapshot writer, the gRPC API,
211    /// etc.) need full `[0, snapshot_epoch]` coverage, so
212    /// this table grows unboundedly with epoch count (one row per epoch, ever)
213    /// by design. Do not move it into the per-epoch checkpoint buckets.
214    ///
215    /// Completeness is tracked by `epoch_info_watermark`.
216    epoch_info: DBMap<EpochId, EpochInfoV2>,
217
218    /// Highest epoch whose `epoch_info` row is finalized (close-of-epoch proof
219    /// present), as a contiguous prefix `[0, watermark]`. Singleton keyed by
220    /// `()`. Advanced atomically with the close-of-epoch upsert in
221    /// `index_epoch`, and recomputed over a seeded prefix by
222    /// `insert_epoch_info`; only ever raised. Never pruned.
223    epoch_info_watermark: DBMap<(), EpochId>,
224
225    /// Watermarks used to determine the highest verified, fully synced, and
226    /// fully executed checkpoints
227    pub(crate) watermarks: DBMap<CheckpointWatermark, (CheckpointSequenceNumber, CheckpointDigest)>,
228}
229
230impl CheckpointStoreTables {
231    /// Opens the checkpoint store's tables together with the historic
232    /// checkpoint buckets, which are column families of the same database.
233    /// `historic_db_path` is as for
234    /// [`CheckpointStore::new_with_historic_db_path`].
235    fn open_with_historic_checkpoints(
236        path: &Path,
237        historic_db_path: Option<&Path>,
238        metric_name: &'static str,
239    ) -> (Self, HistoricCheckpoints) {
240        let db_options = default_db_options();
241        let historic_root = historic_root(path, historic_db_path);
242        let table_options = Self::table_options(path, &db_options, &historic_root);
243        let tables = Self::open_tables_read_write(
244            path.to_path_buf(),
245            MetricConf::new(metric_name),
246            None,
247            Some(table_options),
248        );
249        let historic_checkpoints = HistoricCheckpoints::open(
250            tables.certified_checkpoints.db.clone(),
251            &db_options,
252            &historic_root,
253        )
254        .expect("cannot open the historic checkpoint buckets");
255        (tables, historic_checkpoints)
256    }
257
258    /// The options of the historic checkpoint buckets of the database at
259    /// `path`. Every open of the database must pass these, or a bucket is
260    /// reopened with default options and without the directory its files
261    /// are in.
262    fn table_options(
263        path: &Path,
264        db_options: &DBOptions,
265        historic_root: &Path,
266    ) -> DBMapTableConfigMap {
267        DBMapTableConfigMap::new(
268            HistoricCheckpoints::extra_column_family_options(path, db_options, historic_root)
269                .into_iter()
270                .collect(),
271        )
272    }
273
274    pub fn open_readonly(
275        path: &Path,
276        historic_db_path: Option<&Path>,
277    ) -> CheckpointStoreTablesReadOnly {
278        Self::get_read_only_handle_with_table_options(
279            path.to_path_buf(),
280            None,
281            None,
282            MetricConf::new("checkpoint_readonly"),
283            Self::table_options(
284                path,
285                &default_db_options(),
286                &historic_root(path, historic_db_path),
287            ),
288        )
289    }
290}
291
292pub struct CheckpointStore {
293    pub(crate) tables: CheckpointStoreTables,
294    /// Checkpoint contents and digest-keyed summaries, bucketed by the epoch
295    /// that closed the checkpoint.
296    pub(crate) historic_checkpoints: HistoricCheckpoints,
297    full_checkpoint_contents_cache: FullCheckpointContentsCache,
298    synced_checkpoint_notify_read: NotifyRead<CheckpointSequenceNumber, VerifiedCheckpoint>,
299    executed_checkpoint_notify_read: NotifyRead<CheckpointSequenceNumber, VerifiedCheckpoint>,
300    locally_computed_checkpoint_notify_read:
301        NotifyRead<CheckpointSequenceNumber, CheckpointSummary>,
302    epoch_last_checkpoint_notify_read: NotifyRead<EpochId, CheckpointSequenceNumber>,
303    /// Set by [`Self::hold_synced_watermark_in_memory`]; empty while the saved
304    /// synced watermark is the one readers see.
305    synced_in_memory: OnceLock<SyncedWatermarkInMemory>,
306    /// Held for the whole of every write of the synced watermark, whether or
307    /// not it is held in memory, so that writes apply one at a time and the
308    /// saved watermark never passes the one readers see. Readers never take
309    /// it. Taken before the lock on the value held in memory.
310    synced_writes: Mutex<()>,
311}
312
313/// The synced watermark readers see, held in memory while the saved one only
314/// moves over checkpoints whose contents are stored.
315struct SyncedWatermarkInMemory {
316    historic_ledger: Arc<HistoricLedger>,
317    /// Locked only to copy or replace the value, never across a read of the
318    /// store, so readers do not wait for one.
319    highest_synced: Mutex<Option<(CheckpointSequenceNumber, CheckpointDigest)>>,
320}
321
322impl CheckpointStore {
323    /// A checkpoint store at `path` that keeps its per-epoch history in
324    /// [`HISTORIC_DB_DIR`](crate::epoch_buckets::HISTORIC_DB_DIR) in its own
325    /// directory. A node opens its store with
326    /// [`Self::new_with_historic_db_path`] instead.
327    pub fn new(path: &Path) -> Arc<Self> {
328        Self::new_with_contents_cache(path, None, FullCheckpointContentsCache::default())
329    }
330
331    /// A checkpoint store at `path` that keeps its per-epoch history under
332    /// `historic_db_path`. Every open of a database must pass the same path.
333    pub fn new_with_historic_db_path(path: &Path, historic_db_path: &Path) -> Arc<Self> {
334        Self::new_with_contents_cache(
335            path,
336            Some(historic_db_path),
337            FullCheckpointContentsCache::default(),
338        )
339    }
340
341    pub fn new_with_contents_cache(
342        path: &Path,
343        historic_db_path: Option<&Path>,
344        contents_cache: FullCheckpointContentsCache,
345    ) -> Arc<Self> {
346        let (tables, historic_checkpoints) = CheckpointStoreTables::open_with_historic_checkpoints(
347            path,
348            historic_db_path,
349            "checkpoint",
350        );
351        Arc::new(Self {
352            tables,
353            historic_checkpoints,
354            full_checkpoint_contents_cache: contents_cache,
355            synced_checkpoint_notify_read: NotifyRead::new(),
356            executed_checkpoint_notify_read: NotifyRead::new(),
357            locally_computed_checkpoint_notify_read: NotifyRead::new(),
358            epoch_last_checkpoint_notify_read: NotifyRead::new(),
359            synced_in_memory: OnceLock::new(),
360            synced_writes: Mutex::new(()),
361        })
362    }
363
364    pub fn new_for_tests() -> Arc<Self> {
365        let storage_dir = iota_common::tempdir().keep();
366        CheckpointStore::new(storage_dir.as_path())
367    }
368
369    pub fn open_readonly(
370        path: &Path,
371        historic_db_path: Option<&Path>,
372    ) -> CheckpointStoreTablesReadOnly {
373        CheckpointStoreTables::open_readonly(path, historic_db_path)
374    }
375
376    #[instrument(level = "info", skip_all)]
377    pub fn insert_genesis_checkpoint(
378        &self,
379        checkpoint: VerifiedCheckpoint,
380        contents: CheckpointContents,
381        epoch_store: &AuthorityPerEpochStore,
382    ) {
383        assert_eq!(
384            checkpoint.epoch(),
385            0,
386            "can't call insert_genesis_checkpoint with a checkpoint not in epoch 0"
387        );
388        assert_eq!(
389            checkpoint.sequence_number(),
390            0,
391            "can't call insert_genesis_checkpoint with a checkpoint that doesn't have a sequence number of 0"
392        );
393
394        // Only insert the genesis checkpoint if the DB is empty and doesn't have it
395        // already. Checked by sequence number, since the digest-keyed copy is
396        // gone once epoch 0 has expired.
397        if self
398            .get_checkpoint_by_sequence_number(0)
399            .unwrap()
400            .is_none_or(|stored| stored.digest() != checkpoint.digest())
401        {
402            if epoch_store.epoch() == checkpoint.epoch {
403                epoch_store
404                    .put_genesis_checkpoint_in_builder(checkpoint.data(), &contents)
405                    .unwrap();
406            } else {
407                debug!(
408                    validator_epoch =% epoch_store.epoch(),
409                    genesis_epoch =% checkpoint.epoch(),
410                    "Not inserting checkpoint builder data for genesis checkpoint",
411                );
412            }
413            self.insert_checkpoint_contents(&checkpoint, contents)
414                .unwrap();
415            self.insert_verified_checkpoint(&checkpoint).unwrap();
416            self.update_highest_synced_checkpoint(&checkpoint).unwrap();
417        }
418    }
419
420    pub fn get_checkpoint_by_digest(
421        &self,
422        digest: &CheckpointDigest,
423    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
424        self.historic_checkpoints
425            .find_by_digest(digest)
426            .map(|maybe_checkpoint| maybe_checkpoint.map(|c| c.into()))
427    }
428
429    pub fn get_checkpoint_by_sequence_number(
430        &self,
431        sequence_number: CheckpointSequenceNumber,
432    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
433        self.tables
434            .certified_checkpoints
435            .get(&sequence_number)
436            .map(|maybe_checkpoint| maybe_checkpoint.map(|c| c.into()))
437    }
438
439    pub fn get_locally_computed_checkpoint(
440        &self,
441        sequence_number: CheckpointSequenceNumber,
442    ) -> Result<Option<CheckpointSummary>, TypedStoreError> {
443        self.tables
444            .locally_computed_checkpoints
445            .get(&sequence_number)
446    }
447
448    /// Get full checkpoint contents by contents digest from the in-memory
449    /// contents cache.
450    ///
451    /// Returns `None` once the entry has been evicted; callers reconstruct
452    /// full contents from `checkpoint_content` and the transaction and
453    /// effects stores instead.
454    pub fn get_full_checkpoint_contents_by_digest(
455        &self,
456        digest: &CheckpointContentsDigest,
457    ) -> Option<Arc<FullCheckpointContents>> {
458        self.full_checkpoint_contents_cache.get_by_digest(digest)
459    }
460
461    pub fn get_latest_certified_checkpoint(
462        &self,
463    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
464        Ok(self
465            .tables
466            .certified_checkpoints
467            .safe_range_iter_reversed(..)
468            .next()
469            .transpose()?
470            .map(|(_, v)| v.into()))
471    }
472
473    pub fn get_latest_locally_computed_checkpoint(
474        &self,
475    ) -> Result<Option<CheckpointSummary>, TypedStoreError> {
476        Ok(self
477            .tables
478            .locally_computed_checkpoints
479            .safe_range_iter_reversed(..)
480            .next()
481            .transpose()?
482            .map(|(_, v)| v))
483    }
484
485    pub fn multi_get_checkpoint_by_sequence_number(
486        &self,
487        sequence_numbers: &[CheckpointSequenceNumber],
488    ) -> Result<Vec<Option<VerifiedCheckpoint>>, TypedStoreError> {
489        let checkpoints = self
490            .tables
491            .certified_checkpoints
492            .multi_get(sequence_numbers)?
493            .into_iter()
494            .map(|maybe_checkpoint| maybe_checkpoint.map(|c| c.into()))
495            .collect();
496
497        Ok(checkpoints)
498    }
499
500    /// The contents of each digest, in the order given.
501    pub fn multi_get_checkpoint_content(
502        &self,
503        contents_digest: &[CheckpointContentsDigest],
504    ) -> Result<Vec<Option<CheckpointContents>>, TypedStoreError> {
505        contents_digest
506            .iter()
507            .map(|digest| self.historic_checkpoints.find_contents(digest))
508            .collect()
509    }
510
511    /// Every checkpoint watermark as it is stored, without resolving any of
512    /// them to a checkpoint.
513    pub fn get_checkpoint_watermarks(
514        &self,
515    ) -> Result<
516        Vec<(
517            CheckpointWatermark,
518            CheckpointSequenceNumber,
519            CheckpointDigest,
520        )>,
521        TypedStoreError,
522    > {
523        self.tables
524            .watermarks
525            .safe_iter()
526            .map(|row| row.map(|(mark, (sequence_number, digest))| (mark, sequence_number, digest)))
527            .collect()
528    }
529
530    /// The row `watermark` holds — a sequence number and a digest — and `None`
531    /// when it has never been written.
532    ///
533    /// Only the verified, synced and executed rows name a checkpoint. The
534    /// pruner writes a random digest for `HighestPruned`, since nothing reads
535    /// it, so that row's sequence number is the only part worth having. While
536    /// the synced watermark readers see is held in memory, `HighestSynced`
537    /// answers with that one instead of the saved row.
538    fn get_watermark(
539        &self,
540        watermark: CheckpointWatermark,
541    ) -> Result<Option<(CheckpointSequenceNumber, CheckpointDigest)>, TypedStoreError> {
542        if matches!(watermark, CheckpointWatermark::HighestSynced) {
543            if let Some(in_memory) = self.synced_in_memory.get() {
544                return Ok(*in_memory.highest_synced.lock());
545            }
546        }
547        self.tables.watermarks.get(&watermark)
548    }
549
550    /// The checkpoint `watermark` names.
551    ///
552    /// `None` for a checkpoint the store no longer holds, or one whose
553    /// sequence number now names a different checkpoint. A caller that only
554    /// compares positions wants [`Self::get_watermark_seq_number`].
555    fn get_watermark_checkpoint(
556        &self,
557        watermark: CheckpointWatermark,
558    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
559        let Some((sequence_number, digest)) = self.get_watermark(watermark)? else {
560            return Ok(None);
561        };
562        Ok(self
563            .get_checkpoint_by_sequence_number(sequence_number)?
564            .filter(|checkpoint| *checkpoint.digest() == digest))
565    }
566
567    /// The sequence number of the checkpoint `watermark` names, read from the
568    /// row rather than from the checkpoint.
569    fn get_watermark_seq_number(
570        &self,
571        watermark: CheckpointWatermark,
572    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
573        Ok(self
574            .get_watermark(watermark)?
575            .map(|(sequence_number, _digest)| sequence_number))
576    }
577
578    pub fn get_highest_verified_checkpoint(
579        &self,
580    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
581        self.get_watermark_checkpoint(CheckpointWatermark::HighestVerified)
582    }
583
584    pub fn get_highest_verified_checkpoint_seq_number(
585        &self,
586    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
587        self.get_watermark_seq_number(CheckpointWatermark::HighestVerified)
588    }
589
590    pub fn get_highest_synced_checkpoint(
591        &self,
592    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
593        self.get_watermark_checkpoint(CheckpointWatermark::HighestSynced)
594    }
595
596    pub fn get_highest_synced_checkpoint_seq_number(
597        &self,
598    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
599        self.get_watermark_seq_number(CheckpointWatermark::HighestSynced)
600    }
601
602    pub fn get_highest_executed_checkpoint(
603        &self,
604    ) -> Result<Option<VerifiedCheckpoint>, TypedStoreError> {
605        self.get_watermark_checkpoint(CheckpointWatermark::HighestExecuted)
606    }
607
608    pub fn get_highest_executed_checkpoint_seq_number(
609        &self,
610    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
611        self.get_watermark_seq_number(CheckpointWatermark::HighestExecuted)
612    }
613
614    pub fn get_highest_pruned_checkpoint_seq_number(
615        &self,
616    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
617        self.get_watermark_seq_number(CheckpointWatermark::HighestPruned)
618    }
619
620    pub fn get_checkpoint_contents(
621        &self,
622        digest: &CheckpointContentsDigest,
623    ) -> Result<Option<CheckpointContents>, TypedStoreError> {
624        self.historic_checkpoints.find_contents(digest)
625    }
626
627    /// [`Self::get_checkpoint_contents`], with the epoch of the checkpoint
628    /// they belong to.
629    pub fn get_checkpoint_contents_with_epoch(
630        &self,
631        digest: &CheckpointContentsDigest,
632    ) -> Result<Option<(EpochId, CheckpointContents)>, TypedStoreError> {
633        self.historic_checkpoints.find_contents_with_epoch(digest)
634    }
635
636    /// Get full checkpoint contents from the in-memory contents cache.
637    ///
638    /// Returns `None` once the entry has been evicted; callers fall back to
639    /// loading the individual transactions and effects from their stores.
640    pub fn get_full_checkpoint_contents_by_sequence_number(
641        &self,
642        seq: CheckpointSequenceNumber,
643    ) -> Option<Arc<FullCheckpointContents>> {
644        self.full_checkpoint_contents_cache.get_by_seq(seq)
645    }
646
647    fn prune_local_summaries(&self) -> IotaResult {
648        if let Some((last_local_summary, _)) = self
649            .tables
650            .locally_computed_checkpoints
651            .safe_range_iter_reversed(..)
652            .next()
653            .transpose()?
654        {
655            let mut batch = self.tables.locally_computed_checkpoints.batch();
656            batch.schedule_delete_range(
657                &self.tables.locally_computed_checkpoints,
658                &0,
659                &last_local_summary,
660            )?;
661            batch.write()?;
662            info!("Pruned local summaries up to {:?}", last_local_summary);
663        }
664        Ok(())
665    }
666
667    /// Compares the summary this node built with the certified one for the
668    /// same sequence number.
669    ///
670    /// # Panics
671    ///
672    /// If they differ: the node has forked from the network, so both summaries
673    /// and their contents are logged before the panic.
674    #[instrument(level = "trace", skip_all)]
675    fn check_for_checkpoint_fork(
676        &self,
677        local_checkpoint: &CheckpointSummary,
678        verified_checkpoint: &VerifiedCheckpoint,
679    ) {
680        if local_checkpoint != verified_checkpoint.data() {
681            let verified_contents = self
682                .get_checkpoint_contents(&verified_checkpoint.contents_digest)
683                .map(|opt_contents| {
684                    opt_contents
685                        .map(|contents| format!("{contents:?}"))
686                        .unwrap_or_else(|| {
687                            format!(
688                                "Verified checkpoint contents not found, digest: {:?}",
689                                verified_checkpoint.contents_digest,
690                            )
691                        })
692                })
693                .map_err(|e| {
694                    format!(
695                        "Failed to get verified checkpoint contents, digest: {:?} error: {:?}",
696                        verified_checkpoint.contents_digest, e
697                    )
698                })
699                .unwrap_or_else(|err_msg| err_msg);
700
701            let local_contents = self
702                .get_checkpoint_contents(&local_checkpoint.contents_digest)
703                .map(|opt_contents| {
704                    opt_contents
705                        .map(|contents| format!("{contents:?}"))
706                        .unwrap_or_else(|| {
707                            format!(
708                                "Local checkpoint contents not found, digest: {:?}",
709                                local_checkpoint.contents_digest
710                            )
711                        })
712                })
713                .map_err(|e| {
714                    format!(
715                        "Failed to get local checkpoint contents, digest: {:?} error: {:?}",
716                        local_checkpoint.contents_digest, e
717                    )
718                })
719                .unwrap_or_else(|err_msg| err_msg);
720
721            // checkpoint contents may be too large for panic message.
722            error!(
723                verified_checkpoint = ?verified_checkpoint.data(),
724                ?verified_contents,
725                ?local_checkpoint,
726                ?local_contents,
727                // Two summaries over identical contents can still differ in
728                // their attestation entries, which the dump above would not
729                // show.
730                attestation_entry_differences =
731                    ?attestation_entry_differences(local_checkpoint, verified_checkpoint),
732                attestation_totals_difference =
733                    ?attestation_totals_difference(local_checkpoint, verified_checkpoint),
734                "Local checkpoint fork detected!",
735            );
736            fatal!(
737                "Local checkpoint fork detected for sequence number: {}",
738                local_checkpoint.sequence_number()
739            );
740        }
741    }
742
743    /// Called by consensus (ConsensusAggregator). Different from
744    /// [`Self::insert_verified_checkpoint`], it does not touch the
745    /// `HighestVerified` watermark, such that state sync will have a chance to
746    /// process this checkpoint and perform some state-sync only things.
747    ///
748    /// A checkpoint of an already expired epoch is stored by sequence number
749    /// only, not by digest.
750    pub fn insert_certified_checkpoint(
751        &self,
752        checkpoint: &VerifiedCheckpoint,
753    ) -> Result<(), TypedStoreError> {
754        self.multi_insert_certified_checkpoints(std::slice::from_ref(checkpoint))
755    }
756
757    /// Inserts a batch of certified checkpoints in a single write, like
758    /// [`Self::insert_certified_checkpoint`] for each of them.
759    pub fn multi_insert_certified_checkpoints(
760        &self,
761        checkpoints: &[VerifiedCheckpoint],
762    ) -> Result<(), TypedStoreError> {
763        let Some(last) = checkpoints.last() else {
764            return Ok(());
765        };
766        debug!(
767            checkpoint_seq = last.sequence_number(),
768            count = checkpoints.len(),
769            "Inserting certified checkpoints",
770        );
771        let mut batch = self.tables.certified_checkpoints.batch();
772        batch
773            .insert_batch(
774                &self.tables.certified_checkpoints,
775                checkpoints
776                    .iter()
777                    .map(|c| (c.sequence_number(), c.serializable_ref())),
778            )?
779            .insert_batch(
780                &self.tables.epoch_last_checkpoint_map,
781                checkpoints
782                    .iter()
783                    .filter(|c| c.next_epoch_committee().is_some())
784                    .map(|c| (c.epoch(), c.sequence_number())),
785            )?;
786        // State sync runs ahead of execution and across epoch boundaries, so
787        // this can create the bucket of an epoch not yet executed (see
788        // `HistoricCheckpoints`), or arrive after the epoch has expired.
789        for checkpoint in checkpoints {
790            let Some(bucket) = self
791                .historic_checkpoints
792                .ensure_retained(checkpoint.epoch())?
793            else {
794                debug!(
795                    checkpoint_seq = checkpoint.sequence_number(),
796                    epoch = checkpoint.epoch(),
797                    "not filing a checkpoint summary whose epoch has been expired",
798                );
799                continue;
800            };
801            batch.insert_batch_tagged(
802                &bucket.checkpoint_by_digest,
803                [(checkpoint.digest(), checkpoint.serializable_ref())],
804            )?;
805        }
806        // An epoch can expire between the staging above and the write.
807        batch.write_opt(&drop_tolerant_write_options())?;
808
809        for checkpoint in checkpoints
810            .iter()
811            .filter(|c| c.next_epoch_committee().is_some())
812        {
813            self.epoch_last_checkpoint_notify_read
814                .notify(&checkpoint.epoch(), &checkpoint.sequence_number());
815        }
816
817        for checkpoint in checkpoints {
818            if let Some(local_checkpoint) = self
819                .tables
820                .locally_computed_checkpoints
821                .get(&checkpoint.sequence_number())?
822            {
823                self.check_for_checkpoint_fork(&local_checkpoint, checkpoint);
824            }
825        }
826
827        Ok(())
828    }
829
830    // Called by state sync, apart from inserting the checkpoint and updating
831    // related tables, it also bumps the highest_verified_checkpoint watermark.
832    #[instrument(level = "trace", skip_all)]
833    pub fn insert_verified_checkpoint(
834        &self,
835        checkpoint: &VerifiedCheckpoint,
836    ) -> Result<(), TypedStoreError> {
837        self.insert_certified_checkpoint(checkpoint)?;
838        self.update_highest_verified_checkpoint(checkpoint)
839    }
840
841    pub fn update_highest_verified_checkpoint(
842        &self,
843        checkpoint: &VerifiedCheckpoint,
844    ) -> Result<(), TypedStoreError> {
845        if Some(checkpoint.sequence_number()) > self.get_highest_verified_checkpoint_seq_number()? {
846            debug!(
847                checkpoint_seq = checkpoint.sequence_number(),
848                "Updating highest verified checkpoint",
849            );
850            self.tables.watermarks.insert(
851                &CheckpointWatermark::HighestVerified,
852                &(checkpoint.sequence_number(), *checkpoint.digest()),
853            )?;
854        }
855
856        Ok(())
857    }
858
859    /// Marks `checkpoint` as synced. Returns whether the watermark moved; see
860    /// [`Self::multi_update_highest_synced_checkpoint`].
861    pub fn update_highest_synced_checkpoint(
862        &self,
863        checkpoint: &VerifiedCheckpoint,
864    ) -> Result<bool, TypedStoreError> {
865        self.multi_update_highest_synced_checkpoint(std::slice::from_ref(checkpoint))
866    }
867
868    /// Marks a consecutive run of checkpoints as synced: writes the watermark
869    /// once, for the last checkpoint, and notifies the waiters that write
870    /// releases. Does nothing when another writer has already carried the
871    /// watermark past the run, or when the run starts above the checkpoint
872    /// after the watermark. Returns whether the watermark moved.
873    ///
874    /// Tooling that has to set the watermark regardless uses
875    /// [`Self::set_highest_synced_checkpoint_subtle`].
876    pub fn multi_update_highest_synced_checkpoint(
877        &self,
878        checkpoints: &[VerifiedCheckpoint],
879    ) -> Result<bool, TypedStoreError> {
880        let Some(last) = checkpoints.last() else {
881            return Ok(false);
882        };
883
884        // Only ever forwards, like the other two: another writer advances this
885        // as well, and moving it back offers contents that may not be there.
886        let previous = self.get_highest_synced_checkpoint_seq_number()?;
887        // The watermark promises that the contents of every checkpoint up to
888        // it are stored, and a writer stores them only for the run it marks.
889        // A run that starts above the checkpoint after the watermark would
890        // pass checkpoints whose contents may still be missing; they are
891        // marked synced once the checkpoints before them are.
892        let first = checkpoints[0].sequence_number();
893        if previous.is_some_and(|previous_seq_number| first > previous_seq_number + 1) {
894            debug!(
895                checkpoint_seq = first,
896                highest_synced = previous,
897                "Not marking checkpoints synced before the ones below them",
898            );
899            return Ok(false);
900        }
901        if previous.is_none_or(|previous_seq_number| previous_seq_number < last.sequence_number()) {
902            debug!(
903                checkpoint_seq = last.sequence_number(),
904                "Updating highest synced checkpoint",
905            );
906            self.write_highest_synced(last)?;
907
908            // A reader parks only below the watermark, so only what this
909            // write has just passed can have anyone waiting on it.
910            for checkpoint in checkpoints.iter().filter(|c| {
911                previous.is_none_or(|previous_seq_number| previous_seq_number < c.sequence_number())
912            }) {
913                self.synced_checkpoint_notify_read
914                    .notify(&checkpoint.sequence_number(), checkpoint);
915            }
916            return Ok(true);
917        }
918        Ok(false)
919    }
920
921    async fn notify_read_checkpoint_watermark<F>(
922        &self,
923        notify_read: &NotifyRead<CheckpointSequenceNumber, VerifiedCheckpoint>,
924        seq: CheckpointSequenceNumber,
925        get_watermark: F,
926    ) -> VerifiedCheckpoint
927    where
928        F: Fn() -> Option<CheckpointSequenceNumber>,
929    {
930        type ReadResult = Result<Vec<Option<VerifiedCheckpoint>>, TypedStoreError>;
931
932        notify_read
933            .read("notify_read_checkpoint_watermark", &[seq], |seqs| {
934                let seq = seqs[0];
935                let Some(highest) = get_watermark() else {
936                    return Ok(vec![None]) as ReadResult;
937                };
938                if highest < seq {
939                    return Ok(vec![None]) as ReadResult;
940                }
941                let checkpoint = self
942                    .get_checkpoint_by_sequence_number(seq)
943                    .expect("db error")
944                    .expect("checkpoint not found");
945                Ok(vec![Some(checkpoint)]) as ReadResult
946            })
947            .await
948            .unwrap()
949            .into_iter()
950            .next()
951            .unwrap()
952    }
953
954    pub async fn notify_read_synced_checkpoint(
955        &self,
956        seq: CheckpointSequenceNumber,
957    ) -> VerifiedCheckpoint {
958        self.notify_read_checkpoint_watermark(&self.synced_checkpoint_notify_read, seq, || {
959            self.get_highest_synced_checkpoint_seq_number()
960                .expect("db error")
961        })
962        .await
963    }
964
965    pub async fn notify_read_executed_checkpoint(
966        &self,
967        seq: CheckpointSequenceNumber,
968    ) -> VerifiedCheckpoint {
969        self.notify_read_checkpoint_watermark(&self.executed_checkpoint_notify_read, seq, || {
970            self.get_highest_executed_checkpoint_seq_number()
971                .expect("db error")
972        })
973        .await
974    }
975
976    /// Waits until this node's checkpoint builder has built checkpoint `seq`.
977    pub async fn notify_read_locally_computed_checkpoint(
978        &self,
979        seq: CheckpointSequenceNumber,
980    ) -> CheckpointSummary {
981        self.locally_computed_checkpoint_notify_read
982            .read("notify_read_locally_computed_checkpoint", &[seq], |seqs| {
983                Ok::<_, TypedStoreError>(vec![self.get_locally_computed_checkpoint(seqs[0])?])
984            })
985            .await
986            .expect("db error")
987            .pop()
988            .expect("one key requested")
989    }
990
991    pub(crate) fn notify_locally_computed_checkpoints<'a>(
992        &self,
993        summaries: impl IntoIterator<Item = &'a CheckpointSummary>,
994    ) {
995        for summary in summaries {
996            self.locally_computed_checkpoint_notify_read
997                .notify(&summary.sequence_number, summary);
998        }
999    }
1000
1001    /// Waits until the certified last checkpoint of `epoch` is known and
1002    /// returns its sequence number.
1003    pub async fn notify_read_epoch_last_checkpoint_seq_number(
1004        &self,
1005        epoch: EpochId,
1006    ) -> CheckpointSequenceNumber {
1007        self.epoch_last_checkpoint_notify_read
1008            .read("notify_read_epoch_last_checkpoint", &[epoch], |epochs| {
1009                Ok::<_, TypedStoreError>(vec![
1010                    self.get_epoch_last_checkpoint_seq_number(epochs[0])?,
1011                ])
1012            })
1013            .await
1014            .expect("db error")
1015            .pop()
1016            .expect("one key requested")
1017    }
1018
1019    pub fn update_highest_executed_checkpoint(
1020        &self,
1021        checkpoint: &VerifiedCheckpoint,
1022    ) -> Result<(), TypedStoreError> {
1023        if let Some(seq_number) = self.get_highest_executed_checkpoint_seq_number()? {
1024            if seq_number >= checkpoint.sequence_number() {
1025                return Ok(());
1026            }
1027            assert_eq!(
1028                seq_number + 1,
1029                checkpoint.sequence_number(),
1030                "Cannot update highest executed checkpoint to {} when current highest executed checkpoint is {}",
1031                checkpoint.sequence_number(),
1032                seq_number
1033            );
1034        }
1035        let seq = checkpoint.sequence_number();
1036        debug!(checkpoint_seq = seq, "Updating highest executed checkpoint",);
1037        self.tables.watermarks.insert(
1038            &CheckpointWatermark::HighestExecuted,
1039            &(seq, *checkpoint.digest()),
1040        )?;
1041        self.executed_checkpoint_notify_read
1042            .notify(&seq, checkpoint);
1043        // The checkpoint's outputs are stored now, so the saved synced
1044        // watermark may pass it.
1045        if let Some(in_memory) = self.synced_in_memory.get() {
1046            let _writes = self.synced_writes.lock();
1047            self.advance_saved_synced(in_memory)?;
1048        }
1049        Ok(())
1050    }
1051
1052    /// Moves the synced watermark readers see to `checkpoint`, and the saved
1053    /// one towards it over the checkpoints whose contents are stored.
1054    fn write_highest_synced(&self, checkpoint: &VerifiedCheckpoint) -> Result<(), TypedStoreError> {
1055        let _writes = self.synced_writes.lock();
1056        let row = (checkpoint.sequence_number(), *checkpoint.digest());
1057        let Some(in_memory) = self.synced_in_memory.get() else {
1058            return self
1059                .tables
1060                .watermarks
1061                .insert(&CheckpointWatermark::HighestSynced, &row);
1062        };
1063        {
1064            let mut highest_synced = in_memory.highest_synced.lock();
1065            if highest_synced
1066                .is_none_or(|(sequence_number, _)| sequence_number < checkpoint.sequence_number())
1067            {
1068                *highest_synced = Some(row);
1069            }
1070        }
1071        self.advance_saved_synced(in_memory)
1072    }
1073
1074    /// Moves the saved synced watermark forwards over the checkpoints, up to
1075    /// the one readers see, that have executed or whose transactions and
1076    /// effects are stored, stopping at the first that has neither. Call with
1077    /// `synced_writes` held.
1078    fn advance_saved_synced(
1079        &self,
1080        in_memory: &SyncedWatermarkInMemory,
1081    ) -> Result<(), TypedStoreError> {
1082        let Some((highest_synced, _)) = *in_memory.highest_synced.lock() else {
1083            return Ok(());
1084        };
1085        let saved = self
1086            .tables
1087            .watermarks
1088            .get(&CheckpointWatermark::HighestSynced)?
1089            .map(|(sequence_number, _)| sequence_number);
1090        let highest_executed = self.get_highest_executed_checkpoint_seq_number()?;
1091        let mut advanced_to = None;
1092        for sequence_number in saved.map_or(0, |saved| saved + 1)..=highest_synced {
1093            let stored = highest_executed.is_some_and(|executed| sequence_number <= executed)
1094                || self.contents_stored(sequence_number, &in_memory.historic_ledger)?;
1095            if !stored {
1096                break;
1097            }
1098            advanced_to = Some(sequence_number);
1099        }
1100        let Some(sequence_number) = advanced_to else {
1101            return Ok(());
1102        };
1103        let checkpoint = self
1104            .get_checkpoint_by_sequence_number(sequence_number)?
1105            .expect("a checkpoint at or below the synced watermark is stored");
1106        self.tables.watermarks.insert(
1107            &CheckpointWatermark::HighestSynced,
1108            &(sequence_number, *checkpoint.digest()),
1109        )
1110    }
1111
1112    /// Whether every transaction and effect of synced checkpoint
1113    /// `sequence_number` is in the ledger bucket of its epoch, rather than
1114    /// only in memory.
1115    fn contents_stored(
1116        &self,
1117        sequence_number: CheckpointSequenceNumber,
1118        historic_ledger: &HistoricLedger,
1119    ) -> Result<bool, TypedStoreError> {
1120        let checkpoint = self
1121            .get_checkpoint_by_sequence_number(sequence_number)?
1122            .expect("a checkpoint at or below the synced watermark is stored");
1123        let contents = self
1124            .get_checkpoint_contents(&checkpoint.contents_digest)?
1125            .expect("the contents of a checkpoint at or below the synced watermark are stored");
1126        let (transactions, effects): (Vec<_>, Vec<_>) = contents
1127            .iter()
1128            .map(|digests| (digests.transaction, digests.effects))
1129            .unzip();
1130        historic_ledger.holds_in_epoch(checkpoint.epoch(), &transactions, &effects)
1131    }
1132
1133    pub fn update_highest_pruned_checkpoint(
1134        &self,
1135        checkpoint: &VerifiedCheckpoint,
1136    ) -> Result<(), TypedStoreError> {
1137        self.tables.watermarks.insert(
1138            &CheckpointWatermark::HighestPruned,
1139            &(checkpoint.sequence_number(), *checkpoint.digest()),
1140        )
1141    }
1142
1143    /// From now on, holds the synced watermark that callers read in memory.
1144    /// The value saved in the database passes a checkpoint only once that
1145    /// checkpoint has executed or its transactions and effects are in the
1146    /// ledger bucket of its epoch.
1147    ///
1148    /// The synced watermark promises that the contents of every checkpoint up
1149    /// to it can be loaded. A checkpoint can be marked synced while its
1150    /// transactions and effects are only in memory: this node certified it
1151    /// after building it, or state sync found its contents in memory. With
1152    /// the watermark held in memory, a restarted node starts from a synced
1153    /// checkpoint whose contents can be loaded, and state sync marks the later
1154    /// checkpoints synced again.
1155    ///
1156    /// Turning this on does not change the value callers read. At startup,
1157    /// call it once the one-time startup passes are done and before state
1158    /// sync starts: until then only the genesis checkpoint, whose contents are
1159    /// in the ledger already, and the ledger migration's rewind write the
1160    /// synced watermark. A running node may call it at an epoch change, after
1161    /// every checkpoint of the ending epoch has executed. Once on, it stays on
1162    /// until the process stops, also in later epochs where the node is not in
1163    /// the committee. There, state sync marks a checkpoint synced only after
1164    /// its transactions and effects are in the ledger, so the saved value
1165    /// moves with the one callers read. Does nothing if already on.
1166    pub fn hold_synced_watermark_in_memory(
1167        &self,
1168        historic_ledger: Arc<HistoricLedger>,
1169    ) -> Result<(), TypedStoreError> {
1170        let _writes = self.synced_writes.lock();
1171        if self.synced_in_memory.get().is_some() {
1172            return Ok(());
1173        }
1174        let saved = self
1175            .tables
1176            .watermarks
1177            .get(&CheckpointWatermark::HighestSynced)?;
1178        self.synced_in_memory
1179            .get_or_init(|| SyncedWatermarkInMemory {
1180                historic_ledger,
1181                highest_synced: Mutex::new(saved),
1182            });
1183        Ok(())
1184    }
1185
1186    /// Moves `HighestPruned` up to the last checkpoint of the epoch below
1187    /// `earliest_retained_epoch`, after that epoch's checkpoint history has
1188    /// been dropped. Never moves the watermark backwards.
1189    pub fn advance_highest_pruned_checkpoint(
1190        &self,
1191        earliest_retained_epoch: EpochId,
1192    ) -> IotaResult<()> {
1193        let Some(previous_epoch) = earliest_retained_epoch.checked_sub(1) else {
1194            return Ok(());
1195        };
1196        let Some(seq) = self.get_epoch_last_checkpoint_seq_number(previous_epoch)? else {
1197            return Ok(());
1198        };
1199        if self
1200            .get_highest_pruned_checkpoint_seq_number()?
1201            .is_some_and(|pruned| pruned >= seq)
1202        {
1203            return Ok(());
1204        }
1205        // The watermark stores the digest too, so the summary is needed.
1206        let Some(checkpoint) = self.get_epoch_last_checkpoint(previous_epoch)? else {
1207            return Ok(());
1208        };
1209        self.update_highest_pruned_checkpoint(&checkpoint)?;
1210        Ok(())
1211    }
1212
1213    /// Sets the verified watermark to `checkpoint` whether or not that moves
1214    /// it forwards.
1215    ///
1216    /// Only for tooling that deliberately rewinds it. The node writes this row
1217    /// through [`Self::update_highest_verified_checkpoint`], which declines to
1218    /// move it backwards, under a lock its callers share.
1219    pub fn set_highest_verified_checkpoint_subtle(
1220        &self,
1221        checkpoint: &VerifiedCheckpoint,
1222    ) -> Result<(), TypedStoreError> {
1223        self.tables.watermarks.insert(
1224            &CheckpointWatermark::HighestVerified,
1225            &(checkpoint.sequence_number(), *checkpoint.digest()),
1226        )
1227    }
1228
1229    /// Sets the synced watermark to `checkpoint` whether or not that moves it
1230    /// forwards.
1231    ///
1232    /// Only for tooling that deliberately rewinds it. The node writes this row
1233    /// through [`Self::multi_update_highest_synced_checkpoint`], which declines
1234    /// to move it backwards, under a lock its callers share.
1235    pub fn set_highest_synced_checkpoint_subtle(
1236        &self,
1237        checkpoint: &VerifiedCheckpoint,
1238    ) -> Result<(), TypedStoreError> {
1239        let _writes = self.synced_writes.lock();
1240        let row = (checkpoint.sequence_number(), *checkpoint.digest());
1241        if let Some(in_memory) = self.synced_in_memory.get() {
1242            *in_memory.highest_synced.lock() = Some(row);
1243        }
1244        self.tables
1245            .watermarks
1246            .insert(&CheckpointWatermark::HighestSynced, &row)
1247    }
1248
1249    /// Brings the synced watermark back to the executed one, so that state
1250    /// sync fetches the checkpoints between the two again, and returns the
1251    /// sequence number it now names. Does nothing when execution has already
1252    /// caught up.
1253    ///
1254    /// Writes only the saved watermark, so it must run before
1255    /// [`Self::hold_synced_watermark_in_memory`].
1256    pub fn rewind_highest_synced_to_executed(
1257        &self,
1258    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
1259        debug_assert!(
1260            self.synced_in_memory.get().is_none(),
1261            "the synced watermark is rewound before it is held in memory"
1262        );
1263        let Some(executed) = self.get_watermark(CheckpointWatermark::HighestExecuted)? else {
1264            return Ok(None);
1265        };
1266        let synced = self.get_watermark_seq_number(CheckpointWatermark::HighestSynced)?;
1267        if synced.is_none_or(|synced| synced <= executed.0) {
1268            return Ok(synced);
1269        }
1270        self.tables
1271            .watermarks
1272            .insert(&CheckpointWatermark::HighestSynced, &executed)?;
1273        Ok(Some(executed.0))
1274    }
1275
1276    /// Sets highest executed checkpoint to any value.
1277    ///
1278    /// WARNING: This method is very subtle and can corrupt the database if used
1279    /// incorrectly. It should only be used in one-off cases or tests after
1280    /// fully understanding the risk.
1281    pub fn set_highest_executed_checkpoint_subtle(
1282        &self,
1283        checkpoint: &VerifiedCheckpoint,
1284    ) -> Result<(), TypedStoreError> {
1285        self.tables.watermarks.insert(
1286            &CheckpointWatermark::HighestExecuted,
1287            &(checkpoint.sequence_number(), *checkpoint.digest()),
1288        )
1289    }
1290
1291    /// Persists the checkpoint contents in digest form, in the bucket of the
1292    /// epoch `checkpoint` belongs to.
1293    ///
1294    /// # Panics
1295    ///
1296    /// If `contents` is not the contents of `checkpoint`.
1297    pub fn insert_checkpoint_contents(
1298        &self,
1299        checkpoint: &VerifiedCheckpoint,
1300        contents: CheckpointContents,
1301    ) -> Result<(), TypedStoreError> {
1302        debug!(
1303            checkpoint_seq = ?contents.digest(),
1304            "Inserting checkpoint contents",
1305        );
1306        assert_eq!(checkpoint.contents_digest, contents.digest());
1307        let Some(bucket) = self
1308            .historic_checkpoints
1309            .ensure_retained(checkpoint.epoch())?
1310        else {
1311            debug!(
1312                checkpoint_seq = checkpoint.sequence_number(),
1313                epoch = checkpoint.epoch(),
1314                "not filing checkpoint contents whose epoch has been expired",
1315            );
1316            return Ok(());
1317        };
1318        bucket
1319            .checkpoint_content
1320            .insert(&contents.digest(), &contents)
1321    }
1322
1323    /// Persists the checkpoint contents in digest form, in the bucket of the
1324    /// epoch `checkpoint` belongs to, and caches the full contents in memory.
1325    /// Contents of an already expired epoch are not persisted.
1326    ///
1327    /// INVARIANT: See [`Self::cache_full_checkpoint_contents`].
1328    pub fn insert_verified_checkpoint_contents(
1329        &self,
1330        checkpoint: &VerifiedCheckpoint,
1331        full_contents: VerifiedCheckpointContents,
1332    ) -> Result<(), TypedStoreError> {
1333        self.multi_insert_verified_checkpoint_contents(vec![(checkpoint.clone(), full_contents)])
1334    }
1335
1336    /// Batch variant of [`Self::insert_verified_checkpoint_contents`]:
1337    /// persists all contents rows in a single write, then caches the full
1338    /// contents.
1339    ///
1340    /// INVARIANT: See [`Self::cache_full_checkpoint_contents`].
1341    pub fn multi_insert_verified_checkpoint_contents(
1342        &self,
1343        checkpoints: Vec<(VerifiedCheckpoint, VerifiedCheckpointContents)>,
1344    ) -> Result<(), TypedStoreError> {
1345        let checkpoints: Vec<_> = checkpoints
1346            .into_iter()
1347            .map(|(checkpoint, full_contents)| (checkpoint, full_contents.into_inner()))
1348            .collect();
1349
1350        let mut batch = self.tables.watermarks.batch();
1351        for (checkpoint, full_contents) in &checkpoints {
1352            let contents = full_contents.checkpoint_contents();
1353            assert_eq!(checkpoint.contents_digest, contents.digest());
1354            let Some(bucket) = self
1355                .historic_checkpoints
1356                .ensure_retained(checkpoint.epoch())?
1357            else {
1358                debug!(
1359                    checkpoint_seq = checkpoint.sequence_number(),
1360                    epoch = checkpoint.epoch(),
1361                    "not filing checkpoint contents whose epoch has been expired",
1362                );
1363                continue;
1364            };
1365            batch
1366                .insert_batch_tagged(&bucket.checkpoint_content, [(contents.digest(), contents)])?;
1367        }
1368        // An epoch can expire between the staging above and the write.
1369        batch.write_opt(&drop_tolerant_write_options())?;
1370
1371        for (checkpoint, full_contents) in checkpoints {
1372            self.cache_full_checkpoint_contents(
1373                checkpoint.sequence_number(),
1374                checkpoint.contents_digest,
1375                full_contents,
1376            );
1377        }
1378        Ok(())
1379    }
1380
1381    /// Whether [`Self::cache_full_checkpoint_contents`] would retain contents
1382    /// for this sequence number, so callers can skip assembling contents that
1383    /// the cache would reject (disabled cache, or an entry the lowest-seq
1384    /// eviction would remove immediately).
1385    pub fn should_cache_full_checkpoint_contents(&self, seq: CheckpointSequenceNumber) -> bool {
1386        self.full_checkpoint_contents_cache.should_cache(seq)
1387    }
1388
1389    /// Caches full checkpoint contents in memory without writing anything to
1390    /// disk, so state-sync peers can be served without reconstructing the
1391    /// contents. `contents_digest` must be the digest of `full_contents`.
1392    ///
1393    /// INVARIANT: The caller must have durably written the matching
1394    /// `checkpoint_content` row (and the contained transactions and
1395    /// effects) first for two reasons:
1396    /// 1. once the cache evicts the entry (or after a restart), readers reconstruct the full
1397    ///    contents from those stores.
1398    /// 2. state-sync treats available contents as proof of that row and skips its own durable
1399    ///    write, and the checkpoint executor panics on a missing row.
1400    ///
1401    /// Best-effort: a serialization failure is logged and the insert skipped;
1402    /// readers fall back to reconstructing the contents from the durable
1403    /// stores.
1404    pub fn cache_full_checkpoint_contents(
1405        &self,
1406        sequence_number: CheckpointSequenceNumber,
1407        contents_digest: CheckpointContentsDigest,
1408        full_contents: FullCheckpointContents,
1409    ) {
1410        let size = match bcs::serialized_size(&full_contents) {
1411            Ok(size) => size,
1412            Err(e) => {
1413                warn!(
1414                    sequence_number,
1415                    "failed to serialize full checkpoint contents for caching: {e}"
1416                );
1417                return;
1418            }
1419        };
1420        self.full_checkpoint_contents_cache.insert(
1421            sequence_number,
1422            contents_digest,
1423            Arc::new(full_contents),
1424            size,
1425        );
1426    }
1427
1428    pub fn get_epoch_last_checkpoint(
1429        &self,
1430        epoch_id: EpochId,
1431    ) -> IotaResult<Option<VerifiedCheckpoint>> {
1432        let seq = self.get_epoch_last_checkpoint_seq_number(epoch_id)?;
1433        let checkpoint = match seq {
1434            Some(seq) => self.get_checkpoint_by_sequence_number(seq)?,
1435            None => None,
1436        };
1437        Ok(checkpoint)
1438    }
1439
1440    /// Sequence number of `epoch_id`'s last checkpoint. Unlike
1441    /// [`Self::get_epoch_last_checkpoint`], this does not require the summary
1442    /// itself to still be present: the underlying map is never pruned.
1443    pub fn get_epoch_last_checkpoint_seq_number(
1444        &self,
1445        epoch_id: EpochId,
1446    ) -> Result<Option<CheckpointSequenceNumber>, TypedStoreError> {
1447        self.tables.epoch_last_checkpoint_map.get(&epoch_id)
1448    }
1449
1450    /// The lowest checkpoint whose superseded object versions this node still
1451    /// holds, given the epoch of its oldest historic-object bucket: that
1452    /// epoch's first checkpoint. When there is no bucket, or that checkpoint
1453    /// is unknown, returns one past the highest executed checkpoint.
1454    pub fn lowest_checkpoint_with_retained_objects(
1455        &self,
1456        earliest_bucket_epoch: Option<EpochId>,
1457    ) -> Result<CheckpointSequenceNumber, TypedStoreError> {
1458        let lowest = match earliest_bucket_epoch {
1459            Some(0) => Some(0),
1460            Some(epoch) => self
1461                .get_epoch_last_checkpoint_seq_number(epoch - 1)?
1462                .map(|seq| seq + 1),
1463            None => None,
1464        };
1465        match lowest {
1466            Some(lowest) => Ok(lowest),
1467            None => Ok(self
1468                .get_highest_executed_checkpoint_seq_number()?
1469                .map(|seq| seq + 1)
1470                .unwrap_or(0)),
1471        }
1472    }
1473
1474    pub fn insert_epoch_last_checkpoint(
1475        &self,
1476        epoch_id: EpochId,
1477        checkpoint: &VerifiedCheckpoint,
1478    ) -> IotaResult {
1479        self.tables
1480            .epoch_last_checkpoint_map
1481            .insert(&epoch_id, &checkpoint.sequence_number())?;
1482        self.epoch_last_checkpoint_notify_read
1483            .notify(&epoch_id, &checkpoint.sequence_number());
1484        Ok(())
1485    }
1486
1487    pub fn get_epoch_state_commitments(
1488        &self,
1489        epoch: EpochId,
1490    ) -> IotaResult<Option<Vec<CheckpointCommitment>>> {
1491        let commitments = self.get_epoch_last_checkpoint(epoch)?.map(|checkpoint| {
1492            checkpoint
1493                .end_of_epoch_data
1494                .as_ref()
1495                .expect("Last checkpoint of epoch expected to have EndOfEpochData")
1496                .epoch_commitments
1497                .clone()
1498        });
1499        Ok(commitments)
1500    }
1501
1502    /// Given the epoch ID, and the last checkpoint of the epoch, derive a few
1503    /// statistics of the epoch.
1504    pub fn get_epoch_stats(
1505        &self,
1506        epoch: EpochId,
1507        last_checkpoint: &CheckpointSummary,
1508    ) -> Option<EpochStats> {
1509        let (first_checkpoint, prev_epoch_network_transactions) = if epoch == 0 {
1510            (0, 0)
1511        } else if let Ok(Some(checkpoint)) = self.get_epoch_last_checkpoint(epoch - 1) {
1512            (
1513                checkpoint.sequence_number + 1,
1514                checkpoint.network_total_transactions,
1515            )
1516        } else {
1517            return None;
1518        };
1519        Some(EpochStats {
1520            checkpoint_count: last_checkpoint.sequence_number - first_checkpoint + 1,
1521            transaction_count: last_checkpoint.network_total_transactions
1522                - prev_epoch_network_transactions,
1523            total_gas_reward: last_checkpoint
1524                .epoch_rolling_gas_cost_summary
1525                .computation_cost,
1526        })
1527    }
1528}
1529
1530#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
1531pub enum CheckpointWatermark {
1532    HighestVerified,
1533    HighestSynced,
1534    HighestExecuted,
1535    HighestPruned,
1536}
1537
1538struct CheckpointStateHasher {
1539    epoch_store: Arc<AuthorityPerEpochStore>,
1540    hasher: Weak<GlobalStateHasher>,
1541    receive_from_builder: mpsc::Receiver<(CheckpointSequenceNumber, Vec<TransactionEffects>)>,
1542}
1543
1544impl CheckpointStateHasher {
1545    fn new(
1546        epoch_store: Arc<AuthorityPerEpochStore>,
1547        hasher: Weak<GlobalStateHasher>,
1548        receive_from_builder: mpsc::Receiver<(CheckpointSequenceNumber, Vec<TransactionEffects>)>,
1549    ) -> Self {
1550        Self {
1551            epoch_store,
1552            hasher,
1553            receive_from_builder,
1554        }
1555    }
1556
1557    async fn run(self) {
1558        let Self {
1559            epoch_store,
1560            hasher,
1561            mut receive_from_builder,
1562        } = self;
1563        while let Some((seq, effects)) = receive_from_builder.recv().await {
1564            let Some(hasher) = hasher.upgrade() else {
1565                info!("GlobalStateHash was dropped, stopping checkpoint accumulation");
1566                break;
1567            };
1568            fail_point_async!("checkpoint-state-hasher-accumulate");
1569            hasher
1570                .accumulate_checkpoint(&effects, seq, &epoch_store)
1571                .expect("epoch ended while accumulating checkpoint");
1572        }
1573    }
1574}
1575
1576/// A checkpoint produced by [`CheckpointBuilder::create_checkpoints`],
1577/// written and cached by [`CheckpointBuilder::write_checkpoints`].
1578struct BuiltCheckpoint {
1579    summary: CheckpointSummary,
1580    contents: CheckpointContents,
1581    /// Full contents for the in-memory cache, assembled only when the cache
1582    /// would retain them.
1583    full_contents: Option<FullCheckpointContents>,
1584}
1585
1586#[derive(Debug)]
1587pub enum CheckpointBuilderError {
1588    ChangeEpochTxAlreadyExecuted,
1589    SystemPackagesMissing,
1590    Retry(anyhow::Error),
1591}
1592
1593impl<IotaError: std::error::Error + Send + Sync + 'static> From<IotaError>
1594    for CheckpointBuilderError
1595{
1596    fn from(e: IotaError) -> Self {
1597        Self::Retry(e.into())
1598    }
1599}
1600
1601pub type CheckpointBuilderResult<T = ()> = Result<T, CheckpointBuilderError>;
1602
1603pub struct CheckpointBuilder {
1604    state: Arc<AuthorityState>,
1605    store: Arc<CheckpointStore>,
1606    epoch_store: Arc<AuthorityPerEpochStore>,
1607    notify: Arc<Notify>,
1608    notify_aggregator: Arc<Notify>,
1609    last_built: watch::Sender<CheckpointSequenceNumber>,
1610    effects_store: Arc<dyn TransactionCacheRead>,
1611    global_state_hasher: Weak<GlobalStateHasher>,
1612    send_to_hasher: mpsc::Sender<(CheckpointSequenceNumber, Vec<TransactionEffects>)>,
1613    output: Box<dyn CheckpointOutput>,
1614    checkpoint_service: Weak<CheckpointService>,
1615    metrics: Arc<CheckpointMetrics>,
1616    max_transactions_per_checkpoint: usize,
1617    max_checkpoint_size_bytes: usize,
1618}
1619
1620pub struct CheckpointAggregator {
1621    store: Arc<CheckpointStore>,
1622    epoch_store: Arc<AuthorityPerEpochStore>,
1623    notify: Arc<Notify>,
1624    current: Option<CheckpointSignatureAggregator>,
1625    output: Box<dyn CertifiedCheckpointOutput>,
1626    state: Arc<AuthorityState>,
1627    metrics: Arc<CheckpointMetrics>,
1628}
1629
1630// This holds information to aggregate signatures for one checkpoint
1631pub struct CheckpointSignatureAggregator {
1632    next_index: u64,
1633    summary: CheckpointSummary,
1634    digest: CheckpointDigest,
1635    /// Aggregates voting stake for each signed checkpoint proposal by authority
1636    signatures_by_digest: MultiStakeAggregator<CheckpointDigest, CheckpointSummary, true>,
1637    /// The first summary other than the local one that each validator signed.
1638    /// Its further ones are ignored, so the number of summaries aggregated
1639    /// stays within the committee size.
1640    other_digest_by_signer: HashMap<AuthorityName, CheckpointDigest>,
1641    /// Whether this aggregator already reported a split brain.
1642    split_brain_reported: bool,
1643    /// The other summary that already reached a quorum, if any.
1644    remote_fork_digest: Option<CheckpointDigest>,
1645    store: Arc<CheckpointStore>,
1646    state: Arc<AuthorityState>,
1647    metrics: Arc<CheckpointMetrics>,
1648}
1649
1650impl CheckpointBuilder {
1651    fn new(
1652        state: Arc<AuthorityState>,
1653        store: Arc<CheckpointStore>,
1654        epoch_store: Arc<AuthorityPerEpochStore>,
1655        notify: Arc<Notify>,
1656        effects_store: Arc<dyn TransactionCacheRead>,
1657        // for synchronous accumulation of end-of-epoch checkpoint
1658        global_state_hasher: Weak<GlobalStateHasher>,
1659        // for asynchronous/concurrent accumulation of regular checkpoints
1660        send_to_hasher: mpsc::Sender<(CheckpointSequenceNumber, Vec<TransactionEffects>)>,
1661        output: Box<dyn CheckpointOutput>,
1662        checkpoint_service: Weak<CheckpointService>,
1663        notify_aggregator: Arc<Notify>,
1664        last_built: watch::Sender<CheckpointSequenceNumber>,
1665        metrics: Arc<CheckpointMetrics>,
1666        max_transactions_per_checkpoint: usize,
1667        max_checkpoint_size_bytes: usize,
1668    ) -> Self {
1669        Self {
1670            state,
1671            store,
1672            epoch_store,
1673            notify,
1674            effects_store,
1675            global_state_hasher,
1676            send_to_hasher,
1677            output,
1678            checkpoint_service,
1679            notify_aggregator,
1680            last_built,
1681            metrics,
1682            max_transactions_per_checkpoint,
1683            max_checkpoint_size_bytes,
1684        }
1685    }
1686
1687    /// This function first waits for ConsensusCommitHandler to finish
1688    /// reprocessing commits that have been processed before the last
1689    /// restart, if consensus_replay_waiter is supplied. Then it starts
1690    /// building checkpoints in a loop.
1691    ///
1692    /// It is optional to pass in consensus_replay_waiter, to make it easier to
1693    /// attribute if slow recovery of previously built checkpoints is due to
1694    /// consensus replay or checkpoint building.
1695    ///
1696    /// Stops once this node executes downloaded checkpoints for the rest of
1697    /// the epoch, also in the middle of building, so it signs nothing more.
1698    async fn run(self, consensus_replay_waiter: Option<ReplayWaiter>) {
1699        let epoch_store = self.epoch_store.clone();
1700        tokio::select! {
1701            _ = epoch_store.wait_for_synced_checkpoint_execution() => {
1702                info!("CheckpointBuilder stopping: executing synced checkpoints for the rest of the epoch");
1703            }
1704            _ = self.build_until_stopped(consensus_replay_waiter) => {}
1705        }
1706        epoch_store.clear_user_signatures_for_checkpoints();
1707    }
1708
1709    async fn build_until_stopped(mut self, consensus_replay_waiter: Option<ReplayWaiter>) {
1710        if let Some(replay_waiter) = consensus_replay_waiter {
1711            info!("Waiting for consensus commits to replay ...");
1712            replay_waiter.wait_for_replay().await;
1713            info!("Consensus commits finished replaying");
1714        }
1715        info!("Starting CheckpointBuilder");
1716        loop {
1717            match self.maybe_build_checkpoints().await {
1718                Ok(()) => {}
1719                err @ Err(
1720                    CheckpointBuilderError::ChangeEpochTxAlreadyExecuted
1721                    | CheckpointBuilderError::SystemPackagesMissing,
1722                ) => {
1723                    info!("CheckpointBuilder stopping: {:?}", err);
1724                    return;
1725                }
1726                Err(CheckpointBuilderError::Retry(inner)) => {
1727                    let msg = format!("{inner:?}");
1728                    debug_fatal!("Error while making checkpoint, will retry in 1s: {}", msg);
1729                    tokio::time::sleep(Duration::from_secs(1)).await;
1730                    self.metrics.checkpoint_errors.inc();
1731                    continue;
1732                }
1733            }
1734
1735            self.notify.notified().await;
1736        }
1737    }
1738
1739    async fn maybe_build_checkpoints(&mut self) -> CheckpointBuilderResult {
1740        let _scope = monitored_scope("BuildCheckpoints");
1741
1742        // Collect info about the most recently built checkpoint.
1743        let summary = self
1744            .epoch_store
1745            .last_built_checkpoint_builder_summary()
1746            .expect("epoch should not have ended");
1747        let mut last_height = summary.as_ref().and_then(|s| s.checkpoint_height);
1748        let mut last_timestamp = summary.as_ref().map(|s| s.summary.timestamp_ms);
1749        let mut last_seq = summary.map(|s| s.summary.sequence_number);
1750
1751        let min_checkpoint_interval_ms = self
1752            .epoch_store
1753            .protocol_config()
1754            .min_checkpoint_interval_ms_as_option()
1755            .unwrap_or_default();
1756        // When set, the interval may additionally be amortized over this many
1757        // recent checkpoints of the current epoch.
1758        let checkpoint_rate_window_size = self
1759            .epoch_store
1760            .protocol_config()
1761            .checkpoint_rate_window_size_as_option();
1762        let mut grouped_pending_checkpoints = Vec::new();
1763        let mut checkpoints_iter = self
1764            .epoch_store
1765            .get_pending_checkpoints(last_height)
1766            .expect("unexpected epoch store error")
1767            .into_iter()
1768            .peekable();
1769        while let Some((height, pending)) = checkpoints_iter.next() {
1770            let current_timestamp = pending.details().timestamp_ms;
1771            // Strict interval against the immediately preceding checkpoint.
1772            let adjacent_interval_elapsed = match last_timestamp {
1773                Some(last_timestamp) => {
1774                    current_timestamp >= last_timestamp + min_checkpoint_interval_ms
1775                }
1776                None => true,
1777            };
1778            // Windowed arm: also allow building once the checkpoint `window`
1779            // back is at least `window * interval` older. This recycles the
1780            // slack the strict arm loses to discrete commit timestamps,
1781            // holding the sustained rate at the ceiling, while the strict arm
1782            // keeps every quiet gap — and thus checkpoint sizes — within one
1783            // interval. Only checkpoints built in the current epoch are
1784            // consulted: every validator builds all of them, so the look-back
1785            // resolves identically everywhere and the gate stays
1786            // deterministic. Until the window fills (epoch start, chain
1787            // genesis) the arm is inert.
1788            let interval_elapsed = adjacent_interval_elapsed
1789                || checkpoint_rate_window_size.is_some_and(|window| {
1790                    last_seq
1791                        .and_then(|seq| (seq + 1).checked_sub(window))
1792                        .and_then(|window_start_seq| {
1793                            self.epoch_store
1794                                .get_built_checkpoint_summary(window_start_seq)
1795                                .expect("epoch store should not error reading a built checkpoint summary")
1796                        })
1797                        .is_some_and(|window_start| {
1798                            current_timestamp
1799                                >= window_start.timestamp_ms + window * min_checkpoint_interval_ms
1800                        })
1801                });
1802            // Group PendingCheckpoints until:
1803            // - the minimum interval has elapsed ...
1804            let can_build = interval_elapsed
1805                // - or, next PendingCheckpoint is last-of-epoch (since the last-of-epoch checkpoint
1806                //   should be written separately) ...
1807                || checkpoints_iter
1808                .peek()
1809                .is_some_and(|(_, next_pending)| next_pending.details().last_of_epoch)
1810                // - or, we have reached end of epoch.
1811                || pending.details().last_of_epoch;
1812            grouped_pending_checkpoints.push(pending);
1813            if !can_build {
1814                debug!(
1815                    checkpoint_commit_height = height,
1816                    ?last_timestamp,
1817                    ?current_timestamp,
1818                    "waiting for more PendingCheckpoints: minimum interval not yet elapsed"
1819                );
1820                continue;
1821            }
1822
1823            // Min interval has elapsed, we can now coalesce and build a checkpoint.
1824            last_height = Some(height);
1825            last_timestamp = Some(current_timestamp);
1826            let commits_in_checkpoint = grouped_pending_checkpoints.len();
1827            debug!(
1828                checkpoint_commit_height_from = grouped_pending_checkpoints
1829                    .first()
1830                    .unwrap()
1831                    .details()
1832                    .checkpoint_height,
1833                checkpoint_commit_height_to = last_height,
1834                "Making checkpoint with commit height range"
1835            );
1836
1837            let seq = self
1838                .make_checkpoint(std::mem::take(&mut grouped_pending_checkpoints))
1839                .await?;
1840
1841            // Count only on success; a failed build retries the same
1842            // group and would otherwise double-count it.
1843            self.metrics
1844                .commits_per_checkpoint
1845                .observe(commits_in_checkpoint as f64);
1846            // Advance the window anchor to the highest checkpoint just
1847            // built (a single call may emit several when chunked).
1848            last_seq = Some(seq);
1849            self.last_built.send_if_modified(|cur| {
1850                // when rebuilding checkpoints at startup, seq can be for an old checkpoint
1851                if seq > *cur {
1852                    *cur = seq;
1853                    true
1854                } else {
1855                    false
1856                }
1857            });
1858
1859            // Ensure that the task can be cancelled at end of epoch, even if no other await
1860            // yields execution.
1861            tokio::task::yield_now().await;
1862        }
1863        debug!(
1864            "Waiting for more checkpoints from consensus after processing {last_height:?}; {} pending checkpoints left unprocessed until next interval",
1865            grouped_pending_checkpoints.len(),
1866        );
1867
1868        Ok(())
1869    }
1870
1871    #[instrument(level = "debug", skip_all, fields(last_height = pendings.last().unwrap().details().checkpoint_height
1872    ))]
1873    async fn make_checkpoint(
1874        &self,
1875        pendings: Vec<PendingCheckpoint>,
1876    ) -> CheckpointBuilderResult<CheckpointSequenceNumber> {
1877        let _scope = monitored_scope("CheckpointBuilder::make_checkpoint");
1878        let last_details = pendings.last().unwrap().details().clone();
1879
1880        // Stores the transactions that should be included in the checkpoint.
1881        // Transactions will be recorded in the checkpoint in this order.
1882        let highest_executed_sequence = self
1883            .store
1884            .get_highest_executed_checkpoint_seq_number()
1885            .expect("db error")
1886            .unwrap_or(0);
1887
1888        let (poll_count, result) = poll_count(self.resolve_checkpoint_transactions(pendings)).await;
1889        let (sorted_tx_effects_included_in_checkpoint, all_roots) = result?;
1890
1891        let new_checkpoints = self
1892            .create_checkpoints(
1893                sorted_tx_effects_included_in_checkpoint,
1894                &last_details,
1895                &all_roots,
1896            )
1897            .await?;
1898        let highest_sequence = new_checkpoints.last().summary.sequence_number();
1899        if highest_sequence <= highest_executed_sequence && poll_count > 1 {
1900            debug_fatal!(
1901                "resolve_checkpoint_transactions should be instantaneous when executed checkpoint is ahead of checkpoint builder"
1902            );
1903        }
1904
1905        self.write_checkpoints(last_details.checkpoint_height, new_checkpoints)
1906            .await?;
1907        Ok(highest_sequence)
1908    }
1909
1910    // Given the root transactions of the pending checkpoints, resolve the
1911    // transactions that should be included in the checkpoint, and return them in
1912    // the order they should be included in the checkpoint, together with all the
1913    // resolved roots.
1914    #[instrument(level = "debug", skip_all)]
1915    async fn resolve_checkpoint_transactions(
1916        &self,
1917        pending_checkpoints: Vec<PendingCheckpoint>,
1918    ) -> IotaResult<(Vec<TransactionEffects>, HashSet<TransactionDigest>)> {
1919        let _scope = monitored_scope("CheckpointBuilder::resolve_checkpoint_transactions");
1920
1921        // Keeps track of the effects that are already included in the current
1922        // checkpoint. This is used when there are multiple pending checkpoints
1923        // to create a single checkpoint because in such scenarios, dependencies
1924        // of a transaction may in earlier created checkpoints, or in earlier
1925        // pending checkpoints.
1926        let mut effects_in_current_checkpoint = BTreeSet::new();
1927
1928        let mut tx_effects = Vec::new();
1929        let mut tx_roots = HashSet::new();
1930
1931        for pending_checkpoint in pending_checkpoints.into_iter() {
1932            let pending = pending_checkpoint.into_v1();
1933            debug!(
1934                checkpoint_commit_height = pending.details.checkpoint_height,
1935                roots = ?pending.roots,
1936                "Resolving checkpoint transactions for pending checkpoint.",
1937            );
1938
1939            let roots = &pending.roots;
1940
1941            self.metrics
1942                .checkpoint_roots_count
1943                .inc_by(roots.len() as u64);
1944
1945            let root_digests = self
1946                .epoch_store
1947                .notify_read_tx_key_to_digest(roots)
1948                .in_monitored_scope("CheckpointNotifyDigests")
1949                .await?;
1950            let root_effects = self
1951                .effects_store
1952                .try_notify_read_executed_effects(
1953                    CHECKPOINT_BUILDER_NOTIFY_READ_TASK_NAME,
1954                    &root_digests,
1955                )
1956                .in_monitored_scope("CheckpointNotifyRead")
1957                .await?;
1958
1959            let consensus_commit_prologue = {
1960                // If the roots contains consensus commit prologue transaction, we want to
1961                // extract it, and put it to the front of the checkpoint.
1962
1963                let consensus_commit_prologue =
1964                    self.extract_consensus_commit_prologue(&root_digests, &root_effects)?;
1965
1966                // Get the un-included dependencies of the consensus commit prologue. We should
1967                // expect no other dependencies that haven't been included in
1968                // any previous checkpoints.
1969                if let Some((ccp_digest, ccp_effects)) = &consensus_commit_prologue {
1970                    let unsorted_ccp = self.complete_checkpoint_effects(
1971                        vec![ccp_effects.clone()],
1972                        &mut effects_in_current_checkpoint,
1973                    )?;
1974
1975                    // No other dependencies of this consensus commit prologue that haven't been
1976                    // included in any previous checkpoint.
1977                    if unsorted_ccp.len() != 1 {
1978                        fatal!(
1979                            "Expected 1 consensus commit prologue, got {:?}",
1980                            unsorted_ccp
1981                                .iter()
1982                                .map(|e| e.transaction_digest())
1983                                .collect::<Vec<_>>()
1984                        );
1985                    }
1986                    assert_eq!(unsorted_ccp.len(), 1);
1987                    assert_eq!(unsorted_ccp[0].transaction_digest(), ccp_digest);
1988                }
1989                consensus_commit_prologue
1990            };
1991
1992            let unsorted =
1993                self.complete_checkpoint_effects(root_effects, &mut effects_in_current_checkpoint)?;
1994
1995            let _scope = monitored_scope("CheckpointBuilder::causal_sort");
1996            let mut sorted: Vec<TransactionEffects> = Vec::with_capacity(unsorted.len() + 1);
1997            if let Some((_ccp_digest, ccp_effects)) = consensus_commit_prologue {
1998                #[cfg(debug_assertions)]
1999                {
2000                    // When consensus_commit_prologue is extracted, it should not be included in the
2001                    // `unsorted`.
2002                    for tx in unsorted.iter() {
2003                        assert!(tx.transaction_digest() != &_ccp_digest);
2004                    }
2005                }
2006                sorted.push(ccp_effects);
2007            }
2008            sorted.extend(CausalOrder::causal_sort(unsorted));
2009
2010            #[cfg(msim)]
2011            {
2012                // Check consensus commit prologue invariants in sim test.
2013                self.expensive_consensus_commit_prologue_invariants_check(&root_digests, &sorted);
2014            }
2015
2016            tx_effects.extend(sorted);
2017            tx_roots.extend(root_digests);
2018        }
2019
2020        Ok((tx_effects, tx_roots))
2021    }
2022
2023    // This function is used to extract the consensus commit prologue digest and
2024    // effects from the root transactions.
2025    // The consensus commit prologue is expected to be the first transaction in the
2026    // roots.
2027    fn extract_consensus_commit_prologue(
2028        &self,
2029        root_digests: &[TransactionDigest],
2030        root_effects: &[TransactionEffects],
2031    ) -> IotaResult<Option<(TransactionDigest, TransactionEffects)>> {
2032        let _scope = monitored_scope("CheckpointBuilder::extract_consensus_commit_prologue");
2033        if root_digests.is_empty() {
2034            return Ok(None);
2035        }
2036
2037        // Reads the first transaction in the roots, and checks whether it is a
2038        // consensus commit prologue transaction.
2039        // The consensus commit prologue transaction should be the first transaction
2040        // in the roots written by the consensus handler.
2041        let first_tx = self
2042            .state
2043            .get_transaction_cache_reader()
2044            .try_get_transaction_block(&root_digests[0])?
2045            .expect("Transaction block must exist");
2046
2047        Ok(match first_tx.transaction().kind() {
2048            TransactionKind::ConsensusCommitPrologueV1(_) => {
2049                assert_eq!(first_tx.digest(), root_effects[0].transaction_digest());
2050                Some((*first_tx.digest(), root_effects[0].clone()))
2051            }
2052            _ => None,
2053        })
2054    }
2055
2056    /// Writes the new checkpoints to the DB storage and processes them.
2057    #[instrument(level = "debug", skip_all)]
2058    async fn write_checkpoints(
2059        &self,
2060        height: CheckpointHeight,
2061        mut new_checkpoints: NonEmpty<BuiltCheckpoint>,
2062    ) -> IotaResult {
2063        let _scope = monitored_scope("CheckpointBuilder::write_checkpoints");
2064        fail_point_async!("checkpoint-builder-write-summaries");
2065        let mut batch = self.store.tables.locally_computed_checkpoints.batch();
2066        let mut all_tx_digests =
2067            Vec::with_capacity(new_checkpoints.iter().map(|c| c.contents.len()).sum());
2068
2069        // Write the new checkpoints to the DB storage.
2070        for BuiltCheckpoint {
2071            summary, contents, ..
2072        } in &new_checkpoints
2073        {
2074            debug!(
2075                checkpoint_commit_height = height,
2076                checkpoint_seq = summary.sequence_number,
2077                contents_digest = ?contents.digest(),
2078                "writing checkpoint",
2079            );
2080
2081            if let Some(previously_computed_summary) = self
2082                .store
2083                .tables
2084                .locally_computed_checkpoints
2085                .get(&summary.sequence_number)?
2086            {
2087                if previously_computed_summary != *summary {
2088                    // Panic so that we don't send out an equivocating checkpoint sig.
2089                    fatal!(
2090                        "Checkpoint {} was previously built with a different result: {previously_computed_summary:?} vs {summary:?}",
2091                        summary.sequence_number,
2092                    );
2093                }
2094            }
2095
2096            all_tx_digests.extend(contents.iter().map(|digests| digests.transaction));
2097
2098            self.metrics
2099                .transactions_included_in_checkpoint
2100                .inc_by(contents.len() as u64);
2101            let sequence_number = summary.sequence_number;
2102            self.metrics
2103                .last_constructed_checkpoint
2104                .set(sequence_number as i64);
2105
2106            let bucket = self.store.historic_checkpoints.ensure(summary.epoch)?;
2107            batch
2108                .insert_batch_tagged(&bucket.checkpoint_content, [(contents.digest(), contents)])?;
2109
2110            batch.insert_batch(
2111                &self.store.tables.locally_computed_checkpoints,
2112                [(sequence_number, summary)],
2113            )?;
2114        }
2115
2116        batch.write()?;
2117        fail_point!("checkpoint-summaries-written");
2118        if self.epoch_store.protocol_config().enable_pcool_flow() {
2119            self.store
2120                .notify_locally_computed_checkpoints(new_checkpoints.iter().map(|c| &c.summary));
2121        }
2122
2123        // Cache the full contents only now that the checkpoint_content rows
2124        // are durable
2125        for checkpoint in new_checkpoints.iter_mut() {
2126            if let Some(full_contents) = checkpoint.full_contents.take() {
2127                self.store.cache_full_checkpoint_contents(
2128                    checkpoint.summary.sequence_number,
2129                    checkpoint.summary.contents_digest,
2130                    full_contents,
2131                );
2132            }
2133        }
2134
2135        let checkpoint_service = self.checkpoint_service.upgrade();
2136        // The consensus handler still delivers our own signatures if the service is
2137        // already gone.
2138        let checkpoint_service: &(dyn CheckpointServiceNotify + Sync) = match &checkpoint_service {
2139            Some(service) => service.as_ref(),
2140            None => &CheckpointServiceNoop {},
2141        };
2142        // Send all checkpoint sigs to consensus. The messages including
2143        // MisbehaviorReports are also sent in this step.
2144        for BuiltCheckpoint {
2145            summary, contents, ..
2146        } in &new_checkpoints
2147        {
2148            self.output
2149                .checkpoint_created(
2150                    summary,
2151                    contents,
2152                    &self.epoch_store,
2153                    &self.store,
2154                    checkpoint_service,
2155                )
2156                .await?;
2157        }
2158
2159        for BuiltCheckpoint {
2160            summary: local_checkpoint,
2161            ..
2162        } in &new_checkpoints
2163        {
2164            if let Some(certified_checkpoint) = self
2165                .store
2166                .tables
2167                .certified_checkpoints
2168                .get(&local_checkpoint.sequence_number())?
2169            {
2170                self.store
2171                    .check_for_checkpoint_fork(local_checkpoint, &certified_checkpoint.into());
2172            }
2173        }
2174
2175        self.notify_aggregator.notify_one();
2176        self.epoch_store.process_constructed_checkpoint(
2177            height,
2178            new_checkpoints.map(|c| (c.summary, c.contents)),
2179        );
2180        Ok(())
2181    }
2182
2183    #[expect(clippy::type_complexity)]
2184    fn split_checkpoint_chunks(
2185        &self,
2186        transactions_effects_and_sizes: Vec<(TransactionEnvelope, TransactionEffects, usize)>,
2187        signatures: Vec<Vec<UserSignature>>,
2188        attestations: Vec<Option<AttestationRecord>>,
2189    ) -> CheckpointBuilderResult<
2190        Vec<
2191            Vec<(
2192                TransactionEnvelope,
2193                TransactionEffects,
2194                Vec<UserSignature>,
2195                Option<AttestationRecord>,
2196            )>,
2197        >,
2198    > {
2199        let _guard = monitored_scope("CheckpointBuilder::split_checkpoint_chunks");
2200        let mut chunks = Vec::new();
2201        let mut chunk = Vec::new();
2202        let mut chunk_size: usize = 0;
2203        for (((transaction, effects, transaction_size), signatures), attestation) in
2204            transactions_effects_and_sizes
2205                .into_iter()
2206                .zip(signatures)
2207                .zip(attestations)
2208        {
2209            // Roll over to a new chunk after either max count or max size is reached.
2210            // The size calculation here is intended to estimate the size of the
2211            // FullCheckpointContents struct. If this code is modified, that struct
2212            // should also be updated accordingly.
2213            let size = transaction_size
2214                + bcs::serialized_size(&effects)?
2215                + bcs::serialized_size(&signatures)?;
2216            if chunk.len() == self.max_transactions_per_checkpoint
2217                || (chunk_size + size) > self.max_checkpoint_size_bytes
2218            {
2219                if chunk.is_empty() {
2220                    // Always allow at least one tx in a checkpoint.
2221                    warn!(
2222                        "Size of single transaction ({size}) exceeds max checkpoint size ({}); allowing excessively large checkpoint to go through.",
2223                        self.max_checkpoint_size_bytes
2224                    );
2225                } else {
2226                    chunks.push(chunk);
2227                    chunk = Vec::new();
2228                    chunk_size = 0;
2229                }
2230            }
2231
2232            chunk.push((transaction, effects, signatures, attestation));
2233            chunk_size += size;
2234        }
2235
2236        if !chunk.is_empty() || chunks.is_empty() {
2237            // We intentionally create an empty checkpoint if there is no content provided
2238            // to make a 'heartbeat' checkpoint.
2239            // Important: if some conditions are added here later, we need to make sure we
2240            // always have at least one chunk if last_pending_of_epoch is set
2241            chunks.push(chunk);
2242            // Note: empty checkpoints are ok - they shouldn't happen at all on
2243            // a network with even modest load. Even if they do
2244            // happen, it is still useful as it allows fullnodes to
2245            // distinguish between "no transactions have happened" and "i am not
2246            // receiving new checkpoints".
2247        }
2248        Ok(chunks)
2249    }
2250
2251    /// Creates checkpoints using the provided transaction effects and pending
2252    /// checkpoint information.
2253    fn load_last_built_checkpoint_summary(
2254        epoch_store: &AuthorityPerEpochStore,
2255        store: &CheckpointStore,
2256    ) -> IotaResult<Option<(CheckpointSequenceNumber, CheckpointSummary)>> {
2257        let mut last_checkpoint = epoch_store.last_built_checkpoint_summary()?;
2258        if last_checkpoint.is_none() {
2259            let epoch = epoch_store.epoch();
2260            if epoch > 0 {
2261                let previous_epoch = epoch - 1;
2262                let last_verified = store.get_epoch_last_checkpoint(previous_epoch)?;
2263                last_checkpoint = last_verified.map(VerifiedCheckpoint::into_summary_and_sequence);
2264                if let Some((ref seq, _)) = last_checkpoint {
2265                    debug!(
2266                        "No checkpoints in builder DB, taking checkpoint from previous epoch with sequence {seq}"
2267                    );
2268                } else {
2269                    // This is some serious bug with when CheckpointBuilder started so surfacing it
2270                    // via panic
2271                    panic!("Can not find last checkpoint for previous epoch {previous_epoch}");
2272                }
2273            }
2274        }
2275        Ok(last_checkpoint)
2276    }
2277
2278    #[instrument(level = "debug", skip_all)]
2279    async fn create_checkpoints(
2280        &self,
2281        all_effects: Vec<TransactionEffects>,
2282        details: &PendingCheckpointInfo,
2283        all_roots: &HashSet<TransactionDigest>,
2284    ) -> CheckpointBuilderResult<NonEmpty<BuiltCheckpoint>> {
2285        let _scope = monitored_scope("CheckpointBuilder::create_checkpoints");
2286
2287        let total = all_effects.len();
2288        let mut last_checkpoint =
2289            Self::load_last_built_checkpoint_summary(&self.epoch_store, &self.store)?;
2290        let last_checkpoint_seq = last_checkpoint.as_ref().map(|(seq, _)| *seq);
2291        debug!(
2292            checkpoint_commit_height = details.checkpoint_height,
2293            next_checkpoint_seq = last_checkpoint_seq.unwrap_or_default() + 1,
2294            checkpoint_timestamp = details.timestamp_ms,
2295            "Creating checkpoint(s) for {} transactions",
2296            all_effects.len(),
2297        );
2298
2299        let all_digests: Vec<_> = all_effects
2300            .iter()
2301            .map(|effect| *effect.transaction_digest())
2302            .collect();
2303        let transactions_and_sizes = self
2304            .state
2305            .get_transaction_cache_reader()
2306            .try_get_transactions_and_serialized_sizes(&all_digests)?;
2307        // Only attested transactions carry a verdict, and only the attestation
2308        // flag lets any be attested: without it there is nothing to fetch. The
2309        // records are written in the same batch as the effects, so present for
2310        // every executed digest.
2311        let all_attestations = if self
2312            .epoch_store
2313            .protocol_config()
2314            .enable_validator_attestation()
2315        {
2316            self.state
2317                .get_transaction_cache_reader()
2318                .try_multi_get_attestation_records_in_epoch(
2319                    self.epoch_store.epoch(),
2320                    &all_digests,
2321                )?
2322        } else {
2323            vec![None; all_digests.len()]
2324        };
2325        let mut all_effects_and_transaction_sizes = Vec::with_capacity(all_effects.len());
2326        let mut transactions = Vec::with_capacity(all_effects.len());
2327        let mut transaction_keys = Vec::with_capacity(all_effects.len());
2328        let mut randomness_rounds = BTreeMap::new();
2329        {
2330            let _guard = monitored_scope("CheckpointBuilder::wait_for_transactions_sequenced");
2331            debug!(
2332                ?last_checkpoint_seq,
2333                "Waiting for {:?} certificates to appear in consensus",
2334                all_effects.len()
2335            );
2336
2337            for (effects, transaction_and_size) in all_effects
2338                .into_iter()
2339                .zip(transactions_and_sizes.into_iter())
2340            {
2341                let (transaction, size) = transaction_and_size
2342                    .unwrap_or_else(|| panic!("Could not find executed transaction {effects:?}"));
2343                match transaction.inner().transaction().kind() {
2344                    #[allow(deprecated)]
2345                    TransactionKind::ConsensusCommitPrologueV1(_)
2346                    | TransactionKind::AuthenticatorStateUpdateV1Deprecated => {
2347                        // ConsensusCommitPrologue is guaranteed to be
2348                        // processed before we reach here.
2349                        //
2350                        // Deprecated: Authenticator state (JWK) is deprecated
2351                        // and was never enabled.
2352                        // These transaction kinds are retained
2353                        // only for BCS enum variant compatibility.
2354                    }
2355                    TransactionKind::RandomnessStateUpdate(rsu) => {
2356                        randomness_rounds
2357                            .insert(*effects.transaction_digest(), rsu.randomness_round);
2358                    }
2359                    _ => {
2360                        // Only transactions that are not roots should be included in the call to
2361                        // `consensus_messages_processed_notify`. roots come directly from the
2362                        // consensus commit and so are known to be processed
2363                        // already.
2364                        let digest = *effects.transaction_digest();
2365                        if !all_roots.contains(&digest) {
2366                            // In P-COOL flow, user transactions are submitted as
2367                            // UserTransaction, not as Certificate.
2368                            let key = if self.epoch_store.protocol_config().enable_pcool_flow() {
2369                                ConsensusTransactionKey::UserTransaction(digest)
2370                            } else {
2371                                ConsensusTransactionKey::Certificate(digest)
2372                            };
2373                            transaction_keys.push(SequencedConsensusTransactionKey::External(key));
2374                        }
2375                    }
2376                }
2377                transactions.push(transaction);
2378                all_effects_and_transaction_sizes.push((effects, size));
2379            }
2380
2381            self.epoch_store
2382                .consensus_messages_processed_notify(transaction_keys)
2383                .await?;
2384        }
2385
2386        let signatures = self
2387            .epoch_store
2388            .user_signatures_for_checkpoint(&transactions, &all_digests)?;
2389        debug!(
2390            ?last_checkpoint_seq,
2391            "Received {} checkpoint user signatures from consensus",
2392            signatures.len()
2393        );
2394
2395        let transactions_effects_and_sizes = transactions
2396            .into_iter()
2397            .zip(all_effects_and_transaction_sizes)
2398            .map(|(transaction, (effects, size))| (transaction.into_inner(), effects, size))
2399            .collect();
2400        let chunks = self.split_checkpoint_chunks(
2401            transactions_effects_and_sizes,
2402            signatures,
2403            all_attestations,
2404        )?;
2405        let chunks_count = chunks.len();
2406
2407        let mut checkpoints = Vec::with_capacity(chunks_count);
2408        debug!(
2409            ?last_checkpoint_seq,
2410            "Creating {} checkpoints with {} transactions", chunks_count, total,
2411        );
2412
2413        let epoch = self.epoch_store.epoch();
2414        for (index, chunk) in chunks.into_iter().enumerate() {
2415            let first_checkpoint_of_epoch = index == 0
2416                && last_checkpoint
2417                    .as_ref()
2418                    .map(|(_, c)| c.epoch != epoch)
2419                    .unwrap_or(true);
2420            if first_checkpoint_of_epoch {
2421                self.epoch_store
2422                    .record_epoch_first_checkpoint_creation_time_metric();
2423            }
2424            let last_checkpoint_of_epoch = details.last_of_epoch && index == chunks_count - 1;
2425
2426            let sequence_number = last_checkpoint
2427                .as_ref()
2428                .map(|(_, c)| c.sequence_number + 1)
2429                .unwrap_or_default();
2430            let mut timestamp_ms = details.timestamp_ms;
2431            if let Some((_, last_checkpoint)) = &last_checkpoint {
2432                if last_checkpoint.timestamp_ms > timestamp_ms {
2433                    // The first consensus commit of an epoch can have zero timestamp.
2434                    debug!(
2435                        "Decrease of checkpoint timestamp, possibly due to epoch change. Sequence: {}, previous: {}, current: {}",
2436                        sequence_number, last_checkpoint.timestamp_ms, timestamp_ms,
2437                    );
2438                    timestamp_ms = last_checkpoint.timestamp_ms;
2439                }
2440            }
2441
2442            let (chunk_transactions, mut effects, mut signatures, mut attestations): (
2443                Vec<_>,
2444                Vec<_>,
2445                Vec<_>,
2446                Vec<_>,
2447            ) = chunk.into_iter().multiunzip();
2448            let epoch_rolling_gas_cost_summary =
2449                self.get_epoch_total_gas_cost(last_checkpoint.as_ref().map(|(_, c)| c), &effects);
2450            let attestation_totals = self.get_epoch_attestation_totals(
2451                last_checkpoint.as_ref().map(|(_, c)| c),
2452                &attestations,
2453            );
2454
2455            let end_of_epoch_data = if last_checkpoint_of_epoch {
2456                let mut scores: Vec<u64> = if self
2457                    .epoch_store
2458                    .protocol_config()
2459                    .pass_calculated_validator_scores_to_advance_epoch()
2460                {
2461                    self.epoch_store.scoreboard.scores_for_change_epoch()
2462                } else {
2463                    // Give everyone in the committee the max score
2464                    vec![MAX_SCORE; self.epoch_store.committee().num_members()]
2465                };
2466                if let Some(max_refuted_units_squared) = self
2467                    .epoch_store
2468                    .protocol_config()
2469                    .attestation_max_refuted_units_squared_as_option()
2470                {
2471                    apply_fault_penalties(
2472                        &mut scores,
2473                        &attestation_totals,
2474                        max_refuted_units_squared,
2475                    );
2476                }
2477
2478                let (system_state_obj, system_epoch_info_event) = self
2479                    .augment_epoch_last_checkpoint(
2480                        &epoch_rolling_gas_cost_summary,
2481                        timestamp_ms,
2482                        &mut effects,
2483                        &mut signatures,
2484                        &mut attestations,
2485                        sequence_number,
2486                        scores,
2487                    )
2488                    .await?;
2489
2490                // The system epoch info event can be `None` in case if the `advance_epoch`
2491                // Move function call failed and was executed in the safe mode.
2492                // In this case, the tokens supply should be unchanged.
2493                //
2494                // SAFETY: The number of minted and burnt tokens easily fit into an i64 and due
2495                // to those small numbers, no overflows will occur during conversion or
2496                // subtraction.
2497                let epoch_supply_change =
2498                    system_epoch_info_event.map_or(0, |event| event.supply_change());
2499
2500                let committee = system_state_obj
2501                    .get_current_epoch_committee()
2502                    .committee()
2503                    .clone();
2504
2505                // This must happen after the call to augment_epoch_last_checkpoint,
2506                // otherwise we will not capture the change_epoch tx.
2507                let root_state_digest = {
2508                    let state_acc = self
2509                        .global_state_hasher
2510                        .upgrade()
2511                        .expect("No checkpoints should be getting built after local configuration");
2512                    let acc = state_acc.accumulate_checkpoint(
2513                        &effects,
2514                        sequence_number,
2515                        &self.epoch_store,
2516                    )?;
2517
2518                    state_acc
2519                        .wait_for_previous_running_root(&self.epoch_store, sequence_number)
2520                        .await?;
2521
2522                    state_acc.accumulate_running_root(
2523                        &self.epoch_store,
2524                        sequence_number,
2525                        Some(acc),
2526                    )?;
2527                    state_acc
2528                        .digest_epoch(self.epoch_store.clone(), sequence_number)
2529                        .await?
2530                };
2531                self.metrics.highest_accumulated_epoch.set(epoch as i64);
2532                info!("Epoch {epoch} root state hash digest: {root_state_digest:?}");
2533
2534                let epoch_commitments = vec![CheckpointCommitment::EcmhLiveObjectSet {
2535                    digest: root_state_digest.digest,
2536                }];
2537
2538                Some(EndOfEpochData {
2539                    next_epoch_committee: committee.committee_members(),
2540                    next_epoch_protocol_version: system_state_obj.protocol_version(),
2541                    epoch_commitments,
2542                    epoch_supply_change,
2543                })
2544            } else {
2545                self.send_to_hasher
2546                    .send((sequence_number, effects.clone()))
2547                    .await?;
2548                None
2549            };
2550            let contents = CheckpointContents::new_with_digests_and_signatures(
2551                effects.iter().map(TransactionEffects::execution_digests),
2552                signatures,
2553            );
2554
2555            let num_txns = contents.len() as u64;
2556
2557            let network_total_transactions = last_checkpoint
2558                .as_ref()
2559                .map(|(_, c)| c.network_total_transactions + num_txns)
2560                .unwrap_or(num_txns);
2561
2562            let previous_digest = last_checkpoint.as_ref().map(|(_, c)| c.digest());
2563
2564            let matching_randomness_rounds: Vec<_> = effects
2565                .iter()
2566                .filter_map(|e| randomness_rounds.get(e.transaction_digest()))
2567                .copied()
2568                .collect();
2569
2570            let summary = CheckpointSummary::new_with_protocol_config(
2571                self.epoch_store.protocol_config(),
2572                epoch,
2573                sequence_number,
2574                network_total_transactions,
2575                &contents,
2576                previous_digest,
2577                epoch_rolling_gas_cost_summary,
2578                end_of_epoch_data,
2579                timestamp_ms,
2580                matching_randomness_rounds,
2581                AttestationEntry::from_records(&attestations),
2582                attestation_totals,
2583            );
2584            summary.report_checkpoint_age(&self.metrics.last_created_checkpoint_age);
2585            if last_checkpoint_of_epoch {
2586                info!(
2587                    checkpoint_seq = sequence_number,
2588                    "creating last checkpoint of epoch {}", epoch
2589                );
2590                if let Some(stats) = self.store.get_epoch_stats(epoch, &summary) {
2591                    self.epoch_store
2592                        .report_epoch_metrics_at_last_checkpoint(stats);
2593                }
2594            }
2595
2596            // Assemble the full contents for faster checkpoint propagation to
2597            // peers. End-of-epoch checkpoints carry an appended change-epoch
2598            // transaction not tracked here; the executor caches those via its
2599            // synced path.
2600            let full_contents = (!last_checkpoint_of_epoch
2601                && self
2602                    .store
2603                    .should_cache_full_checkpoint_contents(sequence_number))
2604            .then(|| {
2605                let execution_data = chunk_transactions
2606                    .into_iter()
2607                    .zip(effects.iter().cloned())
2608                    .map(|(transaction, effects)| ExecutionData::new(transaction, effects));
2609                FullCheckpointContents::from_contents_and_local_execution_data(
2610                    contents.clone(),
2611                    execution_data,
2612                )
2613                // `contents` was built from these same transactions and
2614                // effects a few lines above, so the two cannot differ in
2615                // length.
2616                .expect("checkpoint builder pins one signature set per transaction it includes")
2617            });
2618
2619            last_checkpoint = Some((sequence_number, summary.clone()));
2620            checkpoints.push(BuiltCheckpoint {
2621                summary,
2622                contents,
2623                full_contents,
2624            });
2625        }
2626
2627        Ok(NonEmpty::from_vec(checkpoints).expect("at least one checkpoint"))
2628    }
2629
2630    /// The epoch's attestation totals through this checkpoint: the previous
2631    /// summary's totals when it belongs to this epoch, plus this checkpoint's
2632    /// `Refuted` records. Empty without attestation.
2633    ///
2634    /// # Panics
2635    ///
2636    /// If the previous summary's version-specific data does not decode: the
2637    /// builder wrote it itself.
2638    fn get_epoch_attestation_totals(
2639        &self,
2640        last_checkpoint: Option<&CheckpointSummary>,
2641        attestations: &[Option<AttestationRecord>],
2642    ) -> AttestationTotals {
2643        let protocol_config = self.epoch_store.protocol_config();
2644        if !protocol_config.enable_validator_attestation() {
2645            return AttestationTotals::default();
2646        }
2647        last_checkpoint
2648            .filter(|summary| summary.epoch == self.epoch_store.epoch())
2649            .and_then(|summary| {
2650                summary
2651                    .parse_version_specific_data(protocol_config)
2652                    .expect("the builder's own summary decodes")
2653            })
2654            .and_then(|data| data.attestation_totals().cloned())
2655            .unwrap_or_default()
2656            .with_records(attestations)
2657    }
2658
2659    fn get_epoch_total_gas_cost(
2660        &self,
2661        last_checkpoint: Option<&CheckpointSummary>,
2662        cur_checkpoint_effects: &[TransactionEffects],
2663    ) -> GasCostSummary {
2664        let (previous_epoch, previous_gas_costs) = last_checkpoint
2665            .map(|c| (c.epoch, c.epoch_rolling_gas_cost_summary.clone()))
2666            .unwrap_or_default();
2667        let current_gas_costs =
2668            checked::new_gas_cost_summary_from_txn_effects(cur_checkpoint_effects.iter());
2669        if previous_epoch == self.epoch_store.epoch() {
2670            // sum only when we are within the same epoch
2671            GasCostSummary::new(
2672                previous_gas_costs.computation_cost + current_gas_costs.computation_cost,
2673                previous_gas_costs.computation_cost_burned
2674                    + current_gas_costs.computation_cost_burned,
2675                previous_gas_costs.storage_cost + current_gas_costs.storage_cost,
2676                previous_gas_costs.storage_rebate + current_gas_costs.storage_rebate,
2677                previous_gas_costs.non_refundable_storage_fee
2678                    + current_gas_costs.non_refundable_storage_fee,
2679            )
2680        } else {
2681            current_gas_costs
2682        }
2683    }
2684
2685    /// Augments the last checkpoint of the epoch by creating and executing an
2686    /// advance epoch transaction.
2687    #[instrument(level = "error", skip_all)]
2688    async fn augment_epoch_last_checkpoint(
2689        &self,
2690        epoch_total_gas_cost: &GasCostSummary,
2691        epoch_start_timestamp_ms: CheckpointTimestamp,
2692        checkpoint_effects: &mut Vec<TransactionEffects>,
2693        signatures: &mut Vec<Vec<UserSignature>>,
2694        attestations: &mut Vec<Option<AttestationRecord>>,
2695        checkpoint: CheckpointSequenceNumber,
2696        scores: Vec<u64>,
2697    ) -> CheckpointBuilderResult<(IotaSystemState, Option<SystemEpochInfoEvent>)> {
2698        let (system_state, system_epoch_info_event, effects) = self
2699            .state
2700            .create_and_execute_advance_epoch_tx(
2701                &self.epoch_store,
2702                epoch_total_gas_cost,
2703                checkpoint,
2704                epoch_start_timestamp_ms,
2705                scores,
2706            )
2707            .await?;
2708        checkpoint_effects.push(effects);
2709        signatures.push(vec![]);
2710        attestations.push(None);
2711        Ok((system_state, system_epoch_info_event))
2712    }
2713
2714    /// For the given roots return complete list of effects to include in
2715    /// checkpoint This list includes the roots and all their dependencies,
2716    /// which are not part of checkpoint already. Note that this function
2717    /// may be called multiple times to construct the checkpoint.
2718    /// `existing_tx_digests_in_checkpoint` is used to track the transactions
2719    /// that are already included in the checkpoint. Txs in `roots` that
2720    /// need to be included in the checkpoint will be added to
2721    /// `existing_tx_digests_in_checkpoint` after the call of this function.
2722    #[instrument(level = "debug", skip_all)]
2723    fn complete_checkpoint_effects(
2724        &self,
2725        mut roots: Vec<TransactionEffects>,
2726        existing_tx_digests_in_checkpoint: &mut BTreeSet<TransactionDigest>,
2727    ) -> IotaResult<Vec<TransactionEffects>> {
2728        let _scope = monitored_scope("CheckpointBuilder::complete_checkpoint_effects");
2729        let mut results = vec![];
2730        let mut seen = HashSet::new();
2731        loop {
2732            let mut pending = HashSet::new();
2733
2734            let transactions_included = self
2735                .epoch_store
2736                .builder_included_transactions_in_checkpoint(
2737                    roots.iter().map(|e| e.transaction_digest()),
2738                )?;
2739
2740            for (effect, tx_included) in roots.into_iter().zip(transactions_included.into_iter()) {
2741                let digest = effect.transaction_digest();
2742                // Unnecessary to read effects of a dependency if the effect is already
2743                // processed.
2744                seen.insert(*digest);
2745
2746                // Skip roots that are already included in the checkpoint.
2747                if existing_tx_digests_in_checkpoint.contains(effect.transaction_digest()) {
2748                    continue;
2749                }
2750
2751                // Skip roots already included in checkpoints or roots from previous epochs
2752                if tx_included || effect.epoch() < self.epoch_store.epoch() {
2753                    continue;
2754                }
2755
2756                let existing_effects = self
2757                    .epoch_store
2758                    .transactions_executed_in_cur_epoch(effect.dependencies())?;
2759
2760                for (dependency, effects_signature_exists) in
2761                    effect.dependencies().iter().zip(existing_effects.iter())
2762                {
2763                    // Skip here if dependency not executed in the current epoch.
2764                    // Note that the existence of an effects signature in the
2765                    // epoch store for the given digest indicates that the transaction
2766                    // was locally executed in the current epoch
2767                    if !effects_signature_exists {
2768                        continue;
2769                    }
2770                    if seen.insert(*dependency) {
2771                        pending.insert(*dependency);
2772                    }
2773                }
2774                results.push(effect);
2775            }
2776            if pending.is_empty() {
2777                break;
2778            }
2779            let pending = pending.into_iter().collect::<Vec<_>>();
2780            let effects = self
2781                .effects_store
2782                .try_multi_get_executed_effects(&pending)?;
2783            let effects = effects
2784                .into_iter()
2785                .zip(pending)
2786                .map(|(opt, digest)| match opt {
2787                    Some(x) => x,
2788                    None => panic!(
2789                        "Can not find effect for transaction {digest}, however transaction that depend on it was already executed"
2790                    ),
2791                })
2792                .collect::<Vec<_>>();
2793            roots = effects;
2794        }
2795
2796        existing_tx_digests_in_checkpoint.extend(results.iter().map(|e| e.transaction_digest()));
2797        Ok(results)
2798    }
2799
2800    // This function is used to check the invariants of the consensus commit
2801    // prologue transactions in the checkpoint in simtest.
2802    #[cfg(msim)]
2803    fn expensive_consensus_commit_prologue_invariants_check(
2804        &self,
2805        root_digests: &[TransactionDigest],
2806        sorted: &[TransactionEffects],
2807    ) {
2808        // Gets all the consensus commit prologue transactions from the roots.
2809        let root_txs = self
2810            .state
2811            .get_transaction_cache_reader()
2812            .multi_get_transaction_blocks(root_digests);
2813        let ccps = root_txs
2814            .iter()
2815            .filter_map(|tx| {
2816                tx.as_ref().filter(|tx| {
2817                    matches!(
2818                        tx.transaction().kind(),
2819                        TransactionKind::ConsensusCommitPrologueV1(_)
2820                    )
2821                })
2822            })
2823            .collect::<Vec<_>>();
2824
2825        // There should be at most one consensus commit prologue transaction in the
2826        // roots.
2827        assert!(ccps.len() <= 1);
2828
2829        // Get all the transactions in the checkpoint.
2830        let txs = self
2831            .state
2832            .get_transaction_cache_reader()
2833            .multi_get_transaction_blocks(
2834                &sorted
2835                    .iter()
2836                    .map(|tx| *tx.transaction_digest())
2837                    .collect::<Vec<_>>(),
2838            );
2839
2840        if ccps.is_empty() {
2841            // If there is no consensus commit prologue transaction in the roots, then there
2842            // should be no consensus commit prologue transaction in the
2843            // checkpoint.
2844            for tx in txs.iter().flatten() {
2845                assert!(!matches!(
2846                    tx.transaction().kind(),
2847                    TransactionKind::ConsensusCommitPrologueV1(_)
2848                ));
2849            }
2850        } else {
2851            // If there is one consensus commit prologue, it must be the first one in the
2852            // checkpoint.
2853            assert!(matches!(
2854                txs[0].as_ref().unwrap().transaction().kind(),
2855                TransactionKind::ConsensusCommitPrologueV1(_)
2856            ));
2857
2858            assert_eq!(ccps[0].digest(), txs[0].as_ref().unwrap().digest());
2859
2860            for tx in txs.iter().skip(1).flatten() {
2861                assert!(!matches!(
2862                    tx.transaction().kind(),
2863                    TransactionKind::ConsensusCommitPrologueV1(_)
2864                ));
2865            }
2866        }
2867    }
2868}
2869
2870impl CheckpointAggregator {
2871    fn new(
2872        tables: Arc<CheckpointStore>,
2873        epoch_store: Arc<AuthorityPerEpochStore>,
2874        notify: Arc<Notify>,
2875        output: Box<dyn CertifiedCheckpointOutput>,
2876        state: Arc<AuthorityState>,
2877        metrics: Arc<CheckpointMetrics>,
2878    ) -> Self {
2879        let current = None;
2880        Self {
2881            store: tables,
2882            epoch_store,
2883            notify,
2884            current,
2885            output,
2886            state,
2887            metrics,
2888        }
2889    }
2890
2891    /// Runs the `CheckpointAggregator` in an asynchronous loop, managing the
2892    /// aggregation of checkpoints.
2893    /// The function ensures continuous aggregation of checkpoints, handling
2894    /// errors and retries gracefully, and allowing for proper shutdown on
2895    /// receiving an exit signal.
2896    async fn run(mut self) {
2897        info!("Starting CheckpointAggregator");
2898        loop {
2899            if let Err(e) = self.run_and_notify().await {
2900                error!(
2901                    "Error while aggregating checkpoint, will retry in 1s: {:?}",
2902                    e
2903                );
2904                self.metrics.checkpoint_errors.inc();
2905                tokio::time::sleep(Duration::from_secs(1)).await;
2906                continue;
2907            }
2908
2909            let _ = timeout(Duration::from_secs(1), self.notify.notified()).await;
2910        }
2911    }
2912
2913    async fn run_and_notify(&mut self) -> IotaResult {
2914        let summaries = self.run_inner()?;
2915        for summary in summaries {
2916            self.output.certified_checkpoint_created(&summary).await?;
2917        }
2918        Ok(())
2919    }
2920
2921    fn run_inner(&mut self) -> IotaResult<Vec<CertifiedCheckpointSummary>> {
2922        let _scope = monitored_scope("CheckpointAggregator");
2923        let mut result = vec![];
2924        'outer: loop {
2925            let next_to_certify = self.next_checkpoint_to_certify()?;
2926            let current = if let Some(current) = &mut self.current {
2927                // It's possible that the checkpoint was already certified by
2928                // the rest of the network and we've already received the
2929                // certified checkpoint via StateSync. In this case, we reset
2930                // the current signature aggregator to the next checkpoint to
2931                // be certified
2932                if current.summary.sequence_number < next_to_certify {
2933                    self.current = None;
2934                    continue;
2935                }
2936                current
2937            } else {
2938                let Some(summary) = self
2939                    .epoch_store
2940                    .get_built_checkpoint_summary(next_to_certify)?
2941                else {
2942                    return Ok(result);
2943                };
2944                self.current = Some(CheckpointSignatureAggregator {
2945                    next_index: 0,
2946                    digest: summary.digest(),
2947                    summary,
2948                    signatures_by_digest: MultiStakeAggregator::new(
2949                        self.epoch_store.committee().clone(),
2950                    ),
2951                    other_digest_by_signer: HashMap::new(),
2952                    split_brain_reported: false,
2953                    remote_fork_digest: None,
2954                    store: self.store.clone(),
2955                    state: self.state.clone(),
2956                    metrics: self.metrics.clone(),
2957                });
2958                self.current.as_mut().unwrap()
2959            };
2960
2961            let epoch_tables = self
2962                .epoch_store
2963                .tables()
2964                .expect("should not run past end of epoch");
2965            let iter = epoch_tables
2966                .pending_checkpoint_signatures
2967                .safe_iter_with_bounds(
2968                    Some((current.summary.sequence_number, current.next_index)),
2969                    None,
2970                );
2971            for item in iter {
2972                let ((seq, index), data) = item?;
2973                if seq != current.summary.sequence_number {
2974                    trace!(
2975                        checkpoint_seq =? current.summary.sequence_number,
2976                        "Not enough checkpoint signatures",
2977                    );
2978                    // No more signatures (yet) for this checkpoint
2979                    return Ok(result);
2980                }
2981                trace!(
2982                    checkpoint_seq = current.summary.sequence_number,
2983                    "Processing signature for checkpoint (digest: {:?}) from {:?}",
2984                    current.summary.digest(),
2985                    data.summary.auth_sig().authority.concise()
2986                );
2987                self.metrics
2988                    .checkpoint_participation
2989                    .with_label_values(&[&format!(
2990                        "{:?}",
2991                        data.summary.auth_sig().authority.concise()
2992                    )])
2993                    .inc();
2994                if let Ok(auth_signature) = current.try_aggregate(data) {
2995                    debug!(
2996                        checkpoint_seq = current.summary.sequence_number,
2997                        "Successfully aggregated signatures for checkpoint (digest: {:?})",
2998                        current.summary.digest(),
2999                    );
3000                    let summary = VerifiedCheckpoint::new_unchecked(
3001                        CertifiedCheckpointSummary::new_from_data_and_sig(
3002                            current.summary.clone(),
3003                            auth_signature,
3004                        ),
3005                    );
3006
3007                    self.store.insert_certified_checkpoint(&summary)?;
3008                    if summary.next_epoch_committee().is_some() {
3009                        fail_point!("certified-end-of-epoch-checkpoint-before-state-sync");
3010                    }
3011                    self.metrics
3012                        .last_certified_checkpoint
3013                        .set(current.summary.sequence_number as i64);
3014                    current
3015                        .summary
3016                        .report_checkpoint_age(&self.metrics.last_certified_checkpoint_age);
3017                    result.push(summary.into_inner());
3018                    self.current = None;
3019                    continue 'outer;
3020                } else {
3021                    current.next_index = index + 1;
3022                }
3023            }
3024            break;
3025        }
3026        Ok(result)
3027    }
3028
3029    fn next_checkpoint_to_certify(&self) -> IotaResult<CheckpointSequenceNumber> {
3030        Ok(self
3031            .store
3032            .tables
3033            .certified_checkpoints
3034            .safe_range_iter_reversed(..)
3035            .next()
3036            .transpose()?
3037            .map(|(seq, _)| seq + 1)
3038            .unwrap_or_default())
3039    }
3040}
3041
3042impl CheckpointSignatureAggregator {
3043    #[expect(clippy::result_unit_err)]
3044    pub fn try_aggregate(
3045        &mut self,
3046        data: CheckpointSignatureMessage,
3047    ) -> Result<AuthorityStrongQuorumSignInfo, ()> {
3048        let their_digest = *data.summary.digest();
3049        let author = data.summary.auth_sig().authority;
3050        // Another signature of an already reported summary would only
3051        // aggregate and verify the quorum again.
3052        if self.remote_fork_digest == Some(their_digest) {
3053            return Err(());
3054        }
3055        // A validator that signs many summaries of one checkpoint must not
3056        // make this node aggregate them all. Its signature of the local
3057        // summary always counts, so it can still help certify. A dropped
3058        // signature leaves its signer counted as having voted, through the
3059        // summary it signed first, so signing again cannot hide a split.
3060        if their_digest != self.digest
3061            && self
3062                .other_digest_by_signer
3063                .get(&author)
3064                .is_some_and(|first| *first != their_digest)
3065        {
3066            self.metrics
3067                .conflicting_checkpoint_signatures
3068                .with_label_values(&[&format!("{:?}", author.concise())])
3069                .inc();
3070            debug!(
3071                checkpoint_seq = self.summary.sequence_number,
3072                "Ignoring checkpoint signature from validator {:?}: it already signed another summary",
3073                author.concise(),
3074            );
3075            return Err(());
3076        }
3077        // The signature stays with the summary its signer signed, so that a
3078        // quorum on another summary than the local one verifies and is found.
3079        let result = self.signatures_by_digest.insert(their_digest, data.summary);
3080        if their_digest != self.digest && !matches!(result, InsertResult::Failed { .. }) {
3081            self.other_digest_by_signer
3082                .entry(author)
3083                .or_insert(their_digest);
3084        }
3085        match result {
3086            // ignore repeated signatures
3087            InsertResult::Failed {
3088                error:
3089                    IotaError::StakeAggregatorRepeatedSigner {
3090                        conflicting_sig: false,
3091                        ..
3092                    },
3093            } => Err(()),
3094            InsertResult::Failed { error } => {
3095                warn!(
3096                    checkpoint_seq = self.summary.sequence_number,
3097                    "Failed to aggregate new signature from validator {:?}: {:?}",
3098                    author.concise(),
3099                    error
3100                );
3101                self.check_for_split_brain();
3102                Err(())
3103            }
3104            InsertResult::QuorumReached(cert) => {
3105                // It is not guaranteed that signature.authority == consensus_cert.author, but
3106                // we do verify the signature so we know that the author signed
3107                // the message at some point.
3108                if their_digest != self.digest {
3109                    self.remote_fork_digest = Some(their_digest);
3110                    self.metrics.remote_checkpoint_forks.inc();
3111                    error!(
3112                        checkpoint_seq = self.summary.sequence_number,
3113                        "A quorum of validators signed checkpoint digest {}, this node has digest {}. Validator {:?} completed the quorum",
3114                        their_digest,
3115                        self.digest,
3116                        author.concise()
3117                    );
3118                    return Err(());
3119                }
3120                Ok(cert)
3121            }
3122            InsertResult::NotEnoughVotes {
3123                bad_votes: _,
3124                bad_authorities: _,
3125            } => {
3126                self.check_for_split_brain();
3127                Err(())
3128            }
3129        }
3130    }
3131
3132    /// Check if there is a split brain condition in checkpoint signature
3133    /// aggregation, defined as any state wherein it is no longer possible
3134    /// to achieve quorum on a checkpoint proposal, irrespective of the
3135    /// outcome of any outstanding votes. Reports it the first time it holds,
3136    /// not again for each further signature.
3137    fn check_for_split_brain(&mut self) {
3138        debug!(
3139            checkpoint_seq = self.summary.sequence_number,
3140            "Checking for split brain condition"
3141        );
3142        if !self.split_brain_reported && self.signatures_by_digest.quorum_unreachable() {
3143            self.split_brain_reported = true;
3144            // TODO: at this point we should immediately halt processing
3145            // of new transaction certificates to avoid building on top of
3146            // forked output
3147            // self.halt_all_execution();
3148
3149            let digests_by_stake_messages = self
3150                .signatures_by_digest
3151                .get_all_unique_values()
3152                .into_iter()
3153                .sorted_by_key(|(_, (_, stake))| -(*stake as i64))
3154                .map(|(digest, (_authorities, total_stake))| {
3155                    format!("{digest} (total stake: {total_stake})")
3156                })
3157                .collect::<Vec<String>>();
3158            debug_fatal!(
3159                "Split brain detected in checkpoint signature aggregation for checkpoint {:?}. Remaining stake: {:?}, Digests by stake: {:?}",
3160                self.summary.sequence_number,
3161                self.signatures_by_digest.uncommitted_stake(),
3162                digests_by_stake_messages,
3163            );
3164            self.metrics.split_brain_checkpoint_forks.inc();
3165
3166            let all_unique_values = self.signatures_by_digest.get_all_unique_values();
3167            let local_summary = self.summary.clone();
3168            let state = self.state.clone();
3169            let tables = self.store.clone();
3170
3171            tokio::spawn(async move {
3172                diagnose_split_brain(all_unique_values, local_summary, state, tables).await;
3173            });
3174        }
3175    }
3176}
3177
3178/// The attestation entries of two summaries when they disagree.
3179fn attestation_entry_differences(
3180    local: &CheckpointSummary,
3181    verified: &CheckpointSummary,
3182) -> Option<(Vec<AttestationEntry>, Vec<AttestationEntry>)> {
3183    let decode = |summary: &CheckpointSummary| {
3184        decode_version_specific_data(summary)
3185            .map(|data| data.attestation_entries().to_vec())
3186            .unwrap_or_default()
3187    };
3188    let (local, verified) = (decode(local), decode(verified));
3189    (local != verified).then_some((local, verified))
3190}
3191
3192/// The attestation totals of two summaries when they disagree.
3193fn attestation_totals_difference(
3194    local: &CheckpointSummary,
3195    verified: &CheckpointSummary,
3196) -> Option<(AttestationTotals, AttestationTotals)> {
3197    let decode = |summary: &CheckpointSummary| {
3198        decode_version_specific_data(summary)
3199            .and_then(|data| data.attestation_totals().cloned())
3200            .unwrap_or_default()
3201    };
3202    let (local, verified) = (decode(local), decode(verified));
3203    (local != verified).then_some((local, verified))
3204}
3205
3206fn decode_version_specific_data(
3207    summary: &CheckpointSummary,
3208) -> Option<iota_types::messages_checkpoint::CheckpointVersionSpecificData> {
3209    bcs::from_bytes(&summary.version_specific_data).ok()
3210}
3211
3212/// Create data dump containing relevant data for diagnosing cause of the
3213/// split brain by querying one disagreeing validator for full checkpoint
3214/// contents. To minimize peer chatter, we only query one validator at random
3215/// from each disagreeing faction, as all honest validators that participated in
3216/// this round may inevitably run the same process.
3217async fn diagnose_split_brain(
3218    all_unique_values: BTreeMap<CheckpointDigest, (Vec<AuthorityName>, StakeUnit)>,
3219    local_summary: CheckpointSummary,
3220    state: Arc<AuthorityState>,
3221    tables: Arc<CheckpointStore>,
3222) {
3223    debug!(
3224        checkpoint_seq = local_summary.sequence_number,
3225        "Running split brain diagnostics..."
3226    );
3227    let time = SystemTime::now();
3228    // collect one random disagreeing validator per differing digest
3229    let digest_to_validator = all_unique_values
3230        .iter()
3231        .filter_map(|(digest, (validators, _))| {
3232            if *digest != local_summary.digest() {
3233                let random_validator = validators.choose(&mut get_rng()).unwrap();
3234                Some((*digest, *random_validator))
3235            } else {
3236                None
3237            }
3238        })
3239        .collect::<HashMap<_, _>>();
3240    if digest_to_validator.is_empty() {
3241        panic!(
3242            "Given split brain condition, there should be at \
3243                least one validator that disagrees with local signature"
3244        );
3245    }
3246
3247    let epoch_store = state.load_epoch_store_one_call_per_task();
3248    let committee = epoch_store
3249        .epoch_start_state()
3250        .get_iota_committee_with_network_metadata();
3251    let network_config = default_iota_network_config();
3252    let network_clients =
3253        make_network_authority_clients_with_network_config(&committee, &network_config);
3254
3255    // Query all disagreeing validators
3256    let response_futures = digest_to_validator
3257        .values()
3258        .cloned()
3259        .map(|validator| {
3260            let client = network_clients
3261                .get(&validator)
3262                .expect("Failed to get network client");
3263            let request = CheckpointRequest {
3264                sequence_number: Some(local_summary.sequence_number),
3265                request_content: true,
3266                certified: false,
3267            };
3268            client.get_checkpoint_v2(request)
3269        })
3270        .collect::<Vec<_>>();
3271
3272    let digest_name_pair = digest_to_validator.iter();
3273    let response_data = futures::future::join_all(response_futures)
3274        .await
3275        .into_iter()
3276        .zip(digest_name_pair)
3277        .filter_map(|(response, (digest, name))| match response {
3278            Ok(response) => match response {
3279                CheckpointResponse {
3280                    checkpoint: Some(CheckpointSummaryResponse::Pending(summary)),
3281                    contents: Some(contents),
3282                } => Some((*name, *digest, summary, contents)),
3283                CheckpointResponse {
3284                    checkpoint: Some(CheckpointSummaryResponse::Certified(_)),
3285                    contents: _,
3286                } => {
3287                    // The reply is a peer's choice, so it must not stop this node.
3288                    error!(
3289                        "Validator {:?} returned a certified checkpoint {:?} for fork diagnostics, expected a pending one",
3290                        name, local_summary.sequence_number
3291                    );
3292                    None
3293                }
3294                CheckpointResponse {
3295                    checkpoint: None,
3296                    contents: _,
3297                } => {
3298                    error!(
3299                        "Summary for checkpoint {:?} not found on validator {:?}",
3300                        local_summary.sequence_number, name
3301                    );
3302                    None
3303                }
3304                CheckpointResponse {
3305                    checkpoint: _,
3306                    contents: None,
3307                } => {
3308                    error!(
3309                        "Contents for checkpoint {:?} not found on validator {:?}",
3310                        local_summary.sequence_number, name
3311                    );
3312                    None
3313                }
3314            },
3315            Err(e) => {
3316                error!(
3317                    "Failed to get checkpoint contents from validator for fork diagnostics: {:?}",
3318                    e
3319                );
3320                None
3321            }
3322        })
3323        .collect::<Vec<_>>();
3324
3325    let local_checkpoint_contents = tables
3326        .get_checkpoint_contents(&local_summary.contents_digest)
3327        .unwrap_or_else(|_| {
3328            panic!(
3329                "Could not find checkpoint contents for digest {:?}",
3330                local_summary.digest()
3331            )
3332        })
3333        .unwrap_or_else(|| {
3334            panic!(
3335                "Could not find local full checkpoint contents for checkpoint {:?}, digest {:?}",
3336                local_summary.sequence_number,
3337                local_summary.digest()
3338            )
3339        });
3340    let local_contents_text = format!("{local_checkpoint_contents:?}");
3341
3342    let local_summary_text = format!("{local_summary:?}");
3343    let local_validator = state.name.concise();
3344    let diff_patches = response_data
3345        .iter()
3346        .map(|(name, other_digest, other_summary, contents)| {
3347            let other_contents_text = format!("{contents:?}");
3348            let other_summary_text = format!("{other_summary:?}");
3349            let (local_transactions, local_effects): (Vec<_>, Vec<_>) = local_checkpoint_contents
3350                .enumerate_transactions(&local_summary)
3351                .map(|(_, exec_digest)| (exec_digest.transaction, exec_digest.effects))
3352                .unzip();
3353            let (other_transactions, other_effects): (Vec<_>, Vec<_>) = contents
3354                .enumerate_transactions(other_summary)
3355                .map(|(_, exec_digest)| (exec_digest.transaction, exec_digest.effects))
3356                .unzip();
3357            let summary_patch = create_patch(&local_summary_text, &other_summary_text);
3358            let contents_patch = create_patch(&local_contents_text, &other_contents_text);
3359            let local_transactions_text = format!("{local_transactions:#?}");
3360            let other_transactions_text = format!("{other_transactions:#?}");
3361            let transactions_patch =
3362                create_patch(&local_transactions_text, &other_transactions_text);
3363            let local_effects_text = format!("{local_effects:#?}");
3364            let other_effects_text = format!("{other_effects:#?}");
3365            let effects_patch = create_patch(&local_effects_text, &other_effects_text);
3366            let seq_number = local_summary.sequence_number;
3367            let local_digest = local_summary.digest();
3368            let other_validator = name.concise();
3369            format!(
3370                "Checkpoint: {seq_number:?}\n\
3371                Local validator (original): {local_validator:?}, digest: {local_digest}\n\
3372                Other validator (modified): {other_validator:?}, digest: {other_digest}\n\n\
3373                Summary Diff: \n{summary_patch}\n\n\
3374                Contents Diff: \n{contents_patch}\n\n\
3375                Transactions Diff: \n{transactions_patch}\n\n\
3376                Effects Diff: \n{effects_patch}",
3377            )
3378        })
3379        .collect::<Vec<_>>()
3380        .join("\n\n\n");
3381
3382    let header = format!(
3383        "Checkpoint Fork Dump - Authority {local_validator:?}: \n\
3384        Datetime: {time:?}"
3385    );
3386    let fork_logs_text = format!("{header}\n\n{diff_patches}\n\n");
3387    let checkpoint_fork_dir = iota_common::tempdir().keep();
3388    let checkpoint_fork_file_path = checkpoint_fork_dir.join(Path::new("checkpoint_fork_dump.txt"));
3389    let mut file = File::create(checkpoint_fork_file_path).unwrap();
3390    write!(file, "{fork_logs_text}").unwrap();
3391    debug!("{}", fork_logs_text);
3392}
3393
3394pub trait CheckpointServiceNotify {
3395    fn notify_checkpoint_signature(
3396        &self,
3397        epoch_store: &AuthorityPerEpochStore,
3398        info: &CheckpointSignatureMessage,
3399    ) -> IotaResult;
3400
3401    fn notify_checkpoint(&self) -> IotaResult;
3402}
3403
3404enum CheckpointServiceState {
3405    Unstarted(
3406        Box<(
3407            CheckpointBuilder,
3408            CheckpointAggregator,
3409            CheckpointStateHasher,
3410        )>,
3411    ),
3412    Started,
3413}
3414
3415impl CheckpointServiceState {
3416    fn take_unstarted(
3417        &mut self,
3418    ) -> (
3419        CheckpointBuilder,
3420        CheckpointAggregator,
3421        CheckpointStateHasher,
3422    ) {
3423        let mut state = CheckpointServiceState::Started;
3424        std::mem::swap(self, &mut state);
3425
3426        match state {
3427            CheckpointServiceState::Unstarted(tup) => (tup.0, tup.1, tup.2),
3428            CheckpointServiceState::Started => panic!("CheckpointServiceState is already started"),
3429        }
3430    }
3431}
3432
3433pub struct CheckpointService {
3434    tables: Arc<CheckpointStore>,
3435    notify_builder: Arc<Notify>,
3436    notify_aggregator: Arc<Notify>,
3437    last_signature_index: Mutex<u64>,
3438    // A notification for the current highest built sequence number.
3439    highest_currently_built_seq_tx: watch::Sender<CheckpointSequenceNumber>,
3440    // The highest sequence number that had already been built at the time CheckpointService
3441    // was constructed
3442    highest_previously_built_seq: CheckpointSequenceNumber,
3443    metrics: Arc<CheckpointMetrics>,
3444    state: Mutex<CheckpointServiceState>,
3445}
3446
3447impl CheckpointService {
3448    /// Spawns the checkpoint service, initializing and starting the checkpoint
3449    /// builder and aggregator tasks.
3450    /// Constructs a new CheckpointService in an un-started state.
3451    pub fn build(
3452        state: Arc<AuthorityState>,
3453        checkpoint_store: Arc<CheckpointStore>,
3454        epoch_store: Arc<AuthorityPerEpochStore>,
3455        effects_store: Arc<dyn TransactionCacheRead>,
3456        global_state_hasher: Weak<GlobalStateHasher>,
3457        checkpoint_output: Box<dyn CheckpointOutput>,
3458        certified_checkpoint_output: Box<dyn CertifiedCheckpointOutput>,
3459        metrics: Arc<CheckpointMetrics>,
3460        max_transactions_per_checkpoint: usize,
3461        max_checkpoint_size_bytes: usize,
3462    ) -> Arc<Self> {
3463        info!(
3464            "Starting checkpoint service with {max_transactions_per_checkpoint} max_transactions_per_checkpoint and {max_checkpoint_size_bytes} max_checkpoint_size_bytes"
3465        );
3466        let notify_builder = Arc::new(Notify::new());
3467        let notify_aggregator = Arc::new(Notify::new());
3468
3469        // We may have built higher checkpoint numbers before restarting.
3470        let highest_previously_built_seq = checkpoint_store
3471            .get_latest_locally_computed_checkpoint()
3472            .expect("failed to get latest locally computed checkpoint")
3473            .map(|s| s.sequence_number)
3474            .unwrap_or(0);
3475
3476        let highest_currently_built_seq =
3477            CheckpointBuilder::load_last_built_checkpoint_summary(&epoch_store, &checkpoint_store)
3478                .expect("epoch should not have ended")
3479                .map(|(seq, _)| seq)
3480                .unwrap_or(0);
3481
3482        let (highest_currently_built_seq_tx, _) = watch::channel(highest_currently_built_seq);
3483
3484        let aggregator = CheckpointAggregator::new(
3485            checkpoint_store.clone(),
3486            epoch_store.clone(),
3487            notify_aggregator.clone(),
3488            certified_checkpoint_output,
3489            state.clone(),
3490            metrics.clone(),
3491        );
3492
3493        let (send_to_hasher, receive_from_builder) = mpsc::channel(16);
3494
3495        let ckpt_state_hasher = CheckpointStateHasher::new(
3496            epoch_store.clone(),
3497            global_state_hasher.clone(),
3498            receive_from_builder,
3499        );
3500
3501        let last_signature_index = epoch_store
3502            .get_last_checkpoint_signature_index()
3503            .expect("should not cross end of epoch");
3504        let last_signature_index = Mutex::new(last_signature_index);
3505
3506        Arc::new_cyclic(|checkpoint_service| {
3507            let builder = CheckpointBuilder::new(
3508                state,
3509                checkpoint_store.clone(),
3510                epoch_store,
3511                notify_builder.clone(),
3512                effects_store,
3513                global_state_hasher,
3514                send_to_hasher,
3515                checkpoint_output,
3516                checkpoint_service.clone(),
3517                notify_aggregator.clone(),
3518                highest_currently_built_seq_tx.clone(),
3519                metrics.clone(),
3520                max_transactions_per_checkpoint,
3521                max_checkpoint_size_bytes,
3522            );
3523
3524            Self {
3525                tables: checkpoint_store,
3526                notify_builder,
3527                notify_aggregator,
3528                last_signature_index,
3529                highest_currently_built_seq_tx,
3530                highest_previously_built_seq,
3531                metrics,
3532                state: Mutex::new(CheckpointServiceState::Unstarted(Box::new((
3533                    builder,
3534                    aggregator,
3535                    ckpt_state_hasher,
3536                )))),
3537            }
3538        })
3539    }
3540
3541    /// Starts the CheckpointService.
3542    ///
3543    /// This function blocks until the CheckpointBuilder re-builds all
3544    /// checkpoints that had been built before the most recent restart. You
3545    /// can think of this as a WAL replay operation. Upon startup, we may
3546    /// have a number of consensus commits and resulting checkpoints that
3547    /// were built but not committed to disk. We want to reprocess the
3548    /// commits and rebuild the checkpoints before starting normal operation.
3549    pub async fn spawn(&self, consensus_replay_waiter: Option<ReplayWaiter>) -> JoinSet<()> {
3550        let mut tasks = JoinSet::new();
3551
3552        let (builder, aggregator, state_hasher) = self.state.lock().take_unstarted();
3553        let (builder_finished_tx, builder_finished_rx) = tokio::sync::oneshot::channel();
3554        tasks.spawn(monitored_future!(async move {
3555            builder.run(consensus_replay_waiter).await;
3556            builder_finished_tx.send(()).ok();
3557        }));
3558        tasks.spawn(monitored_future!(aggregator.run()));
3559        tasks.spawn(monitored_future!(state_hasher.run()));
3560
3561        // If this times out, the validator may still start up. The worst that can
3562        // happen is that we will crash later on instead of immediately. The eventual
3563        // crash would occur because we may be missing transactions that are below the
3564        // highest_synced_checkpoint watermark, which can cause a crash in
3565        // `CheckpointExecutor::extract_randomness_rounds`.
3566        if tokio::time::timeout(Duration::from_secs(120), async move {
3567            tokio::select! {
3568                _ = builder_finished_rx => { debug!("CheckpointBuilder finished"); }
3569                _ = self.wait_for_rebuilt_checkpoints() => (),
3570            }
3571        })
3572        .await
3573        .is_err()
3574        {
3575            debug_fatal!("Timed out waiting for checkpoints to be rebuilt");
3576        }
3577
3578        tasks
3579    }
3580}
3581
3582impl CheckpointService {
3583    /// Waits until all checkpoints had been built before the node restarted
3584    /// are rebuilt. This is required to preserve the invariant that all
3585    /// checkpoints (and their transactions) below the
3586    /// highest_synced_checkpoint watermark are available. Once the
3587    /// checkpoints are constructed, we can be sure that the transactions
3588    /// have also been executed.
3589    pub async fn wait_for_rebuilt_checkpoints(&self) {
3590        let highest_previously_built_seq = self.highest_previously_built_seq;
3591        let mut rx = self.highest_currently_built_seq_tx.subscribe();
3592        let mut highest_currently_built_seq = *rx.borrow_and_update();
3593        info!(
3594            "Waiting for checkpoints to be rebuilt, previously built seq: \
3595            {highest_previously_built_seq}, currently built seq: {highest_currently_built_seq}"
3596        );
3597        loop {
3598            if highest_currently_built_seq >= highest_previously_built_seq {
3599                info!("Checkpoint rebuild complete");
3600                break;
3601            }
3602            rx.changed().await.unwrap();
3603            highest_currently_built_seq = *rx.borrow_and_update();
3604        }
3605    }
3606
3607    #[cfg(test)]
3608    fn write_and_notify_checkpoint_for_testing(
3609        &self,
3610        epoch_store: &AuthorityPerEpochStore,
3611        checkpoint: PendingCheckpoint,
3612    ) -> IotaResult {
3613        use crate::authority::authority_per_epoch_store::consensus_quarantine::ConsensusCommitOutput;
3614
3615        let mut output = ConsensusCommitOutput::new(0, 0);
3616        epoch_store.write_pending_checkpoint(&mut output, &checkpoint)?;
3617        output.set_default_commit_stats_for_testing();
3618        epoch_store.push_consensus_output_for_tests(output);
3619        self.notify_checkpoint()?;
3620        Ok(())
3621    }
3622}
3623
3624impl CheckpointServiceNotify for CheckpointService {
3625    fn notify_checkpoint_signature(
3626        &self,
3627        epoch_store: &AuthorityPerEpochStore,
3628        info: &CheckpointSignatureMessage,
3629    ) -> IotaResult {
3630        let sequence = info.summary.sequence_number;
3631        let signer = info.summary.auth_sig().authority.concise();
3632
3633        if let Some(highest_verified_checkpoint) =
3634            self.tables.get_highest_verified_checkpoint_seq_number()?
3635        {
3636            if sequence <= highest_verified_checkpoint {
3637                trace!(
3638                    checkpoint_seq = sequence,
3639                    "Ignore checkpoint signature from {} - already certified", signer,
3640                );
3641                self.metrics
3642                    .last_ignored_checkpoint_signature_received
3643                    .set(sequence as i64);
3644                return Ok(());
3645            }
3646        }
3647        trace!(
3648            checkpoint_seq = sequence,
3649            "Received checkpoint signature, digest {} from {}",
3650            info.summary.digest(),
3651            signer,
3652        );
3653        self.metrics
3654            .last_received_checkpoint_signatures
3655            .with_label_values(&[&signer.to_string()])
3656            .set(sequence as i64);
3657        // While it can be tempting to make last_signature_index into AtomicU64, this
3658        // won't work We need to make sure we write to `pending_signatures` and
3659        // trigger `notify_aggregator` without race conditions
3660        let mut index = self.last_signature_index.lock();
3661        *index += 1;
3662        epoch_store.insert_checkpoint_signature(sequence, *index, info)?;
3663        self.notify_aggregator.notify_one();
3664        Ok(())
3665    }
3666
3667    fn notify_checkpoint(&self) -> IotaResult {
3668        self.notify_builder.notify_one();
3669        Ok(())
3670    }
3671}
3672
3673#[iota_macros::with_checked_arithmetic]
3674mod checked {
3675    use iota_sdk_types::{GasCostSummary, TransactionEffects};
3676    use iota_types::effects::TransactionEffectsAPI;
3677    use itertools::MultiUnzip;
3678
3679    #[expect(clippy::type_complexity)]
3680    pub fn new_gas_cost_summary_from_txn_effects<'a>(
3681        transactions: impl Iterator<Item = &'a TransactionEffects>,
3682    ) -> GasCostSummary {
3683        let (
3684            storage_costs,
3685            computation_costs,
3686            computation_costs_burned,
3687            storage_rebates,
3688            non_refundable_storage_fee,
3689        ): (Vec<u64>, Vec<u64>, Vec<u64>, Vec<u64>, Vec<u64>) = transactions
3690            .map(|e| {
3691                (
3692                    e.gas_cost_summary().storage_cost,
3693                    e.gas_cost_summary().computation_cost,
3694                    e.gas_cost_summary().computation_cost_burned,
3695                    e.gas_cost_summary().storage_rebate,
3696                    e.gas_cost_summary().non_refundable_storage_fee,
3697                )
3698            })
3699            .multiunzip();
3700
3701        GasCostSummary::new(
3702            computation_costs.iter().sum(),
3703            computation_costs_burned.iter().sum(),
3704            storage_costs.iter().sum(),
3705            storage_rebates.iter().sum(),
3706            non_refundable_storage_fee.iter().sum(),
3707        )
3708    }
3709}
3710/// Discards every notification.
3711pub struct CheckpointServiceNoop {}
3712impl CheckpointServiceNotify for CheckpointServiceNoop {
3713    fn notify_checkpoint_signature(
3714        &self,
3715        _: &AuthorityPerEpochStore,
3716        _: &CheckpointSignatureMessage,
3717    ) -> IotaResult {
3718        Ok(())
3719    }
3720
3721    fn notify_checkpoint(&self) -> IotaResult {
3722        Ok(())
3723    }
3724}
3725
3726pin_project! {
3727    pub struct PollCounter<Fut> {
3728        #[pin]
3729        future: Fut,
3730        count: usize,
3731    }
3732}
3733
3734impl<Fut> PollCounter<Fut> {
3735    pub fn new(future: Fut) -> Self {
3736        Self { future, count: 0 }
3737    }
3738
3739    pub fn count(&self) -> usize {
3740        self.count
3741    }
3742}
3743
3744impl<Fut: Future> Future for PollCounter<Fut> {
3745    type Output = (usize, Fut::Output);
3746
3747    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3748        let this = self.project();
3749        *this.count += 1;
3750        match this.future.poll(cx) {
3751            Poll::Ready(output) => Poll::Ready((*this.count, output)),
3752            Poll::Pending => Poll::Pending,
3753        }
3754    }
3755}
3756
3757fn poll_count<Fut>(future: Fut) -> PollCounter<Fut> {
3758    PollCounter::new(future)
3759}
3760
3761/// A verified checkpoint over `full_contents` with a placeholder signature.
3762#[cfg(test)]
3763pub(crate) fn test_checkpoint_with_contents(
3764    epoch: EpochId,
3765    sequence_number: CheckpointSequenceNumber,
3766    full_contents: &FullCheckpointContents,
3767) -> VerifiedCheckpoint {
3768    let contents = full_contents.checkpoint_contents();
3769    let summary = CheckpointSummary {
3770        epoch,
3771        sequence_number,
3772        network_total_transactions: full_contents.size() as u64,
3773        contents_digest: contents.digest(),
3774        previous_digest: None,
3775        epoch_rolling_gas_cost_summary: GasCostSummary::default(),
3776        end_of_epoch_data: None,
3777        timestamp_ms: 0,
3778        version_specific_data: Vec::new(),
3779        checkpoint_commitments: Vec::new(),
3780    };
3781    let sig = AuthorityStrongQuorumSignInfo {
3782        epoch,
3783        signature: Default::default(),
3784        signers_map: Default::default(),
3785    };
3786    VerifiedCheckpoint::new_unchecked(
3787        iota_types::message_envelope::Envelope::new_from_data_and_sig(summary, sig),
3788    )
3789}
3790
3791#[cfg(test)]
3792mod tests {
3793    use std::{
3794        collections::{BTreeMap, HashMap},
3795        ops::Deref,
3796    };
3797
3798    use fastcrypto::traits::KeyPair as _;
3799    use futures::{FutureExt as _, future::BoxFuture};
3800    use iota_macros::sim_test;
3801    use iota_protocol_config::{Chain, ProtocolConfig, ProtocolVersion};
3802    use iota_sdk_types::{
3803        GenesisObject, Identifier, MovePackage, ObjectData, ObjectId, Owner, TransactionEffects,
3804        TransactionEffectsDigest, TransactionEvents, Version,
3805    };
3806    use iota_types::{
3807        attestation::AttestationVerdict,
3808        effects::{TransactionEffectsAPIForTesting, TransactionEffectsExtForTesting},
3809        messages_checkpoint::SignedCheckpointSummary,
3810        messages_consensus::{ConsensusTransaction, ConsensusTransactionKind},
3811        transaction::VerifiedTransaction,
3812    };
3813    use tokio::sync::mpsc;
3814
3815    use super::*;
3816    use crate::{
3817        authority::test_authority_builder::TestAuthorityBuilder,
3818        consensus_adapter::SubmitToConsensus, epoch::reconfiguration::ReconfigurationInitiator,
3819    };
3820
3821    /// The lowest checkpoint with retained objects starts after the oldest
3822    /// bucket's previous epoch, at genesis for a bucket of epoch 0, and past
3823    /// the highest executed checkpoint when there is no bucket.
3824    #[tokio::test]
3825    async fn the_lowest_checkpoint_with_objects_follows_the_oldest_bucket() {
3826        let store = CheckpointStore::new_for_tests();
3827        store
3828            .insert_epoch_last_checkpoint(0, &crate::test_utils::executed_checkpoint(0, 9))
3829            .unwrap();
3830
3831        let lowest = |earliest_bucket_epoch| {
3832            store
3833                .lowest_checkpoint_with_retained_objects(earliest_bucket_epoch)
3834                .unwrap()
3835        };
3836        assert_eq!(lowest(Some(1)), 10);
3837        assert_eq!(lowest(Some(0)), 0);
3838        assert_eq!(lowest(None), 0);
3839    }
3840
3841    #[tokio::test]
3842    async fn insert_verified_checkpoint_contents_persists_digests_and_caches_full_contents() {
3843        let tempdir = iota_common::tempdir();
3844        let path = tempdir.path();
3845
3846        let full_contents = FullCheckpointContents::random_for_testing();
3847        let checkpoint = test_checkpoint_with_contents(0, 0, &full_contents);
3848        let contents_digest = checkpoint.contents_digest;
3849
3850        {
3851            let store = CheckpointStore::new(path);
3852            store
3853                .insert_verified_checkpoint_contents(
3854                    &checkpoint,
3855                    VerifiedCheckpointContents::new_unchecked(full_contents.clone()),
3856                )
3857                .unwrap();
3858
3859            // Full contents are served from the in-memory cache.
3860            assert_eq!(
3861                store
3862                    .get_full_checkpoint_contents_by_sequence_number(0)
3863                    .unwrap()
3864                    .as_ref(),
3865                &full_contents
3866            );
3867            assert_eq!(
3868                store
3869                    .get_full_checkpoint_contents_by_digest(&contents_digest)
3870                    .unwrap()
3871                    .as_ref(),
3872                &full_contents
3873            );
3874            // The digest-form contents are durable.
3875            assert_eq!(
3876                store
3877                    .get_checkpoint_contents(&contents_digest)
3878                    .unwrap()
3879                    .map(|c| c.digest()),
3880                Some(contents_digest)
3881            );
3882        }
3883
3884        // Reopening drops the in-memory cache, but the digest-form contents
3885        // survive for readers to reconstruct full contents from.
3886        let store = CheckpointStore::new(path);
3887        assert!(
3888            store
3889                .get_full_checkpoint_contents_by_sequence_number(0)
3890                .is_none()
3891        );
3892        assert!(
3893            store
3894                .get_full_checkpoint_contents_by_digest(&contents_digest)
3895                .is_none()
3896        );
3897        assert!(
3898            store
3899                .get_checkpoint_contents(&contents_digest)
3900                .unwrap()
3901                .is_some()
3902        );
3903    }
3904
3905    #[tokio::test]
3906    async fn cache_full_checkpoint_contents_serves_reads_without_disk_writes() {
3907        let store = CheckpointStore::new_for_tests();
3908        let full_contents = FullCheckpointContents::random_for_testing();
3909        let checkpoint = test_checkpoint_with_contents(0, 0, &full_contents);
3910        let contents_digest = checkpoint.contents_digest;
3911
3912        store.cache_full_checkpoint_contents(
3913            checkpoint.sequence_number(),
3914            contents_digest,
3915            full_contents.clone(),
3916        );
3917
3918        assert_eq!(
3919            store
3920                .get_full_checkpoint_contents_by_sequence_number(0)
3921                .unwrap()
3922                .as_ref(),
3923            &full_contents
3924        );
3925        assert_eq!(
3926            store
3927                .get_full_checkpoint_contents_by_digest(&contents_digest)
3928                .unwrap()
3929                .as_ref(),
3930            &full_contents
3931        );
3932        // Cache-only: the digest-form contents row is untouched.
3933        assert!(
3934            store
3935                .get_checkpoint_contents(&contents_digest)
3936                .unwrap()
3937                .is_none()
3938        );
3939    }
3940
3941    // State-sync skips its own durable `checkpoint_content` write when the
3942    // full contents are already available, and the checkpoint executor panics
3943    // on a missing row. So the builder must not serve contents from the cache
3944    // before the row is durable.
3945    #[tokio::test]
3946    async fn builder_caches_full_contents_only_after_durable_contents_write() {
3947        let state = TestAuthorityBuilder::new().build().await;
3948        let epoch_store = state.epoch_store_for_testing();
3949
3950        let tx = VerifiedTransaction::new_genesis_transaction(vec![], vec![]);
3951        let digest = *tx.digest();
3952        let mut effects_map = HashMap::new();
3953        store_executed_tx(&state, &mut effects_map, &tx);
3954        let effects = effects_map[&digest].clone();
3955
3956        let tmp_dir = iota_common::tempdir();
3957        let checkpoint_store = CheckpointStore::new(tmp_dir.path());
3958        // Drive the builder manually instead of spawning it, to observe the
3959        // store between checkpoint creation and the durable batch write.
3960        let service = manual_checkpoint_service(&state, checkpoint_store.clone(), effects_map);
3961        let (builder, _aggregator, _hasher) = service.service.state.lock().take_unstarted();
3962
3963        service
3964            .service
3965            .write_and_notify_checkpoint_for_testing(&epoch_store, p(0, vec![digest], 0))
3966            .unwrap();
3967
3968        let details = PendingCheckpointInfo {
3969            timestamp_ms: 0,
3970            last_of_epoch: false,
3971            checkpoint_height: 0,
3972        };
3973        let new_checkpoints = builder
3974            .create_checkpoints(vec![effects], &details, &HashSet::from([digest]))
3975            .await
3976            .unwrap();
3977        let summary = new_checkpoints.first().summary.clone();
3978
3979        assert!(
3980            checkpoint_store
3981                .get_full_checkpoint_contents_by_sequence_number(summary.sequence_number)
3982                .is_none(),
3983            "full contents must not be served before the checkpoint_content row is durable"
3984        );
3985        assert!(
3986            checkpoint_store
3987                .get_checkpoint_contents(&summary.contents_digest)
3988                .unwrap()
3989                .is_none()
3990        );
3991
3992        builder
3993            .write_checkpoints(details.checkpoint_height, new_checkpoints)
3994            .await
3995            .unwrap();
3996
3997        assert!(
3998            checkpoint_store
3999                .get_checkpoint_contents(&summary.contents_digest)
4000                .unwrap()
4001                .is_some()
4002        );
4003        let cached = checkpoint_store
4004            .get_full_checkpoint_contents_by_sequence_number(summary.sequence_number)
4005            .expect("builder should cache full contents once the row is durable");
4006        assert_eq!(
4007            cached.checkpoint_contents().digest(),
4008            summary.contents_digest
4009        );
4010    }
4011
4012    // A build that fails after `create_checkpoints`, for example while writing
4013    // the checkpoints, leaves the pending checkpoint in place, and the builder
4014    // builds it again on its next round.
4015    #[tokio::test]
4016    async fn builder_rebuilds_pending_checkpoint_after_unwritten_build() {
4017        let state = TestAuthorityBuilder::new().build().await;
4018        let epoch_store = state.epoch_store_for_testing();
4019
4020        let tx = VerifiedTransaction::new_genesis_transaction(vec![], vec![]);
4021        let digest = *tx.digest();
4022        let mut effects_map = HashMap::new();
4023        store_executed_tx(&state, &mut effects_map, &tx);
4024        let effects = effects_map[&digest].clone();
4025
4026        let tmp_dir = iota_common::tempdir();
4027        let checkpoint_store = CheckpointStore::new(tmp_dir.path());
4028        let service = manual_checkpoint_service(&state, checkpoint_store.clone(), effects_map);
4029        let (mut builder, _aggregator, _hasher) = service.service.state.lock().take_unstarted();
4030
4031        service
4032            .service
4033            .write_and_notify_checkpoint_for_testing(&epoch_store, p(0, vec![digest], 0))
4034            .unwrap();
4035
4036        let details = PendingCheckpointInfo {
4037            timestamp_ms: 0,
4038            last_of_epoch: false,
4039            checkpoint_height: 0,
4040        };
4041        let unwritten = builder
4042            .create_checkpoints(vec![effects], &details, &HashSet::from([digest]))
4043            .await
4044            .unwrap();
4045        let expected_summary = unwritten.first().summary.clone();
4046
4047        builder
4048            .maybe_build_checkpoints()
4049            .await
4050            .expect("the rebuild must find the user signatures");
4051
4052        let built = checkpoint_store
4053            .tables
4054            .locally_computed_checkpoints
4055            .get(&expected_summary.sequence_number)
4056            .unwrap()
4057            .expect("the rebuild must write the checkpoint");
4058        assert_eq!(built, expected_summary);
4059        assert!(
4060            epoch_store
4061                .user_signatures_for_checkpoint(&[tx], &[digest])
4062                .is_err(),
4063            "user signatures must be dropped once the checkpoint is built"
4064        );
4065    }
4066
4067    /// The checkpoint builder stops once this node executes synced checkpoints
4068    /// for the rest of the epoch.
4069    #[tokio::test]
4070    pub async fn checkpoint_builder_stops_when_executing_synced_checkpoints() {
4071        let state = TestAuthorityBuilder::new().build().await;
4072        let (output, _result) = mpsc::channel::<(CheckpointContents, CheckpointSummary)>(10);
4073        let (certified_output, _certified_result) = mpsc::channel::<CertifiedCheckpointSummary>(10);
4074        let tmp_dir = iota_common::tempdir();
4075        let epoch_store = state.epoch_store_for_testing();
4076        let global_state_hasher = Arc::new(GlobalStateHasher::new_for_tests(
4077            state.get_global_state_hash_store().clone(),
4078        ));
4079        let checkpoint_service = CheckpointService::build(
4080            state.clone(),
4081            CheckpointStore::new(tmp_dir.path()),
4082            epoch_store.clone(),
4083            Arc::new(HashMap::<TransactionDigest, TransactionEffects>::new()),
4084            Arc::downgrade(&global_state_hasher),
4085            Box::new(output),
4086            Box::new(certified_output),
4087            CheckpointMetrics::new_for_tests(),
4088            3,
4089            100_000,
4090        );
4091        let mut tasks = checkpoint_service.spawn(None).await;
4092        assert!(
4093            tokio::time::timeout(Duration::from_millis(100), tasks.join_next())
4094                .await
4095                .is_err()
4096        );
4097
4098        let tx = VerifiedTransaction::new_genesis_transaction(vec![], vec![]);
4099        let digest = *tx.digest();
4100        epoch_store.test_insert_user_signature(digest, tx.signatures().to_vec());
4101        assert!(
4102            epoch_store
4103                .user_signatures_for_checkpoint(std::slice::from_ref(&tx), &[digest])
4104                .is_ok()
4105        );
4106
4107        epoch_store.start_executing_synced_checkpoints().await;
4108        tokio::time::timeout(Duration::from_secs(5), tasks.join_next())
4109            .await
4110            .expect("the checkpoint builder should stop")
4111            .unwrap()
4112            .unwrap();
4113        assert!(
4114            epoch_store
4115                .user_signatures_for_checkpoint(&[tx], &[digest])
4116                .is_err(),
4117            "user signatures must be dropped once the checkpoint builder stops"
4118        );
4119    }
4120
4121    /// Validator 0 of a committee under the P-COOL flow, with checkpoint 0
4122    /// built and its own signature of it submitted and stored.
4123    struct ValidatorWithBuiltCheckpoint {
4124        network_config: iota_swarm_config::network_config::NetworkConfig,
4125        state: Arc<AuthorityState>,
4126        epoch_store: Arc<AuthorityPerEpochStore>,
4127        checkpoint_store: Arc<CheckpointStore>,
4128        checkpoint_service: Arc<CheckpointService>,
4129        aggregator: CheckpointAggregator,
4130        summary: CheckpointSummary,
4131        /// What the validator submitted to consensus.
4132        submitted: mpsc::Receiver<ConsensusTransaction>,
4133        /// What the service needs for as long as it is used.
4134        _kept_alive: Box<dyn std::any::Any>,
4135    }
4136
4137    /// [`ValidatorWithBuiltCheckpoint`] in a committee of four members.
4138    async fn validator_with_built_checkpoint() -> ValidatorWithBuiltCheckpoint {
4139        validator_with_built_checkpoint_in_committee_of(4).await
4140    }
4141
4142    /// As [`validator_with_built_checkpoint`], in a committee of
4143    /// `committee_size` members.
4144    async fn validator_with_built_checkpoint_in_committee_of(
4145        committee_size: usize,
4146    ) -> ValidatorWithBuiltCheckpoint {
4147        let network_config =
4148            iota_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
4149                .committee_size(std::num::NonZeroUsize::new(committee_size).unwrap())
4150                .build();
4151        let state = TestAuthorityBuilder::new()
4152            .with_network_config(&network_config, 0)
4153            .build()
4154            .await;
4155
4156        let tx = VerifiedTransaction::new_genesis_transaction(vec![], vec![]);
4157        let digest = *tx.digest();
4158        state
4159            .database_for_testing()
4160            .get_historic_ledger()
4161            .ensure(0)
4162            .unwrap()
4163            .transactions
4164            .insert(&digest, tx.serializable_ref())
4165            .unwrap();
4166
4167        let mut effects_map = HashMap::new();
4168        commit_cert_for_test(
4169            &mut effects_map,
4170            state.clone(),
4171            digest,
4172            vec![],
4173            GasCostSummary::new(1, 1, 1, 1, 1),
4174        );
4175        let effects = effects_map[&digest].clone();
4176
4177        let signature = iota_types::crypto::zero_ed25519_signature().into();
4178        state
4179            .epoch_store_for_testing()
4180            .test_insert_user_signature(digest, vec![signature]);
4181
4182        let (submitted_tx, submitted) = mpsc::channel::<ConsensusTransaction>(10);
4183        let output = SubmitCheckpointToConsensus {
4184            sender: submitted_tx,
4185            signer: state.secret.clone(),
4186            authority: state.name,
4187            next_reconfiguration_timestamp_ms: u64::MAX,
4188            metrics: CheckpointMetrics::new_for_tests(),
4189        };
4190        let (certified_output, certified_result) = mpsc::channel::<CertifiedCheckpointSummary>(10);
4191
4192        let tmp_dir = iota_common::tempdir();
4193        let checkpoint_store = CheckpointStore::new(tmp_dir.path());
4194        let epoch_store = state.epoch_store_for_testing().clone();
4195
4196        let global_state_hasher = Arc::new(GlobalStateHasher::new_for_tests(
4197            state.get_global_state_hash_store().clone(),
4198        ));
4199
4200        let checkpoint_service = CheckpointService::build(
4201            state.clone(),
4202            checkpoint_store.clone(),
4203            epoch_store.clone(),
4204            Arc::new(effects_map),
4205            Arc::downgrade(&global_state_hasher),
4206            Box::new(output),
4207            Box::new(certified_output),
4208            CheckpointMetrics::new_for_tests(),
4209            3,
4210            100_000,
4211        );
4212        let (builder, aggregator, hasher) = checkpoint_service.state.lock().take_unstarted();
4213
4214        checkpoint_service
4215            .write_and_notify_checkpoint_for_testing(&epoch_store, p(0, vec![digest], 0))
4216            .unwrap();
4217        let details = PendingCheckpointInfo {
4218            timestamp_ms: 0,
4219            last_of_epoch: false,
4220            checkpoint_height: 0,
4221        };
4222        let new_checkpoints = builder
4223            .create_checkpoints(vec![effects], &details, &HashSet::from([digest]))
4224            .await
4225            .unwrap();
4226        let summary = new_checkpoints.first().summary.clone();
4227        builder
4228            .write_checkpoints(details.checkpoint_height, new_checkpoints)
4229            .await
4230            .unwrap();
4231
4232        ValidatorWithBuiltCheckpoint {
4233            network_config,
4234            state,
4235            epoch_store,
4236            checkpoint_store,
4237            checkpoint_service,
4238            aggregator,
4239            summary,
4240            submitted,
4241            _kept_alive: Box::new((
4242                tmp_dir,
4243                global_state_hasher,
4244                certified_result,
4245                builder,
4246                hasher,
4247            )),
4248        }
4249    }
4250
4251    // A validator does not verify its own consensus blocks, so under the P-COOL
4252    // flow its own signature must reach its aggregator when it is submitted,
4253    // without waiting for the consensus handler to process the commit that
4254    // includes it. The copy that the handler delivers later, and a signature
4255    // made again for the same summary after a restart, must be the same bytes
4256    // and be ignored.
4257    #[tokio::test]
4258    async fn own_checkpoint_signature_reaches_aggregator_without_consensus() {
4259        let ValidatorWithBuiltCheckpoint {
4260            network_config,
4261            state,
4262            epoch_store,
4263            checkpoint_service,
4264            mut aggregator,
4265            summary,
4266            mut submitted,
4267            // Bound, so it lives as long as the test.
4268            _kept_alive,
4269            ..
4270        } = validator_with_built_checkpoint().await;
4271        let validator_key = |i: usize| network_config.validator_configs()[i].authority_key_pair();
4272
4273        // The signature was submitted to consensus, but nothing delivers it back
4274        // yet. Take the copy the consensus handler would see after the round trip.
4275        let submitted = submitted.try_recv().unwrap();
4276        let submitted: ConsensusTransaction =
4277            bcs::from_bytes(&bcs::to_bytes(&submitted).unwrap()).unwrap();
4278        let ConsensusTransactionKind::CheckpointSignature(handler_copy) = submitted.kind else {
4279            panic!("expected a checkpoint signature, got {submitted:?}");
4280        };
4281        assert_eq!(handler_copy.summary.auth_sig().authority, state.name);
4282
4283        let local_copies = epoch_store
4284            .tables()
4285            .unwrap()
4286            .pending_checkpoint_signatures
4287            .safe_iter()
4288            .map(|item| item.unwrap().1)
4289            .collect::<Vec<_>>();
4290        assert_eq!(local_copies.len(), 1);
4291        assert_eq!(
4292            bcs::to_bytes(&local_copies[0]).unwrap(),
4293            bcs::to_bytes(&*handler_copy).unwrap(),
4294        );
4295
4296        // Signing the same summary again, as after a restart, gives the same
4297        // signature.
4298        let signed_again = SignedCheckpointSummary::new(
4299            summary.epoch,
4300            summary.clone(),
4301            &*state.secret,
4302            state.name,
4303        );
4304        assert_eq!(signed_again.auth_sig(), handler_copy.summary.auth_sig());
4305
4306        let signed_by = |i: usize| {
4307            let key = validator_key(i);
4308            CheckpointSignatureMessage {
4309                summary: SignedCheckpointSummary::new(
4310                    summary.epoch,
4311                    summary.clone(),
4312                    key,
4313                    key.public().into(),
4314                ),
4315            }
4316        };
4317        checkpoint_service
4318            .notify_checkpoint_signature(&epoch_store, &signed_by(1))
4319            .unwrap();
4320        assert!(aggregator.run_inner().unwrap().is_empty());
4321        let votes_before = aggregator
4322            .current
4323            .as_ref()
4324            .unwrap()
4325            .signatures_by_digest
4326            .get_all_unique_values();
4327        assert_eq!(votes_before[&summary.digest()].0.len(), 2);
4328
4329        // A repeated signature from this validator, whether the handler's copy or
4330        // one made again, is a repeat of the same signature, which is ignored
4331        // without a warning or a split-brain check.
4332        for repeat in [
4333            (*handler_copy).clone(),
4334            CheckpointSignatureMessage {
4335                summary: signed_again,
4336            },
4337        ] {
4338            let current = aggregator.current.as_mut().unwrap();
4339            let envelope = SignedCheckpointSummary::new_from_data_and_sig(
4340                summary.clone(),
4341                repeat.summary.auth_sig().clone(),
4342            );
4343            assert!(matches!(
4344                current
4345                    .signatures_by_digest
4346                    .insert(summary.digest(), envelope),
4347                InsertResult::Failed {
4348                    error: IotaError::StakeAggregatorRepeatedSigner {
4349                        conflicting_sig: false,
4350                        ..
4351                    }
4352                }
4353            ));
4354            checkpoint_service
4355                .notify_checkpoint_signature(&epoch_store, &repeat)
4356                .unwrap();
4357            assert!(aggregator.run_inner().unwrap().is_empty());
4358            assert_eq!(
4359                aggregator
4360                    .current
4361                    .as_ref()
4362                    .unwrap()
4363                    .signatures_by_digest
4364                    .get_all_unique_values(),
4365                votes_before
4366            );
4367        }
4368
4369        // Two peer signatures and the local one certify the checkpoint; the peer
4370        // signatures alone would not reach a quorum of four validators.
4371        checkpoint_service
4372            .notify_checkpoint_signature(&epoch_store, &signed_by(2))
4373            .unwrap();
4374        let certified = aggregator.run_inner().unwrap();
4375        assert_eq!(certified.len(), 1);
4376        assert_eq!(certified[0].digest(), &summary.digest());
4377    }
4378
4379    /// A block with the signature of `signer` for each of `summaries`, verified
4380    /// by `validator` as a block from a peer.
4381    fn verify_block_of_checkpoint_signatures(
4382        validator: &ValidatorWithBuiltCheckpoint,
4383        signer: usize,
4384        summaries: &[CheckpointSummary],
4385    ) {
4386        use starfish_core::TransactionVerifier as _;
4387
4388        use crate::consensus_validator::{IotaTxValidator, IotaTxValidatorMetrics};
4389
4390        let key = validator.network_config.validator_configs()[signer].authority_key_pair();
4391        let block: Vec<Vec<u8>> = summaries
4392            .iter()
4393            .map(|summary| {
4394                let message = CheckpointSignatureMessage {
4395                    summary: SignedCheckpointSummary::new(
4396                        summary.epoch,
4397                        summary.clone(),
4398                        key,
4399                        key.public().into(),
4400                    ),
4401                };
4402                bcs::to_bytes(&ConsensusTransaction::new_checkpoint_signature_message(
4403                    message,
4404                ))
4405                .unwrap()
4406            })
4407            .collect();
4408        IotaTxValidator::new(
4409            validator.epoch_store.clone(),
4410            validator.checkpoint_service.clone(),
4411            IotaTxValidatorMetrics::new(&Default::default()),
4412        )
4413        .verify_batch(&block.iter().map(Vec::as_slice).collect::<Vec<_>>())
4414        .unwrap();
4415    }
4416
4417    /// `count` summaries of the checkpoint of `summary` that differ from it
4418    /// and from each other.
4419    fn other_summaries(summary: &CheckpointSummary, count: u64) -> Vec<CheckpointSummary> {
4420        (1..=count)
4421            .map(|offset| CheckpointSummary {
4422                timestamp_ms: summary.timestamp_ms + offset,
4423                ..summary.clone()
4424            })
4425            .collect()
4426    }
4427
4428    /// How many signatures of `signer` the aggregator ignored because it had
4429    /// already signed another summary.
4430    fn conflicting_signatures(validator: &ValidatorWithBuiltCheckpoint, signer: usize) -> u64 {
4431        let name: AuthorityName = validator.network_config.validator_configs()[signer]
4432            .authority_key_pair()
4433            .public()
4434            .into();
4435        validator
4436            .aggregator
4437            .metrics
4438            .conflicting_checkpoint_signatures
4439            .with_label_values(&[&format!("{:?}", name.concise())])
4440            .get()
4441    }
4442
4443    /// A member that signed other summaries of a checkpoint still counts with
4444    /// its signature of the local one. Here that signature is needed for the
4445    /// quorum.
4446    #[tokio::test]
4447    async fn member_that_signed_other_summaries_counts_for_the_local_one() {
4448        let mut validator = validator_with_built_checkpoint().await;
4449        let summary = validator.summary.clone();
4450
4451        verify_block_of_checkpoint_signatures(&validator, 1, &other_summaries(&summary, 3));
4452        verify_block_of_checkpoint_signatures(&validator, 1, std::slice::from_ref(&summary));
4453        assert!(validator.aggregator.run_inner().unwrap().is_empty());
4454
4455        verify_block_of_checkpoint_signatures(&validator, 2, std::slice::from_ref(&summary));
4456        let certified = validator.aggregator.run_inner().unwrap();
4457        assert_eq!(certified.len(), 1);
4458        assert_eq!(certified[0].digest(), &summary.digest());
4459        assert_eq!(conflicting_signatures(&validator, 1), 2);
4460    }
4461
4462    /// A quorum of the other members signs another summary of the checkpoint
4463    /// than the one this validator built. Their signatures are verified against
4464    /// the summary they signed, so they stay, and the remote fork is counted
4465    /// once. A further signature of that summary is not aggregated.
4466    #[tokio::test]
4467    async fn quorum_on_another_summary_is_counted_as_a_remote_fork() {
4468        let mut validator = validator_with_built_checkpoint_in_committee_of(7).await;
4469        let summary = validator.summary.clone();
4470        let other = other_summaries(&summary, 1).remove(0);
4471        let remote_forks = |validator: &ValidatorWithBuiltCheckpoint| {
4472            validator.aggregator.metrics.remote_checkpoint_forks.get()
4473        };
4474        let signers_of_other = |validator: &ValidatorWithBuiltCheckpoint| {
4475            let current = validator.aggregator.current.as_ref().unwrap();
4476            current.signatures_by_digest.get_all_unique_values()[&other.digest()]
4477                .0
4478                .len()
4479        };
4480
4481        // Four of seven members are below the quorum.
4482        for signer in 1..=4 {
4483            verify_block_of_checkpoint_signatures(&validator, signer, std::slice::from_ref(&other));
4484        }
4485        assert!(validator.aggregator.run_inner().unwrap().is_empty());
4486        assert_eq!(remote_forks(&validator), 0);
4487        assert_eq!(signers_of_other(&validator), 4);
4488
4489        // The fifth reaches it, and the sixth is skipped.
4490        for signer in [5, 6] {
4491            verify_block_of_checkpoint_signatures(&validator, signer, std::slice::from_ref(&other));
4492            assert!(validator.aggregator.run_inner().unwrap().is_empty());
4493            assert_eq!(remote_forks(&validator), 1);
4494            assert_eq!(signers_of_other(&validator), 5);
4495        }
4496        assert!(
4497            !validator
4498                .aggregator
4499                .current
4500                .as_ref()
4501                .unwrap()
4502                .split_brain_reported
4503        );
4504    }
4505
4506    /// The fork diagnostics ask a validator that signed another summary for
4507    /// its checkpoint. A reply with a certified checkpoint, which an honest
4508    /// validator never gives to that request, is skipped and does not stop
4509    /// the node.
4510    #[tokio::test]
4511    async fn fork_diagnostics_skip_a_certified_reply() {
4512        use std::sync::atomic::{AtomicUsize, Ordering};
4513
4514        /// Replies with the certificate and counts the requests.
4515        struct CertifiedReply(CertifiedCheckpointSummary, Arc<AtomicUsize>);
4516        #[async_trait::async_trait]
4517        impl iota_network::api::ValidatorPeer for CertifiedReply {
4518            async fn get_checkpoint(
4519                &self,
4520                _request: tonic::Request<iota_network::api::GetCheckpointRequest>,
4521            ) -> Result<tonic::Response<iota_network::api::GetCheckpointResponse>, tonic::Status>
4522            {
4523                self.1.fetch_add(1, Ordering::SeqCst);
4524                let response = CheckpointResponse {
4525                    checkpoint: Some(CheckpointSummaryResponse::Certified(self.0.clone())),
4526                    contents: None,
4527                };
4528                Ok(tonic::Response::new(response.try_into().unwrap()))
4529            }
4530        }
4531
4532        use iota_types::committee::CommitteeTrait as _;
4533
4534        let validator = validator_with_built_checkpoint().await;
4535        let summary = validator.summary.clone();
4536        let peer_config = &validator.network_config.validator_configs()[1];
4537        let peer: AuthorityName = peer_config.authority_key_pair().public().into();
4538        let peer_weight = validator.epoch_store.committee().weight(&peer);
4539        let peer_summary = &other_summaries(&summary, 1)[0];
4540
4541        // Nothing checks the certificate before the reply is matched, so one
4542        // without signatures will do.
4543        let certificate = CertifiedCheckpointSummary::new_from_data_and_sig(
4544            summary.clone(),
4545            AuthorityStrongQuorumSignInfo {
4546                epoch: summary.epoch,
4547                signature: Default::default(),
4548                signers_map: Default::default(),
4549            },
4550        );
4551        let requests = Arc::new(AtomicUsize::new(0));
4552        let tls_config = iota_tls::create_rustls_server_config(
4553            peer_config.network_private_key(),
4554            iota_network_stack::server::IOTA_TLS_SERVER_NAME.to_string(),
4555        );
4556        let _server = iota_network_stack::config::Config::new()
4557            .server_builder()
4558            .add_service(iota_network::api::ValidatorPeerServer::new(CertifiedReply(
4559                certificate,
4560                requests.clone(),
4561            )))
4562            .bind(&peer_config.network_address, Some(tls_config))
4563            .await
4564            .unwrap();
4565
4566        let diagnostics = tokio::spawn(diagnose_split_brain(
4567            BTreeMap::from([(peer_summary.digest(), (vec![peer], peer_weight))]),
4568            summary,
4569            validator.state.clone(),
4570            validator.checkpoint_store.clone(),
4571        ));
4572        tokio::time::timeout(Duration::from_secs(60), diagnostics)
4573            .await
4574            .expect("the diagnostics must finish")
4575            .expect("a peer's reply must not make the diagnostics panic");
4576        assert_eq!(requests.load(Ordering::SeqCst), 1);
4577    }
4578
4579    /// The summary certifies only the records other than `Valid`, each at
4580    /// its transaction's position in contents order.
4581    #[tokio::test]
4582    async fn summary_certifies_records_other_than_valid_at_their_positions() {
4583        let mut protocol_config =
4584            ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4585        protocol_config.set_enable_pcool_flow_for_testing(true);
4586        protocol_config.set_enable_validator_attestation_for_testing(true);
4587        protocol_config.set_checkpoint_summary_version_specific_data_for_testing(2);
4588        let state = TestAuthorityBuilder::new()
4589            .with_protocol_config(protocol_config)
4590            .build()
4591            .await;
4592        let epoch_store = state.epoch_store_for_testing();
4593
4594        let txs = [genesis_package_tx(1, 1), genesis_package_tx(2, 1)];
4595        let digests: Vec<_> = txs.iter().map(|tx| *tx.digest()).collect();
4596        let mut effects_map = HashMap::new();
4597        for tx in &txs {
4598            store_executed_tx(&state, &mut effects_map, tx);
4599        }
4600        // A valid record for the first transaction, a refuted one for the second.
4601        let bucket = state
4602            .database_for_testing()
4603            .get_historic_ledger()
4604            .ensure(epoch_store.epoch())
4605            .unwrap();
4606        let records = &bucket.attestation_records;
4607        records
4608            .insert(
4609                &digests[0],
4610                &AttestationRecord {
4611                    attestor: 0,
4612                    verdict: AttestationVerdict::Valid,
4613                },
4614            )
4615            .unwrap();
4616        let refuted = AttestationRecord {
4617            attestor: 2,
4618            verdict: AttestationVerdict::Refuted { units: 7 },
4619        };
4620        records.insert(&digests[1], &refuted).unwrap();
4621        let effects: Vec<_> = digests.iter().map(|d| effects_map[d].clone()).collect();
4622
4623        let tmp_dir = iota_common::tempdir();
4624        let service =
4625            manual_checkpoint_service(&state, CheckpointStore::new(tmp_dir.path()), effects_map);
4626        let (builder, _aggregator, _hasher) = service.service.state.lock().take_unstarted();
4627        service
4628            .service
4629            .write_and_notify_checkpoint_for_testing(&epoch_store, p(0, digests.clone(), 0))
4630            .unwrap();
4631        let details = PendingCheckpointInfo {
4632            timestamp_ms: 0,
4633            last_of_epoch: false,
4634            checkpoint_height: 0,
4635        };
4636        let new_checkpoints = builder
4637            .create_checkpoints(
4638                effects,
4639                &details,
4640                &digests.iter().copied().collect::<HashSet<_>>(),
4641            )
4642            .await
4643            .unwrap();
4644        let built = new_checkpoints.first();
4645
4646        let entries = built
4647            .summary
4648            .parse_version_specific_data(epoch_store.protocol_config())
4649            .unwrap()
4650            .expect("version 2 summaries carry version specific data")
4651            .attestation_entries()
4652            .to_vec();
4653        let position = built
4654            .contents
4655            .iter()
4656            .position(|d| d.transaction == digests[1])
4657            .unwrap();
4658        assert_eq!(
4659            entries,
4660            vec![AttestationEntry {
4661                position: position as u32,
4662                record: refuted,
4663            }]
4664        );
4665    }
4666
4667    /// The summary carries the epoch's refuted totals so far: the previous
4668    /// summary's totals plus this checkpoint's `Refuted` records.
4669    #[tokio::test]
4670    async fn summary_attestation_totals_accumulate_across_checkpoints() {
4671        let mut protocol_config =
4672            ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4673        protocol_config.set_enable_pcool_flow_for_testing(true);
4674        protocol_config.set_enable_validator_attestation_for_testing(true);
4675        protocol_config.set_checkpoint_summary_version_specific_data_for_testing(2);
4676        let state = TestAuthorityBuilder::new()
4677            .with_protocol_config(protocol_config)
4678            .build()
4679            .await;
4680        let epoch_store = state.epoch_store_for_testing();
4681
4682        let txs = [
4683            genesis_package_tx(1, 1),
4684            genesis_package_tx(2, 1),
4685            genesis_package_tx(3, 1),
4686        ];
4687        let digests: Vec<_> = txs.iter().map(|tx| *tx.digest()).collect();
4688        let mut effects_map = HashMap::new();
4689        for tx in &txs {
4690            store_executed_tx(&state, &mut effects_map, tx);
4691        }
4692        let record = |digest, attestor, verdict| {
4693            state
4694                .database_for_testing()
4695                .get_historic_ledger()
4696                .ensure(epoch_store.epoch())
4697                .unwrap()
4698                .attestation_records
4699                .insert(digest, &AttestationRecord { attestor, verdict })
4700                .unwrap();
4701        };
4702        record(&digests[0], 1, AttestationVerdict::Valid);
4703        record(&digests[1], 2, AttestationVerdict::Refuted { units: 7 });
4704        record(&digests[2], 2, AttestationVerdict::Refuted { units: 7 });
4705
4706        let tmp_dir = iota_common::tempdir();
4707        let service = manual_checkpoint_service(
4708            &state,
4709            CheckpointStore::new(tmp_dir.path()),
4710            effects_map.clone(),
4711        );
4712        let (builder, _aggregator, _hasher) = service.service.state.lock().take_unstarted();
4713        let builder = &builder;
4714        let build = |height, roots: Vec<TransactionDigest>| {
4715            let effects = roots.iter().map(|d| effects_map[d].clone()).collect();
4716            let roots_set: HashSet<_> = roots.iter().copied().collect();
4717            service
4718                .service
4719                .write_and_notify_checkpoint_for_testing(&epoch_store, p(height, roots, 0))
4720                .unwrap();
4721            let details = PendingCheckpointInfo {
4722                timestamp_ms: 0,
4723                last_of_epoch: false,
4724                checkpoint_height: height,
4725            };
4726            async move {
4727                builder
4728                    .create_checkpoints(effects, &details, &roots_set)
4729                    .await
4730                    .unwrap()
4731            }
4732        };
4733        let totals_of = |built: &BuiltCheckpoint| {
4734            built
4735                .summary
4736                .parse_version_specific_data(epoch_store.protocol_config())
4737                .unwrap()
4738                .expect("version 2 summaries carry version specific data")
4739                .attestation_totals()
4740                .cloned()
4741                .expect("version 2 summaries carry totals")
4742        };
4743
4744        // Each refuted record wasted 7 units, below one max-gas run.
4745        let checkpoints = build(0, digests[..2].to_vec()).await;
4746        assert_eq!(
4747            totals_of(checkpoints.first()).refuted_units_squared,
4748            BTreeMap::from([(2, 49)])
4749        );
4750        builder.write_checkpoints(0, checkpoints).await.unwrap();
4751
4752        let checkpoints = build(1, digests[2..].to_vec()).await;
4753        assert_eq!(
4754            totals_of(checkpoints.first()).refuted_units_squared,
4755            BTreeMap::from([(2, 98)]),
4756            "the second checkpoint adds to the first one's totals"
4757        );
4758    }
4759
4760    #[sim_test]
4761    pub async fn checkpoint_builder_test() {
4762        telemetry_subscribers::init_for_testing();
4763
4764        let mut protocol_config =
4765            ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4766        protocol_config.set_min_checkpoint_interval_ms_for_testing(100);
4767        // This test exercises the strict adjacent-checkpoint interval.
4768        protocol_config.disable_checkpoint_rate_window_size_for_testing();
4769        let state = TestAuthorityBuilder::new()
4770            .with_protocol_config(protocol_config)
4771            .build()
4772            .await;
4773
4774        // Build distinct genesis transactions and assign their digests to
4775        // indices so that, within any pending checkpoint, digest order matches
4776        // index order: `CausalOrder` orders non-dependent transactions by
4777        // digest, and the assertions below rely on that order. Transactions
4778        // 15..20 carry a large payload to exercise size-based checkpoint
4779        // splitting.
4780        let mut small: Vec<_> = (0..15).map(|seed| genesis_package_tx(seed, 1)).collect();
4781        small.sort_by_key(|tx| *tx.digest());
4782
4783        let mut large: Vec<_> = (0..5)
4784            .map(|seed| genesis_package_tx(100 + seed, 40000))
4785            .collect();
4786        large.sort_by_key(|tx| *tx.digest());
4787
4788        let txns: Vec<_> = small.into_iter().chain(large).collect();
4789        let digests: Vec<TransactionDigest> = txns.iter().map(|tx| *tx.digest()).collect();
4790
4791        // Digest for test index `i`; ascending within the small (0..15) and
4792        // large (15..20) pools, so index order implies digest order per pool.
4793        let d = |i: u8| digests[i as usize];
4794
4795        let ledger_bucket = state
4796            .database_for_testing()
4797            .get_historic_ledger()
4798            .ensure(0)
4799            .unwrap();
4800        for (tx, digest) in txns.iter().zip(&digests) {
4801            ledger_bucket
4802                .transactions
4803                .insert(digest, tx.serializable_ref())
4804                .unwrap();
4805        }
4806
4807        let mut store = HashMap::<TransactionDigest, TransactionEffects>::new();
4808        commit_cert_for_test(
4809            &mut store,
4810            state.clone(),
4811            d(1),
4812            vec![d(2), d(3)],
4813            GasCostSummary::new(11, 11, 12, 11, 1),
4814        );
4815        commit_cert_for_test(
4816            &mut store,
4817            state.clone(),
4818            d(2),
4819            vec![d(3), d(4)],
4820            GasCostSummary::new(21, 21, 22, 21, 1),
4821        );
4822        commit_cert_for_test(
4823            &mut store,
4824            state.clone(),
4825            d(3),
4826            vec![],
4827            GasCostSummary::new(31, 31, 32, 31, 1),
4828        );
4829        commit_cert_for_test(
4830            &mut store,
4831            state.clone(),
4832            d(4),
4833            vec![],
4834            GasCostSummary::new(41, 41, 42, 41, 1),
4835        );
4836        for i in [5, 6, 7, 10, 11, 12, 13] {
4837            commit_cert_for_test(
4838                &mut store,
4839                state.clone(),
4840                d(i),
4841                vec![],
4842                GasCostSummary::new(41, 41, 42, 41, 1),
4843            );
4844        }
4845        for i in [15, 16, 17] {
4846            commit_cert_for_test(
4847                &mut store,
4848                state.clone(),
4849                d(i),
4850                vec![],
4851                GasCostSummary::new(51, 51, 52, 51, 1),
4852            );
4853        }
4854        let all_digests: Vec<_> = store.keys().copied().collect();
4855        for digest in all_digests {
4856            let signature = iota_types::crypto::zero_ed25519_signature().into();
4857            state
4858                .epoch_store_for_testing()
4859                .test_insert_user_signature(digest, vec![signature]);
4860        }
4861
4862        let (output, mut result) = mpsc::channel::<(CheckpointContents, CheckpointSummary)>(10);
4863        let (certified_output, mut certified_result) =
4864            mpsc::channel::<CertifiedCheckpointSummary>(10);
4865        let store = Arc::new(store);
4866
4867        let tmp_dir = iota_common::tempdir();
4868        let checkpoint_store = CheckpointStore::new(tmp_dir.path());
4869        let epoch_store = state.epoch_store_for_testing();
4870
4871        let global_state_hasher = Arc::new(GlobalStateHasher::new_for_tests(
4872            state.get_global_state_hash_store().clone(),
4873        ));
4874
4875        let checkpoint_service = CheckpointService::build(
4876            state.clone(),
4877            checkpoint_store.clone(),
4878            epoch_store.clone(),
4879            store,
4880            Arc::downgrade(&global_state_hasher),
4881            Box::new(output),
4882            Box::new(certified_output),
4883            CheckpointMetrics::new_for_tests(),
4884            3,
4885            100_000,
4886        );
4887        let _tasks = checkpoint_service.spawn(None).await;
4888
4889        checkpoint_service
4890            .write_and_notify_checkpoint_for_testing(&epoch_store, p(0, vec![d(4)], 0))
4891            .unwrap();
4892        checkpoint_service
4893            .write_and_notify_checkpoint_for_testing(&epoch_store, p(1, vec![d(1), d(3)], 2000))
4894            .unwrap();
4895        checkpoint_service
4896            .write_and_notify_checkpoint_for_testing(
4897                &epoch_store,
4898                p(2, vec![d(10), d(11), d(12), d(13)], 3000),
4899            )
4900            .unwrap();
4901        checkpoint_service
4902            .write_and_notify_checkpoint_for_testing(
4903                &epoch_store,
4904                p(3, vec![d(15), d(16), d(17)], 4000),
4905            )
4906            .unwrap();
4907        checkpoint_service
4908            .write_and_notify_checkpoint_for_testing(&epoch_store, p(4, vec![d(5)], 4001))
4909            .unwrap();
4910        checkpoint_service
4911            .write_and_notify_checkpoint_for_testing(&epoch_store, p(5, vec![d(6)], 5000))
4912            .unwrap();
4913
4914        let (c1c, c1s) = result.recv().await.unwrap();
4915        let (c2c, c2s) = result.recv().await.unwrap();
4916
4917        let c1t = c1c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4918        let c2t = c2c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4919        assert_eq!(c1t, vec![d(4)]);
4920        assert_eq!(c1s.previous_digest, None);
4921        assert_eq!(c1s.sequence_number, 0);
4922        assert_eq!(
4923            c1s.epoch_rolling_gas_cost_summary,
4924            GasCostSummary::new(41, 41, 42, 41, 1)
4925        );
4926
4927        assert_eq!(c2t, vec![d(3), d(2), d(1)]);
4928        assert_eq!(c2s.previous_digest, Some(c1s.digest()));
4929        assert_eq!(c2s.sequence_number, 1);
4930        assert_eq!(
4931            c2s.epoch_rolling_gas_cost_summary,
4932            GasCostSummary::new(104, 104, 108, 104, 4)
4933        );
4934
4935        // The builder caches the full contents of each locally built checkpoint.
4936        // The cached contents must match the checkpoint's transactions and hash
4937        // to its content digest, so state-sync peers can be served from memory.
4938        for (summary, digest_contents) in [(&c1s, &c1c), (&c2s, &c2c)] {
4939            let cached = checkpoint_store
4940                .get_full_checkpoint_contents_by_sequence_number(summary.sequence_number)
4941                .expect("builder should cache full contents of a locally built checkpoint");
4942            assert_eq!(&cached.checkpoint_contents(), digest_contents);
4943            assert_eq!(
4944                cached.checkpoint_contents().digest(),
4945                summary.contents_digest
4946            );
4947            // A cached entry must imply a durable checkpoint_content row:
4948            // state-sync skips its own durable write when contents are
4949            // already available.
4950            assert!(
4951                checkpoint_store
4952                    .get_checkpoint_contents(&summary.contents_digest)
4953                    .unwrap()
4954                    .is_some()
4955            );
4956        }
4957
4958        // Pending at index 2 had 4 transactions, and we configured 3 transactions max.
4959        // Verify that we split into 2 checkpoints.
4960        let (c3c, c3s) = result.recv().await.unwrap();
4961        let c3t = c3c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4962        let (c4c, c4s) = result.recv().await.unwrap();
4963        let c4t = c4c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4964        assert_eq!(c3s.sequence_number, 2);
4965        assert_eq!(c3s.previous_digest, Some(c2s.digest()));
4966        assert_eq!(c4s.sequence_number, 3);
4967        assert_eq!(c4s.previous_digest, Some(c3s.digest()));
4968        assert_eq!(c3t, vec![d(10), d(11), d(12)]);
4969        assert_eq!(c4t, vec![d(13)]);
4970
4971        // Pending at index 3 had 3 transactions of 40K size, and we configured 100K
4972        // max. Verify that we split into 2 checkpoints.
4973        let (c5c, c5s) = result.recv().await.unwrap();
4974        let c5t = c5c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4975        let (c6c, c6s) = result.recv().await.unwrap();
4976        let c6t = c6c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4977        assert_eq!(c5s.sequence_number, 4);
4978        assert_eq!(c5s.previous_digest, Some(c4s.digest()));
4979        assert_eq!(c6s.sequence_number, 5);
4980        assert_eq!(c6s.previous_digest, Some(c5s.digest()));
4981        assert_eq!(c5t, vec![d(15), d(16)]);
4982        assert_eq!(c6t, vec![d(17)]);
4983
4984        // Pending at index 4 was too soon after the prior one and should be coalesced
4985        // into the next one.
4986        let (c7c, c7s) = result.recv().await.unwrap();
4987        let c7t = c7c.iter().map(|d| d.transaction).collect::<Vec<_>>();
4988        assert_eq!(c7t, vec![d(5), d(6)]);
4989        assert_eq!(c7s.previous_digest, Some(c6s.digest()));
4990        assert_eq!(c7s.sequence_number, 6);
4991
4992        let c1ss = SignedCheckpointSummary::new(c1s.epoch, c1s, state.secret.deref(), state.name);
4993        let c2ss = SignedCheckpointSummary::new(c2s.epoch, c2s, state.secret.deref(), state.name);
4994
4995        checkpoint_service
4996            .notify_checkpoint_signature(
4997                &epoch_store,
4998                &CheckpointSignatureMessage { summary: c2ss },
4999            )
5000            .unwrap();
5001        checkpoint_service
5002            .notify_checkpoint_signature(
5003                &epoch_store,
5004                &CheckpointSignatureMessage { summary: c1ss },
5005            )
5006            .unwrap();
5007
5008        let c1sc = certified_result.recv().await.unwrap();
5009        let c2sc = certified_result.recv().await.unwrap();
5010        assert_eq!(c1sc.sequence_number, 0);
5011        assert_eq!(c2sc.sequence_number, 1);
5012    }
5013
5014    #[sim_test]
5015    pub async fn checkpoint_builder_windowed_interval_test() {
5016        telemetry_subscribers::init_for_testing();
5017
5018        // 100ms interval with a window of 3 checkpoints: a checkpoint is built
5019        // when either 100ms passed since the previous one or the checkpoint 3
5020        // back is >= 300ms older. The windowed arm permits sub-interval bursts
5021        // while banked budget lasts; the adjacent arm caps every quiet gap at
5022        // one interval regardless of window state.
5023        let mut protocol_config =
5024            ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
5025        protocol_config.set_min_checkpoint_interval_ms_for_testing(100);
5026        protocol_config.set_checkpoint_rate_window_size_for_testing(3);
5027        let state = TestAuthorityBuilder::new()
5028            .with_protocol_config(protocol_config)
5029            .build()
5030            .await;
5031
5032        // Distinct real transactions: only build timing is under test, but the
5033        // builder pairs each stored transaction with its effects by digest, so
5034        // effects must reference the digests of actually stored transactions.
5035        let txns: Vec<_> = (1..=8).map(|seed| genesis_package_tx(seed, 1)).collect();
5036        let digests: Vec<TransactionDigest> = txns.iter().map(|tx| *tx.digest()).collect();
5037        // Digest for test index `i` (1-based).
5038        let d = |i: u8| digests[(i - 1) as usize];
5039
5040        let ledger_bucket = state
5041            .database_for_testing()
5042            .get_historic_ledger()
5043            .ensure(0)
5044            .unwrap();
5045        for tx in &txns {
5046            ledger_bucket
5047                .transactions
5048                .insert(tx.digest(), tx.serializable_ref())
5049                .unwrap();
5050        }
5051
5052        let mut store = HashMap::<TransactionDigest, TransactionEffects>::new();
5053        for i in 1..=8 {
5054            commit_cert_for_test(
5055                &mut store,
5056                state.clone(),
5057                d(i),
5058                vec![],
5059                GasCostSummary::new(11, 11, 12, 11, 1),
5060            );
5061        }
5062        let all_digests: Vec<_> = store.keys().copied().collect();
5063        for digest in all_digests {
5064            let signature = iota_types::crypto::zero_ed25519_signature().into();
5065            state
5066                .epoch_store_for_testing()
5067                .test_insert_user_signature(digest, vec![signature]);
5068        }
5069
5070        let (output, mut result) = mpsc::channel::<(CheckpointContents, CheckpointSummary)>(10);
5071        let (certified_output, _certified_result) = mpsc::channel::<CertifiedCheckpointSummary>(10);
5072        let store = Arc::new(store);
5073
5074        let tmp_dir = iota_common::tempdir();
5075        let checkpoint_store = CheckpointStore::new(tmp_dir.path());
5076        let epoch_store = state.epoch_store_for_testing();
5077
5078        let global_state_hasher = Arc::new(GlobalStateHasher::new_for_tests(
5079            state.get_global_state_hash_store().clone(),
5080        ));
5081
5082        let checkpoint_service = CheckpointService::build(
5083            state.clone(),
5084            checkpoint_store,
5085            epoch_store.clone(),
5086            store,
5087            Arc::downgrade(&global_state_hasher),
5088            Box::new(output),
5089            Box::new(certified_output),
5090            CheckpointMetrics::new_for_tests(),
5091            3,
5092            100_000,
5093        );
5094        let _tasks = checkpoint_service.spawn(None).await;
5095
5096        // The windowed arm is inert until 3 checkpoints exist; the first three
5097        // build via the adjacent arm, which their spread-out timestamps
5098        // (0, 1000, 2000) satisfy while accruing burst budget.
5099        // window_ms = 3 * 100 = 300.
5100        for (height, root, timestamp_ms) in [(0, 1u8, 0), (1, 2, 1000), (2, 3, 2000)] {
5101            checkpoint_service
5102                .write_and_notify_checkpoint_for_testing(
5103                    &epoch_store,
5104                    p(height, vec![d(root)], timestamp_ms),
5105                )
5106                .unwrap();
5107        }
5108        // p3 @ 2010: adjacent red (< C2 + 100 = 2100) but windowed green
5109        // (>= C0(0) + 300) -> builds, only 10ms after C2. A strict adjacent
5110        // rule would instead coalesce it.
5111        checkpoint_service
5112            .write_and_notify_checkpoint_for_testing(&epoch_store, p(3, vec![d(4)], 2010))
5113            .unwrap();
5114        // p4 @ 2020: windowed green (>= C1(1000) + 300) -> builds, another
5115        // sub-interval burst.
5116        checkpoint_service
5117            .write_and_notify_checkpoint_for_testing(&epoch_store, p(4, vec![d(5)], 2020))
5118            .unwrap();
5119        // Budget now spent: the window covers the tight 2000-2020 cluster.
5120        // p5 @ 2030: adjacent red (< C4 + 100 = 2120), windowed red
5121        // (< C2(2000) + 300 = 2300) -> coalesced.
5122        checkpoint_service
5123            .write_and_notify_checkpoint_for_testing(&epoch_store, p(5, vec![d(6)], 2030))
5124            .unwrap();
5125        // p6 @ 2130: windowed still red (< 2300), but adjacent green
5126        // (>= 2120) -> builds, coalescing p5 and p6. A window-only gate would
5127        // keep coalescing until 2300; the adjacent arm caps the gap.
5128        checkpoint_service
5129            .write_and_notify_checkpoint_for_testing(&epoch_store, p(6, vec![d(7)], 2130))
5130            .unwrap();
5131        // p7 @ 2300: windowed red (< C3(2010) + 300 = 2310), adjacent green
5132        // (>= C5 + 100 = 2230) -> builds.
5133        checkpoint_service
5134            .write_and_notify_checkpoint_for_testing(&epoch_store, p(7, vec![d(8)], 2300))
5135            .unwrap();
5136
5137        let mut built = Vec::new();
5138        for _ in 0..7 {
5139            let (contents, summary) = result.recv().await.unwrap();
5140            built.push((summary.sequence_number, contents.iter().count()));
5141        }
5142
5143        // Seven checkpoints, contiguous sequence numbers.
5144        let sequence_numbers: Vec<_> = built.iter().map(|(seq, _)| *seq).collect();
5145        assert_eq!(sequence_numbers, vec![0, 1, 2, 3, 4, 5, 6]);
5146        // Bursts (seq 3, 4) stand alone despite sub-interval spacing; once the
5147        // budget is spent, pendings coalesce only until the adjacent interval
5148        // elapses (seq 5), never longer. A strict adjacent rule would build
5149        // [0,1,2] and then coalesce the whole 2010-2130 cluster into one
5150        // checkpoint; a window-only rule would coalesce p5-p7 into one
5151        // checkpoint at 2300.
5152        let sizes: Vec<_> = built.iter().map(|(_, size)| *size).collect();
5153        assert_eq!(sizes, vec![1, 1, 1, 1, 1, 2, 1]);
5154    }
5155
5156    impl TransactionCacheRead for HashMap<TransactionDigest, TransactionEffects> {
5157        fn try_multi_get_attestation_records_in_epoch(
5158            &self,
5159            _: EpochId,
5160            digests: &[TransactionDigest],
5161        ) -> IotaResult<Vec<Option<AttestationRecord>>> {
5162            Ok(vec![None; digests.len()])
5163        }
5164
5165        fn try_notify_read_executed_effects(
5166            &self,
5167            _: &str,
5168            digests: &[TransactionDigest],
5169        ) -> BoxFuture<'_, IotaResult<Vec<TransactionEffects>>> {
5170            std::future::ready(Ok(digests
5171                .iter()
5172                .map(|d| self.get(d).expect("effects not found").clone())
5173                .collect()))
5174            .boxed()
5175        }
5176
5177        fn try_notify_read_executed_effects_digests(
5178            &self,
5179            _: &str,
5180            digests: &[TransactionDigest],
5181        ) -> BoxFuture<'_, IotaResult<Vec<TransactionEffectsDigest>>> {
5182            std::future::ready(Ok(digests
5183                .iter()
5184                .map(|d| {
5185                    self.get(d)
5186                        .map(|fx| fx.digest())
5187                        .expect("effects not found")
5188                })
5189                .collect()))
5190            .boxed()
5191        }
5192
5193        fn try_multi_get_executed_effects(
5194            &self,
5195            digests: &[TransactionDigest],
5196        ) -> IotaResult<Vec<Option<TransactionEffects>>> {
5197            Ok(digests.iter().map(|d| self.get(d).cloned()).collect())
5198        }
5199
5200        // Unimplemented methods - its unfortunate to have this big blob of useless
5201        // code, but it wasn't worth it to keep EffectsNotifyRead around just
5202        // for these tests, as it caused a ton of complication in non-test code.
5203        // (e.g. had to implement EFfectsNotifyRead for all ExecutionCacheRead
5204        // implementors).
5205
5206        fn try_multi_get_transaction_blocks(
5207            &self,
5208            _: &[TransactionDigest],
5209        ) -> IotaResult<Vec<Option<Arc<VerifiedTransaction>>>> {
5210            unimplemented!()
5211        }
5212
5213        fn try_multi_get_executed_effects_digests(
5214            &self,
5215            _: &[TransactionDigest],
5216        ) -> IotaResult<Vec<Option<TransactionEffectsDigest>>> {
5217            unimplemented!()
5218        }
5219
5220        fn try_multi_get_effects(
5221            &self,
5222            _: &[TransactionEffectsDigest],
5223        ) -> IotaResult<Vec<Option<TransactionEffects>>> {
5224            unimplemented!()
5225        }
5226
5227        fn try_multi_get_events(
5228            &self,
5229            _: &[TransactionDigest],
5230        ) -> IotaResult<Vec<Option<TransactionEvents>>> {
5231            unimplemented!()
5232        }
5233    }
5234
5235    #[async_trait::async_trait]
5236    impl CheckpointOutput for mpsc::Sender<(CheckpointContents, CheckpointSummary)> {
5237        async fn checkpoint_created(
5238            &self,
5239            summary: &CheckpointSummary,
5240            contents: &CheckpointContents,
5241            _epoch_store: &Arc<AuthorityPerEpochStore>,
5242            _checkpoint_store: &Arc<CheckpointStore>,
5243            _checkpoint_service: &(dyn CheckpointServiceNotify + Sync),
5244        ) -> IotaResult {
5245            self.try_send((contents.clone(), summary.clone())).unwrap();
5246            Ok(())
5247        }
5248    }
5249
5250    impl SubmitToConsensus for mpsc::Sender<ConsensusTransaction> {
5251        fn submit_to_consensus(
5252            &self,
5253            transactions: &[ConsensusTransaction],
5254            _epoch_store: &Arc<AuthorityPerEpochStore>,
5255        ) -> IotaResult {
5256            for transaction in transactions {
5257                self.try_send(transaction.clone()).unwrap();
5258            }
5259            Ok(())
5260        }
5261    }
5262
5263    impl ReconfigurationInitiator for mpsc::Sender<ConsensusTransaction> {
5264        fn close_epoch(&self, _epoch_store: &Arc<AuthorityPerEpochStore>) {}
5265    }
5266
5267    #[async_trait::async_trait]
5268    impl CertifiedCheckpointOutput for mpsc::Sender<CertifiedCheckpointSummary> {
5269        async fn certified_checkpoint_created(
5270            &self,
5271            summary: &CertifiedCheckpointSummary,
5272        ) -> IotaResult {
5273            self.try_send(summary.clone()).unwrap();
5274            Ok(())
5275        }
5276    }
5277
5278    /// A distinct genesis transaction publishing an empty package whose id
5279    /// starts with `seed`; `payload_size` pads it to exercise size limits.
5280    fn genesis_package_tx(seed: u8, payload_size: usize) -> VerifiedTransaction {
5281        let mut id = [0u8; 32];
5282        id[0] = seed;
5283        VerifiedTransaction::new_genesis_transaction(
5284            vec![GenesisObject::new(
5285                ObjectData::Package(MovePackage::new(
5286                    ObjectId::new(id),
5287                    Version::default(),
5288                    BTreeMap::from([(Identifier::new_unchecked("m"), vec![0u8; payload_size])]),
5289                    // No modules, so no type origins and no linkage.
5290                    Vec::new(),
5291                    BTreeMap::new(),
5292                )),
5293                Owner::Immutable,
5294            )],
5295            vec![],
5296        )
5297    }
5298
5299    /// Stores `tx` as executed: in the epoch's ledger bucket, with effects in
5300    /// `effects_map`, and with a user signature for the checkpoint builder.
5301    fn store_executed_tx(
5302        state: &Arc<AuthorityState>,
5303        effects_map: &mut HashMap<TransactionDigest, TransactionEffects>,
5304        tx: &VerifiedTransaction,
5305    ) {
5306        let digest = *tx.digest();
5307        state
5308            .database_for_testing()
5309            .get_historic_ledger()
5310            .ensure(state.epoch_store_for_testing().epoch())
5311            .unwrap()
5312            .transactions
5313            .insert(&digest, tx.serializable_ref())
5314            .unwrap();
5315        commit_cert_for_test(
5316            effects_map,
5317            state.clone(),
5318            digest,
5319            vec![],
5320            GasCostSummary::new(1, 1, 1, 1, 1),
5321        );
5322        let signature = iota_types::crypto::zero_ed25519_signature().into();
5323        state
5324            .epoch_store_for_testing()
5325            .test_insert_user_signature(digest, vec![signature]);
5326    }
5327
5328    /// A checkpoint service whose builder is driven by hand. Keeps alive what
5329    /// the builder needs: the state hasher `create_checkpoints` sends to and
5330    /// the output channels.
5331    struct ManualCheckpointService {
5332        service: Arc<CheckpointService>,
5333        _hasher: Arc<GlobalStateHasher>,
5334        _outputs: (
5335            mpsc::Receiver<(CheckpointContents, CheckpointSummary)>,
5336            mpsc::Receiver<CertifiedCheckpointSummary>,
5337        ),
5338    }
5339
5340    fn manual_checkpoint_service(
5341        state: &Arc<AuthorityState>,
5342        checkpoint_store: Arc<CheckpointStore>,
5343        effects_map: HashMap<TransactionDigest, TransactionEffects>,
5344    ) -> ManualCheckpointService {
5345        let (output, result) = mpsc::channel(10);
5346        let (certified_output, certified_result) = mpsc::channel(10);
5347        let hasher = Arc::new(GlobalStateHasher::new_for_tests(
5348            state.get_global_state_hash_store().clone(),
5349        ));
5350        let service = CheckpointService::build(
5351            state.clone(),
5352            checkpoint_store,
5353            state.epoch_store_for_testing().clone(),
5354            Arc::new(effects_map),
5355            Arc::downgrade(&hasher),
5356            Box::new(output),
5357            Box::new(certified_output),
5358            CheckpointMetrics::new_for_tests(),
5359            3,
5360            100_000,
5361        );
5362        ManualCheckpointService {
5363            service,
5364            _hasher: hasher,
5365            _outputs: (result, certified_result),
5366        }
5367    }
5368
5369    fn p(i: u64, roots: Vec<TransactionDigest>, timestamp_ms: u64) -> PendingCheckpoint {
5370        PendingCheckpoint::V1(PendingCheckpointContentsV1 {
5371            roots: roots.into_iter().map(TransactionKey::Digest).collect(),
5372            details: PendingCheckpointInfo {
5373                timestamp_ms,
5374                last_of_epoch: false,
5375                checkpoint_height: i,
5376            },
5377        })
5378    }
5379
5380    fn e(
5381        transaction_digest: TransactionDigest,
5382        dependencies: Vec<TransactionDigest>,
5383        gas_cost_summary: GasCostSummary,
5384    ) -> TransactionEffects {
5385        let mut effects = TransactionEffects::new_empty_v1_for_testing(transaction_digest);
5386        *effects.dependencies_mut_for_testing() = dependencies;
5387        *effects.gas_cost_summary_mut_for_testing() = gas_cost_summary;
5388        effects
5389    }
5390
5391    fn commit_cert_for_test(
5392        store: &mut HashMap<TransactionDigest, TransactionEffects>,
5393        state: Arc<AuthorityState>,
5394        digest: TransactionDigest,
5395        dependencies: Vec<TransactionDigest>,
5396        gas_cost_summary: GasCostSummary,
5397    ) {
5398        let epoch_store = state.epoch_store_for_testing();
5399        let effects = e(digest, dependencies, gas_cost_summary);
5400        store.insert(digest, effects);
5401        epoch_store.insert_executed_in_epoch(&digest);
5402    }
5403}