Skip to main content

forest/chain/
mod.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4pub mod ec_finality;
5mod snapshot_format;
6pub mod store;
7#[cfg(test)]
8mod tests;
9mod weight;
10
11pub use self::{snapshot_format::*, store::*, weight::*};
12
13use crate::blocks::{Tipset, TipsetKey};
14use crate::chain::index::{ChainIndex, ResolveNullTipset};
15use crate::cid_collections::{CidHashSet, CidHashSetLike, FileBackedCidHashSet};
16use crate::db::car::AnyCar;
17use crate::db::car::forest::{self, ForestCarFrame, finalize_frame};
18use crate::db::{EthMappingsStore, IndexMapBlockstore};
19use crate::ipld::{IpldStream, should_save_block_to_snapshot, stream_chain};
20use crate::prelude::*;
21use crate::shim::executor::Receipt;
22use crate::utils;
23use crate::utils::db::car_stream::{CarBlock, CarBlockWrite};
24use crate::utils::io::{AsyncWriterWithChecksum, Checksum};
25use crate::utils::multihash::MultihashCode;
26use crate::utils::stream::par_buffer;
27use fil_actors_shared::fvm_ipld_hamt::Hamt;
28use futures::{StreamExt as _, TryStreamExt as _};
29use fvm_ipld_encoding::DAG_CBOR;
30use multihash_derive::MultihashDigest as _;
31use nunny::Vec as NonEmpty;
32use sha2::digest::{self, Digest};
33use std::io::{Read, Seek, SeekFrom};
34use std::path::Path;
35use std::time::Instant;
36use tokio::io::{AsyncWrite, AsyncWriteExt, BufWriter};
37use tokio_util::task::AbortOnDropHandle;
38
39pub const TIPSET_LOOKUP_HAMT_BIT_WIDTH: u32 = 5;
40
41pub struct ExportOptions<S> {
42    pub skip_checksum: bool,
43    pub include_receipts: bool,
44    pub include_events: bool,
45    pub include_tipset_keys: bool,
46    pub include_tipset_lookup: bool,
47    pub seen: S,
48    /// Ancestor of the exported tipset where the chain walk stops (exclusive)
49    pub diff_base: Option<TipsetKey>,
50}
51
52impl<S: Default> Default for ExportOptions<S> {
53    fn default() -> Self {
54        Self {
55            skip_checksum: Default::default(),
56            include_receipts: Default::default(),
57            include_events: Default::default(),
58            include_tipset_keys: Default::default(),
59            include_tipset_lookup: Default::default(),
60            seen: Default::default(),
61            diff_base: Default::default(),
62        }
63    }
64}
65
66pub struct ExportResult<D: Digest> {
67    pub checksum: Option<digest::Output<D>>,
68    #[allow(dead_code)]
69    pub tipset_lookup: Option<anyhow::Result<Hamt<IndexMapBlockstore, TipsetKey, ChainEpoch>>>,
70}
71
72/// Oldest epoch whose state roots an export walks.
73fn lookup_epoch_limit(
74    tipset_epoch: ChainEpoch,
75    lookup_depth: ChainEpoch,
76) -> anyhow::Result<ChainEpoch> {
77    tipset_epoch
78        .checked_sub(lookup_depth)
79        .with_context(|| format!("depth {lookup_depth} is out of range below epoch {tipset_epoch}"))
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display)]
83enum RootKind {
84    #[strum(to_string = "messages")]
85    Messages,
86    #[strum(to_string = "state root")]
87    StateRoot,
88}
89
90#[derive(Debug, PartialEq, Eq, thiserror::Error)]
91#[error(
92    "{kind} {cid} at epoch {epoch} is missing, the database does not hold {depth} recent roots"
93)]
94pub(crate) struct MissingRecentRoot {
95    kind: RootKind,
96    cid: Cid,
97    epoch: ChainEpoch,
98    depth: ChainEpochDelta,
99}
100
101/// Fails fast when the oldest tipset an export walks lacks its roots, instead of hours into the export.
102/// Only the roots are checked, as verifying the full trees would cost as much as the export.
103async fn ensure_recent_roots_present(
104    db: &(impl Blockstore + ShallowClone + Send + Sync + 'static),
105    tipset: &Tipset,
106    stateroot_lookup_limit: ChainEpoch,
107) -> anyhow::Result<()> {
108    let db = db.shallow_clone();
109    let tipset = tipset.shallow_clone();
110    let depth = tipset.epoch() - stateroot_lookup_limit;
111    tokio::task::spawn_blocking(move || {
112        let Some(oldest) = tipset
113            .chain(&db)
114            .take_while(|ts| ts.epoch() > stateroot_lookup_limit)
115            .last()
116        else {
117            return Ok(());
118        };
119        let roots = std::iter::once((RootKind::StateRoot, *oldest.parent_state())).chain(
120            oldest
121                .block_headers()
122                .iter()
123                .map(|b| (RootKind::Messages, b.messages)),
124        );
125        for (kind, cid) in roots {
126            if should_save_block_to_snapshot(cid) && !db.has(&cid)? {
127                return Err(MissingRecentRoot {
128                    kind,
129                    cid,
130                    epoch: oldest.epoch(),
131                    depth,
132                }
133                .into());
134            }
135        }
136        Ok(())
137    })
138    .await?
139}
140
141/// Builds `seen` from the tipset at `diff` down to `diff - diff_depth`, plus genesis.
142pub async fn prepare_diff_export(
143    db: &(impl Blockstore + ShallowClone + Unpin),
144    index: &ChainIndex,
145    tipset: &Tipset,
146    diff: Option<ChainEpoch>,
147    diff_depth: Option<ChainEpochDelta>,
148    temp_dir: &Path,
149) -> anyhow::Result<ExportOptions<FileBackedCidHashSet>> {
150    let (seen, diff_base) = match diff {
151        None => (FileBackedCidHashSet::new(temp_dir)?, None),
152        Some(diff) => {
153            anyhow::ensure!(
154                diff < tipset.epoch(),
155                "diff epoch {diff} must be smaller than target epoch {}",
156                tipset.epoch()
157            );
158            let diff_ts = index
159                .load_required_tipset_by_height(
160                    diff,
161                    tipset.shallow_clone(),
162                    ResolveNullTipset::TakeOlder,
163                )
164                .await
165                .with_context(|| format!("failed to load the diff tipset at epoch {diff}"))?;
166            let diff_base = diff_ts.key().clone();
167            let diff_limit = diff_depth
168                .map(|depth| lookup_epoch_limit(diff_ts.epoch(), depth))
169                .transpose()
170                .context("invalid diff depth")?
171                .unwrap_or(0);
172            tracing::info!(
173                "building the diff base CID set, from epoch {} down to {diff_limit} and genesis...",
174                diff_ts.epoch()
175            );
176            let start = Instant::now();
177            // The export never reads headers below the base, but later state can share genesis state.
178            let tipsets = diff_ts
179                .chain_owned(db.shallow_clone())
180                .take_while(move |ts| ts.epoch() > diff_limit.max(0))
181                .chain(std::iter::once(index.genesis().shallow_clone()));
182            let mut stream = stream_chain(
183                db.shallow_clone(),
184                tipsets,
185                diff_limit,
186                FileBackedCidHashSet::new(temp_dir)?,
187            );
188            while stream.try_next().await?.is_some() {}
189            tracing::info!(
190                "built the diff base CID set, took {}",
191                utils::format_duration(start.elapsed())
192            );
193            (stream.into_seen(), Some(diff_base))
194        }
195    };
196    Ok(ExportOptions {
197        skip_checksum: false,
198        include_receipts: false,
199        include_events: false,
200        include_tipset_keys: false,
201        include_tipset_lookup: false,
202        seen,
203        diff_base,
204    })
205}
206
207/// Exports a Filecoin snapshot in v1 format
208/// See <https://github.com/filecoin-project/FIPs/blob/98e33b9fa306959aa0131519eb4cc155522b2081/FRCs/frc-0108.md#v1-specification>
209pub async fn export<D: Digest, S: CidHashSetLike + Send + Sync + 'static>(
210    db: &(impl Blockstore + ShallowClone + Unpin + Send + Sync + 'static),
211    tipset: &Tipset,
212    lookup_depth: ChainEpochDelta,
213    writer: impl AsyncWrite + Unpin,
214    options: ExportOptions<S>,
215) -> anyhow::Result<ExportResult<D>> {
216    let roots = tipset.key().to_cids();
217    export_to_forest_car::<D, S>(roots, None, db, tipset, lookup_depth, writer, options).await
218}
219
220/// Exports a Filecoin snapshot in v2 format
221/// See <https://github.com/filecoin-project/FIPs/blob/98e33b9fa306959aa0131519eb4cc155522b2081/FRCs/frc-0108.md#v2-specification>
222pub async fn export_v2<D: Digest, F: Seek + Read, S: CidHashSetLike + Send + Sync + 'static>(
223    db: &(impl Blockstore + ShallowClone + Unpin + Send + Sync + 'static),
224    mut f3: Option<(Cid, F)>,
225    tipset: &Tipset,
226    lookup_depth: ChainEpochDelta,
227    writer: impl AsyncWrite + Unpin,
228    options: ExportOptions<S>,
229) -> anyhow::Result<ExportResult<D>> {
230    // validate f3 data
231    if let Some((f3_cid, f3_data)) = &mut f3 {
232        f3_data.seek(SeekFrom::Start(0))?;
233        let expected_cid = crate::f3::snapshot::get_f3_snapshot_cid(f3_data)?;
234        anyhow::ensure!(
235            f3_cid == &expected_cid,
236            "f3 snapshot integrity check failed, actual cid: {f3_cid}, expected cid: {expected_cid}"
237        );
238    }
239
240    let head = tipset.key().to_cids();
241    let f3_cid = f3.as_ref().map(|(cid, _)| *cid);
242    let snap_meta = FilecoinSnapshotMetadata::new_v2(head, f3_cid);
243    let snap_meta_cbor_encoded = fvm_ipld_encoding::to_vec(&snap_meta)?;
244    let snap_meta_block = CarBlock {
245        cid: Cid::new_v1(
246            DAG_CBOR,
247            MultihashCode::Blake2b256.digest(&snap_meta_cbor_encoded),
248        ),
249        data: snap_meta_cbor_encoded.into(),
250    };
251    let roots = nunny::vec![snap_meta_block.cid];
252    let mut prefix_data_frames = vec![{
253        let mut encoder = forest::new_encoder(forest::DEFAULT_FOREST_CAR_COMPRESSION_LEVEL)?;
254        snap_meta_block.write(&mut encoder)?;
255        anyhow::Ok((
256            vec![snap_meta_block.cid],
257            finalize_frame(forest::DEFAULT_FOREST_CAR_COMPRESSION_LEVEL, &mut encoder)?,
258        ))
259    }];
260
261    if let Some((f3_cid, mut f3_data)) = f3 {
262        let f3_data_len = f3_data.seek(SeekFrom::End(0))?;
263        f3_data.seek(SeekFrom::Start(0))?;
264        prefix_data_frames.push({
265            let mut encoder = forest::new_encoder(forest::DEFAULT_FOREST_CAR_COMPRESSION_LEVEL)?;
266            encoder.write_car_block(f3_cid, f3_data_len, &mut f3_data)?;
267            anyhow::Ok((
268                vec![f3_cid],
269                finalize_frame(forest::DEFAULT_FOREST_CAR_COMPRESSION_LEVEL, &mut encoder)?,
270            ))
271        });
272    }
273
274    export_to_forest_car::<D, S>(
275        roots,
276        Some(prefix_data_frames),
277        db,
278        tipset,
279        lookup_depth,
280        writer,
281        options,
282    )
283    .await
284}
285
286#[allow(clippy::too_many_arguments)]
287async fn export_to_forest_car<D: Digest, S: CidHashSetLike + Send + Sync + 'static>(
288    roots: NonEmpty<Cid>,
289    prefix_data_frames: Option<Vec<anyhow::Result<ForestCarFrame>>>,
290    db: &(impl Blockstore + ShallowClone + Unpin + Send + Sync + 'static),
291    tipset: &Tipset,
292    lookup_depth: ChainEpochDelta,
293    writer: impl AsyncWrite + Unpin,
294    ExportOptions {
295        skip_checksum,
296        include_receipts,
297        include_events,
298        include_tipset_keys,
299        include_tipset_lookup,
300        seen,
301        diff_base,
302    }: ExportOptions<S>,
303) -> anyhow::Result<ExportResult<D>> {
304    if include_events && !include_receipts {
305        anyhow::bail!("message receipts must be included when events are included");
306    }
307    anyhow::ensure!(
308        diff_base.is_none() || !(include_tipset_keys || include_tipset_lookup),
309        "tipset keys and tipset lookup are not supported in diff exports"
310    );
311
312    let start = Instant::now();
313    tracing::info!(
314        "Exporting snapshot, epoch={}, depth={lookup_depth}, prefix_frames={}",
315        tipset.epoch(),
316        prefix_data_frames.as_ref().map(|v| v.len()).unwrap_or(0)
317    );
318
319    let stateroot_lookup_limit =
320        lookup_epoch_limit(tipset.epoch(), lookup_depth).context("invalid recent roots depth")?;
321    ensure_recent_roots_present(db, tipset, stateroot_lookup_limit).await?;
322
323    // Wrap writer in optional checksum calculator
324    let mut writer = AsyncWriterWithChecksum::<D, _>::new(BufWriter::new(writer), !skip_checksum);
325
326    let (ts_lookup_tx, ts_lookup_handle) = if include_tipset_lookup {
327        let (ts_lookup_tx, ts_lookup_rx) = flume::bounded::<(ChainEpoch, TipsetKey)>(1024);
328        let handle = AbortOnDropHandle::new(tokio::spawn(async move {
329            let mut hamt = Hamt::new_with_bit_width(
330                IndexMapBlockstore::default(),
331                TIPSET_LOOKUP_HAMT_BIT_WIDTH,
332            );
333            while let Ok((epoch, tsk)) = ts_lookup_rx.recv_async().await {
334                hamt.set(epoch, tsk)?;
335            }
336            hamt.flush()?;
337            anyhow::Ok(hamt)
338        }));
339        (Some(ts_lookup_tx), Some(handle))
340    } else {
341        (None, None)
342    };
343
344    // Stream stateroots in range (stateroot_lookup_limit+1)..=tipset.epoch(). Also
345    // stream all block headers until genesis, or until `diff_base` (exclusive) for diff exports.
346    let (blocks, _drop_guard) = par_buffer(
347        // Queue 1k blocks. This is enough to saturate the compressor and blocks
348        // are small enough that keeping 1k in memory isn't a problem. Average
349        // block size is between 1kb and 2kb.
350        1024,
351        stream_chain(
352            db.shallow_clone(),
353            tipset
354                .shallow_clone()
355                .chain_owned(db.shallow_clone())
356                .take_while(move |ts| diff_base.as_ref() != Some(ts.key()))
357                .inspect(move |ts| {
358                    if let Some(ts_lookup_tx) = &ts_lookup_tx
359                        && ChainIndex::is_tipset_lookup_checkpoint(ts.epoch())
360                    {
361                        _ = ts_lookup_tx.send((ts.epoch(), ts.key().clone()));
362                    }
363                }),
364            stateroot_lookup_limit,
365            seen,
366        )
367        .with_message_receipts(include_receipts)
368        .with_events(include_events)
369        .with_tipset_keys(include_tipset_keys)
370        .track_progress(true),
371    );
372
373    // Encode Ipld key-value pairs in zstd frames
374    let block_frames = forest::Encoder::compress_stream_default(blocks);
375    let frames = futures::stream::iter(prefix_data_frames.unwrap_or_default()).chain(block_frames);
376
377    // Write zstd frames and include a skippable index
378    forest::Encoder::write(&mut writer, roots, frames).await?;
379
380    // Flush to ensure everything has been successfully written
381    tokio::time::timeout(forest::ASYNC_OPS_TIMEOUT, writer.flush())
382        .await
383        .context("`writer.flush` timed out")??;
384
385    let digest = writer.finalize().map_err(|e| Error::Other(e.to_string()))?;
386
387    let tipset_lookup = if let Some(ts_lookup_handle) = ts_lookup_handle {
388        // This join is not I/O-bound: the task finishes once the `par_buffer` producer
389        // exits and drops `ts_lookup_tx`, which `Encoder::write` guarantees by exhausting
390        // the frame stream. The timeout guards against a pipeline lifecycle bug keeping a
391        // sender alive, not against slowness.
392        Some(
393            tokio::time::timeout(forest::ASYNC_OPS_TIMEOUT, ts_lookup_handle)
394                .await
395                .context(
396                    "tipset-lookup task did not finish; is a `ts_lookup_tx` sender still alive?",
397                )??,
398        )
399    } else {
400        None
401    };
402
403    tracing::info!(
404        "Exported snapshot, took {}",
405        utils::format_duration(start.elapsed())
406    );
407
408    Ok(ExportResult {
409        checksum: digest,
410        tipset_lookup,
411    })
412}
413
414pub async fn export_receipts_events_to_forest_car(
415    db: &(impl Blockstore + ShallowClone + Unpin + Send + Sync + 'static),
416    tipset: &Tipset,
417    lookup_depth: ChainEpochDelta,
418    writer: impl AsyncWrite + Unpin,
419) -> anyhow::Result<()> {
420    let start = Instant::now();
421    tracing::info!(
422        "Exporting message receipts and events snapshot, epoch={}, depth={lookup_depth}",
423        tipset.epoch(),
424    );
425
426    let min_lookup_epoch_exclusive =
427        lookup_epoch_limit(tipset.epoch(), lookup_depth).context("invalid recent roots depth")?;
428    let ipld_roots = tokio::task::spawn_blocking({
429        let tipset = tipset.shallow_clone();
430        let db = db.shallow_clone();
431        move || {
432            // With 2k state trees on mainnet, it's `~2k receipt roots` + `~8k event roots` ~= `~10k ipld roots`.
433            let mut ipld_roots = vec![];
434            for ts in tipset
435                .chain(&db)
436                .take_while(|ts| ts.epoch() > min_lookup_epoch_exclusive)
437            {
438                let message_receipts_root = *ts.parent_message_receipts();
439                ipld_roots.push(message_receipts_root);
440                let receipts = Receipt::get_receipts(&db, message_receipts_root).with_context(|| {
441                    format!(
442                        "failed to get receipts, root: {message_receipts_root}, epoch: {}, tipset key: {}",
443                        ts.epoch(),
444                        ts.key(),
445                    )
446                })?;
447                ipld_roots.extend(receipts.into_iter().filter_map(|r| r.events_root()));
448            }
449            anyhow::Ok(ipld_roots)
450        }
451    })
452    .await??;
453
454    let stream = IpldStream::new(db.shallow_clone(), ipld_roots, CidHashSet::default());
455    let mut writer = BufWriter::new(writer);
456    let (blocks, _drop_guard) = par_buffer(
457        // Queue 1k blocks. This is enough to saturate the compressor and blocks
458        // are small enough that keeping 1k in memory isn't a problem. Average
459        // block size is between 1kb and 2kb.
460        1024, stream,
461    );
462    // Encode Ipld key-value pairs in zstd frames
463    let block_frames = forest::Encoder::compress_stream_default(blocks);
464
465    // There's no data root for this snapshot, use a default CID as placeholder.
466    // Note that the output CAR could only be validated with `forest-tool snapshot validate-extended`.
467    // Another option could be including chain spine in the CAR and use head tipset key as root,
468    // whose downside would be bloating the CAR.
469    let roots = nunny::vec![Cid::default()];
470
471    // Write zstd frames and include a skippable index
472    forest::Encoder::write(&mut writer, roots, block_frames).await?;
473
474    // Flush to ensure everything has been successfully written
475    tokio::time::timeout(forest::ASYNC_OPS_TIMEOUT, writer.flush())
476        .await
477        .context("`writer.flush` timed out")??;
478
479    tracing::info!(
480        "Exported message receipts and events snapshot, took {}",
481        utils::format_duration(start.elapsed())
482    );
483
484    Ok(())
485}
486
487/// Check that the entry is at a checkpoint epoch and that the stored tipset is at that epoch.
488pub fn validate_tipset_lookup_entry<DB>(
489    db: &DB,
490    epoch: ChainEpoch,
491    tsk: &TipsetKey,
492) -> anyhow::Result<Tipset>
493where
494    DB: Blockstore,
495{
496    anyhow::ensure!(
497        ChainIndex::is_tipset_lookup_checkpoint(epoch),
498        "epoch {epoch} is not a tipset lookup checkpoint"
499    );
500    let ts: Tipset = Tipset::load_required(db, tsk)?;
501    anyhow::ensure!(
502        ts.epoch() == epoch,
503        "epochs do not match, {epoch} in hamt, {} in database",
504        ts.epoch()
505    );
506    Ok(ts)
507}
508
509/// Imports a tipset lookup snapshot into `db`, calling `on_imported` after each entry is written.
510/// Every entry is validated against the stored chain before the first write.
511pub fn import_tipset_lookup_snapshot<DB>(
512    db: &DB,
513    path: &Path,
514    mut on_imported: impl FnMut(),
515) -> anyhow::Result<()>
516where
517    DB: Blockstore + EthMappingsStore,
518{
519    let started = Instant::now();
520    let hamt_car = AnyCar::try_from(path)?;
521    anyhow::ensure!(
522        hamt_car.header_v1().roots.len() == 1,
523        "hamt car should have a single root"
524    );
525    let hamt_root = *hamt_car.header_v1().roots.first();
526    let hamt: Hamt<_, TipsetKey, ChainEpoch> =
527        Hamt::load_with_bit_width(&hamt_root, hamt_car, TIPSET_LOOKUP_HAMT_BIT_WIDTH)
528            .context("failed to load tipset lookup HAMT")?;
529    tracing::info!("Validating tipset lookup entries against the chain, this can take a while");
530    hamt.for_each_cacheless(|&epoch, tsk| {
531        validate_tipset_lookup_entry(db, epoch, tsk)?;
532        Ok(())
533    })?;
534    hamt.for_each_cacheless(|&epoch, tsk| {
535        db.set_tipset_key_at_epoch_raw(epoch, tsk)?;
536        on_imported();
537        Ok(())
538    })?;
539    tracing::info!(
540        "Imported tipset lookup entries in {:.1}s",
541        started.elapsed().as_secs_f64()
542    );
543    Ok(())
544}