-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathstate_cmd.rs
More file actions
278 lines (265 loc) · 9.45 KB
/
state_cmd.rs
File metadata and controls
278 lines (265 loc) · 9.45 KB
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
// Copyright 2019-2026 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use crate::{
blocks::Tipset,
chain::{ChainStore, index::ResolveNullTipset},
chain_sync::{load_full_tipset, tipset_syncer::validate_tipset},
cli_shared::{chain_path, read_config},
db::{SettingsStoreExt, db_engine::db_root},
genesis::read_genesis_header,
interpreter::VMTrace,
networks::{ChainConfig, NetworkChain},
shim::clock::ChainEpoch,
state_manager::{StateManager, StateOutput},
tool::subcommands::api_cmd::generate_test_snapshot,
};
use human_repr::HumanCount as _;
use nonzero_ext::nonzero;
use std::{num::NonZeroUsize, path::PathBuf, sync::Arc, time::Instant};
/// Interact with Filecoin chain state
#[derive(Debug, clap::Subcommand)]
pub enum StateCommand {
Compute(ComputeCommand),
ReplayCompute(ReplayComputeCommand),
Validate(ValidateCommand),
ReplayValidate(ReplayValidateCommand),
}
impl StateCommand {
pub async fn run(self) -> anyhow::Result<()> {
match self {
Self::Compute(cmd) => cmd.run().await,
Self::ReplayCompute(cmd) => cmd.run().await,
Self::Validate(cmd) => cmd.run().await,
Self::ReplayValidate(cmd) => cmd.run().await,
}
}
}
/// Compute state tree for an epoch
#[derive(Debug, clap::Args)]
pub struct ComputeCommand {
/// Which epoch to compute the state transition for
#[arg(long, required = true)]
epoch: ChainEpoch,
/// Filecoin network chain
#[arg(long, required = true)]
chain: NetworkChain,
/// Optional path to the database folder
#[arg(long)]
db: Option<PathBuf>,
/// Optional path to the database snapshot `CAR` file to write to for reproducing the computation
#[arg(long)]
export_db_to: Option<PathBuf>,
}
impl ComputeCommand {
pub async fn run(self) -> anyhow::Result<()> {
let Self {
epoch,
chain,
db,
export_db_to,
} = self;
disable_tipset_cache();
let db_root_path = if let Some(db) = db {
db
} else {
let (_, config) = read_config(None, Some(chain.clone()))?;
db_root(&chain_path(&config))?
};
let db = generate_test_snapshot::load_db(&db_root_path, Some(&chain)).await?;
let chain_config = Arc::new(ChainConfig::from_chain(&chain));
let genesis_header =
read_genesis_header(None, chain_config.genesis_bytes(&db).await?.as_deref(), &db)
.await?;
let chain_store = Arc::new(ChainStore::new(
db.clone(),
db.clone(),
db.clone(),
chain_config,
genesis_header,
)?);
let (ts, ts_next) = {
// We don't want to track all entries that are visited by `tipset_by_height`
db.pause_tracking();
let ts = chain_store.chain_index().tipset_by_height(
epoch,
chain_store.heaviest_tipset(),
ResolveNullTipset::TakeOlder,
)?;
let ts_next = chain_store.load_child_tipset(&ts)?;
db.resume_tracking();
SettingsStoreExt::write_obj(
&db.tracker,
crate::db::setting_keys::HEAD_KEY,
ts_next.key(),
)?;
// Only track the desired tipsets
(
Tipset::load_required(&db, ts.key())?,
Tipset::load_required(&db, ts_next.key())?,
)
};
let epoch = ts.epoch();
let state_manager = Arc::new(StateManager::new(chain_store)?);
let StateOutput {
state_root,
receipt_root,
} = state_manager
.compute_tipset_state(ts, crate::state_manager::NO_CALLBACK, VMTrace::NotTraced)
.await?;
let mut db_snapshot = vec![];
db.export_forest_car(&mut db_snapshot).await?;
println!(
"epoch: {epoch}, state_root: {state_root}, receipt_root: {receipt_root}, db_snapshot_size: {}",
db_snapshot.len().human_count_bytes()
);
let expected_state_root = *ts_next.parent_state();
let expected_receipt_root = *ts_next.parent_message_receipts();
anyhow::ensure!(
state_root == expected_state_root,
"state root mismatch, state_root: {state_root}, expected_state_root: {expected_state_root}"
);
anyhow::ensure!(
receipt_root == expected_receipt_root,
"receipt root mismatch, receipt_root: {receipt_root}, expected_receipt_root: {expected_receipt_root}"
);
if let Some(export_db_to) = export_db_to {
std::fs::write(export_db_to, db_snapshot)?;
}
Ok(())
}
}
/// Replay state computation with a db snapshot
/// To be used in conjunction with `forest-dev state compute`.
#[derive(Debug, clap::Args)]
pub struct ReplayComputeCommand {
/// Path to the database snapshot `CAR` file generated by `forest-dev state compute`
snapshot: PathBuf,
/// Filecoin network chain
#[arg(long, required = true)]
chain: NetworkChain,
/// Number of times to repeat the state computation
#[arg(short, long, default_value_t = nonzero!(1usize))]
n: NonZeroUsize,
}
impl ReplayComputeCommand {
pub async fn run(self) -> anyhow::Result<()> {
let Self { snapshot, chain, n } = self;
let (sm, ts, ts_next) =
crate::state_manager::utils::state_compute::prepare_state_compute(&chain, &snapshot)
.await?;
for _ in 0..n.get() {
crate::state_manager::utils::state_compute::state_compute(&sm, ts.clone(), &ts_next)
.await?;
}
Ok(())
}
}
/// Validate tipset at a certain epoch
#[derive(Debug, clap::Args)]
pub struct ValidateCommand {
/// Tipset epoch to validate
#[arg(long, required = true)]
epoch: ChainEpoch,
/// Filecoin network chain
#[arg(long, required = true)]
chain: NetworkChain,
/// Optional path to the database folder
#[arg(long)]
db: Option<PathBuf>,
/// Optional path to the database snapshot `CAR` file to write to for reproducing the computation
#[arg(long)]
export_db_to: Option<PathBuf>,
}
impl ValidateCommand {
pub async fn run(self) -> anyhow::Result<()> {
let Self {
epoch,
chain,
db,
export_db_to,
} = self;
disable_tipset_cache();
let db_root_path = if let Some(db) = db {
db
} else {
let (_, config) = read_config(None, Some(chain.clone()))?;
db_root(&chain_path(&config))?
};
let db = generate_test_snapshot::load_db(&db_root_path, Some(&chain)).await?;
let chain_config = Arc::new(ChainConfig::from_chain(&chain));
let genesis_header =
read_genesis_header(None, chain_config.genesis_bytes(&db).await?.as_deref(), &db)
.await?;
let chain_store = Arc::new(ChainStore::new(
db.clone(),
db.clone(),
db.clone(),
chain_config,
genesis_header,
)?);
let ts = {
// We don't want to track all entries that are visited by `tipset_by_height`
db.pause_tracking();
let ts = chain_store.chain_index().tipset_by_height(
epoch,
chain_store.heaviest_tipset(),
ResolveNullTipset::TakeOlder,
)?;
db.resume_tracking();
SettingsStoreExt::write_obj(&db.tracker, crate::db::setting_keys::HEAD_KEY, ts.key())?;
// Only track the desired tipset
Tipset::load_required(&db, ts.key())?
};
let epoch = ts.epoch();
let fts = load_full_tipset(&chain_store, ts.key())?;
let state_manager = Arc::new(StateManager::new(chain_store)?);
validate_tipset(&state_manager, fts, None).await?;
let mut db_snapshot = vec![];
db.export_forest_car(&mut db_snapshot).await?;
println!(
"epoch: {epoch}, db_snapshot_size: {}",
db_snapshot.len().human_count_bytes()
);
if let Some(export_db_to) = export_db_to {
std::fs::write(export_db_to, db_snapshot)?;
}
Ok(())
}
}
/// Replay tipset validation with a db snapshot
/// To be used in conjunction with `forest-dev state validate`.
#[derive(Debug, clap::Args)]
pub struct ReplayValidateCommand {
/// Path to the database snapshot `CAR` file generated by `forest-dev state validate`
snapshot: PathBuf,
/// Filecoin network chain
#[arg(long, required = true)]
chain: NetworkChain,
/// Number of times to repeat the state computation
#[arg(short, long, default_value_t = nonzero!(1usize))]
n: NonZeroUsize,
}
impl ReplayValidateCommand {
pub async fn run(self) -> anyhow::Result<()> {
let Self { snapshot, chain, n } = self;
let (sm, fts) =
crate::state_manager::utils::state_compute::prepare_state_validate(&chain, &snapshot)
.await?;
let epoch = fts.epoch();
for _ in 0..n.get() {
let fts = fts.clone();
let start = Instant::now();
validate_tipset(&sm, fts, None).await?;
println!(
"epoch: {epoch}, took {}.",
humantime::format_duration(start.elapsed())
);
}
Ok(())
}
}
fn disable_tipset_cache() {
unsafe {
std::env::set_var("FOREST_TIPSET_CACHE_DISABLED", "1");
}
}