referrerpolicy=no-referrer-when-downgrade

sc_service/client/
call_executor.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use super::{code_provider::CodeProvider, ClientConfig};
20use sc_client_api::{
21	backend, call_executor::CallExecutor, execution_extensions::ExecutionExtensions, HeaderBackend,
22	TrieCacheContext,
23};
24use sc_executor::{RuntimeVersion, RuntimeVersionOf};
25use sp_api::ProofRecorder;
26use sp_core::traits::{CallContext, CodeExecutor};
27use sp_externalities::Extensions;
28use sp_runtime::{
29	generic::BlockId,
30	traits::{Block as BlockT, HashingFor},
31};
32use sp_state_machine::{
33	backend::{AsTrieBackend, TryPendingCode},
34	OverlayedChanges, StateMachine, StorageProof,
35};
36use std::{cell::RefCell, sync::Arc};
37
38/// Call executor that executes methods locally, querying all required
39/// data from local backend.
40pub struct LocalCallExecutor<Block: BlockT, B, E> {
41	backend: Arc<B>,
42	executor: E,
43	code_provider: CodeProvider<Block, B, E>,
44	execution_extensions: Arc<ExecutionExtensions<Block>>,
45}
46
47impl<Block: BlockT, B, E> LocalCallExecutor<Block, B, E>
48where
49	E: CodeExecutor + RuntimeVersionOf + Clone + 'static,
50	B: backend::Backend<Block>,
51{
52	/// Creates new instance of local call executor.
53	pub fn new(
54		backend: Arc<B>,
55		executor: E,
56		client_config: ClientConfig<Block>,
57		execution_extensions: ExecutionExtensions<Block>,
58	) -> sp_blockchain::Result<Self> {
59		let code_provider = CodeProvider::new(&client_config, executor.clone(), backend.clone())?;
60
61		Ok(LocalCallExecutor {
62			backend,
63			executor,
64			code_provider,
65			execution_extensions: Arc::new(execution_extensions),
66		})
67	}
68}
69
70impl<Block: BlockT, B, E> Clone for LocalCallExecutor<Block, B, E>
71where
72	E: Clone,
73{
74	fn clone(&self) -> Self {
75		LocalCallExecutor {
76			backend: self.backend.clone(),
77			executor: self.executor.clone(),
78			code_provider: self.code_provider.clone(),
79			execution_extensions: self.execution_extensions.clone(),
80		}
81	}
82}
83
84impl<B, E, Block> CallExecutor<Block> for LocalCallExecutor<Block, B, E>
85where
86	B: backend::Backend<Block>,
87	E: CodeExecutor + RuntimeVersionOf + Clone + 'static,
88	Block: BlockT,
89{
90	type Error = E::Error;
91
92	type Backend = B;
93
94	fn execution_extensions(&self) -> &ExecutionExtensions<Block> {
95		&self.execution_extensions
96	}
97
98	fn call(
99		&self,
100		at_hash: Block::Hash,
101		method: &str,
102		call_data: &[u8],
103		context: CallContext,
104	) -> sp_blockchain::Result<Vec<u8>> {
105		let mut changes = OverlayedChanges::default();
106		let at_number =
107			self.backend.blockchain().expect_block_number_from_id(&BlockId::Hash(at_hash))?;
108		let state = self.backend.state_at(at_hash, context.into())?;
109
110		let state_runtime_code =
111			sp_state_machine::backend::BackendRuntimeCode::new(&state, context.into());
112		let runtime_code =
113			state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?;
114
115		let runtime_code = self.code_provider.maybe_override_code(runtime_code, &state, at_hash)?.0;
116
117		let mut extensions = self.execution_extensions.extensions(at_hash, at_number);
118
119		let mut sm = StateMachine::new(
120			&state,
121			&mut changes,
122			&self.executor,
123			method,
124			call_data,
125			&mut extensions,
126			&runtime_code,
127			context,
128		)
129		.set_parent_hash(at_hash);
130
131		sm.execute().map_err(Into::into)
132	}
133
134	fn contextual_call(
135		&self,
136		at_hash: Block::Hash,
137		method: &str,
138		call_data: &[u8],
139		changes: &RefCell<OverlayedChanges<HashingFor<Block>>>,
140		recorder: &Option<ProofRecorder<Block>>,
141		call_context: CallContext,
142		extensions: &RefCell<Extensions>,
143	) -> Result<Vec<u8>, sp_blockchain::Error> {
144		let state = self.backend.state_at(at_hash, call_context.into())?;
145
146		let changes = &mut *changes.borrow_mut();
147
148		// It is important to extract the runtime code here before we create the proof
149		// recorder to not record it. We also need to fetch the runtime code from `state` to
150		// make sure we use the caching layers.
151		let state_runtime_code =
152			sp_state_machine::backend::BackendRuntimeCode::new(&state, call_context.into());
153
154		let runtime_code =
155			state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?;
156		let runtime_code = self.code_provider.maybe_override_code(runtime_code, &state, at_hash)?.0;
157		let mut extensions = extensions.borrow_mut();
158
159		match recorder {
160			Some(recorder) => {
161				let trie_state = state.as_trie_backend();
162
163				let backend = sp_state_machine::TrieBackendBuilder::wrap(&trie_state)
164					.with_recorder(recorder.clone())
165					.build();
166
167				let mut state_machine = StateMachine::new(
168					&backend,
169					changes,
170					&self.executor,
171					method,
172					call_data,
173					&mut extensions,
174					&runtime_code,
175					call_context,
176				)
177				.set_parent_hash(at_hash);
178				state_machine.execute()
179			},
180			None => {
181				let mut state_machine = StateMachine::new(
182					&state,
183					changes,
184					&self.executor,
185					method,
186					call_data,
187					&mut extensions,
188					&runtime_code,
189					call_context,
190				)
191				.set_parent_hash(at_hash);
192				state_machine.execute()
193			},
194		}
195		.map_err(Into::into)
196	}
197
198	fn runtime_version(
199		&self,
200		at_hash: Block::Hash,
201		call_context: CallContext,
202	) -> sp_blockchain::Result<RuntimeVersion> {
203		let state = self.backend.state_at(at_hash, backend::TrieCacheContext::Untrusted)?;
204		let state_runtime_code =
205			sp_state_machine::backend::BackendRuntimeCode::new(&state, call_context.into());
206
207		let runtime_code =
208			state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?;
209		self.code_provider
210			.maybe_override_code(runtime_code, &state, at_hash)
211			.map(|(_, v)| v)
212	}
213
214	fn prove_execution(
215		&self,
216		at_hash: Block::Hash,
217		method: &str,
218		call_data: &[u8],
219	) -> sp_blockchain::Result<(Vec<u8>, StorageProof)> {
220		let at_number =
221			self.backend.blockchain().expect_block_number_from_id(&BlockId::Hash(at_hash))?;
222		let state = self.backend.state_at(at_hash, TrieCacheContext::Untrusted)?;
223
224		let trie_backend = state.as_trie_backend();
225
226		let state_runtime_code =
227			sp_state_machine::backend::BackendRuntimeCode::new(trie_backend, TryPendingCode::No);
228		let runtime_code =
229			state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?;
230		let runtime_code = self.code_provider.maybe_override_code(runtime_code, &state, at_hash)?.0;
231
232		sp_state_machine::prove_execution_on_trie_backend(
233			trie_backend,
234			&mut Default::default(),
235			&self.executor,
236			method,
237			call_data,
238			&runtime_code,
239			&mut self.execution_extensions.extensions(at_hash, at_number),
240		)
241		.map_err(Into::into)
242	}
243}
244
245impl<B, E, Block> RuntimeVersionOf for LocalCallExecutor<Block, B, E>
246where
247	E: RuntimeVersionOf,
248	Block: BlockT,
249{
250	fn runtime_version(
251		&self,
252		ext: &mut dyn sp_externalities::Externalities,
253		runtime_code: &sp_core::traits::RuntimeCode,
254	) -> Result<sp_version::RuntimeVersion, sc_executor::error::Error> {
255		RuntimeVersionOf::runtime_version(&self.executor, ext, runtime_code)
256	}
257}
258
259impl<Block, B, E> sp_version::GetRuntimeVersionAt<Block> for LocalCallExecutor<Block, B, E>
260where
261	B: backend::Backend<Block>,
262	E: CodeExecutor + RuntimeVersionOf + Clone + 'static,
263	Block: BlockT,
264{
265	fn runtime_version(
266		&self,
267		at: Block::Hash,
268		call_context: CallContext,
269	) -> Result<sp_version::RuntimeVersion, String> {
270		CallExecutor::runtime_version(self, at, call_context).map_err(|e| e.to_string())
271	}
272}
273
274impl<Block, B, E> sp_version::GetNativeVersion for LocalCallExecutor<Block, B, E>
275where
276	B: backend::Backend<Block>,
277	E: CodeExecutor + sp_version::GetNativeVersion + Clone + 'static,
278	Block: BlockT,
279{
280	fn native_version(&self) -> &sp_version::NativeVersion {
281		self.executor.native_version()
282	}
283}