forked from paritytech/try-runtime-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecute_block.rs
More file actions
258 lines (228 loc) · 9.3 KB
/
Copy pathexecute_block.rs
File metadata and controls
258 lines (228 loc) · 9.3 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
// This file is part of try-runtime-cli.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{fmt::Debug, str::FromStr};
use parity_scale_codec::Encode;
use sc_executor::{sp_wasm_interface::HostFunctions, WasmExecutor};
use sp_rpc::{list::ListOrValue, number::NumberOrHex};
use sp_runtime::{
generic::SignedBlock,
traits::{Block as BlockT, Header as HeaderT, NumberFor},
};
use substrate_rpc_client::{ws_client, ChainApi, WsClient};
use crate::{
common::state::{
build_executor, state_machine_call_with_proof, LiveState, RuntimeChecks, State,
},
full_extensions, rpc_err_handler, SharedParams, LOG_TARGET,
};
/// Configurations for [`run`].
///
/// This will always call into `TryRuntime_execute_block`, which can optionally skip the state-root
/// check (useful for trying a unreleased runtime), and can execute runtime sanity checks as well.
#[derive(Debug, Clone, clap::Parser)]
pub struct Command {
/// Which try-state targets to execute when running this command.
///
/// Expected values:
/// - `all`
/// - `none`
/// - A comma separated list of pallets, as per pallet names in `construct_runtime!()` (e.g.
/// `Staking, System`).
/// - `rr-[x]` where `[x]` is a number. Then, the given number of pallets are checked in a
/// round-robin fashion.
#[arg(long, default_value = "all")]
pub try_state: frame_try_runtime::TryStateSelect,
/// Block number to start execution from.
#[arg(long, requires = "to")]
pub from: Option<u64>,
/// Block number to stop execution at.
#[arg(long, requires = "from")]
pub to: Option<u64>,
/// The ws uri from which to fetch the block.
///
/// This will always fetch the next block of whatever `state` is referring to, because this is
/// the only sensible combination. In other words, if you have the state of block `n`, you
/// should execute block `n+1` on top of it.
///
/// If `state` is `Live`, this can be ignored and the same uri is used for both.
#[arg(
long,
value_parser = crate::common::parse::url
)]
pub block_ws_uri: Option<String>,
/// The state type to use.
#[command(subcommand)]
pub state: State,
}
impl Command {
fn block_ws_uri(&self) -> String {
match (&self.block_ws_uri, &self.state) {
(Some(block_ws_uri), State::Snap { .. }) => block_ws_uri.to_owned(),
(Some(block_ws_uri), State::Live { .. }) => {
log::error!(target: LOG_TARGET, "--block-uri is provided while state type is live, Are you sure you know what you are doing?");
block_ws_uri.to_owned()
}
(None, State::Live(LiveState { uri, .. })) => uri[0].clone(),
(None, State::Snap { .. }) => {
panic!("either `--block-uri` must be provided, or state must be `live`");
}
}
}
}
// Runs the `execute_block` command.
pub async fn run<Block, HostFns>(shared: SharedParams, command: Command) -> sc_cli::Result<()>
where
Block: BlockT + serde::de::DeserializeOwned,
<Block::Hash as FromStr>::Err: Debug,
Block::Hash: serde::de::DeserializeOwned,
Block::Header: serde::de::DeserializeOwned,
<NumberFor<Block> as TryInto<u64>>::Error: Debug,
HostFns: HostFunctions,
{
let executor = build_executor::<HostFns>(&shared);
let block_ws_uri = command.block_ws_uri();
let rpc = ws_client(&block_ws_uri).await?;
// If --from and --to is passed, they take precedence over LiveState --at.
if let (Some(from), Some(to)) = (command.from, command.to) {
if from > to {
return Err(sc_cli::Error::Application(
format!("--from ({from}) must be less than or equal to --to ({to})").into(),
));
}
let block_numbers = (from..=to).map(NumberOrHex::Number).collect::<Vec<_>>();
let hash_list = ChainApi::<(), Block::Hash, Block::Header, SignedBlock<Block>>::block_hash(
&rpc,
Some(ListOrValue::List(block_numbers)),
)
.await
.map_err(rpc_err_handler)?;
if let ListOrValue::List(hashes) = hash_list {
for (block_number, hash) in (from..=to).zip(hashes) {
let Some(hash) = hash else {
log::warn!(target: LOG_TARGET, "skipping block {block_number}, hash was None");
continue;
};
log::info!(target: LOG_TARGET, "hash found, block number: {block_number}, hash: {hash}");
let header =
ChainApi::<(), Block::Hash, Block::Header, SignedBlock<Block>>::header(
&rpc,
Some(hash),
)
.await
.map_err(rpc_err_handler)?
.expect("hash exists, header should exist;");
let live_state = LiveState {
uri: vec![block_ws_uri.clone()],
at: Some(hex::encode(header.hash().encode())),
pallet: Default::default(),
hashed_prefixes: Default::default(),
child_tree: Default::default(),
};
execute_block::<Block, HostFns>(&shared, &command, &executor, &rpc, live_state)
.await?;
}
}
Ok(())
} else {
let live_state = match &command.state {
State::Live(live_state) => {
// If no --at is provided, get the latest block to replay
if live_state.at.is_some() {
live_state.clone()
} else {
let header =
ChainApi::<(), Block::Hash, Block::Header, SignedBlock<Block>>::header(
&rpc, None,
)
.await
.map_err(rpc_err_handler)?
.expect("header exists, block should also exist; qed");
LiveState {
uri: vec![block_ws_uri],
at: Some(hex::encode(header.hash().encode())),
pallet: Default::default(),
hashed_prefixes: Default::default(),
child_tree: Default::default(),
}
}
}
_ => {
unreachable!("execute block currently only supports Live state")
}
};
execute_block::<Block, HostFns>(&shared, &command, &executor, &rpc, live_state).await
}
}
// Perform block execution on live state
pub async fn execute_block<Block, HostFns>(
shared: &SharedParams,
command: &Command,
executor: &WasmExecutor<HostFns>,
rpc: &WsClient,
live_state: LiveState,
) -> sc_cli::Result<()>
where
Block: BlockT + serde::de::DeserializeOwned,
<Block::Hash as FromStr>::Err: Debug,
Block::Hash: serde::de::DeserializeOwned,
Block::Header: serde::de::DeserializeOwned,
<NumberFor<Block> as TryInto<u64>>::Error: Debug,
HostFns: HostFunctions,
{
// The block we want to *execute* at is the block passed by the user
let execute_at = live_state.at::<Block>()?;
let prev_block_live_state = live_state.to_prev_block_live_state::<Block>().await?;
// Get state for the prev block
let runtime_checks = RuntimeChecks {
name_matches: !shared.disable_spec_name_check,
version_increases: false,
try_runtime_feature_enabled: true,
};
let ext = State::Live(prev_block_live_state)
.to_ext::<Block, HostFns>(shared, executor, None, runtime_checks)
.await?;
// Execute the desired block on top of it
let block =
ChainApi::<(), Block::Hash, Block::Header, SignedBlock<Block>>::block(rpc, execute_at)
.await
.map_err(rpc_err_handler)?
.expect("header exists, block should also exist; qed")
.block;
// A digest item gets added when the runtime is processing the block, so we need to pop
// the last one to be consistent with what a gossiped block would contain.
let (mut header, extrinsics) = block.deconstruct();
header.digest_mut().pop();
let block = Block::new(header, extrinsics);
// for now, hardcoded for the sake of simplicity. We might customize them one day.
let state_root_check = false;
let signature_check = false;
let payload = (
block.clone(),
state_root_check,
signature_check,
command.try_state.clone(),
)
.encode();
let _ = state_machine_call_with_proof::<Block, HostFns>(
&ext,
&mut Default::default(),
executor,
"TryRuntime_execute_block",
&payload,
full_extensions(executor.clone()),
shared.export_proof.clone(),
)?;
Ok(())
}