referrerpolicy=no-referrer-when-downgrade

frame_remote_externalities/
config.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Configuration types for remote externalities.
19
20use codec::{Compact, Decode, Encode};
21use sp_runtime::{traits::Block as BlockT, StateVersion};
22use std::{
23	fs,
24	path::{Path, PathBuf},
25};
26
27use crate::Result;
28
29pub(crate) const DEFAULT_WS_ENDPOINT: &str = "wss://try-runtime.polkadot.io:443";
30pub(crate) type SnapshotVersion = Compact<u16>;
31pub(crate) const SNAPSHOT_VERSION: SnapshotVersion = Compact(4);
32
33/// The execution mode.
34#[derive(Clone)]
35pub enum Mode<H> {
36	/// Online. Potentially writes to a snapshot file.
37	Online(OnlineConfig<H>),
38	/// Offline. Uses a state snapshot file and needs not any client config.
39	Offline(OfflineConfig),
40	/// Prefer using a snapshot file if it exists, else use a remote server.
41	OfflineOrElseOnline(OfflineConfig, OnlineConfig<H>),
42}
43
44impl<H> Default for Mode<H> {
45	fn default() -> Self {
46		Mode::Online(OnlineConfig::default())
47	}
48}
49
50/// Configuration of the offline execution.
51///
52/// A state snapshot config must be present.
53#[derive(Clone)]
54pub struct OfflineConfig {
55	/// The configuration of the state snapshot file to use. It must be present.
56	pub state_snapshot: SnapshotConfig,
57}
58
59/// Configuration of the online execution.
60///
61/// A state snapshot config may be present and will be written to in that case.
62#[derive(Clone)]
63pub struct OnlineConfig<H> {
64	/// The block hash at which to get the runtime state. Will be latest finalized head if not
65	/// provided.
66	pub at: Option<H>,
67	/// An optional state snapshot file to WRITE to, not for reading. Not written if set to `None`.
68	pub state_snapshot: Option<SnapshotConfig>,
69	/// The pallets to scrape. These values are hashed and added to `hashed_prefix`.
70	pub pallets: Vec<String>,
71	/// Transport URIs. Can be a single URI or multiple for load distribution.
72	pub transport_uris: Vec<String>,
73	/// Lookout for child-keys, and scrape them as well if set to true.
74	pub child_trie: bool,
75	/// Storage entry key prefixes to be injected into the externalities. The *hashed* prefix must
76	/// be given.
77	pub hashed_prefixes: Vec<Vec<u8>>,
78	/// Storage entry keys to be injected into the externalities. The *hashed* key must be given.
79	pub hashed_keys: Vec<Vec<u8>>,
80	/// Disable verifying the downloaded storage root against the block header's state root.
81	///
82	/// The check fails `build` when the scraped state is incomplete or corrupted. Set this to
83	/// bypass it when deliberately overwriting the state version. Use with care.
84	pub disable_root_check: bool,
85}
86
87impl<H: Clone> OnlineConfig<H> {
88	pub(crate) fn at_expected(&self) -> H {
89		self.at.clone().expect("block at must be initialized; qed")
90	}
91}
92
93impl<H> Default for OnlineConfig<H> {
94	fn default() -> Self {
95		Self {
96			transport_uris: vec![DEFAULT_WS_ENDPOINT.to_owned()],
97			child_trie: true,
98			at: None,
99			state_snapshot: None,
100			pallets: Default::default(),
101			hashed_keys: Default::default(),
102			hashed_prefixes: Default::default(),
103			disable_root_check: false,
104		}
105	}
106}
107
108impl<H> From<String> for OnlineConfig<H> {
109	fn from(uri: String) -> Self {
110		Self { transport_uris: vec![uri], ..Default::default() }
111	}
112}
113
114/// Configuration of the state snapshot.
115#[derive(Clone)]
116pub struct SnapshotConfig {
117	/// The path to the snapshot file.
118	pub path: PathBuf,
119}
120
121impl SnapshotConfig {
122	pub fn new<P: Into<PathBuf>>(path: P) -> Self {
123		Self { path: path.into() }
124	}
125}
126
127impl From<String> for SnapshotConfig {
128	fn from(s: String) -> Self {
129		Self::new(s)
130	}
131}
132
133impl Default for SnapshotConfig {
134	fn default() -> Self {
135		Self { path: Path::new("SNAPSHOT").into() }
136	}
137}
138
139/// The snapshot that we store on disk.
140#[derive(Decode, Encode)]
141pub(crate) struct Snapshot<B: BlockT> {
142	snapshot_version: SnapshotVersion,
143	pub(crate) state_version: StateVersion,
144	pub(crate) raw_storage: Vec<(Vec<u8>, (Vec<u8>, i32))>,
145	pub(crate) storage_root: B::Hash,
146	pub(crate) header: B::Header,
147}
148
149impl<B: BlockT> Snapshot<B> {
150	pub(crate) fn new(
151		state_version: StateVersion,
152		raw_storage: Vec<(Vec<u8>, (Vec<u8>, i32))>,
153		storage_root: B::Hash,
154		header: B::Header,
155	) -> Self {
156		Self {
157			snapshot_version: SNAPSHOT_VERSION,
158			state_version,
159			raw_storage,
160			storage_root,
161			header,
162		}
163	}
164
165	pub(crate) fn load(path: &PathBuf) -> Result<Snapshot<B>> {
166		let bytes = fs::read(path).map_err(|_| "fs::read failed.")?;
167		// The first item in the SCALE encoded struct bytes is the snapshot version. We decode and
168		// check that first, before proceeding to decode the rest of the snapshot.
169		let snapshot_version = SnapshotVersion::decode(&mut &*bytes)
170			.map_err(|_| "Failed to decode snapshot version")?;
171
172		if snapshot_version != SNAPSHOT_VERSION {
173			return Err("Unsupported snapshot version detected. Please create a new snapshot.");
174		}
175
176		Decode::decode(&mut &*bytes).map_err(|_| "Decode failed")
177	}
178}