referrerpolicy=no-referrer-when-downgrade

sp_api/
lib.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//! Substrate runtime api
19//!
20//! The Substrate runtime api is the interface between the node and the runtime. There isn't a fixed
21//! set of runtime apis, instead it is up to the user to declare and implement these runtime apis.
22//! The declaration of a runtime api is normally done outside of a runtime, while the implementation
23//! of it has to be done in the runtime. We provide the [`decl_runtime_apis!`] macro for declaring
24//! a runtime api and the [`impl_runtime_apis!`] for implementing them. The macro docs provide more
25//! information on how to use them and what kind of attributes we support.
26//!
27//! It is required that each runtime implements at least the [`Core`] runtime api. This runtime api
28//! provides all the core functions that Substrate expects from a runtime.
29//!
30//! # Versioning
31//!
32//! Runtime apis support versioning. Each runtime api itself has a version attached. It is also
33//! supported to change function signatures or names in a non-breaking way. For more information on
34//! versioning check the [`decl_runtime_apis!`] macro.
35//!
36//! All runtime apis and their versions are returned as part of the [`RuntimeVersion`]. This can be
37//! used to check which runtime api version is currently provided by the on-chain runtime.
38//!
39//! # Testing
40//!
41//! For testing we provide the [`mock_impl_runtime_apis!`] macro that lets you implement a runtime
42//! api for a mocked object to use it in tests.
43//!
44//! # Logging
45//!
46//! Substrate supports logging from the runtime in native and in wasm. For that purpose it provides
47//! the [`RuntimeLogger`](sp_runtime::runtime_logger::RuntimeLogger). This runtime logger is
48//! automatically enabled for each call into the runtime through the runtime api. As logging
49//! introduces extra code that isn't actually required for the logic of your runtime and also
50//! increases the final wasm blob size, it is recommended to disable the logging for on-chain
51//! wasm blobs. This can be done by enabling the `disable-logging` feature of this crate. Be aware
52//! that this feature instructs `log` and `tracing` to disable logging at compile time by setting
53//! the `max_level_off` feature for these crates. So, you should not enable this feature for a
54//! native build as otherwise the node will not output any log messages.
55//!
56//! # How does it work?
57//!
58//! Each runtime api is declared as a trait with functions. When compiled to WASM, each implemented
59//! runtime api function is exported as a function with the following naming scheme
60//! `${TRAIT_NAME}_${FUNCTION_NAME}`. Such a function has the following signature
61//! `(ptr: *u8, length: u32) -> u64`. It takes a pointer to an `u8` array and its length as an
62//! argument. This `u8` array is expected to be the SCALE encoded parameters of the function as
63//! defined in the trait. The return value is an `u64` that represents `length << 32 | pointer` of
64//! an `u8` array. This return value `u8` array contains the SCALE encoded return value as defined
65//! by the trait function. The macros take care to encode the parameters and to decode the return
66//! value.
67
68#![cfg_attr(not(feature = "std"), no_std)]
69
70// Make doc tests happy
71extern crate self as sp_api;
72
73extern crate alloc;
74
75/// Private exports used by the macros.
76///
77/// This is seen as internal API and can change at any point.
78#[doc(hidden)]
79pub mod __private {
80	#[cfg(feature = "std")]
81	mod std_imports {
82		pub use hash_db::Hasher;
83		pub use sp_core::traits::CallContext;
84		pub use sp_externalities::{Extension, Extensions};
85		pub use sp_runtime::StateVersion;
86		pub use sp_state_machine::{
87			Backend as StateBackend, InMemoryBackend, OverlayedChanges, StorageProof, TrieBackend,
88			TrieBackendBuilder,
89		};
90	}
91	#[cfg(feature = "std")]
92	pub use std_imports::*;
93
94	pub use crate::*;
95	pub use alloc::vec;
96	pub use codec::{self, Decode, DecodeLimit, Encode};
97	pub use core::{mem, slice};
98	pub use scale_info;
99	pub use sp_core::offchain;
100	#[cfg(not(feature = "std"))]
101	pub use sp_core::to_substrate_wasm_fn_return_value;
102	#[cfg(feature = "frame-metadata")]
103	pub use sp_metadata_ir::{self as metadata_ir, frame_metadata as metadata};
104	pub use sp_runtime::{
105		generic::BlockId,
106		traits::{Block as BlockT, Hash as HashT, HashingFor, Header as HeaderT, NumberFor},
107		transaction_validity::TransactionValidity,
108		ExtrinsicInclusionMode, TransactionOutcome,
109	};
110	pub use sp_version::{create_apis_vec, ApiId, ApisVec, RuntimeVersion};
111
112	#[cfg(all(any(target_arch = "riscv32", target_arch = "riscv64"), substrate_runtime))]
113	pub use sp_runtime_interface::polkavm::{polkavm_abi, polkavm_export};
114}
115
116#[cfg(feature = "std")]
117pub use sp_core::traits::CallContext;
118use sp_core::OpaqueMetadata;
119#[cfg(feature = "std")]
120use sp_externalities::{Extension, Extensions};
121#[cfg(feature = "std")]
122use sp_runtime::traits::HashingFor;
123#[cfg(feature = "std")]
124pub use sp_runtime::TransactionOutcome;
125use sp_runtime::{traits::Block as BlockT, ExtrinsicInclusionMode};
126#[cfg(feature = "std")]
127pub use sp_state_machine::StorageProof;
128#[cfg(feature = "std")]
129use sp_state_machine::{backend::AsTrieBackend, Backend as StateBackend, OverlayedChanges};
130use sp_version::RuntimeVersion;
131#[cfg(feature = "std")]
132use std::cell::RefCell;
133
134/// Declares given traits as runtime apis.
135///
136/// The macro will create two declarations, one for using on the client side and one for using
137/// on the runtime side. The declaration for the runtime side is hidden in its own module.
138/// The client side declaration gets two extra parameters per function,
139/// `&self` and `at: Block::Hash`. The runtime side declaration will match the given trait
140/// declaration. Besides one exception, the macro adds an extra generic parameter `Block:
141/// BlockT` to the client side and the runtime side. This generic parameter is usable by the
142/// user.
143///
144/// For implementing these macros you should use the
145/// [`impl_runtime_apis!`] macro.
146///
147/// # Example
148///
149/// ```rust
150/// sp_api::decl_runtime_apis! {
151///     /// Declare the api trait.
152///     pub trait Balance {
153///         /// Get the balance.
154///         fn get_balance() -> u64;
155///         /// Set the balance.
156///         fn set_balance(val: u64);
157///     }
158///
159///     /// You can declare multiple api traits in one macro call.
160///     /// In one module you can call the macro at maximum one time.
161///     pub trait BlockBuilder {
162///         /// The macro adds an explicit `Block: BlockT` generic parameter for you.
163///         /// You can use this generic parameter as you would defined it manually.
164///         fn build_block() -> Block;
165///     }
166/// }
167///
168/// # fn main() {}
169/// ```
170///
171/// # Runtime api trait versioning
172///
173/// To support versioning of the traits, the macro supports the attribute `#[api_version(1)]`.
174/// The attribute supports any `u32` as version. By default, each trait is at version `1`, if
175/// no version is provided. We also support changing the signature of a method. This signature
176/// change is highlighted with the `#[changed_in(2)]` attribute above a method. A method that
177/// is tagged with this attribute is callable by the name `METHOD_before_version_VERSION`. This
178/// method will only support calling into wasm, trying to call into native will fail (change
179/// the spec version!). Such a method also does not need to be implemented in the runtime. It
180/// is required that there exist the "default" of the method without the `#[changed_in(_)]`
181/// attribute, this method will be used to call the current default implementation.
182///
183/// ```rust
184/// sp_api::decl_runtime_apis! {
185///     /// Declare the api trait.
186///     #[api_version(2)]
187///     pub trait Balance {
188///         /// Get the balance.
189///         fn get_balance() -> u64;
190///         /// Set balance.
191///         fn set_balance(val: u64);
192///         /// Set balance, old version.
193///         ///
194///         /// Is callable by `set_balance_before_version_2`.
195///         #[changed_in(2)]
196///         fn set_balance(val: u16);
197///         /// In version 2, we added this new function.
198///         fn increase_balance(val: u64);
199///     }
200/// }
201///
202/// # fn main() {}
203/// ```
204///
205/// To check if a given runtime implements a runtime api trait, the `RuntimeVersion` has the
206/// function `has_api<A>()`. Also the `ApiExt` provides a function `has_api<A>(at: Hash)`
207/// to check if the runtime at the given block id implements the requested runtime api trait.
208///
209/// # Declaring multiple api versions
210///
211/// Optionally multiple versions of the same api can be declared. This is useful for
212/// development purposes. For example you want to have a testing version of the api which is
213/// available only on a testnet. You can define one stable and one development version. This
214/// can be done like this:
215/// ```rust
216/// sp_api::decl_runtime_apis! {
217///     /// Declare the api trait.
218/// 	#[api_version(2)]
219///     pub trait Balance {
220///         /// Get the balance.
221///         fn get_balance() -> u64;
222///         /// Set the balance.
223///         fn set_balance(val: u64);
224///         /// Transfer the balance to another user id
225///         #[api_version(3)]
226///         fn transfer_balance(uid: u64);
227///     }
228/// }
229///
230/// # fn main() {}
231/// ```
232/// The example above defines two api versions - 2 and 3. Version 2 contains `get_balance` and
233/// `set_balance`. Version 3 additionally contains `transfer_balance`, which is not available
234/// in version 2. Version 2 in this case is considered the default/base version of the api.
235/// More than two versions can be defined this way. For example:
236/// ```rust
237/// sp_api::decl_runtime_apis! {
238///     /// Declare the api trait.
239///     #[api_version(2)]
240///     pub trait Balance {
241///         /// Get the balance.
242///         fn get_balance() -> u64;
243///         /// Set the balance.
244///         fn set_balance(val: u64);
245///         /// Transfer the balance to another user id
246///         #[api_version(3)]
247///         fn transfer_balance(uid: u64);
248///         /// Clears the balance
249///         #[api_version(4)]
250///         fn clear_balance();
251///     }
252/// }
253///
254/// # fn main() {}
255/// ```
256/// Note that the latest version (4 in our example above) always contains all methods from all
257/// the versions before.
258///
259/// ## Note on deprecation.
260///
261/// - Usage of `deprecated` attribute will propagate deprecation information to the metadata.
262/// - For general usage examples of `deprecated` attribute please refer to <https://doc.rust-lang.org/nightly/reference/attributes/diagnostics.html#the-deprecated-attribute>
263pub use sp_api_proc_macro::decl_runtime_apis;
264
265/// Tags given trait implementations as runtime apis.
266///
267/// All traits given to this macro, need to be declared with the
268/// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro. The implementation of the trait
269/// should follow the declaration given to the
270/// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro, besides the `Block` type that
271/// is required as first generic parameter for each runtime api trait. When implementing a
272/// runtime api trait, it is required that the trait is referenced by a path, e.g. `impl
273/// my_trait::MyTrait for Runtime`. The macro will use this path to access the declaration of
274/// the trait for the runtime side.
275///
276/// The macro also generates the api implementations for the client side and provides it
277/// through the `RuntimeApi` type. The `RuntimeApi` is hidden behind a `feature` called `std`.
278///
279/// To expose version information about all implemented api traits, the constant
280/// `RUNTIME_API_VERSIONS` is generated. This constant should be used to instantiate the `apis`
281/// field of `RuntimeVersion`.
282///
283/// # Example
284///
285/// ```rust
286/// extern crate alloc;
287/// #
288/// # use sp_runtime::{ExtrinsicInclusionMode, traits::Block as BlockT};
289/// # use sp_test_primitives::Block;
290/// #
291/// # /// The declaration of the `Runtime` type is done by the `construct_runtime!` macro
292/// # /// in a real runtime.
293/// # pub enum Runtime {}
294/// #
295/// # sp_api::decl_runtime_apis! {
296/// #     /// Declare the api trait.
297/// #     pub trait Balance {
298/// #         /// Get the balance.
299/// #         fn get_balance() -> u64;
300/// #         /// Set the balance.
301/// #         fn set_balance(val: u64);
302/// #     }
303/// #     pub trait BlockBuilder {
304/// #        fn build_block() -> Block;
305/// #     }
306/// # }
307///
308/// /// All runtime api implementations need to be done in one call of the macro!
309/// sp_api::impl_runtime_apis! {
310/// #   impl sp_api::Core<Block> for Runtime {
311/// #       fn version() -> sp_version::RuntimeVersion {
312/// #           unimplemented!()
313/// #       }
314/// #       fn execute_block(_block: Block) {}
315/// #       fn initialize_block(_header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode {
316/// #           unimplemented!()
317/// #       }
318/// #   }
319///
320///     impl self::Balance<Block> for Runtime {
321///         fn get_balance() -> u64 {
322///             1
323///         }
324///         fn set_balance(_bal: u64) {
325///             // Store the balance
326///         }
327///     }
328///
329///     impl self::BlockBuilder<Block> for Runtime {
330///         fn build_block() -> Block {
331///              unimplemented!("Please implement me!")
332///         }
333///     }
334/// }
335///
336/// /// Runtime version. This needs to be declared for each runtime.
337/// pub const VERSION: sp_version::RuntimeVersion = sp_version::RuntimeVersion {
338///     spec_name: alloc::borrow::Cow::Borrowed("node"),
339///     impl_name: alloc::borrow::Cow::Borrowed("test-node"),
340///     authoring_version: 1,
341///     spec_version: 1,
342///     impl_version: 0,
343///     // Here we are exposing the runtime api versions.
344///     apis: RUNTIME_API_VERSIONS,
345///     transaction_version: 1,
346///     system_version: 1,
347/// };
348///
349/// # fn main() {}
350/// ```
351///
352/// # Implementing specific api version
353///
354/// If `decl_runtime_apis!` declares multiple versions for an api `impl_runtime_apis!`
355/// should specify which version it implements by adding `api_version` attribute to the
356/// `impl` block. If omitted - the base/default version is implemented. Here is an example:
357/// ```ignore
358/// sp_api::impl_runtime_apis! {
359///     #[api_version(3)]
360///     impl self::Balance<Block> for Runtime {
361///          // implementation
362///     }
363/// }
364/// ```
365/// In this case `Balance` api version 3 is being implemented for `Runtime`. The `impl` block
366/// must contain all methods declared in version 3 and below.
367///
368/// # Conditional version implementation
369///
370/// `impl_runtime_apis!` supports `cfg_attr` attribute for conditional compilation. For example
371/// let's say you want to implement a staging version of the runtime api and put it behind a
372/// feature flag. You can do it this way:
373/// ```ignore
374/// pub enum Runtime {}
375/// sp_api::decl_runtime_apis! {
376///     pub trait ApiWithStagingMethod {
377///         fn stable_one(data: u64);
378///
379///         #[api_version(99)]
380///         fn staging_one();
381///     }
382/// }
383///
384/// sp_api::impl_runtime_apis! {
385///     #[cfg_attr(feature = "enable-staging-api", api_version(99))]
386///     impl self::ApiWithStagingMethod<Block> for Runtime {
387///         fn stable_one(_: u64) {}
388///
389///         #[cfg(feature = "enable-staging-api")]
390///         fn staging_one() {}
391///     }
392/// }
393/// ```
394///
395/// [`decl_runtime_apis!`] declares two version of the api - 1 (the default one, which is
396/// considered stable in our example) and 99 (which is considered staging). In
397/// `impl_runtime_apis!` a `cfg_attr` attribute is attached to the `ApiWithStagingMethod`
398/// implementation. If the code is compiled with  `enable-staging-api` feature a version 99 of
399/// the runtime api will be built which will include `staging_one`. Note that `staging_one`
400/// implementation is feature gated by `#[cfg(feature = ... )]` attribute.
401///
402/// If the code is compiled without `enable-staging-api` version 1 (the default one) will be
403/// built which doesn't include `staging_one`.
404///
405/// `cfg_attr` can also be used together with `api_version`. For the next snippet will build
406/// version 99 if `enable-staging-api` is enabled and version 2 otherwise because both
407/// `cfg_attr` and `api_version` are attached to the impl block:
408/// ```ignore
409/// #[cfg_attr(feature = "enable-staging-api", api_version(99))]
410/// #[api_version(2)]
411/// impl self::ApiWithStagingAndVersionedMethods<Block> for Runtime {
412///  // impl skipped
413/// }
414/// ```
415pub use sp_api_proc_macro::impl_runtime_apis;
416
417/// Mocks given trait implementations as runtime apis.
418///
419/// Accepts similar syntax as [`impl_runtime_apis!`] and generates simplified mock
420/// implementations of the given runtime apis. The difference in syntax is that the trait does
421/// not need to be referenced by a qualified path, methods accept the `&self` parameter and the
422/// error type can be specified as associated type. If no error type is specified [`String`] is
423/// used as error type.
424///
425/// Besides implementing the given traits, the [`Core`] and [`ApiExt`] are implemented
426/// automatically.
427///
428/// # Example
429///
430/// ```rust
431/// # use sp_runtime::traits::Block as BlockT;
432/// # use sp_test_primitives::Block;
433/// #
434/// # sp_api::decl_runtime_apis! {
435/// #     /// Declare the api trait.
436/// #     pub trait Balance {
437/// #         /// Get the balance.
438/// #         fn get_balance() -> u64;
439/// #         /// Set the balance.
440/// #         fn set_balance(val: u64);
441/// #     }
442/// #     pub trait BlockBuilder {
443/// #        fn build_block() -> Block;
444/// #     }
445/// # }
446/// struct MockApi {
447///     balance: u64,
448/// }
449///
450/// /// All runtime api mock implementations need to be done in one call of the macro!
451/// sp_api::mock_impl_runtime_apis! {
452///     impl Balance<Block> for MockApi {
453///         /// Here we take the `&self` to access the instance.
454///         fn get_balance(&self) -> u64 {
455///             self.balance
456///         }
457///         fn set_balance(_bal: u64) {
458///             // Store the balance
459///         }
460///     }
461///
462///     impl BlockBuilder<Block> for MockApi {
463///         fn build_block() -> Block {
464///              unimplemented!("Not Required in tests")
465///         }
466///     }
467/// }
468///
469/// # fn main() {}
470/// ```
471///
472/// # `advanced` attribute
473///
474/// This attribute can be placed above individual function in the mock implementation to
475/// request more control over the function declaration. From the client side each runtime api
476/// function is called with the `at` parameter that is a [`Hash`](sp_runtime::traits::Hash).
477/// When using the `advanced` attribute, the macro expects that the first parameter of the
478/// function is this `at` parameter. Besides that the macro also doesn't do the automatic
479/// return value rewrite, which means that full return value must be specified. The full return
480/// value is constructed like [`Result`]`<<ReturnValue>, Error>` while `ReturnValue` being the
481/// return value that is specified in the trait declaration.
482///
483/// ## Example
484/// ```rust
485/// # use sp_runtime::traits::Block as BlockT;
486/// # use sp_test_primitives::Block;
487/// # use codec;
488/// #
489/// # sp_api::decl_runtime_apis! {
490/// #     /// Declare the api trait.
491/// #     pub trait Balance {
492/// #         /// Get the balance.
493/// #         fn get_balance() -> u64;
494/// #         /// Set the balance.
495/// #         fn set_balance(val: u64);
496/// #     }
497/// # }
498/// struct MockApi {
499///     balance: u64,
500/// }
501///
502/// sp_api::mock_impl_runtime_apis! {
503///     impl Balance<Block> for MockApi {
504///         #[advanced]
505///         fn get_balance(&self, at: <Block as BlockT>::Hash) -> Result<u64, sp_api::ApiError> {
506///             println!("Being called at: {}", at);
507///
508///             Ok(self.balance.into())
509///         }
510///         #[advanced]
511///         fn set_balance(at: <Block as BlockT>::Hash, val: u64) -> Result<(), sp_api::ApiError> {
512///             println!("Being called at: {}", at);
513///
514///             Ok(().into())
515///         }
516///     }
517/// }
518///
519/// # fn main() {}
520/// ```
521pub use sp_api_proc_macro::mock_impl_runtime_apis;
522
523/// A type that records all accessed trie nodes and generates a proof out of it.
524#[cfg(feature = "std")]
525pub type ProofRecorder<B> = sp_trie::recorder::Recorder<HashingFor<B>>;
526
527#[cfg(feature = "std")]
528pub type ProofRecorderIgnoredNodes<B> = sp_trie::recorder::IgnoredNodes<<B as BlockT>::Hash>;
529
530#[cfg(feature = "std")]
531pub type StorageChanges<Block> = sp_state_machine::StorageChanges<HashingFor<Block>>;
532
533/// Something that can be constructed to a runtime api.
534#[cfg(feature = "std")]
535pub trait ConstructRuntimeApi<Block: BlockT, C: CallApiAt<Block>> {
536	/// The actual runtime api that will be constructed.
537	type RuntimeApi: ApiExt<Block>;
538
539	/// Construct an instance of the runtime api.
540	fn construct_runtime_api(call: &C) -> ApiRef<Self::RuntimeApi>;
541}
542
543#[docify::export]
544/// Init the [`RuntimeLogger`](sp_runtime::runtime_logger::RuntimeLogger).
545pub fn init_runtime_logger() {
546	#[cfg(not(feature = "disable-logging"))]
547	sp_runtime::runtime_logger::RuntimeLogger::init();
548}
549
550/// An error describing which API call failed.
551#[cfg(feature = "std")]
552#[derive(Debug, thiserror::Error)]
553pub enum ApiError {
554	#[error("Failed to decode return value of {function}: {error} raw data: {raw:?}")]
555	FailedToDecodeReturnValue {
556		function: &'static str,
557		#[source]
558		error: codec::Error,
559		raw: Vec<u8>,
560	},
561	#[error("Failed to convert return value from runtime to node of {function}")]
562	FailedToConvertReturnValue {
563		function: &'static str,
564		#[source]
565		error: codec::Error,
566	},
567	#[error("Failed to convert parameter `{parameter}` from node to runtime of {function}")]
568	FailedToConvertParameter {
569		function: &'static str,
570		parameter: &'static str,
571		#[source]
572		error: codec::Error,
573	},
574	#[error("The given `StateBackend` isn't a `TrieBackend`.")]
575	StateBackendIsNotTrie,
576	#[error(transparent)]
577	Application(#[from] Box<dyn std::error::Error + Send + Sync>),
578	#[error("Api called for an unknown Block: {0}")]
579	UnknownBlock(String),
580	#[error("Using the same api instance to call into multiple independent blocks.")]
581	UsingSameInstanceForDifferentBlocks,
582}
583
584/// Extends the runtime api implementation with some common functionality.
585#[cfg(feature = "std")]
586pub trait ApiExt<Block: BlockT> {
587	/// Execute the given closure inside a new transaction.
588	///
589	/// Depending on the outcome of the closure, the transaction is committed or rolled-back.
590	///
591	/// The internal result of the closure is returned afterwards.
592	fn execute_in_transaction<F: FnOnce(&Self) -> TransactionOutcome<R>, R>(&self, call: F) -> R
593	where
594		Self: Sized;
595
596	/// Checks if the given api is implemented and versions match.
597	fn has_api<A: RuntimeApiInfo + ?Sized>(&self, at_hash: Block::Hash) -> Result<bool, ApiError>
598	where
599		Self: Sized;
600
601	/// Check if the given api is implemented and the version passes a predicate.
602	fn has_api_with<A: RuntimeApiInfo + ?Sized, P: Fn(u32) -> bool>(
603		&self,
604		at_hash: Block::Hash,
605		pred: P,
606	) -> Result<bool, ApiError>
607	where
608		Self: Sized;
609
610	/// Returns the version of the given api.
611	fn api_version<A: RuntimeApiInfo + ?Sized>(
612		&self,
613		at_hash: Block::Hash,
614	) -> Result<Option<u32>, ApiError>
615	where
616		Self: Sized;
617
618	/// Start recording all accessed trie nodes.
619	///
620	/// The recorded trie nodes can be converted into a proof using [`Self::extract_proof`].
621	fn record_proof(&mut self);
622
623	/// Start recording all accessed trie nodes using the given proof recorder.
624	///
625	/// The recorded trie nodes can be converted into a proof using [`Self::extract_proof`].
626	fn record_proof_with_recorder(&mut self, recorder: ProofRecorder<Block>);
627
628	/// Extract the recorded proof.
629	///
630	/// This stops the proof recording.
631	///
632	/// If `record_proof` was not called before, this will return `None`.
633	fn extract_proof(&mut self) -> Option<StorageProof>;
634
635	/// Returns the current active proof recorder.
636	fn proof_recorder(&self) -> Option<ProofRecorder<Block>>;
637
638	/// Convert the api object into the storage changes that were done while executing runtime
639	/// api functions.
640	///
641	/// After executing this function, all collected changes are reset.
642	fn into_storage_changes<B: StateBackend<HashingFor<Block>>>(
643		&self,
644		backend: &B,
645		parent_hash: Block::Hash,
646	) -> Result<StorageChanges<Block>, String>
647	where
648		Self: Sized;
649
650	/// Set the [`CallContext`] to be used by the runtime api calls done by this instance.
651	fn set_call_context(&mut self, call_context: CallContext);
652
653	/// Register an [`Extension`] that will be accessible while executing a runtime api call.
654	fn register_extension<E: Extension>(&mut self, extension: E);
655}
656
657/// Parameters for [`CallApiAt::call_api_at`].
658#[cfg(feature = "std")]
659pub struct CallApiAtParams<'a, Block: BlockT> {
660	/// The block id that determines the state that should be setup when calling the function.
661	pub at: Block::Hash,
662	/// The name of the function that should be called.
663	pub function: &'static str,
664	/// The encoded arguments of the function.
665	pub arguments: Vec<u8>,
666	/// The overlayed changes that are on top of the state.
667	pub overlayed_changes: &'a RefCell<OverlayedChanges<HashingFor<Block>>>,
668	/// The call context of this call.
669	pub call_context: CallContext,
670	/// The optional proof recorder for recording storage accesses.
671	pub recorder: &'a Option<ProofRecorder<Block>>,
672	/// The extensions that should be used for this call.
673	pub extensions: &'a RefCell<Extensions>,
674}
675
676/// Something that can call into an api at a given block.
677#[cfg(feature = "std")]
678pub trait CallApiAt<Block: BlockT> {
679	/// The state backend that is used to store the block states.
680	type StateBackend: StateBackend<HashingFor<Block>> + AsTrieBackend<HashingFor<Block>>;
681
682	/// Calls the given api function with the given encoded arguments at the given block and returns
683	/// the encoded result.
684	fn call_api_at(&self, params: CallApiAtParams<Block>) -> Result<Vec<u8>, ApiError>;
685
686	/// Returns the runtime version at the given block.
687	fn runtime_version_at(&self, at_hash: Block::Hash) -> Result<RuntimeVersion, ApiError>;
688
689	/// Get the state `at` the given block.
690	fn state_at(&self, at: Block::Hash) -> Result<Self::StateBackend, ApiError>;
691
692	/// Initialize the `extensions` for the given block `at` by using the global extensions factory.
693	fn initialize_extensions(
694		&self,
695		at: Block::Hash,
696		extensions: &mut Extensions,
697	) -> Result<(), ApiError>;
698}
699
700#[cfg(feature = "std")]
701impl<Block: BlockT, T: CallApiAt<Block>> CallApiAt<Block> for std::sync::Arc<T> {
702	type StateBackend = T::StateBackend;
703
704	fn call_api_at(&self, params: CallApiAtParams<Block>) -> Result<Vec<u8>, ApiError> {
705		(**self).call_api_at(params)
706	}
707
708	fn runtime_version_at(
709		&self,
710		at_hash: <Block as BlockT>::Hash,
711	) -> Result<RuntimeVersion, ApiError> {
712		(**self).runtime_version_at(at_hash)
713	}
714
715	fn state_at(&self, at: <Block as BlockT>::Hash) -> Result<Self::StateBackend, ApiError> {
716		(**self).state_at(at)
717	}
718
719	fn initialize_extensions(
720		&self,
721		at: <Block as BlockT>::Hash,
722		extensions: &mut Extensions,
723	) -> Result<(), ApiError> {
724		(**self).initialize_extensions(at, extensions)
725	}
726}
727
728/// Auxiliary wrapper that holds an api instance and binds it to the given lifetime.
729#[cfg(feature = "std")]
730pub struct ApiRef<'a, T>(T, std::marker::PhantomData<&'a ()>);
731
732#[cfg(feature = "std")]
733impl<'a, T> From<T> for ApiRef<'a, T> {
734	fn from(api: T) -> Self {
735		ApiRef(api, Default::default())
736	}
737}
738
739#[cfg(feature = "std")]
740impl<'a, T> std::ops::Deref for ApiRef<'a, T> {
741	type Target = T;
742
743	fn deref(&self) -> &Self::Target {
744		&self.0
745	}
746}
747
748#[cfg(feature = "std")]
749impl<'a, T> std::ops::DerefMut for ApiRef<'a, T> {
750	fn deref_mut(&mut self) -> &mut T {
751		&mut self.0
752	}
753}
754
755/// Something that provides a runtime api.
756#[cfg(feature = "std")]
757pub trait ProvideRuntimeApi<Block: BlockT> {
758	/// The concrete type that provides the api.
759	type Api: ApiExt<Block>;
760
761	/// Returns the runtime api.
762	/// The returned instance will keep track of modifications to the storage. Any successful
763	/// call to an api function, will `commit` its changes to an internal buffer. Otherwise,
764	/// the modifications will be `discarded`. The modifications will not be applied to the
765	/// storage, even on a `commit`.
766	fn runtime_api(&self) -> ApiRef<Self::Api>;
767}
768
769/// Something that provides information about a runtime api.
770#[cfg(feature = "std")]
771pub trait RuntimeApiInfo {
772	/// The identifier of the runtime api.
773	const ID: [u8; 8];
774	/// The version of the runtime api.
775	const VERSION: u32;
776}
777
778/// The number of bytes required to encode a [`RuntimeApiInfo`].
779///
780/// 8 bytes for `ID` and 4 bytes for a version.
781pub const RUNTIME_API_INFO_SIZE: usize = 12;
782
783/// Crude and simple way to serialize the `RuntimeApiInfo` into a bunch of bytes.
784pub const fn serialize_runtime_api_info(id: [u8; 8], version: u32) -> [u8; RUNTIME_API_INFO_SIZE] {
785	let version = version.to_le_bytes();
786
787	let mut r = [0; RUNTIME_API_INFO_SIZE];
788	r[0] = id[0];
789	r[1] = id[1];
790	r[2] = id[2];
791	r[3] = id[3];
792	r[4] = id[4];
793	r[5] = id[5];
794	r[6] = id[6];
795	r[7] = id[7];
796
797	r[8] = version[0];
798	r[9] = version[1];
799	r[10] = version[2];
800	r[11] = version[3];
801	r
802}
803
804/// Deserialize the runtime API info serialized by [`serialize_runtime_api_info`].
805pub fn deserialize_runtime_api_info(bytes: [u8; RUNTIME_API_INFO_SIZE]) -> ([u8; 8], u32) {
806	let id: [u8; 8] = bytes[0..8]
807		.try_into()
808		.expect("the source slice size is equal to the dest array length; qed");
809
810	let version = u32::from_le_bytes(
811		bytes[8..12]
812			.try_into()
813			.expect("the source slice size is equal to the array length; qed"),
814	);
815
816	(id, version)
817}
818
819decl_runtime_apis! {
820	/// The `Core` runtime api that every Substrate runtime needs to implement.
821	#[core_trait]
822	#[api_version(5)]
823	pub trait Core {
824		/// Returns the version of the runtime.
825		fn version() -> RuntimeVersion;
826		/// Execute the given block.
827		fn execute_block(block: Block);
828		/// Initialize a block with the given header.
829		#[changed_in(5)]
830		#[renamed("initialise_block", 2)]
831		fn initialize_block(header: &<Block as BlockT>::Header);
832		/// Initialize a block with the given header and return the runtime executive mode.
833		fn initialize_block(header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode;
834	}
835
836	/// The `Metadata` api trait that returns metadata for the runtime.
837	#[api_version(2)]
838	pub trait Metadata {
839		/// Returns the metadata of a runtime.
840		fn metadata() -> OpaqueMetadata;
841
842		/// Returns the metadata at a given version.
843		///
844		/// If the given `version` isn't supported, this will return `None`.
845		/// Use [`Self::metadata_versions`] to find out about supported metadata version of the runtime.
846		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata>;
847
848		/// Returns the supported metadata versions.
849		///
850		/// This can be used to call `metadata_at_version`.
851		fn metadata_versions() -> alloc::vec::Vec<u32>;
852	}
853}
854
855sp_core::generate_feature_enabled_macro!(std_enabled, feature = "std", $);
856sp_core::generate_feature_enabled_macro!(std_disabled, not(feature = "std"), $);
857sp_core::generate_feature_enabled_macro!(frame_metadata_enabled, feature = "frame-metadata", $);