tet_core/
traits.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2019-2021 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//! Shareable Tetcore traits.
19
20use std::{
21	borrow::Cow,
22	fmt::{Debug, Display},
23	panic::UnwindSafe,
24};
25
26pub use externalities::{Externalities, ExternalitiesExt};
27
28/// Code execution engine.
29pub trait CodeExecutor: Sized + Send + Sync + CallInWasm + Clone + 'static {
30	/// Externalities error type.
31	type Error: Display + Debug + Send + Sync + 'static;
32
33	/// Call a given method in the runtime. Returns a tuple of the result (either the output data
34	/// or an execution error) together with a `bool`, which is true if native execution was used.
35	fn call<
36		R: codec::Codec + PartialEq,
37		NC: FnOnce() -> Result<R, String> + UnwindSafe,
38	>(
39		&self,
40		ext: &mut dyn Externalities,
41		runtime_code: &RuntimeCode,
42		method: &str,
43		data: &[u8],
44		use_native: bool,
45		native_call: Option<NC>,
46	) -> (Result<crate::NativeOrEncoded<R>, Self::Error>, bool);
47}
48
49/// Something that can fetch the runtime `:code`.
50pub trait FetchRuntimeCode {
51	/// Fetch the runtime `:code`.
52	///
53	/// If the `:code` could not be found/not available, `None` should be returned.
54	fn fetch_runtime_code<'a>(&'a self) -> Option<Cow<'a, [u8]>>;
55}
56
57/// Wrapper to use a `u8` slice or `Vec` as [`FetchRuntimeCode`].
58pub struct WrappedRuntimeCode<'a>(pub std::borrow::Cow<'a, [u8]>);
59
60impl<'a> FetchRuntimeCode for WrappedRuntimeCode<'a> {
61	fn fetch_runtime_code<'b>(&'b self) -> Option<Cow<'b, [u8]>> {
62		Some(self.0.as_ref().into())
63	}
64}
65
66/// Type that implements [`FetchRuntimeCode`] and always returns `None`.
67pub struct NoneFetchRuntimeCode;
68
69impl FetchRuntimeCode for NoneFetchRuntimeCode {
70	fn fetch_runtime_code<'a>(&'a self) -> Option<Cow<'a, [u8]>> {
71		None
72	}
73}
74
75/// The Wasm code of a Tetcore runtime.
76#[derive(Clone)]
77pub struct RuntimeCode<'a> {
78	/// The code fetcher that can be used to lazily fetch the code.
79	pub code_fetcher: &'a dyn FetchRuntimeCode,
80	/// The optional heap pages this `code` should be executed with.
81	///
82	/// If `None` are given, the default value of the executor will be used.
83	pub heap_pages: Option<u64>,
84	/// The SCALE encoded hash of `code`.
85	///
86	/// The hashing algorithm isn't that important, as long as all runtime
87	/// code instances use the same.
88	pub hash: Vec<u8>,
89}
90
91impl<'a> PartialEq for RuntimeCode<'a> {
92	fn eq(&self, other: &Self) -> bool {
93		self.hash == other.hash
94	}
95}
96
97impl<'a> RuntimeCode<'a> {
98	/// Create an empty instance.
99	///
100	/// This is only useful for tests that don't want to execute any code.
101	pub fn empty() -> Self {
102		Self {
103			code_fetcher: &NoneFetchRuntimeCode,
104			hash: Vec::new(),
105			heap_pages: None,
106		}
107	}
108}
109
110impl<'a> FetchRuntimeCode for RuntimeCode<'a> {
111	fn fetch_runtime_code<'b>(&'b self) -> Option<Cow<'b, [u8]>> {
112		self.code_fetcher.fetch_runtime_code()
113	}
114}
115
116/// Could not find the `:code` in the externalities while initializing the [`RuntimeCode`].
117#[derive(Debug)]
118pub struct CodeNotFound;
119
120impl std::fmt::Display for CodeNotFound {
121	fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
122		write!(f, "the storage entry `:code` doesn't have any code")
123	}
124}
125
126/// `Allow` or `Disallow` missing host functions when instantiating a WASM blob.
127#[derive(Clone, Copy, Debug)]
128pub enum MissingHostFunctions {
129	/// Any missing host function will be replaced by a stub that returns an error when
130	/// being called.
131	Allow,
132	/// Any missing host function will result in an error while instantiating the WASM blob,
133	Disallow,
134}
135
136impl MissingHostFunctions {
137	/// Are missing host functions allowed?
138	pub fn allowed(self) -> bool {
139		matches!(self, Self::Allow)
140	}
141}
142
143/// Something that can call a method in a WASM blob.
144pub trait CallInWasm: Send + Sync {
145	/// Call the given `method` in the given `wasm_blob` using `call_data` (SCALE encoded arguments)
146	/// to decode the arguments for the method.
147	///
148	/// Returns the SCALE encoded return value of the method.
149	///
150	/// # Note
151	///
152	/// If `code_hash` is `Some(_)` the `wasm_code` module and instance will be cached internally,
153	/// otherwise it is thrown away after the call.
154	fn call_in_wasm(
155		&self,
156		wasm_code: &[u8],
157		code_hash: Option<Vec<u8>>,
158		method: &str,
159		call_data: &[u8],
160		ext: &mut dyn Externalities,
161		missing_host_functions: MissingHostFunctions,
162	) -> Result<Vec<u8>, String>;
163}
164
165externalities::decl_extension! {
166	/// The call-in-wasm extension to register/retrieve from the externalities.
167	pub struct CallInWasmExt(Box<dyn CallInWasm>);
168}
169
170impl CallInWasmExt {
171	/// Creates a new instance of `Self`.
172	pub fn new<T: CallInWasm + 'static>(inner: T) -> Self {
173		Self(Box::new(inner))
174	}
175}
176
177externalities::decl_extension! {
178	/// Task executor extension.
179	pub struct TaskExecutorExt(Box<dyn SpawnNamed>);
180}
181
182impl TaskExecutorExt {
183	/// New instance of task executor extension.
184	pub fn new(spawn_handle: impl SpawnNamed + Send + 'static) -> Self {
185		Self(Box::new(spawn_handle))
186	}
187}
188
189/// Runtime spawn extension.
190pub trait RuntimeSpawn: Send {
191	/// Create new runtime instance and use dynamic dispatch to invoke with specified payload.
192	///
193	/// Returns handle of the spawned task.
194	///
195	/// Function pointers (`dispatcher_ref`, `func`) are WASM pointer types.
196	fn spawn_call(&self, dispatcher_ref: u32, func: u32, payload: Vec<u8>) -> u64;
197
198	/// Join the result of previously created runtime instance invocation.
199	fn join(&self, handle: u64) -> Vec<u8>;
200}
201
202#[cfg(feature = "std")]
203externalities::decl_extension! {
204	/// Extension that supports spawning extra runtime instances in externalities.
205	pub struct RuntimeSpawnExt(Box<dyn RuntimeSpawn>);
206}
207
208/// Something that can spawn futures (blocking and non-blocking) with an assigned name.
209#[dyn_clonable::clonable]
210pub trait SpawnNamed: Clone + Send + Sync {
211	/// Spawn the given blocking future.
212	///
213	/// The given `name` is used to identify the future in tracing.
214	fn spawn_blocking(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>);
215	/// Spawn the given non-blocking future.
216	///
217	/// The given `name` is used to identify the future in tracing.
218	fn spawn(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>);
219}
220
221impl SpawnNamed for Box<dyn SpawnNamed> {
222	fn spawn_blocking(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>) {
223		(**self).spawn_blocking(name, future)
224	}
225
226	fn spawn(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>) {
227		(**self).spawn(name, future)
228	}
229}