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, time::Duration};
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, runtime_version) =
116			self.code_provider.maybe_override_code(runtime_code, &state, at_hash)?;
117
118		let mut extensions = self.execution_extensions.extensions(at_hash, at_number);
119
120		let mut sm = StateMachine::new(
121			&state,
122			&mut changes,
123			&self.executor,
124			method,
125			call_data,
126			&mut extensions,
127			&runtime_code,
128			context,
129			runtime_version.state_version(),
130		)
131		.set_parent_hash(at_hash);
132
133		sm.execute().map_err(Into::into)
134	}
135
136	fn contextual_call(
137		&self,
138		at_hash: Block::Hash,
139		method: &str,
140		call_data: &[u8],
141		changes: &RefCell<OverlayedChanges<HashingFor<Block>>>,
142		recorder: &Option<ProofRecorder<Block>>,
143		call_context: CallContext,
144		extensions: &RefCell<Extensions>,
145	) -> Result<Vec<u8>, sp_blockchain::Error> {
146		let state = self.backend.state_at(at_hash, call_context.into())?;
147
148		let changes = &mut *changes.borrow_mut();
149
150		// It is important to extract the runtime code here before we create the proof
151		// recorder to not record it. We also need to fetch the runtime code from `state` to
152		// make sure we use the caching layers.
153		let state_runtime_code =
154			sp_state_machine::backend::BackendRuntimeCode::new(&state, call_context.into());
155
156		let runtime_code =
157			state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?;
158		let (runtime_code, runtime_version) =
159			self.code_provider.maybe_override_code(runtime_code, &state, at_hash)?;
160		let mut extensions = extensions.borrow_mut();
161
162		match recorder {
163			Some(recorder) => {
164				let trie_state = state.as_trie_backend();
165
166				let backend = sp_state_machine::TrieBackendBuilder::wrap(&trie_state)
167					.with_recorder(recorder.clone())
168					.build();
169
170				let mut state_machine = StateMachine::new(
171					&backend,
172					changes,
173					&self.executor,
174					method,
175					call_data,
176					&mut extensions,
177					&runtime_code,
178					call_context,
179					runtime_version.state_version(),
180				)
181				.set_parent_hash(at_hash);
182				state_machine.execute()
183			},
184			None => {
185				let mut state_machine = StateMachine::new(
186					&state,
187					changes,
188					&self.executor,
189					method,
190					call_data,
191					&mut extensions,
192					&runtime_code,
193					call_context,
194					runtime_version.state_version(),
195				)
196				.set_parent_hash(at_hash);
197				state_machine.execute()
198			},
199		}
200		.map_err(Into::into)
201	}
202
203	fn runtime_version(
204		&self,
205		at_hash: Block::Hash,
206		call_context: CallContext,
207	) -> sp_blockchain::Result<RuntimeVersion> {
208		let state = self.backend.state_at(at_hash, backend::TrieCacheContext::Untrusted)?;
209		let state_runtime_code =
210			sp_state_machine::backend::BackendRuntimeCode::new(&state, call_context.into());
211
212		let runtime_code =
213			state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?;
214		self.code_provider
215			.maybe_override_code(runtime_code, &state, at_hash)
216			.map(|(_, v)| v)
217	}
218
219	fn prove_execution(
220		&self,
221		at_hash: Block::Hash,
222		method: &str,
223		call_data: &[u8],
224		timeout: Option<Duration>,
225	) -> sp_blockchain::Result<(Vec<u8>, StorageProof)> {
226		let at_number =
227			self.backend.blockchain().expect_block_number_from_id(&BlockId::Hash(at_hash))?;
228		let state = self.backend.state_at(at_hash, TrieCacheContext::Untrusted)?;
229
230		let trie_backend = state.as_trie_backend();
231
232		let state_runtime_code =
233			sp_state_machine::backend::BackendRuntimeCode::new(trie_backend, TryPendingCode::No);
234		let runtime_code =
235			state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?;
236		let (runtime_code, runtime_version) =
237			self.code_provider.maybe_override_code(runtime_code, &state, at_hash)?;
238
239		sp_state_machine::prove_execution_on_trie_backend(
240			trie_backend,
241			&mut Default::default(),
242			&self.executor,
243			method,
244			call_data,
245			&runtime_code,
246			&mut self.execution_extensions.extensions(at_hash, at_number),
247			runtime_version.state_version(),
248			timeout,
249		)
250		.map_err(Into::into)
251	}
252}
253
254impl<B, E, Block> RuntimeVersionOf for LocalCallExecutor<Block, B, E>
255where
256	E: RuntimeVersionOf,
257	Block: BlockT,
258{
259	fn runtime_version(
260		&self,
261		ext: &mut dyn sp_externalities::Externalities,
262		runtime_code: &sp_core::traits::RuntimeCode,
263	) -> Result<sp_version::RuntimeVersion, sc_executor::error::Error> {
264		RuntimeVersionOf::runtime_version(&self.executor, ext, runtime_code)
265	}
266}
267
268impl<Block, B, E> sp_version::GetRuntimeVersionAt<Block> for LocalCallExecutor<Block, B, E>
269where
270	B: backend::Backend<Block>,
271	E: CodeExecutor + RuntimeVersionOf + Clone + 'static,
272	Block: BlockT,
273{
274	fn runtime_version(
275		&self,
276		at: Block::Hash,
277		call_context: CallContext,
278	) -> Result<sp_version::RuntimeVersion, String> {
279		CallExecutor::runtime_version(self, at, call_context).map_err(|e| e.to_string())
280	}
281}