1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright 2019-2026 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use crate::chain::FilecoinSnapshotVersion;
use crate::chain_sync::chain_muxer::DEFAULT_RECENT_STATE_ROOTS;
use crate::cli_shared::snapshot::{self, TrustedVendor};
use crate::db::car::forest::new_forest_car_temp_path_in;
use crate::networks::calibnet;
use crate::rpc::chain::ForestChainExportDiffParams;
use crate::rpc::types::ApiExportResult;
use crate::rpc::{self, chain::ForestChainExportParams, prelude::*};
use crate::shim::policy::policy_constants::CHAIN_FINALITY;
use anyhow::Context as _;
use chrono::DateTime;
use clap::Subcommand;
use indicatif::{ProgressBar, ProgressStyle};
use std::{
path::{Path, PathBuf},
time::Duration,
};
use tokio::io::AsyncWriteExt;
#[derive(Debug, Clone, clap::ValueEnum)]
pub enum Format {
Json,
Text,
}
#[derive(Debug, Subcommand)]
pub enum SnapshotCommands {
/// Export a snapshot of the chain to `<output_path>`
Export {
/// `./forest_snapshot_{chain}_{year}-{month}-{day}_height_{epoch}.car.zst`.
#[arg(short, long, default_value = ".", verbatim_doc_comment)]
output_path: PathBuf,
/// Skip creating the checksum file.
#[arg(long)]
skip_checksum: bool,
/// Don't write the archive.
#[arg(long)]
dry_run: bool,
/// Tipset to start the export from, default is the chain head
#[arg(short, long)]
tipset: Option<i64>,
/// How many state trees to include. 0 for chain spine with no state trees.
#[arg(short, long, default_value_t = DEFAULT_RECENT_STATE_ROOTS)]
depth: crate::chain::ChainEpochDelta,
/// Snapshot format to export.
#[arg(long, value_enum, default_value_t = FilecoinSnapshotVersion::V2)]
format: FilecoinSnapshotVersion,
},
/// Show status of the current export.
ExportStatus {
/// Wait until it completes and print progress.
#[arg(long)]
wait: bool,
/// Format of the output. `json` or `text`.
#[arg(long, value_enum, default_value_t = Format::Text)]
format: Format,
},
/// Cancel the current export.
ExportCancel {},
/// Export a diff snapshot between `from` and `to` epochs to `<output_path>`
ExportDiff {
/// `./forest_snapshot_diff_{chain}_{from}_{to}+{depth}.car.zst`.
#[arg(short, long, default_value = ".", verbatim_doc_comment)]
output_path: PathBuf,
/// Epoch to export from
#[arg(long)]
from: i64,
/// Epoch to diff against
#[arg(long)]
to: i64,
/// How many state-roots to include. Lower limit is 900 for `calibnet` and `mainnet`.
#[arg(short, long)]
depth: Option<crate::chain::ChainEpochDelta>,
},
}
impl SnapshotCommands {
pub async fn run(self, client: rpc::Client) -> anyhow::Result<()> {
match self {
Self::Export {
output_path,
skip_checksum,
dry_run,
tipset,
depth,
format,
} => {
anyhow::ensure!(
depth >= 0,
"--depth must be non-negative; use 0 for spine-only snapshots"
);
if depth < CHAIN_FINALITY {
tracing::warn!(
"Depth {depth} should be no less than CHAIN_FINALITY {CHAIN_FINALITY} to export a valid lite snapshot"
);
}
let raw_network_name = StateNetworkName::call(&client, ()).await?;
// For historical reasons and backwards compatibility if snapshot services or their
// consumers relied on the `calibnet`, we use `calibnet` as the chain name.
let chain_name = if raw_network_name == calibnet::NETWORK_GENESIS_NAME {
calibnet::NETWORK_COMMON_NAME
} else {
raw_network_name.as_str()
};
let tipset = if let Some(epoch) = tipset {
// This could take a while when the requested epoch is far behind the chain head
client
.call(
ChainGetTipSetByHeight::request((epoch, Default::default()))?
.with_timeout(Duration::from_secs(60 * 15)),
)
.await?
} else {
ChainHead::call(&client, ()).await?
};
let output_path = match output_path.is_dir() {
true => output_path.join(snapshot::filename(
TrustedVendor::Forest,
chain_name,
DateTime::from_timestamp(tipset.min_ticket_block().timestamp as i64, 0)
.unwrap_or_default()
.naive_utc()
.date(),
tipset.epoch(),
true,
)),
false => output_path.clone(),
};
let output_dir = output_path.parent().context("invalid output path")?;
let temp_path = new_forest_car_temp_path_in(output_dir)?;
let params = ForestChainExportParams {
version: format,
epoch: tipset.epoch(),
recent_roots: depth,
output_path: temp_path.to_path_buf(),
tipset_keys: tipset.key().clone().into(),
include_receipts: false,
include_events: false,
include_tipset_keys: false,
skip_checksum,
dry_run,
};
let pb = ProgressBar::new_spinner().with_style(
ProgressStyle::with_template(
"{spinner} {msg} {binary_total_bytes} written in {elapsed} ({binary_bytes_per_sec})",
)
.expect("indicatif template must be valid"),
).with_message(format!("Exporting v{} snapshot to {} ...", format as u64, output_path.display()));
pb.enable_steady_tick(std::time::Duration::from_millis(80));
let handle = tokio::spawn({
let path: PathBuf = (&temp_path).into();
let pb = pb.clone();
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(1));
async move {
loop {
interval.tick().await;
if let Ok(meta) = std::fs::metadata(&path) {
pb.set_position(meta.len());
}
}
}
});
// Manually construct RpcRequest because snapshot export could
// take a few hours on mainnet
let export_result = client
.call(ForestChainExport::request((params,))?.with_timeout(Duration::MAX))
.await?;
handle.abort();
pb.finish();
_ = handle.await;
if !dry_run {
match export_result.clone() {
ApiExportResult::Done(hash_opt) => {
// Move the file first; prevents orphaned checksum on persist error.
temp_path.persist(&output_path)?;
if let Some(hash) = hash_opt {
save_checksum(&output_path, hash).await?;
}
}
ApiExportResult::Cancelled => { /* no file to persist on cancel */ }
}
}
match export_result {
ApiExportResult::Done(_) => {
println!("Export completed.");
}
ApiExportResult::Cancelled => {
println!("Export cancelled.");
}
}
Ok(())
}
Self::ExportStatus { wait, format } => {
let result = client
.call(
ForestChainExportStatus::request(())?.with_timeout(Duration::from_secs(30)),
)
.await?;
if !result.exporting
&& let Format::Text = format
{
if result.cancelled {
println!("No export in progress (last export was cancelled)");
} else {
println!("No export in progress");
}
return Ok(());
}
if wait {
let elapsed = chrono::Utc::now()
.signed_duration_since(result.start_time.unwrap_or_default())
.to_std()
.unwrap_or(Duration::ZERO);
let pb = ProgressBar::new(10000)
.with_elapsed(elapsed)
.with_message("Exporting");
pb.set_style(
ProgressStyle::with_template(
"[{elapsed_precise}] [{wide_bar}] {percent}% {msg} ",
)
.expect("indicatif template must be valid")
.progress_chars("#>-"),
);
loop {
let result = client
.call(
ForestChainExportStatus::request(())?
.with_timeout(Duration::from_secs(30)),
)
.await?;
if result.cancelled {
pb.set_message("Export cancelled");
pb.abandon();
return Ok(());
}
let position = (result.progress.clamp(0.0, 1.0) * 10000.0).trunc() as u64;
pb.set_position(position);
if position >= 10000 {
break;
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
pb.finish_with_message("Export completed");
return Ok(());
}
match format {
Format::Text => {
println!("Exporting: {:.1}%", result.progress.clamp(0.0, 1.0) * 100.0);
}
Format::Json => {
println!("{}", serde_json::to_string_pretty(&result)?);
}
}
Ok(())
}
Self::ExportCancel {} => {
let result = client
.call(
ForestChainExportCancel::request(())?.with_timeout(Duration::from_secs(30)),
)
.await?;
if result {
println!("Export cancelled.");
} else {
println!("No export in progress to cancel.");
}
Ok(())
}
Self::ExportDiff {
output_path,
from,
to,
depth,
} => {
let raw_network_name = StateNetworkName::call(&client, ()).await?;
// For historical reasons and backwards compatibility if snapshot services or their
// consumers relied on the `calibnet`, we use `calibnet` as the chain name.
let chain_name = if raw_network_name == calibnet::NETWORK_GENESIS_NAME {
calibnet::NETWORK_COMMON_NAME
} else {
raw_network_name.as_str()
};
let depth = depth.unwrap_or_else(|| from - to);
anyhow::ensure!(depth > 0, "depth must be positive");
let output_path = match output_path.is_dir() {
true => output_path.join(format!(
"forest_snapshot_diff_{chain_name}_{from}_{to}+{depth}.car.zst"
)),
false => output_path.clone(),
};
let output_dir = output_path.parent().context("invalid output path")?;
let temp_path = new_forest_car_temp_path_in(output_dir)?;
let params = ForestChainExportDiffParams {
output_path: temp_path.to_path_buf(),
from,
to,
depth,
};
let pb = ProgressBar::new_spinner().with_style(
ProgressStyle::with_template(
"{spinner} {msg} {binary_total_bytes} written in {elapsed} ({binary_bytes_per_sec})",
)
.expect("indicatif template must be valid"),
).with_message(format!("Exporting {} ...", output_path.display()));
pb.enable_steady_tick(std::time::Duration::from_millis(80));
let handle = tokio::spawn({
let path: PathBuf = (&temp_path).into();
let pb = pb.clone();
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(1));
async move {
loop {
interval.tick().await;
if let Ok(meta) = std::fs::metadata(&path) {
pb.set_position(meta.len());
}
}
}
});
// Manually construct RpcRequest because snapshot export could
// take a few hours on mainnet
client
.call(ForestChainExportDiff::request((params,))?.with_timeout(Duration::MAX))
.await?;
handle.abort();
pb.finish();
_ = handle.await;
temp_path.persist(output_path)?;
println!("Export completed.");
Ok(())
}
}
}
}
/// Prints hex-encoded representation of SHA-256 checksum and saves it to a file
/// with the same name but with a `.sha256sum` extension.
async fn save_checksum(source: &Path, encoded_hash: String) -> anyhow::Result<()> {
let checksum_file_content = format!(
"{encoded_hash} {}\n",
source
.file_name()
.and_then(std::ffi::OsStr::to_str)
.context("Failed to retrieve file name while saving checksum")?
);
let checksum_path = PathBuf::from(source).with_extension("sha256sum");
let mut checksum_file = tokio::fs::File::create(&checksum_path).await?;
checksum_file
.write_all(checksum_file_content.as_bytes())
.await?;
checksum_file.flush().await?;
Ok(())
}