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
71
extern crate self as sp_api;
72

            
73
extern 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)]
79
pub 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, RuntimeString, 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")]
117
pub use sp_core::traits::CallContext;
118
use sp_core::OpaqueMetadata;
119
#[cfg(feature = "std")]
120
use sp_externalities::{Extension, Extensions};
121
#[cfg(feature = "std")]
122
use sp_runtime::traits::HashingFor;
123
#[cfg(feature = "std")]
124
pub use sp_runtime::TransactionOutcome;
125
use sp_runtime::{traits::Block as BlockT, ExtrinsicInclusionMode};
126
#[cfg(feature = "std")]
127
pub use sp_state_machine::StorageProof;
128
#[cfg(feature = "std")]
129
use sp_state_machine::{backend::AsTrieBackend, Backend as StateBackend, OverlayedChanges};
130
use sp_version::RuntimeVersion;
131
#[cfg(feature = "std")]
132
use std::cell::RefCell;
133

            
134
/// Maximum nesting level for extrinsics.
135
pub const MAX_EXTRINSIC_DEPTH: u32 = 256;
136

            
137
/// Declares given traits as runtime apis.
138
///
139
/// The macro will create two declarations, one for using on the client side and one for using
140
/// on the runtime side. The declaration for the runtime side is hidden in its own module.
141
/// The client side declaration gets two extra parameters per function,
142
/// `&self` and `at: Block::Hash`. The runtime side declaration will match the given trait
143
/// declaration. Besides one exception, the macro adds an extra generic parameter `Block:
144
/// BlockT` to the client side and the runtime side. This generic parameter is usable by the
145
/// user.
146
///
147
/// For implementing these macros you should use the
148
/// [`impl_runtime_apis!`] macro.
149
///
150
/// # Example
151
///
152
/// ```rust
153
/// sp_api::decl_runtime_apis! {
154
///     /// Declare the api trait.
155
///     pub trait Balance {
156
///         /// Get the balance.
157
///         fn get_balance() -> u64;
158
///         /// Set the balance.
159
///         fn set_balance(val: u64);
160
///     }
161
///
162
///     /// You can declare multiple api traits in one macro call.
163
///     /// In one module you can call the macro at maximum one time.
164
///     pub trait BlockBuilder {
165
///         /// The macro adds an explicit `Block: BlockT` generic parameter for you.
166
///         /// You can use this generic parameter as you would defined it manually.
167
///         fn build_block() -> Block;
168
///     }
169
/// }
170
///
171
/// # fn main() {}
172
/// ```
173
///
174
/// # Runtime api trait versioning
175
///
176
/// To support versioning of the traits, the macro supports the attribute `#[api_version(1)]`.
177
/// The attribute supports any `u32` as version. By default, each trait is at version `1`, if
178
/// no version is provided. We also support changing the signature of a method. This signature
179
/// change is highlighted with the `#[changed_in(2)]` attribute above a method. A method that
180
/// is tagged with this attribute is callable by the name `METHOD_before_version_VERSION`. This
181
/// method will only support calling into wasm, trying to call into native will fail (change
182
/// the spec version!). Such a method also does not need to be implemented in the runtime. It
183
/// is required that there exist the "default" of the method without the `#[changed_in(_)]`
184
/// attribute, this method will be used to call the current default implementation.
185
///
186
/// ```rust
187
/// sp_api::decl_runtime_apis! {
188
///     /// Declare the api trait.
189
///     #[api_version(2)]
190
///     pub trait Balance {
191
///         /// Get the balance.
192
///         fn get_balance() -> u64;
193
///         /// Set balance.
194
///         fn set_balance(val: u64);
195
///         /// Set balance, old version.
196
///         ///
197
///         /// Is callable by `set_balance_before_version_2`.
198
///         #[changed_in(2)]
199
///         fn set_balance(val: u16);
200
///         /// In version 2, we added this new function.
201
///         fn increase_balance(val: u64);
202
///     }
203
/// }
204
///
205
/// # fn main() {}
206
/// ```
207
///
208
/// To check if a given runtime implements a runtime api trait, the `RuntimeVersion` has the
209
/// function `has_api<A>()`. Also the `ApiExt` provides a function `has_api<A>(at: Hash)`
210
/// to check if the runtime at the given block id implements the requested runtime api trait.
211
///
212
/// # Declaring multiple api versions
213
///
214
/// Optionally multiple versions of the same api can be declared. This is useful for
215
/// development purposes. For example you want to have a testing version of the api which is
216
/// available only on a testnet. You can define one stable and one development version. This
217
/// can be done like this:
218
/// ```rust
219
/// sp_api::decl_runtime_apis! {
220
///     /// Declare the api trait.
221
/// 	#[api_version(2)]
222
///     pub trait Balance {
223
///         /// Get the balance.
224
///         fn get_balance() -> u64;
225
///         /// Set the balance.
226
///         fn set_balance(val: u64);
227
///         /// Transfer the balance to another user id
228
///         #[api_version(3)]
229
///         fn transfer_balance(uid: u64);
230
///     }
231
/// }
232
///
233
/// # fn main() {}
234
/// ```
235
/// The example above defines two api versions - 2 and 3. Version 2 contains `get_balance` and
236
/// `set_balance`. Version 3 additionally contains `transfer_balance`, which is not available
237
/// in version 2. Version 2 in this case is considered the default/base version of the api.
238
/// More than two versions can be defined this way. For example:
239
/// ```rust
240
/// sp_api::decl_runtime_apis! {
241
///     /// Declare the api trait.
242
///     #[api_version(2)]
243
///     pub trait Balance {
244
///         /// Get the balance.
245
///         fn get_balance() -> u64;
246
///         /// Set the balance.
247
///         fn set_balance(val: u64);
248
///         /// Transfer the balance to another user id
249
///         #[api_version(3)]
250
///         fn transfer_balance(uid: u64);
251
///         /// Clears the balance
252
///         #[api_version(4)]
253
///         fn clear_balance();
254
///     }
255
/// }
256
///
257
/// # fn main() {}
258
/// ```
259
/// Note that the latest version (4 in our example above) always contains all methods from all
260
/// the versions before.
261
pub use sp_api_proc_macro::decl_runtime_apis;
262

            
263
/// Tags given trait implementations as runtime apis.
264
///
265
/// All traits given to this macro, need to be declared with the
266
/// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro. The implementation of the trait
267
/// should follow the declaration given to the
268
/// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro, besides the `Block` type that
269
/// is required as first generic parameter for each runtime api trait. When implementing a
270
/// runtime api trait, it is required that the trait is referenced by a path, e.g. `impl
271
/// my_trait::MyTrait for Runtime`. The macro will use this path to access the declaration of
272
/// the trait for the runtime side.
273
///
274
/// The macro also generates the api implementations for the client side and provides it
275
/// through the `RuntimeApi` type. The `RuntimeApi` is hidden behind a `feature` called `std`.
276
///
277
/// To expose version information about all implemented api traits, the constant
278
/// `RUNTIME_API_VERSIONS` is generated. This constant should be used to instantiate the `apis`
279
/// field of `RuntimeVersion`.
280
///
281
/// # Example
282
///
283
/// ```rust
284
/// use sp_version::create_runtime_str;
285
/// #
286
/// # use sp_runtime::{ExtrinsicInclusionMode, traits::Block as BlockT};
287
/// # use sp_test_primitives::Block;
288
/// #
289
/// # /// The declaration of the `Runtime` type is done by the `construct_runtime!` macro
290
/// # /// in a real runtime.
291
/// # pub enum Runtime {}
292
/// #
293
/// # sp_api::decl_runtime_apis! {
294
/// #     /// Declare the api trait.
295
/// #     pub trait Balance {
296
/// #         /// Get the balance.
297
/// #         fn get_balance() -> u64;
298
/// #         /// Set the balance.
299
/// #         fn set_balance(val: u64);
300
/// #     }
301
/// #     pub trait BlockBuilder {
302
/// #        fn build_block() -> Block;
303
/// #     }
304
/// # }
305
///
306
/// /// All runtime api implementations need to be done in one call of the macro!
307
/// sp_api::impl_runtime_apis! {
308
/// #   impl sp_api::Core<Block> for Runtime {
309
/// #       fn version() -> sp_version::RuntimeVersion {
310
/// #           unimplemented!()
311
/// #       }
312
/// #       fn execute_block(_block: Block) {}
313
/// #       fn initialize_block(_header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode {
314
/// #           unimplemented!()
315
/// #       }
316
/// #   }
317
///
318
///     impl self::Balance<Block> for Runtime {
319
///         fn get_balance() -> u64 {
320
///             1
321
///         }
322
///         fn set_balance(_bal: u64) {
323
///             // Store the balance
324
///         }
325
///     }
326
///
327
///     impl self::BlockBuilder<Block> for Runtime {
328
///         fn build_block() -> Block {
329
///              unimplemented!("Please implement me!")
330
///         }
331
///     }
332
/// }
333
///
334
/// /// Runtime version. This needs to be declared for each runtime.
335
/// pub const VERSION: sp_version::RuntimeVersion = sp_version::RuntimeVersion {
336
///     spec_name: create_runtime_str!("node"),
337
///     impl_name: create_runtime_str!("test-node"),
338
///     authoring_version: 1,
339
///     spec_version: 1,
340
///     impl_version: 0,
341
///     // Here we are exposing the runtime api versions.
342
///     apis: RUNTIME_API_VERSIONS,
343
///     transaction_version: 1,
344
///     state_version: 1,
345
/// };
346
///
347
/// # fn main() {}
348
/// ```
349
///
350
/// # Implementing specific api version
351
///
352
/// If `decl_runtime_apis!` declares multiple versions for an api `impl_runtime_apis!`
353
/// should specify which version it implements by adding `api_version` attribute to the
354
/// `impl` block. If omitted - the base/default version is implemented. Here is an example:
355
/// ```ignore
356
/// sp_api::impl_runtime_apis! {
357
///     #[api_version(3)]
358
///     impl self::Balance<Block> for Runtime {
359
///          // implementation
360
///     }
361
/// }
362
/// ```
363
/// In this case `Balance` api version 3 is being implemented for `Runtime`. The `impl` block
364
/// must contain all methods declared in version 3 and below.
365
///
366
/// # Conditional version implementation
367
///
368
/// `impl_runtime_apis!` supports `cfg_attr` attribute for conditional compilation. For example
369
/// let's say you want to implement a staging version of the runtime api and put it behind a
370
/// feature flag. You can do it this way:
371
/// ```ignore
372
/// pub enum Runtime {}
373
/// sp_api::decl_runtime_apis! {
374
///     pub trait ApiWithStagingMethod {
375
///         fn stable_one(data: u64);
376
///
377
///         #[api_version(99)]
378
///         fn staging_one();
379
///     }
380
/// }
381
///
382
/// sp_api::impl_runtime_apis! {
383
///     #[cfg_attr(feature = "enable-staging-api", api_version(99))]
384
///     impl self::ApiWithStagingMethod<Block> for Runtime {
385
///         fn stable_one(_: u64) {}
386
///
387
///         #[cfg(feature = "enable-staging-api")]
388
///         fn staging_one() {}
389
///     }
390
/// }
391
/// ```
392
///
393
/// [`decl_runtime_apis!`] declares two version of the api - 1 (the default one, which is
394
/// considered stable in our example) and 99 (which is considered staging). In
395
/// `impl_runtime_apis!` a `cfg_attr` attribute is attached to the `ApiWithStagingMethod`
396
/// implementation. If the code is compiled with  `enable-staging-api` feature a version 99 of
397
/// the runtime api will be built which will include `staging_one`. Note that `staging_one`
398
/// implementation is feature gated by `#[cfg(feature = ... )]` attribute.
399
///
400
/// If the code is compiled without `enable-staging-api` version 1 (the default one) will be
401
/// built which doesn't include `staging_one`.
402
///
403
/// `cfg_attr` can also be used together with `api_version`. For the next snippet will build
404
/// version 99 if `enable-staging-api` is enabled and version 2 otherwise because both
405
/// `cfg_attr` and `api_version` are attached to the impl block:
406
/// ```ignore
407
/// #[cfg_attr(feature = "enable-staging-api", api_version(99))]
408
/// #[api_version(2)]
409
/// impl self::ApiWithStagingAndVersionedMethods<Block> for Runtime {
410
///  // impl skipped
411
/// }
412
/// ```
413
pub use sp_api_proc_macro::impl_runtime_apis;
414

            
415
/// Mocks given trait implementations as runtime apis.
416
///
417
/// Accepts similar syntax as [`impl_runtime_apis!`] and generates simplified mock
418
/// implementations of the given runtime apis. The difference in syntax is that the trait does
419
/// not need to be referenced by a qualified path, methods accept the `&self` parameter and the
420
/// error type can be specified as associated type. If no error type is specified [`String`] is
421
/// used as error type.
422
///
423
/// Besides implementing the given traits, the [`Core`] and [`ApiExt`] are implemented
424
/// automatically.
425
///
426
/// # Example
427
///
428
/// ```rust
429
/// # use sp_runtime::traits::Block as BlockT;
430
/// # use sp_test_primitives::Block;
431
/// #
432
/// # sp_api::decl_runtime_apis! {
433
/// #     /// Declare the api trait.
434
/// #     pub trait Balance {
435
/// #         /// Get the balance.
436
/// #         fn get_balance() -> u64;
437
/// #         /// Set the balance.
438
/// #         fn set_balance(val: u64);
439
/// #     }
440
/// #     pub trait BlockBuilder {
441
/// #        fn build_block() -> Block;
442
/// #     }
443
/// # }
444
/// struct MockApi {
445
///     balance: u64,
446
/// }
447
///
448
/// /// All runtime api mock implementations need to be done in one call of the macro!
449
/// sp_api::mock_impl_runtime_apis! {
450
///     impl Balance<Block> for MockApi {
451
///         /// Here we take the `&self` to access the instance.
452
///         fn get_balance(&self) -> u64 {
453
///             self.balance
454
///         }
455
///         fn set_balance(_bal: u64) {
456
///             // Store the balance
457
///         }
458
///     }
459
///
460
///     impl BlockBuilder<Block> for MockApi {
461
///         fn build_block() -> Block {
462
///              unimplemented!("Not Required in tests")
463
///         }
464
///     }
465
/// }
466
///
467
/// # fn main() {}
468
/// ```
469
///
470
/// # `advanced` attribute
471
///
472
/// This attribute can be placed above individual function in the mock implementation to
473
/// request more control over the function declaration. From the client side each runtime api
474
/// function is called with the `at` parameter that is a [`Hash`](sp_runtime::traits::Hash).
475
/// When using the `advanced` attribute, the macro expects that the first parameter of the
476
/// function is this `at` parameter. Besides that the macro also doesn't do the automatic
477
/// return value rewrite, which means that full return value must be specified. The full return
478
/// value is constructed like [`Result`]`<<ReturnValue>, Error>` while `ReturnValue` being the
479
/// return value that is specified in the trait declaration.
480
///
481
/// ## Example
482
/// ```rust
483
/// # use sp_runtime::traits::Block as BlockT;
484
/// # use sp_test_primitives::Block;
485
/// # use codec;
486
/// #
487
/// # sp_api::decl_runtime_apis! {
488
/// #     /// Declare the api trait.
489
/// #     pub trait Balance {
490
/// #         /// Get the balance.
491
/// #         fn get_balance() -> u64;
492
/// #         /// Set the balance.
493
/// #         fn set_balance(val: u64);
494
/// #     }
495
/// # }
496
/// struct MockApi {
497
///     balance: u64,
498
/// }
499
///
500
/// sp_api::mock_impl_runtime_apis! {
501
///     impl Balance<Block> for MockApi {
502
///         #[advanced]
503
///         fn get_balance(&self, at: <Block as BlockT>::Hash) -> Result<u64, sp_api::ApiError> {
504
///             println!("Being called at: {}", at);
505
///
506
///             Ok(self.balance.into())
507
///         }
508
///         #[advanced]
509
///         fn set_balance(at: <Block as BlockT>::Hash, val: u64) -> Result<(), sp_api::ApiError> {
510
///             println!("Being called at: {}", at);
511
///
512
///             Ok(().into())
513
///         }
514
///     }
515
/// }
516
///
517
/// # fn main() {}
518
/// ```
519
pub use sp_api_proc_macro::mock_impl_runtime_apis;
520

            
521
/// A type that records all accessed trie nodes and generates a proof out of it.
522
#[cfg(feature = "std")]
523
pub type ProofRecorder<B> = sp_trie::recorder::Recorder<HashingFor<B>>;
524

            
525
#[cfg(feature = "std")]
526
pub type StorageChanges<Block> = sp_state_machine::StorageChanges<HashingFor<Block>>;
527

            
528
/// Something that can be constructed to a runtime api.
529
#[cfg(feature = "std")]
530
pub trait ConstructRuntimeApi<Block: BlockT, C: CallApiAt<Block>> {
531
	/// The actual runtime api that will be constructed.
532
	type RuntimeApi: ApiExt<Block>;
533

            
534
	/// Construct an instance of the runtime api.
535
	fn construct_runtime_api(call: &C) -> ApiRef<Self::RuntimeApi>;
536
}
537

            
538
#[docify::export]
539
/// Init the [`RuntimeLogger`](sp_runtime::runtime_logger::RuntimeLogger).
540
pub fn init_runtime_logger() {
541
	#[cfg(not(feature = "disable-logging"))]
542
	sp_runtime::runtime_logger::RuntimeLogger::init();
543
}
544

            
545
/// An error describing which API call failed.
546
#[cfg(feature = "std")]
547
#[derive(Debug, thiserror::Error)]
548
pub enum ApiError {
549
	#[error("Failed to decode return value of {function}: {error} raw data: {raw:?}")]
550
	FailedToDecodeReturnValue {
551
		function: &'static str,
552
		#[source]
553
		error: codec::Error,
554
		raw: Vec<u8>,
555
	},
556
	#[error("Failed to convert return value from runtime to node of {function}")]
557
	FailedToConvertReturnValue {
558
		function: &'static str,
559
		#[source]
560
		error: codec::Error,
561
	},
562
	#[error("Failed to convert parameter `{parameter}` from node to runtime of {function}")]
563
	FailedToConvertParameter {
564
		function: &'static str,
565
		parameter: &'static str,
566
		#[source]
567
		error: codec::Error,
568
	},
569
	#[error("The given `StateBackend` isn't a `TrieBackend`.")]
570
	StateBackendIsNotTrie,
571
	#[error(transparent)]
572
	Application(#[from] Box<dyn std::error::Error + Send + Sync>),
573
	#[error("Api called for an unknown Block: {0}")]
574
	UnknownBlock(String),
575
	#[error("Using the same api instance to call into multiple independent blocks.")]
576
	UsingSameInstanceForDifferentBlocks,
577
}
578

            
579
/// Extends the runtime api implementation with some common functionality.
580
#[cfg(feature = "std")]
581
pub trait ApiExt<Block: BlockT> {
582
	/// Execute the given closure inside a new transaction.
583
	///
584
	/// Depending on the outcome of the closure, the transaction is committed or rolled-back.
585
	///
586
	/// The internal result of the closure is returned afterwards.
587
	fn execute_in_transaction<F: FnOnce(&Self) -> TransactionOutcome<R>, R>(&self, call: F) -> R
588
	where
589
		Self: Sized;
590

            
591
	/// Checks if the given api is implemented and versions match.
592
	fn has_api<A: RuntimeApiInfo + ?Sized>(&self, at_hash: Block::Hash) -> Result<bool, ApiError>
593
	where
594
		Self: Sized;
595

            
596
	/// Check if the given api is implemented and the version passes a predicate.
597
	fn has_api_with<A: RuntimeApiInfo + ?Sized, P: Fn(u32) -> bool>(
598
		&self,
599
		at_hash: Block::Hash,
600
		pred: P,
601
	) -> Result<bool, ApiError>
602
	where
603
		Self: Sized;
604

            
605
	/// Returns the version of the given api.
606
	fn api_version<A: RuntimeApiInfo + ?Sized>(
607
		&self,
608
		at_hash: Block::Hash,
609
	) -> Result<Option<u32>, ApiError>
610
	where
611
		Self: Sized;
612

            
613
	/// Start recording all accessed trie nodes for generating proofs.
614
	fn record_proof(&mut self);
615

            
616
	/// Extract the recorded proof.
617
	///
618
	/// This stops the proof recording.
619
	///
620
	/// If `record_proof` was not called before, this will return `None`.
621
	fn extract_proof(&mut self) -> Option<StorageProof>;
622

            
623
	/// Returns the current active proof recorder.
624
	fn proof_recorder(&self) -> Option<ProofRecorder<Block>>;
625

            
626
	/// Convert the api object into the storage changes that were done while executing runtime
627
	/// api functions.
628
	///
629
	/// After executing this function, all collected changes are reset.
630
	fn into_storage_changes<B: StateBackend<HashingFor<Block>>>(
631
		&self,
632
		backend: &B,
633
		parent_hash: Block::Hash,
634
	) -> Result<StorageChanges<Block>, String>
635
	where
636
		Self: Sized;
637

            
638
	/// Set the [`CallContext`] to be used by the runtime api calls done by this instance.
639
	fn set_call_context(&mut self, call_context: CallContext);
640

            
641
	/// Register an [`Extension`] that will be accessible while executing a runtime api call.
642
	fn register_extension<E: Extension>(&mut self, extension: E);
643
}
644

            
645
/// Parameters for [`CallApiAt::call_api_at`].
646
#[cfg(feature = "std")]
647
pub struct CallApiAtParams<'a, Block: BlockT> {
648
	/// The block id that determines the state that should be setup when calling the function.
649
	pub at: Block::Hash,
650
	/// The name of the function that should be called.
651
	pub function: &'static str,
652
	/// The encoded arguments of the function.
653
	pub arguments: Vec<u8>,
654
	/// The overlayed changes that are on top of the state.
655
	pub overlayed_changes: &'a RefCell<OverlayedChanges<HashingFor<Block>>>,
656
	/// The call context of this call.
657
	pub call_context: CallContext,
658
	/// The optional proof recorder for recording storage accesses.
659
	pub recorder: &'a Option<ProofRecorder<Block>>,
660
	/// The extensions that should be used for this call.
661
	pub extensions: &'a RefCell<Extensions>,
662
}
663

            
664
/// Something that can call into the an api at a given block.
665
#[cfg(feature = "std")]
666
pub trait CallApiAt<Block: BlockT> {
667
	/// The state backend that is used to store the block states.
668
	type StateBackend: StateBackend<HashingFor<Block>> + AsTrieBackend<HashingFor<Block>>;
669

            
670
	/// Calls the given api function with the given encoded arguments at the given block and returns
671
	/// the encoded result.
672
	fn call_api_at(&self, params: CallApiAtParams<Block>) -> Result<Vec<u8>, ApiError>;
673

            
674
	/// Returns the runtime version at the given block.
675
	fn runtime_version_at(&self, at_hash: Block::Hash) -> Result<RuntimeVersion, ApiError>;
676

            
677
	/// Get the state `at` the given block.
678
	fn state_at(&self, at: Block::Hash) -> Result<Self::StateBackend, ApiError>;
679

            
680
	/// Initialize the `extensions` for the given block `at` by using the global extensions factory.
681
	fn initialize_extensions(
682
		&self,
683
		at: Block::Hash,
684
		extensions: &mut Extensions,
685
	) -> Result<(), ApiError>;
686
}
687

            
688
#[cfg(feature = "std")]
689
impl<Block: BlockT, T: CallApiAt<Block>> CallApiAt<Block> for std::sync::Arc<T> {
690
	type StateBackend = T::StateBackend;
691

            
692
	fn call_api_at(&self, params: CallApiAtParams<Block>) -> Result<Vec<u8>, ApiError> {
693
		(**self).call_api_at(params)
694
	}
695

            
696
	fn runtime_version_at(
697
		&self,
698
		at_hash: <Block as BlockT>::Hash,
699
	) -> Result<RuntimeVersion, ApiError> {
700
		(**self).runtime_version_at(at_hash)
701
	}
702

            
703
	fn state_at(&self, at: <Block as BlockT>::Hash) -> Result<Self::StateBackend, ApiError> {
704
		(**self).state_at(at)
705
	}
706

            
707
	fn initialize_extensions(
708
		&self,
709
		at: <Block as BlockT>::Hash,
710
		extensions: &mut Extensions,
711
	) -> Result<(), ApiError> {
712
		(**self).initialize_extensions(at, extensions)
713
	}
714
}
715

            
716
/// Auxiliary wrapper that holds an api instance and binds it to the given lifetime.
717
#[cfg(feature = "std")]
718
pub struct ApiRef<'a, T>(T, std::marker::PhantomData<&'a ()>);
719

            
720
#[cfg(feature = "std")]
721
impl<'a, T> From<T> for ApiRef<'a, T> {
722
	fn from(api: T) -> Self {
723
		ApiRef(api, Default::default())
724
	}
725
}
726

            
727
#[cfg(feature = "std")]
728
impl<'a, T> std::ops::Deref for ApiRef<'a, T> {
729
	type Target = T;
730

            
731
	fn deref(&self) -> &Self::Target {
732
		&self.0
733
	}
734
}
735

            
736
#[cfg(feature = "std")]
737
impl<'a, T> std::ops::DerefMut for ApiRef<'a, T> {
738
	fn deref_mut(&mut self) -> &mut T {
739
		&mut self.0
740
	}
741
}
742

            
743
/// Something that provides a runtime api.
744
#[cfg(feature = "std")]
745
pub trait ProvideRuntimeApi<Block: BlockT> {
746
	/// The concrete type that provides the api.
747
	type Api: ApiExt<Block>;
748

            
749
	/// Returns the runtime api.
750
	/// The returned instance will keep track of modifications to the storage. Any successful
751
	/// call to an api function, will `commit` its changes to an internal buffer. Otherwise,
752
	/// the modifications will be `discarded`. The modifications will not be applied to the
753
	/// storage, even on a `commit`.
754
	fn runtime_api(&self) -> ApiRef<Self::Api>;
755
}
756

            
757
/// Something that provides information about a runtime api.
758
#[cfg(feature = "std")]
759
pub trait RuntimeApiInfo {
760
	/// The identifier of the runtime api.
761
	const ID: [u8; 8];
762
	/// The version of the runtime api.
763
	const VERSION: u32;
764
}
765

            
766
/// The number of bytes required to encode a [`RuntimeApiInfo`].
767
///
768
/// 8 bytes for `ID` and 4 bytes for a version.
769
pub const RUNTIME_API_INFO_SIZE: usize = 12;
770

            
771
/// Crude and simple way to serialize the `RuntimeApiInfo` into a bunch of bytes.
772
pub const fn serialize_runtime_api_info(id: [u8; 8], version: u32) -> [u8; RUNTIME_API_INFO_SIZE] {
773
	let version = version.to_le_bytes();
774

            
775
	let mut r = [0; RUNTIME_API_INFO_SIZE];
776
	r[0] = id[0];
777
	r[1] = id[1];
778
	r[2] = id[2];
779
	r[3] = id[3];
780
	r[4] = id[4];
781
	r[5] = id[5];
782
	r[6] = id[6];
783
	r[7] = id[7];
784

            
785
	r[8] = version[0];
786
	r[9] = version[1];
787
	r[10] = version[2];
788
	r[11] = version[3];
789
	r
790
}
791

            
792
/// Deserialize the runtime API info serialized by [`serialize_runtime_api_info`].
793
pub fn deserialize_runtime_api_info(bytes: [u8; RUNTIME_API_INFO_SIZE]) -> ([u8; 8], u32) {
794
	let id: [u8; 8] = bytes[0..8]
795
		.try_into()
796
		.expect("the source slice size is equal to the dest array length; qed");
797

            
798
	let version = u32::from_le_bytes(
799
		bytes[8..12]
800
			.try_into()
801
			.expect("the source slice size is equal to the array length; qed"),
802
	);
803

            
804
	(id, version)
805
}
806

            
807
decl_runtime_apis! {
808
	/// The `Core` runtime api that every Substrate runtime needs to implement.
809
	#[core_trait]
810
	#[api_version(5)]
811
	pub trait Core {
812
		/// Returns the version of the runtime.
813
		fn version() -> RuntimeVersion;
814
		/// Execute the given block.
815
		fn execute_block(block: Block);
816
		/// Initialize a block with the given header.
817
		#[changed_in(5)]
818
		#[renamed("initialise_block", 2)]
819
		fn initialize_block(header: &<Block as BlockT>::Header);
820
		/// Initialize a block with the given header and return the runtime executive mode.
821
		fn initialize_block(header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode;
822
	}
823

            
824
	/// The `Metadata` api trait that returns metadata for the runtime.
825
	#[api_version(2)]
826
	pub trait Metadata {
827
		/// Returns the metadata of a runtime.
828
		fn metadata() -> OpaqueMetadata;
829

            
830
		/// Returns the metadata at a given version.
831
		///
832
		/// If the given `version` isn't supported, this will return `None`.
833
		/// Use [`Self::metadata_versions`] to find out about supported metadata version of the runtime.
834
		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata>;
835

            
836
		/// Returns the supported metadata versions.
837
		///
838
		/// This can be used to call `metadata_at_version`.
839
		fn metadata_versions() -> alloc::vec::Vec<u32>;
840
	}
841
}
842

            
843
sp_core::generate_feature_enabled_macro!(std_enabled, feature = "std", $);
844
sp_core::generate_feature_enabled_macro!(std_disabled, not(feature = "std"), $);
845
sp_core::generate_feature_enabled_macro!(frame_metadata_enabled, feature = "frame-metadata", $);