mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-14 05:11:09 +00:00
Rewrap all comments to 100 line width (#9490)
* reformat everything again * manual formatting * last manual fix * Fix build
This commit is contained in:
@@ -60,9 +60,10 @@
|
||||
//! `${TRAIT_NAME}_${FUNCTION_NAME}`. Such a function has the following signature
|
||||
//! `(ptr: *u8, length: u32) -> u64`. It takes a pointer to an `u8` array and its length as an
|
||||
//! argument. This `u8` array is expected to be the SCALE encoded parameters of the function as
|
||||
//! defined in the trait. The return value is an `u64` that represents `length << 32 | pointer` of an
|
||||
//! `u8` array. This return value `u8` array contains the SCALE encoded return value as defined by
|
||||
//! the trait function. The macros take care to encode the parameters and to decode the return value.
|
||||
//! defined in the trait. The return value is an `u64` that represents `length << 32 | pointer` of
|
||||
//! an `u8` array. This return value `u8` array contains the SCALE encoded return value as defined
|
||||
//! by the trait function. The macros take care to encode the parameters and to decode the return
|
||||
//! value.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
@@ -116,8 +117,9 @@ pub const MAX_EXTRINSIC_DEPTH: u32 = 256;
|
||||
/// on the runtime side. The declaration for the runtime side is hidden in its own module.
|
||||
/// The client side declaration gets two extra parameters per function,
|
||||
/// `&self` and `at: &BlockId<Block>`. The runtime side declaration will match the given trait
|
||||
/// declaration. Besides one exception, the macro adds an extra generic parameter `Block: BlockT`
|
||||
/// to the client side and the runtime side. This generic parameter is usable by the user.
|
||||
/// declaration. Besides one exception, the macro adds an extra generic parameter `Block:
|
||||
/// BlockT` to the client side and the runtime side. This generic parameter is usable by the
|
||||
/// user.
|
||||
///
|
||||
/// For implementing these macros you should use the
|
||||
/// [`impl_runtime_apis!`] macro.
|
||||
@@ -149,14 +151,14 @@ pub const MAX_EXTRINSIC_DEPTH: u32 = 256;
|
||||
/// # Runtime api trait versioning
|
||||
///
|
||||
/// To support versioning of the traits, the macro supports the attribute `#[api_version(1)]`.
|
||||
/// The attribute supports any `u32` as version. By default, each trait is at version `1`, if no
|
||||
/// version is provided. We also support changing the signature of a method. This signature
|
||||
/// change is highlighted with the `#[changed_in(2)]` attribute above a method. A method that is
|
||||
/// tagged with this attribute is callable by the name `METHOD_before_version_VERSION`. This
|
||||
/// method will only support calling into wasm, trying to call into native will fail (change the
|
||||
/// spec version!). Such a method also does not need to be implemented in the runtime. It is
|
||||
/// required that there exist the "default" of the method without the `#[changed_in(_)]` attribute,
|
||||
/// this method will be used to call the current default implementation.
|
||||
/// The attribute supports any `u32` as version. By default, each trait is at version `1`, if
|
||||
/// no version is provided. We also support changing the signature of a method. This signature
|
||||
/// change is highlighted with the `#[changed_in(2)]` attribute above a method. A method that
|
||||
/// is tagged with this attribute is callable by the name `METHOD_before_version_VERSION`. This
|
||||
/// method will only support calling into wasm, trying to call into native will fail (change
|
||||
/// the spec version!). Such a method also does not need to be implemented in the runtime. It
|
||||
/// is required that there exist the "default" of the method without the `#[changed_in(_)]`
|
||||
/// attribute, this method will be used to call the current default implementation.
|
||||
///
|
||||
/// ```rust
|
||||
/// sp_api::decl_runtime_apis! {
|
||||
@@ -181,22 +183,23 @@ pub const MAX_EXTRINSIC_DEPTH: u32 = 256;
|
||||
/// ```
|
||||
///
|
||||
/// To check if a given runtime implements a runtime api trait, the `RuntimeVersion` has the
|
||||
/// function `has_api<A>()`. Also the `ApiExt` provides a function `has_api<A>(at: &BlockId)` to
|
||||
/// check if the runtime at the given block id implements the requested runtime api trait.
|
||||
/// function `has_api<A>()`. Also the `ApiExt` provides a function `has_api<A>(at: &BlockId)`
|
||||
/// to check if the runtime at the given block id implements the requested runtime api trait.
|
||||
pub use sp_api_proc_macro::decl_runtime_apis;
|
||||
|
||||
/// Tags given trait implementations as runtime apis.
|
||||
///
|
||||
/// All traits given to this macro, need to be declared with the
|
||||
/// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro. The implementation of the trait
|
||||
/// should follow the declaration given to the [`decl_runtime_apis!`](macro.decl_runtime_apis.html)
|
||||
/// macro, besides the `Block` type that is required as first generic parameter for each runtime
|
||||
/// api trait. When implementing a runtime api trait, it is required that the trait is referenced
|
||||
/// by a path, e.g. `impl my_trait::MyTrait for Runtime`. The macro will use this path to access
|
||||
/// the declaration of the trait for the runtime side.
|
||||
/// should follow the declaration given to the
|
||||
/// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro, besides the `Block` type that
|
||||
/// is required as first generic parameter for each runtime api trait. When implementing a
|
||||
/// runtime api trait, it is required that the trait is referenced by a path, e.g. `impl
|
||||
/// my_trait::MyTrait for Runtime`. The macro will use this path to access the declaration of
|
||||
/// the trait for the runtime side.
|
||||
///
|
||||
/// The macro also generates the api implementations for the client side and provides it through
|
||||
/// the `RuntimeApi` type. The `RuntimeApi` is hidden behind a `feature` called `std`.
|
||||
/// The macro also generates the api implementations for the client side and provides it
|
||||
/// through the `RuntimeApi` type. The `RuntimeApi` is hidden behind a `feature` called `std`.
|
||||
///
|
||||
/// To expose version information about all implemented api traits, the constant
|
||||
/// `RUNTIME_API_VERSIONS` is generated. This constant should be used to instantiate the `apis`
|
||||
@@ -275,13 +278,13 @@ pub use sp_api_proc_macro::impl_runtime_apis;
|
||||
/// Mocks given trait implementations as runtime apis.
|
||||
///
|
||||
/// Accepts similar syntax as [`impl_runtime_apis!`] and generates
|
||||
/// simplified mock implementations of the given runtime apis. The difference in syntax is that the
|
||||
/// trait does not need to be referenced by a qualified path, methods accept the `&self` parameter
|
||||
/// and the error type can be specified as associated type. If no error type is specified [`String`]
|
||||
/// is used as error type.
|
||||
/// simplified mock implementations of the given runtime apis. The difference in syntax is that
|
||||
/// the trait does not need to be referenced by a qualified path, methods accept the `&self`
|
||||
/// parameter and the error type can be specified as associated type. If no error type is
|
||||
/// specified [`String`] is used as error type.
|
||||
///
|
||||
/// Besides implementing the given traits, the [`Core`](sp_api::Core) and [`ApiExt`](sp_api::ApiExt)
|
||||
/// are implemented automatically.
|
||||
/// Besides implementing the given traits, the [`Core`](sp_api::Core) and
|
||||
/// [`ApiExt`](sp_api::ApiExt) are implemented automatically.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
@@ -329,14 +332,15 @@ pub use sp_api_proc_macro::impl_runtime_apis;
|
||||
///
|
||||
/// # `advanced` attribute
|
||||
///
|
||||
/// This attribute can be placed above individual function in the mock implementation to request
|
||||
/// more control over the function declaration. From the client side each runtime api function is
|
||||
/// called with the `at` parameter that is a [`BlockId`](sp_api::BlockId). When using the `advanced`
|
||||
/// attribute, the macro expects that the first parameter of the function is this `at` parameter.
|
||||
/// Besides that the macro also doesn't do the automatic return value rewrite, which means that full
|
||||
/// return value must be specified. The full return value is constructed like
|
||||
/// [`Result`]`<`[`NativeOrEncoded`](sp_api::NativeOrEncoded)`<ReturnValue>, Error>` while
|
||||
/// `ReturnValue` being the return value that is specified in the trait declaration.
|
||||
/// This attribute can be placed above individual function in the mock implementation to
|
||||
/// request more control over the function declaration. From the client side each runtime api
|
||||
/// function is called with the `at` parameter that is a [`BlockId`](sp_api::BlockId). When
|
||||
/// using the `advanced` attribute, the macro expects that the first parameter of the function
|
||||
/// is this `at` parameter. Besides that the macro also doesn't do the automatic return value
|
||||
/// rewrite, which means that full return value must be specified. The full return value is
|
||||
/// constructed like [`Result`]`<`[`NativeOrEncoded`](sp_api::NativeOrEncoded)`<ReturnValue>,
|
||||
/// Error>` while `ReturnValue` being the return value that is specified in the trait
|
||||
/// declaration.
|
||||
///
|
||||
/// ## Example
|
||||
/// ```rust
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
// limitations under the License.
|
||||
|
||||
//! # Running
|
||||
//! Running this fuzzer can be done with `cargo hfuzz run multiply_by_rational`. `honggfuzz` CLI options can
|
||||
//! be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4 threads.
|
||||
//! Running this fuzzer can be done with `cargo hfuzz run multiply_by_rational`. `honggfuzz` CLI
|
||||
//! options can be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4 threads.
|
||||
//!
|
||||
//! # Debugging a panic
|
||||
//! Once a panic is found, it can be debugged with
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
// limitations under the License.
|
||||
|
||||
//! # Running
|
||||
//! Running this fuzzer can be done with `cargo hfuzz run per_thing_rational`. `honggfuzz` CLI options can
|
||||
//! be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4 threads.
|
||||
//! Running this fuzzer can be done with `cargo hfuzz run per_thing_rational`. `honggfuzz` CLI
|
||||
//! options can be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4 threads.
|
||||
//!
|
||||
//! # Debugging a panic
|
||||
//! Once a panic is found, it can be debugged with
|
||||
|
||||
@@ -62,8 +62,8 @@ pub fn to_big_uint(x: u128) -> biguint::BigUint {
|
||||
|
||||
/// Safely and accurately compute `a * b / c`. The approach is:
|
||||
/// - Simply try `a * b / c`.
|
||||
/// - Else, convert them both into big numbers and re-try. `Err` is returned if the result
|
||||
/// cannot be safely casted back to u128.
|
||||
/// - Else, convert them both into big numbers and re-try. `Err` is returned if the result cannot
|
||||
/// be safely casted back to u128.
|
||||
///
|
||||
/// Invariant: c must be greater than or equal to 1.
|
||||
pub fn multiply_by_rational(mut a: u128, mut b: u128, mut c: u128) -> Result<u128, &'static str> {
|
||||
|
||||
@@ -69,14 +69,16 @@ pub trait HeaderBackend<Block: BlockT>: Send + Sync {
|
||||
.ok_or_else(|| Error::UnknownBlock(format!("Expect header: {}", id)))
|
||||
}
|
||||
|
||||
/// Convert an arbitrary block ID into a block number. Returns `UnknownBlock` error if block is not found.
|
||||
/// Convert an arbitrary block ID into a block number. Returns `UnknownBlock` error if block is
|
||||
/// not found.
|
||||
fn expect_block_number_from_id(&self, id: &BlockId<Block>) -> Result<NumberFor<Block>> {
|
||||
self.block_number_from_id(id).and_then(|n| {
|
||||
n.ok_or_else(|| Error::UnknownBlock(format!("Expect block number from id: {}", id)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Convert an arbitrary block ID into a block hash. Returns `UnknownBlock` error if block is not found.
|
||||
/// Convert an arbitrary block ID into a block hash. Returns `UnknownBlock` error if block is
|
||||
/// not found.
|
||||
fn expect_block_hash_from_id(&self, id: &BlockId<Block>) -> Result<Block::Hash> {
|
||||
self.block_hash_from_id(id).and_then(|n| {
|
||||
n.ok_or_else(|| Error::UnknownBlock(format!("Expect block hash from id: {}", id)))
|
||||
|
||||
@@ -60,9 +60,9 @@ pub trait BlockAnnounceValidator<B: Block> {
|
||||
/// Returning [`Validation::Failure`] will lead to a decrease of the
|
||||
/// peers reputation as it sent us invalid data.
|
||||
///
|
||||
/// The returned future should only resolve to an error iff there was an internal error validating
|
||||
/// the block announcement. If the block announcement itself is invalid, this should *always*
|
||||
/// return [`Validation::Failure`].
|
||||
/// The returned future should only resolve to an error iff there was an internal error
|
||||
/// validating the block announcement. If the block announcement itself is invalid, this should
|
||||
/// *always* return [`Validation::Failure`].
|
||||
fn validate(
|
||||
&mut self,
|
||||
header: &B::Header,
|
||||
|
||||
@@ -255,8 +255,8 @@ pub trait Ss58Codec: Sized + AsMut<[u8]> + AsRef<[u8]> + Default {
|
||||
let (prefix_len, ident) = match data[0] {
|
||||
0..=63 => (1, data[0] as u16),
|
||||
64..=127 => {
|
||||
// weird bit manipulation owing to the combination of LE encoding and missing two bits
|
||||
// from the left.
|
||||
// weird bit manipulation owing to the combination of LE encoding and missing two
|
||||
// bits from the left.
|
||||
// d[0] d[1] are: 01aaaaaa bbcccccc
|
||||
// they make the LE-encoded 16-bit value: aaaaaabb 00cccccc
|
||||
// so the lower byte is formed of aaaaaabb and the higher byte is 00cccccc
|
||||
@@ -1029,9 +1029,9 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static {
|
||||
/// Get the public key.
|
||||
fn public(&self) -> Self::Public;
|
||||
|
||||
/// Interprets the string `s` in order to generate a key Pair. Returns both the pair and an optional seed, in the
|
||||
/// case that the pair can be expressed as a direct derivation from a seed (some cases, such as Sr25519 derivations
|
||||
/// with path components, cannot).
|
||||
/// Interprets the string `s` in order to generate a key Pair. Returns both the pair and an
|
||||
/// optional seed, in the case that the pair can be expressed as a direct derivation from a seed
|
||||
/// (some cases, such as Sr25519 derivations with path components, cannot).
|
||||
///
|
||||
/// This takes a helper function to do the key generation from a phrase, password and
|
||||
/// junction iterator.
|
||||
@@ -1043,7 +1043,8 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static {
|
||||
/// - the phrase may be followed by one or more items delimited by `/` characters.
|
||||
/// - the path may be followed by `///`, in which case everything after the `///` is treated
|
||||
/// as a password.
|
||||
/// - If `s` begins with a `/` character it is prefixed with the Substrate public `DEV_PHRASE` and
|
||||
/// - If `s` begins with a `/` character it is prefixed with the Substrate public `DEV_PHRASE`
|
||||
/// and
|
||||
/// interpreted as above.
|
||||
///
|
||||
/// In this case they are interpreted as HDKD junctions; purely numeric items are interpreted as
|
||||
@@ -1053,8 +1054,8 @@ pub trait Pair: CryptoType + Sized + Clone + Send + Sync + 'static {
|
||||
/// There is no correspondence mapping between SURI strings and the keys they represent.
|
||||
/// Two different non-identical strings can actually lead to the same secret being derived.
|
||||
/// Notably, integer junction indices may be legally prefixed with arbitrary number of zeros.
|
||||
/// Similarly an empty password (ending the SURI with `///`) is perfectly valid and will generally
|
||||
/// be equivalent to no password at all.
|
||||
/// Similarly an empty password (ending the SURI with `///`) is perfectly valid and will
|
||||
/// generally be equivalent to no password at all.
|
||||
///
|
||||
/// `None` is returned if no matches are found.
|
||||
#[cfg(feature = "std")]
|
||||
|
||||
@@ -118,7 +118,8 @@ impl ExecutionContext {
|
||||
|
||||
match self {
|
||||
Importing | Syncing | BlockConstruction => offchain::Capabilities::none(),
|
||||
// Enable keystore, transaction pool and Offchain DB reads by default for offchain calls.
|
||||
// Enable keystore, transaction pool and Offchain DB reads by default for offchain
|
||||
// calls.
|
||||
OffchainCall(None) => [
|
||||
offchain::Capability::Keystore,
|
||||
offchain::Capability::OffchainDbRead,
|
||||
|
||||
@@ -344,8 +344,8 @@ pub trait Externalities: Send {
|
||||
|
||||
/// Initiates a http request given HTTP verb and the URL.
|
||||
///
|
||||
/// Meta is a future-reserved field containing additional, parity-scale-codec encoded parameters.
|
||||
/// Returns the id of newly started request.
|
||||
/// Meta is a future-reserved field containing additional, parity-scale-codec encoded
|
||||
/// parameters. Returns the id of newly started request.
|
||||
///
|
||||
/// Returns an error if:
|
||||
/// - No new request identifier could be allocated.
|
||||
@@ -388,8 +388,8 @@ pub trait Externalities: Send {
|
||||
/// - The request identifier is invalid.
|
||||
/// - `http_response_wait` has already been called on this request.
|
||||
/// - The deadline is reached.
|
||||
/// - An I/O error has happened, for example the remote has closed our
|
||||
/// request. The request is then considered invalid.
|
||||
/// - An I/O error has happened, for example the remote has closed our request. The request is
|
||||
/// then considered invalid.
|
||||
fn http_request_write_body(
|
||||
&mut self,
|
||||
request_id: HttpRequestId,
|
||||
@@ -440,8 +440,8 @@ pub trait Externalities: Send {
|
||||
/// Returns an error if:
|
||||
/// - The request identifier is invalid.
|
||||
/// - The deadline is reached.
|
||||
/// - An I/O error has happened, for example the remote has closed our
|
||||
/// request. The request is then considered invalid.
|
||||
/// - An I/O error has happened, for example the remote has closed our request. The request is
|
||||
/// then considered invalid.
|
||||
fn http_response_read_body(
|
||||
&mut self,
|
||||
request_id: HttpRequestId,
|
||||
|
||||
@@ -168,8 +168,8 @@ impl OffchainState {
|
||||
/// Add expected HTTP request.
|
||||
///
|
||||
/// This method can be used to initialize expected HTTP requests and their responses
|
||||
/// before running the actual code that utilizes them (for instance before calling into runtime).
|
||||
/// Expected request has to be fulfilled before this struct is dropped,
|
||||
/// before running the actual code that utilizes them (for instance before calling into
|
||||
/// runtime). Expected request has to be fulfilled before this struct is dropped,
|
||||
/// the `response` and `response_headers` fields will be used to return results to the callers.
|
||||
/// Requests are expected to be performed in the insertion order.
|
||||
pub fn expect_request(&mut self, expected: PendingRequest) {
|
||||
|
||||
@@ -870,7 +870,8 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn verify_from_old_wasm_works() {
|
||||
// The values in this test case are compared to the output of `node-test.js` in schnorrkel-js.
|
||||
// The values in this test case are compared to the output of `node-test.js` in
|
||||
// schnorrkel-js.
|
||||
//
|
||||
// This is to make sure that the wasm library is compatible.
|
||||
let pk = Pair::from_seed(&hex!(
|
||||
|
||||
@@ -126,13 +126,13 @@ pub trait ReadRuntimeVersion: Send + Sync {
|
||||
/// The version information may be embedded into the wasm binary itself. If it is not present,
|
||||
/// then this function may fallback to the legacy way of reading the version.
|
||||
///
|
||||
/// The legacy mechanism involves instantiating the passed wasm runtime and calling `Core_version`
|
||||
/// on it. This is a very expensive operation.
|
||||
/// The legacy mechanism involves instantiating the passed wasm runtime and calling
|
||||
/// `Core_version` on it. This is a very expensive operation.
|
||||
///
|
||||
/// `ext` is only needed in case the calling into runtime happens. Otherwise it is ignored.
|
||||
///
|
||||
/// Compressed wasm blobs are supported and will be decompressed if needed. If uncompression fails,
|
||||
/// the error is returned.
|
||||
/// Compressed wasm blobs are supported and will be decompressed if needed. If uncompression
|
||||
/// fails, the error is returned.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
|
||||
@@ -30,7 +30,8 @@ use sp_std::{
|
||||
ops::DerefMut,
|
||||
};
|
||||
|
||||
/// Marker trait for types that should be registered as [`Externalities`](crate::Externalities) extension.
|
||||
/// Marker trait for types that should be registered as [`Externalities`](crate::Externalities)
|
||||
/// extension.
|
||||
///
|
||||
/// As extensions are stored as `Box<Any>`, this trait should give more confidence that the correct
|
||||
/// type is registered and requested.
|
||||
@@ -95,7 +96,8 @@ macro_rules! decl_extension {
|
||||
///
|
||||
/// This is a super trait of the [`Externalities`](crate::Externalities).
|
||||
pub trait ExtensionStore {
|
||||
/// Tries to find a registered extension by the given `type_id` and returns it as a `&mut dyn Any`.
|
||||
/// Tries to find a registered extension by the given `type_id` and returns it as a `&mut dyn
|
||||
/// Any`.
|
||||
///
|
||||
/// It is advised to use [`ExternalitiesExt::extension`](crate::ExternalitiesExt::extension)
|
||||
/// instead of this function to get type system support and automatic type downcasting.
|
||||
|
||||
@@ -94,7 +94,8 @@ pub trait Externalities: ExtensionStore {
|
||||
self.place_storage(key.to_vec(), None);
|
||||
}
|
||||
|
||||
/// Clear a child storage entry (`key`) of current contract being called (effective immediately).
|
||||
/// Clear a child storage entry (`key`) of current contract being called (effective
|
||||
/// immediately).
|
||||
fn clear_child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) {
|
||||
self.place_child_storage(child_info, key.to_vec(), None)
|
||||
}
|
||||
@@ -144,7 +145,8 @@ pub trait Externalities: ExtensionStore {
|
||||
limit: Option<u32>,
|
||||
) -> (bool, u32);
|
||||
|
||||
/// Set or clear a storage entry (`key`) of current contract being called (effective immediately).
|
||||
/// Set or clear a storage entry (`key`) of current contract being called (effective
|
||||
/// immediately).
|
||||
fn place_storage(&mut self, key: Vec<u8>, value: Option<Vec<u8>>);
|
||||
|
||||
/// Set or clear a child storage entry.
|
||||
@@ -167,7 +169,8 @@ pub trait Externalities: ExtensionStore {
|
||||
|
||||
/// Append storage item.
|
||||
///
|
||||
/// This assumes specific format of the storage item. Also there is no way to undo this operation.
|
||||
/// This assumes specific format of the storage item. Also there is no way to undo this
|
||||
/// operation.
|
||||
fn storage_append(&mut self, key: Vec<u8>, value: Vec<u8>);
|
||||
|
||||
/// Get the changes trie root of the current storage overlay at a block with given `parent`.
|
||||
|
||||
@@ -21,9 +21,9 @@ use crate::Externalities;
|
||||
|
||||
environmental::environmental!(ext: trait Externalities);
|
||||
|
||||
/// Set the given externalities while executing the given closure. To get access to the externalities
|
||||
/// while executing the given closure [`with_externalities`] grants access to them. The externalities
|
||||
/// are only set for the same thread this function was called from.
|
||||
/// Set the given externalities while executing the given closure. To get access to the
|
||||
/// externalities while executing the given closure [`with_externalities`] grants access to them.
|
||||
/// The externalities are only set for the same thread this function was called from.
|
||||
pub fn set_and_run_with_externalities<F, R>(ext: &mut dyn Externalities, f: F) -> R
|
||||
where
|
||||
F: FnOnce() -> R,
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
//! runtime implementation to require an inherent for each block or to make it optional. Inherents
|
||||
//! are mainly used to pass data from the block producer to the runtime. So, inherents require some
|
||||
//! part that is running on the client side and some part that is running on the runtime side. Any
|
||||
//! data that is required by an inherent is passed as [`InherentData`] from the client to the runtime
|
||||
//! when the inherents are constructed.
|
||||
//! data that is required by an inherent is passed as [`InherentData`] from the client to the
|
||||
//! runtime when the inherents are constructed.
|
||||
//!
|
||||
//! The process of constructing and applying inherents is the following:
|
||||
//!
|
||||
|
||||
@@ -258,8 +258,8 @@ pub trait Storage {
|
||||
pub trait DefaultChildStorage {
|
||||
/// Get a default child storage value for a given key.
|
||||
///
|
||||
/// Parameter `storage_key` is the unprefixed location of the root of the child trie in the parent trie.
|
||||
/// Result is `None` if the value for `key` in the child storage can not be found.
|
||||
/// Parameter `storage_key` is the unprefixed location of the root of the child trie in the
|
||||
/// parent trie. Result is `None` if the value for `key` in the child storage can not be found.
|
||||
fn get(&self, storage_key: &[u8], key: &[u8]) -> Option<Vec<u8>> {
|
||||
let child_info = ChildInfo::new_default(storage_key);
|
||||
self.child_storage(&child_info, key).map(|s| s.to_vec())
|
||||
@@ -435,11 +435,12 @@ pub trait Trie {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interface that provides miscellaneous functions for communicating between the runtime and the node.
|
||||
/// Interface that provides miscellaneous functions for communicating between the runtime and the
|
||||
/// node.
|
||||
#[runtime_interface]
|
||||
pub trait Misc {
|
||||
// NOTE: We use the target 'runtime' for messages produced by general printing functions, instead
|
||||
// of LOG_TARGET.
|
||||
// NOTE: We use the target 'runtime' for messages produced by general printing functions,
|
||||
// instead of LOG_TARGET.
|
||||
|
||||
/// Print a number.
|
||||
fn print_num(val: u64) {
|
||||
@@ -466,8 +467,8 @@ pub trait Misc {
|
||||
/// # Performance
|
||||
///
|
||||
/// This function may be very expensive to call depending on the wasm binary. It may be
|
||||
/// relatively cheap if the wasm binary contains version information. In that case, uncompression
|
||||
/// of the wasm blob is the dominating factor.
|
||||
/// relatively cheap if the wasm binary contains version information. In that case,
|
||||
/// uncompression of the wasm blob is the dominating factor.
|
||||
///
|
||||
/// If the wasm binary does not have the version information attached, then a legacy mechanism
|
||||
/// may be involved. This means that a runtime call will be performed to query the version.
|
||||
@@ -986,8 +987,8 @@ pub trait Offchain {
|
||||
|
||||
/// Initiates a http request given HTTP verb and the URL.
|
||||
///
|
||||
/// Meta is a future-reserved field containing additional, parity-scale-codec encoded parameters.
|
||||
/// Returns the id of newly started request.
|
||||
/// Meta is a future-reserved field containing additional, parity-scale-codec encoded
|
||||
/// parameters. Returns the id of newly started request.
|
||||
fn http_request_start(
|
||||
&mut self,
|
||||
method: &str,
|
||||
@@ -1149,13 +1150,14 @@ where
|
||||
#[runtime_interface(wasm_only, no_tracing)]
|
||||
pub trait WasmTracing {
|
||||
/// Whether the span described in `WasmMetadata` should be traced wasm-side
|
||||
/// On the host converts into a static Metadata and checks against the global `tracing` dispatcher.
|
||||
/// On the host converts into a static Metadata and checks against the global `tracing`
|
||||
/// dispatcher.
|
||||
///
|
||||
/// When returning false the calling code should skip any tracing-related execution. In general
|
||||
/// within the same block execution this is not expected to change and it doesn't have to be
|
||||
/// checked more than once per metadata. This exists for optimisation purposes but is still not
|
||||
/// cheap as it will jump the wasm-native-barrier every time it is called. So an implementation might
|
||||
/// chose to cache the result for the execution of the entire block.
|
||||
/// cheap as it will jump the wasm-native-barrier every time it is called. So an implementation
|
||||
/// might chose to cache the result for the execution of the entire block.
|
||||
fn enabled(&mut self, metadata: Crossing<sp_tracing::WasmMetadata>) -> bool {
|
||||
let metadata: &tracing_core::metadata::Metadata<'static> = (&metadata.into_inner()).into();
|
||||
tracing::dispatcher::get_default(|d| d.enabled(metadata))
|
||||
|
||||
@@ -12,18 +12,20 @@ fn main() {
|
||||
fuzz!(|fuzzer_data: &[u8]| {
|
||||
let result_decoded: Result<InnerTestSolutionCompact, Error> =
|
||||
<InnerTestSolutionCompact as codec::Decode>::decode(&mut &fuzzer_data[..]);
|
||||
// Ignore errors as not every random sequence of bytes can be decoded as InnerTestSolutionCompact
|
||||
// Ignore errors as not every random sequence of bytes can be decoded as
|
||||
// InnerTestSolutionCompact
|
||||
if let Ok(decoded) = result_decoded {
|
||||
// Decoding works, let's re-encode it and compare results.
|
||||
let reencoded: std::vec::Vec<u8> = decoded.encode();
|
||||
// The reencoded value may or may not be equal to the original fuzzer output. However, the
|
||||
// original decoder should be optimal (in the sense that there is no shorter encoding of
|
||||
// the same object). So let's see if the fuzzer can find something shorter:
|
||||
// The reencoded value may or may not be equal to the original fuzzer output.
|
||||
// However, the original decoder should be optimal (in the sense that there is no
|
||||
// shorter encoding of the same object). So let's see if the fuzzer can find
|
||||
// something shorter:
|
||||
if fuzzer_data.len() < reencoded.len() {
|
||||
panic!("fuzzer_data.len() < reencoded.len()");
|
||||
}
|
||||
// The reencoded value should definitely be decodable (if unwrap() fails that is a valid
|
||||
// panic/finding for the fuzzer):
|
||||
// The reencoded value should definitely be decodable (if unwrap() fails that is a
|
||||
// valid panic/finding for the fuzzer):
|
||||
let decoded2: InnerTestSolutionCompact =
|
||||
<InnerTestSolutionCompact as codec::Decode>::decode(&mut reencoded.as_slice())
|
||||
.unwrap();
|
||||
|
||||
@@ -94,8 +94,8 @@ fn main() {
|
||||
iterations, unbalanced_score, balanced_score, enhance,
|
||||
);
|
||||
|
||||
// The only guarantee of balancing is such that the first and third element of the score
|
||||
// cannot decrease.
|
||||
// The only guarantee of balancing is such that the first and third element of the
|
||||
// score cannot decrease.
|
||||
assert!(
|
||||
balanced_score[0] >= unbalanced_score[0] &&
|
||||
balanced_score[1] == unbalanced_score[1] &&
|
||||
|
||||
@@ -21,17 +21,17 @@
|
||||
//! ## Running a single iteration
|
||||
//!
|
||||
//! Honggfuzz shuts down each individual loop iteration after a configurable time limit.
|
||||
//! It can be helpful to run a single iteration on your hardware to help benchmark how long that time
|
||||
//! limit should reasonably be. Simply run the program without the `fuzzing` configuration to run a
|
||||
//! single iteration: `cargo run --bin phragmen_pjr`.
|
||||
//! It can be helpful to run a single iteration on your hardware to help benchmark how long that
|
||||
//! time limit should reasonably be. Simply run the program without the `fuzzing` configuration to
|
||||
//! run a single iteration: `cargo run --bin phragmen_pjr`.
|
||||
//!
|
||||
//! ## Running
|
||||
//!
|
||||
//! Run with `HFUZZ_RUN_ARGS="-t 10" cargo hfuzz run phragmen_pjr`.
|
||||
//!
|
||||
//! Note the environment variable: by default, `cargo hfuzz` shuts down each iteration after 1 second
|
||||
//! of runtime. We significantly increase that to ensure that the fuzzing gets a chance to complete.
|
||||
//! Running a single iteration can help determine an appropriate value for this parameter.
|
||||
//! Note the environment variable: by default, `cargo hfuzz` shuts down each iteration after 1
|
||||
//! second of runtime. We significantly increase that to ensure that the fuzzing gets a chance to
|
||||
//! complete. Running a single iteration can help determine an appropriate value for this parameter.
|
||||
//!
|
||||
//! ## Debugging a panic
|
||||
//!
|
||||
|
||||
@@ -406,7 +406,8 @@ pub(crate) fn build_support_map_float(
|
||||
supports
|
||||
}
|
||||
|
||||
/// Generate voter and assignment lists. Makes no attempt to be realistic about winner or assignment fairness.
|
||||
/// Generate voter and assignment lists. Makes no attempt to be realistic about winner or assignment
|
||||
/// fairness.
|
||||
///
|
||||
/// Maintains these invariants:
|
||||
///
|
||||
|
||||
@@ -237,7 +237,8 @@ mod tests {
|
||||
#[test]
|
||||
fn basic_election_manual_works() {
|
||||
//! Manually run the internal steps of phragmms. In each round we select a new winner by
|
||||
//! `max_score`, then apply this change by `apply_elected`, and finally do a `balance` round.
|
||||
//! `max_score`, then apply this change by `apply_elected`, and finally do a `balance`
|
||||
//! round.
|
||||
let candidates = vec![1, 2, 3];
|
||||
let voters = vec![(10, 10, vec![1, 2]), (20, 20, vec![1, 3]), (30, 30, vec![2, 3])];
|
||||
|
||||
|
||||
@@ -35,9 +35,9 @@ type Threshold = ExtendedBalance;
|
||||
|
||||
/// Compute the threshold corresponding to the standard PJR property
|
||||
///
|
||||
/// `t-PJR` checks can check PJR according to an arbitrary threshold. The threshold can be any value,
|
||||
/// but the property gets stronger as the threshold gets smaller. The strongest possible `t-PJR` property
|
||||
/// corresponds to `t == 0`.
|
||||
/// `t-PJR` checks can check PJR according to an arbitrary threshold. The threshold can be any
|
||||
/// value, but the property gets stronger as the threshold gets smaller. The strongest possible
|
||||
/// `t-PJR` property corresponds to `t == 0`.
|
||||
///
|
||||
/// However, standard PJR is less stringent than that. This function returns the threshold whose
|
||||
/// strength corresponds to the standard PJR property.
|
||||
@@ -74,13 +74,13 @@ pub fn pjr_check<AccountId: IdentifierT>(
|
||||
///
|
||||
/// ### Semantics
|
||||
///
|
||||
/// The t-PJR property is defined in the paper ["Validator Election in Nominated Proof-of-Stake"][NPoS],
|
||||
/// section 5, definition 1.
|
||||
/// The t-PJR property is defined in the paper ["Validator Election in Nominated
|
||||
/// Proof-of-Stake"][NPoS], section 5, definition 1.
|
||||
///
|
||||
/// In plain language, the t-PJR condition is: if there is a group of `N` voters
|
||||
/// who have `r` common candidates and can afford to support each of them with backing stake `t`
|
||||
/// (i.e `sum(stake(v) for v in voters) == r * t`), then this committee needs to be represented by at
|
||||
/// least `r` elected candidates.
|
||||
/// (i.e `sum(stake(v) for v in voters) == r * t`), then this committee needs to be represented by
|
||||
/// at least `r` elected candidates.
|
||||
///
|
||||
/// Section 5 of the NPoS paper shows that this property can be tested by: for a feasible solution,
|
||||
/// if `Max {score(c)} < t` where c is every unelected candidate, then this solution is t-PJR. There
|
||||
@@ -120,8 +120,8 @@ pub fn t_pjr_check<AccountId: IdentifierT>(
|
||||
///
|
||||
/// [`pjr_check`] or [`t_pjr_check`] are typically easier to work with.
|
||||
///
|
||||
/// This function returns an `AccountId` in the `Err` case. This is the counter_example: the ID of the
|
||||
/// unelected candidate with the highest prescore, such that `pre_score(counter_example) >= t`.
|
||||
/// This function returns an `AccountId` in the `Err` case. This is the counter_example: the ID of
|
||||
/// the unelected candidate with the highest prescore, such that `pre_score(counter_example) >= t`.
|
||||
pub fn pjr_check_core<AccountId: IdentifierT>(
|
||||
candidates: &[CandidatePtr<AccountId>],
|
||||
voters: &[Voter<AccountId>],
|
||||
@@ -141,8 +141,8 @@ pub fn pjr_check_core<AccountId: IdentifierT>(
|
||||
/// Validate a challenge to an election result.
|
||||
///
|
||||
/// A challenge to an election result is valid if there exists some counter_example for which
|
||||
/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is computationally
|
||||
/// cheaper than re-running the PJR check.
|
||||
/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is
|
||||
/// computationally cheaper than re-running the PJR check.
|
||||
///
|
||||
/// This function uses the standard threshold.
|
||||
///
|
||||
@@ -164,8 +164,8 @@ pub fn validate_pjr_challenge<AccountId: IdentifierT>(
|
||||
/// Validate a challenge to an election result.
|
||||
///
|
||||
/// A challenge to an election result is valid if there exists some counter_example for which
|
||||
/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is computationally
|
||||
/// cheaper than re-running the PJR check.
|
||||
/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is
|
||||
/// computationally cheaper than re-running the PJR check.
|
||||
///
|
||||
/// This function uses a supplied threshold.
|
||||
///
|
||||
@@ -185,8 +185,8 @@ pub fn validate_t_pjr_challenge<AccountId: IdentifierT>(
|
||||
/// Validate a challenge to an election result.
|
||||
///
|
||||
/// A challenge to an election result is valid if there exists some counter_example for which
|
||||
/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is computationally
|
||||
/// cheaper than re-running the PJR check.
|
||||
/// `pre_score(counter_example) >= threshold`. Validating an existing counter_example is
|
||||
/// computationally cheaper than re-running the PJR check.
|
||||
///
|
||||
/// Returns `true` if the challenge is valid: the proposed solution does not satisfy PJR.
|
||||
/// Returns `false` if the challenge is invalid: the proposed solution does in fact satisfy PJR.
|
||||
@@ -222,8 +222,8 @@ fn validate_pjr_challenge_core<AccountId: IdentifierT>(
|
||||
///
|
||||
/// The ultimate goal, in any case, is to convert the election data into [`Candidate`] and [`Voter`]
|
||||
/// types defined by this crate, whilst setting correct value for some of their fields, namely:
|
||||
/// 1. Candidate [`backing_stake`](Candidate::backing_stake) and [`elected`](Candidate::elected) if they are a winner.
|
||||
/// 2. Voter edge [`weight`](Edge::weight) if they are backing a winner.
|
||||
/// 1. Candidate [`backing_stake`](Candidate::backing_stake) and [`elected`](Candidate::elected) if
|
||||
/// they are a winner. 2. Voter edge [`weight`](Edge::weight) if they are backing a winner.
|
||||
/// 3. Voter [`budget`](Voter::budget).
|
||||
///
|
||||
/// None of the `load` or `score` values are used and can be ignored. This is similar to
|
||||
@@ -487,9 +487,9 @@ mod tests {
|
||||
assert_core_failure(&candidates, &voters, 20);
|
||||
}
|
||||
|
||||
// These next tests ensure that the threshold phase change property holds for us, but that's not their real purpose.
|
||||
// They were written to help develop an intuition about what the threshold value actually means
|
||||
// in layman's terms.
|
||||
// These next tests ensure that the threshold phase change property holds for us, but that's not
|
||||
// their real purpose. They were written to help develop an intuition about what the threshold
|
||||
// value actually means in layman's terms.
|
||||
//
|
||||
// The results tend to support the intuition that the threshold is the voting power at and below
|
||||
// which a voter's preferences can simply be ignored.
|
||||
|
||||
@@ -506,8 +506,8 @@ fn reduce_all<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32
|
||||
};
|
||||
|
||||
if next_value.is_zero() {
|
||||
// if the removed edge is from the current assignment, dis_index
|
||||
// should NOT be increased.
|
||||
// if the removed edge is from the current assignment,
|
||||
// index should NOT be increased.
|
||||
if target_ass_index == assignment_index {
|
||||
should_inc_counter = false
|
||||
}
|
||||
@@ -551,8 +551,8 @@ fn reduce_all<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32
|
||||
};
|
||||
|
||||
if next_value.is_zero() {
|
||||
// if the removed edge is from the current assignment, dis_index
|
||||
// should NOT be increased.
|
||||
// if the removed edge is from the current assignment,
|
||||
// index should NOT be increased.
|
||||
if target_ass_index == assignment_index {
|
||||
should_inc_counter = false
|
||||
}
|
||||
|
||||
@@ -112,7 +112,8 @@ impl AbortGuard {
|
||||
}
|
||||
|
||||
/// Create a new guard. While the guard is alive, panics that happen in the current thread will
|
||||
/// **never** abort the process (even if `AbortGuard::force_abort()` guard will be created afterwards).
|
||||
/// **never** abort the process (even if `AbortGuard::force_abort()` guard will be created
|
||||
/// afterwards).
|
||||
pub fn never_abort() -> AbortGuard {
|
||||
AbortGuard { previous_val: set_abort(OnPanic::NeverAbort), _not_send: PhantomData }
|
||||
}
|
||||
|
||||
@@ -22,9 +22,10 @@
|
||||
//!
|
||||
//! 1. The [`#[runtime_interface]`](attr.runtime_interface.html) attribute macro for generating the
|
||||
//! runtime interfaces.
|
||||
//! 2. The [`PassByCodec`](derive.PassByCodec.html) derive macro for implementing `PassBy` with `Codec`.
|
||||
//! 3. The [`PassByEnum`](derive.PassByInner.html) derive macro for implementing `PassBy` with `Enum`.
|
||||
//! 4. The [`PassByInner`](derive.PassByInner.html) derive macro for implementing `PassBy` with `Inner`.
|
||||
//! 2. The [`PassByCodec`](derive.PassByCodec.html) derive macro for implementing `PassBy` with
|
||||
//! `Codec`. 3. The [`PassByEnum`](derive.PassByInner.html) derive macro for implementing `PassBy`
|
||||
//! with `Enum`. 4. The [`PassByInner`](derive.PassByInner.html) derive macro for implementing
|
||||
//! `PassBy` with `Inner`.
|
||||
|
||||
use syn::{
|
||||
parse::{Parse, ParseStream},
|
||||
|
||||
+2
-2
@@ -184,8 +184,8 @@ fn generate_host_functions_struct(
|
||||
})
|
||||
}
|
||||
|
||||
/// Generates the host function struct that implements `wasm_interface::Function` and returns a static
|
||||
/// reference to this struct.
|
||||
/// Generates the host function struct that implements `wasm_interface::Function` and returns a
|
||||
/// static reference to this struct.
|
||||
///
|
||||
/// When calling from wasm into the host, we will call the `execute` function that calls the native
|
||||
/// implementation of the function.
|
||||
|
||||
@@ -26,11 +26,12 @@
|
||||
//! # Using a type in a runtime interface
|
||||
//!
|
||||
//! Any type that should be used in a runtime interface as argument or return value needs to
|
||||
//! implement [`RIType`]. The associated type [`FFIType`](./trait.RIType.html#associatedtype.FFIType)
|
||||
//! is the type that is used in the FFI function to represent the actual type. For example `[T]` is
|
||||
//! represented by an `u64`. The slice pointer and the length will be mapped to an `u64` value.
|
||||
//! For more information see this [table](#ffi-type-and-conversion).
|
||||
//! The FFI function definition is used when calling from the wasm runtime into the node.
|
||||
//! implement [`RIType`]. The associated type
|
||||
//! [`FFIType`](./trait.RIType.html#associatedtype.FFIType) is the type that is used in the FFI
|
||||
//! function to represent the actual type. For example `[T]` is represented by an `u64`. The slice
|
||||
//! pointer and the length will be mapped to an `u64` value. For more information see this
|
||||
//! [table](#ffi-type-and-conversion). The FFI function definition is used when calling from the
|
||||
//! wasm runtime into the node.
|
||||
//!
|
||||
//! Traits are used to convert from a type to the corresponding
|
||||
//! [`RIType::FFIType`](./trait.RIType.html#associatedtype.FFIType).
|
||||
@@ -93,13 +94,14 @@
|
||||
//! | `&str` | `u64` | <code>v.len() 32bit << 32 | v.as_ptr() 32bit</code> |
|
||||
//! | `&[u8]` | `u64` | <code>v.len() 32bit << 32 | v.as_ptr() 32bit</code> |
|
||||
//! | `Vec<u8>` | `u64` | <code>v.len() 32bit << 32 | v.as_ptr() 32bit</code> |
|
||||
//! | `Vec<T> where T: Encode` | `u64` | `let e = v.encode();`<br><br><code>e.len() 32bit << 32 | e.as_ptr() 32bit</code> |
|
||||
//! | `&[T] where T: Encode` | `u64` | `let e = v.encode();`<br><br><code>e.len() 32bit << 32 | e.as_ptr() 32bit</code> |
|
||||
//! | `[u8; N]` | `u32` | `v.as_ptr()` |
|
||||
//! | `*const T` | `u32` | `Identity` |
|
||||
//! | `Option<T>` | `u64` | `let e = v.encode();`<br><br><code>e.len() 32bit << 32 | e.as_ptr() 32bit</code> |
|
||||
//! | [`T where T: PassBy<PassBy=Inner>`](./pass_by#Inner) | Depends on inner | Depends on inner |
|
||||
//! | [`T where T: PassBy<PassBy=Codec>`](./pass_by#Codec)|`u64`|<code>v.len() 32bit << 32 |v.as_ptr() 32bit</code>|
|
||||
//! | `Vec<T> where T: Encode` | `u64` | `let e = v.encode();`<br><br><code>e.len() 32bit << 32
|
||||
//! | e.as_ptr() 32bit</code> | | `&[T] where T: Encode` | `u64` | `let e =
|
||||
//! v.encode();`<br><br><code>e.len() 32bit << 32 | e.as_ptr() 32bit</code> | | `[u8; N]` |
|
||||
//! `u32` | `v.as_ptr()` | | `*const T` | `u32` | `Identity` |
|
||||
//! | `Option<T>` | `u64` | `let e = v.encode();`<br><br><code>e.len() 32bit << 32 | e.as_ptr()
|
||||
//! 32bit</code> | | [`T where T: PassBy<PassBy=Inner>`](./pass_by#Inner) | Depends on inner |
|
||||
//! Depends on inner | | [`T where T: PassBy<PassBy=Codec>`](./pass_by#Codec)|`u64`|<code>v.len()
|
||||
//! 32bit << 32 |v.as_ptr() 32bit</code>|
|
||||
//!
|
||||
//! `Identity` means that the value is converted directly into the corresponding FFI type.
|
||||
|
||||
@@ -119,10 +121,10 @@ pub use sp_std;
|
||||
|
||||
/// Attribute macro for transforming a trait declaration into a runtime interface.
|
||||
///
|
||||
/// A runtime interface is a fixed interface between a Substrate compatible runtime and the native
|
||||
/// node. This interface is callable from a native and a wasm runtime. The macro will generate the
|
||||
/// corresponding code for the native implementation and the code for calling from the wasm
|
||||
/// side to the native implementation.
|
||||
/// A runtime interface is a fixed interface between a Substrate compatible runtime and the
|
||||
/// native node. This interface is callable from a native and a wasm runtime. The macro will
|
||||
/// generate the corresponding code for the native implementation and the code for calling from
|
||||
/// the wasm side to the native implementation.
|
||||
///
|
||||
/// The macro expects the runtime interface declaration as trait declaration:
|
||||
///
|
||||
@@ -273,25 +275,25 @@ pub use sp_std;
|
||||
/// The macro supports any kind of argument type, as long as it implements [`RIType`] and the
|
||||
/// required `FromFFIValue`/`IntoFFIValue`. The macro will convert each
|
||||
/// argument to the corresponding FFI representation and will call into the host using this FFI
|
||||
/// representation. On the host each argument is converted back to the native representation and
|
||||
/// the native implementation is called. Any return value is handled in the same way.
|
||||
/// representation. On the host each argument is converted back to the native representation
|
||||
/// and the native implementation is called. Any return value is handled in the same way.
|
||||
///
|
||||
/// # Wasm only interfaces
|
||||
///
|
||||
/// Some interfaces are only required from within the wasm runtime e.g. the allocator interface.
|
||||
/// To support this, the macro can be called like `#[runtime_interface(wasm_only)]`. This instructs
|
||||
/// the macro to make two significant changes to the generated code:
|
||||
/// Some interfaces are only required from within the wasm runtime e.g. the allocator
|
||||
/// interface. To support this, the macro can be called like `#[runtime_interface(wasm_only)]`.
|
||||
/// This instructs the macro to make two significant changes to the generated code:
|
||||
///
|
||||
/// 1. The generated functions are not callable from the native side.
|
||||
/// 2. The trait as shown above is not implemented for `Externalities` and is instead implemented
|
||||
/// for `FunctionExecutor` (from `sp-wasm-interface`).
|
||||
/// 2. The trait as shown above is not implemented for `Externalities` and is instead
|
||||
/// implemented for `FunctionExecutor` (from `sp-wasm-interface`).
|
||||
///
|
||||
/// # Disable tracing
|
||||
/// By addding `no_tracing` to the list of options you can prevent the wasm-side interface from
|
||||
/// generating the default `sp-tracing`-calls. Note that this is rarely needed but only meant for
|
||||
/// the case when that would create a circular dependency. You usually _do not_ want to add this
|
||||
/// flag, as tracing doesn't cost you anything by default anyways (it is added as a no-op) but is
|
||||
/// super useful for debugging later.
|
||||
/// generating the default `sp-tracing`-calls. Note that this is rarely needed but only meant
|
||||
/// for the case when that would create a circular dependency. You usually _do not_ want to add
|
||||
/// this flag, as tracing doesn't cost you anything by default anyways (it is added as a no-op)
|
||||
/// but is super useful for debugging later.
|
||||
pub use sp_runtime_interface_proc_macro::runtime_interface;
|
||||
|
||||
#[doc(hidden)]
|
||||
|
||||
@@ -40,8 +40,8 @@ use sp_std::vec::Vec;
|
||||
|
||||
/// Derive macro for implementing [`PassBy`] with the [`Codec`] strategy.
|
||||
///
|
||||
/// This requires that the type implements [`Encode`](codec::Encode) and [`Decode`](codec::Decode)
|
||||
/// from `parity-scale-codec`.
|
||||
/// This requires that the type implements [`Encode`](codec::Encode) and
|
||||
/// [`Decode`](codec::Decode) from `parity-scale-codec`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
@@ -58,11 +58,12 @@ pub use sp_runtime_interface_proc_macro::PassByCodec;
|
||||
|
||||
/// Derive macro for implementing [`PassBy`] with the [`Inner`] strategy.
|
||||
///
|
||||
/// Besides implementing [`PassBy`], this derive also implements the helper trait [`PassByInner`].
|
||||
/// Besides implementing [`PassBy`], this derive also implements the helper trait
|
||||
/// [`PassByInner`].
|
||||
///
|
||||
/// The type is required to be a struct with just one field. The field type needs to implement
|
||||
/// the required traits to pass it between the wasm and the native side. (See the runtime interface
|
||||
/// crate for more information about these traits.)
|
||||
/// the required traits to pass it between the wasm and the native side. (See the runtime
|
||||
/// interface crate for more information about these traits.)
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
@@ -86,8 +87,8 @@ pub use sp_runtime_interface_proc_macro::PassByInner;
|
||||
/// Besides implementing [`PassBy`], this derive also implements `TryFrom<u8>` and
|
||||
/// `From<Self> for u8` for the type.
|
||||
///
|
||||
/// The type is required to be an enum with only unit variants and at maximum `256` variants. Also
|
||||
/// it is required that the type implements `Copy`.
|
||||
/// The type is required to be an enum with only unit variants and at maximum `256` variants.
|
||||
/// Also it is required that the type implements `Copy`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
|
||||
@@ -29,8 +29,8 @@ pub fn pack_ptr_and_len(ptr: u32, len: u32) -> u64 {
|
||||
/// Unpacks an `u64` into the pointer and length.
|
||||
///
|
||||
/// Runtime API functions return a 64-bit value which encodes a pointer in the least-significant
|
||||
/// 32-bits and a length in the most-significant 32 bits. This interprets the returned value as a pointer,
|
||||
/// length tuple.
|
||||
/// 32-bits and a length in the most-significant 32 bits. This interprets the returned value as a
|
||||
/// pointer, length tuple.
|
||||
pub fn unpack_ptr_and_len(val: u64) -> (u32, u32) {
|
||||
// The static assertions from above are changed into a runtime check.
|
||||
#[cfg(all(not(feature = "std"), feature = "disable_target_static_assertions"))]
|
||||
|
||||
@@ -128,12 +128,11 @@ pub enum ChangesTrieSignal {
|
||||
///
|
||||
/// The block that emits this signal will contain changes trie (CT) that covers
|
||||
/// blocks range [BEGIN; current block], where BEGIN is (order matters):
|
||||
/// - LAST_TOP_LEVEL_DIGEST_BLOCK+1 if top level digest CT has ever been created
|
||||
/// using current configuration AND the last top level digest CT has been created
|
||||
/// at block LAST_TOP_LEVEL_DIGEST_BLOCK;
|
||||
/// - LAST_CONFIGURATION_CHANGE_BLOCK+1 if there has been CT configuration change
|
||||
/// before and the last configuration change happened at block
|
||||
/// LAST_CONFIGURATION_CHANGE_BLOCK;
|
||||
/// - LAST_TOP_LEVEL_DIGEST_BLOCK+1 if top level digest CT has ever been created using current
|
||||
/// configuration AND the last top level digest CT has been created at block
|
||||
/// LAST_TOP_LEVEL_DIGEST_BLOCK;
|
||||
/// - LAST_CONFIGURATION_CHANGE_BLOCK+1 if there has been CT configuration change before and
|
||||
/// the last configuration change happened at block LAST_CONFIGURATION_CHANGE_BLOCK;
|
||||
/// - 1 otherwise.
|
||||
NewConfiguration(Option<ChangesTrieConfiguration>),
|
||||
}
|
||||
|
||||
@@ -55,8 +55,9 @@ pub enum Era {
|
||||
// phase = 1
|
||||
// n = Q(current - phase, period) + phase
|
||||
impl Era {
|
||||
/// Create a new era based on a period (which should be a power of two between 4 and 65536 inclusive)
|
||||
/// and a block number on which it should start (or, for long periods, be shortly after the start).
|
||||
/// Create a new era based on a period (which should be a power of two between 4 and 65536
|
||||
/// inclusive) and a block number on which it should start (or, for long periods, be shortly
|
||||
/// after the start).
|
||||
///
|
||||
/// If using `Era` in the context of `FRAME` runtime, make sure that `period`
|
||||
/// does not exceed `BlockHashCount` parameter passed to `system` module, since that
|
||||
|
||||
@@ -728,10 +728,10 @@ pub type DispatchOutcome = Result<(), DispatchError>;
|
||||
///
|
||||
/// Examples of reasons preventing inclusion in a block:
|
||||
/// - More block weight is required to process the extrinsic than is left in the block being built.
|
||||
/// This doesn't necessarily mean that the extrinsic is invalid, since it can still be
|
||||
/// included in the next block if it has enough spare weight available.
|
||||
/// - The sender doesn't have enough funds to pay the transaction inclusion fee. Including such
|
||||
/// a transaction in the block doesn't make sense.
|
||||
/// This doesn't necessarily mean that the extrinsic is invalid, since it can still be included in
|
||||
/// the next block if it has enough spare weight available.
|
||||
/// - The sender doesn't have enough funds to pay the transaction inclusion fee. Including such a
|
||||
/// transaction in the block doesn't make sense.
|
||||
/// - The extrinsic supplied a bad signature. This transaction won't become valid ever.
|
||||
pub type ApplyExtrinsicResult =
|
||||
Result<DispatchOutcome, transaction_validity::TransactionValidityError>;
|
||||
|
||||
@@ -288,7 +288,8 @@ impl PendingRequest {
|
||||
|
||||
/// Attempt to wait for all provided requests, but up to given deadline.
|
||||
///
|
||||
/// Requests that are complete will resolve to an `Ok` others will return a `DeadlineReached` error.
|
||||
/// Requests that are complete will resolve to an `Ok` others will return a `DeadlineReached`
|
||||
/// error.
|
||||
pub fn try_wait_all(
|
||||
requests: Vec<PendingRequest>,
|
||||
deadline: impl Into<Option<Timestamp>>,
|
||||
|
||||
@@ -738,8 +738,8 @@ pub trait Extrinsic: Sized + MaybeMallocSizeOf {
|
||||
///
|
||||
/// Extrinsics can be split into:
|
||||
/// 1. Inherents (no signature; created by validators during block production)
|
||||
/// 2. Unsigned Transactions (no signature; represent "system calls" or other special kinds of calls)
|
||||
/// 3. Signed Transactions (with signature; a regular transactions with known origin)
|
||||
/// 2. Unsigned Transactions (no signature; represent "system calls" or other special kinds of
|
||||
/// calls) 3. Signed Transactions (with signature; a regular transactions with known origin)
|
||||
fn new(_call: Self::Call, _signed_data: Option<Self::SignaturePayload>) -> Option<Self> {
|
||||
None
|
||||
}
|
||||
@@ -765,8 +765,8 @@ pub type DigestItemFor<B> = DigestItem<<<B as Block>::Header as Header>::Hash>;
|
||||
|
||||
/// A "checkable" piece of information, used by the standard Substrate Executive in order to
|
||||
/// check the validity of a piece of extrinsic information, usually by verifying the signature.
|
||||
/// Implement for pieces of information that require some additional context `Context` in order to be
|
||||
/// checked.
|
||||
/// Implement for pieces of information that require some additional context `Context` in order to
|
||||
/// be checked.
|
||||
pub trait Checkable<Context>: Sized {
|
||||
/// Returned if `check` succeeds.
|
||||
type Checked;
|
||||
|
||||
@@ -60,7 +60,8 @@ pub enum InvalidTransaction {
|
||||
/// # Possible causes
|
||||
///
|
||||
/// For `FRAME`-based runtimes this would be caused by `current block number
|
||||
/// - Era::birth block number > BlockHashCount`. (e.g. in Polkadot `BlockHashCount` = 2400, so a
|
||||
/// - Era::birth block number > BlockHashCount`. (e.g. in Polkadot `BlockHashCount` = 2400, so
|
||||
/// a
|
||||
/// transaction with birth block number 1337 would be valid up until block number 1337 + 2400,
|
||||
/// after which point the transaction would be considered to have an ancient birth block.)
|
||||
AncientBirthBlock,
|
||||
@@ -72,8 +73,8 @@ pub enum InvalidTransaction {
|
||||
/// Any other custom invalid validity that is not covered by this enum.
|
||||
Custom(u8),
|
||||
/// An extrinsic with a Mandatory dispatch resulted in Error. This is indicative of either a
|
||||
/// malicious validator or a buggy `provide_inherent`. In any case, it can result in dangerously
|
||||
/// overweight blocks and therefore if found, invalidates the block.
|
||||
/// malicious validator or a buggy `provide_inherent`. In any case, it can result in
|
||||
/// dangerously overweight blocks and therefore if found, invalidates the block.
|
||||
BadMandatory,
|
||||
/// A transaction with a mandatory dispatch. This is invalid; only inherent extrinsics are
|
||||
/// allowed to have mandatory dispatches.
|
||||
|
||||
@@ -23,9 +23,9 @@
|
||||
//! and without the performance penalty of full wasm emulation inside wasm.
|
||||
//!
|
||||
//! This is achieved by using bindings to the wasm VM, which are published by the host API.
|
||||
//! This API is thin and consists of only a handful functions. It contains functions for instantiating
|
||||
//! modules and executing them, but doesn't contain functions for inspecting the module
|
||||
//! structure. The user of this library is supposed to read the wasm module.
|
||||
//! This API is thin and consists of only a handful functions. It contains functions for
|
||||
//! instantiating modules and executing them, but doesn't contain functions for inspecting the
|
||||
//! module structure. The user of this library is supposed to read the wasm module.
|
||||
//!
|
||||
//! When this crate is used in the `std` environment all these functions are implemented by directly
|
||||
//! calling the wasm VM.
|
||||
@@ -168,8 +168,8 @@ impl<T> Instance<T> {
|
||||
/// run the `start` function (if it is present in the module) with the given `state`.
|
||||
///
|
||||
/// Returns `Err(Error::Module)` if this module can't be instantiated with the given
|
||||
/// environment. If execution of `start` function generated a trap, then `Err(Error::Execution)` will
|
||||
/// be returned.
|
||||
/// environment. If execution of `start` function generated a trap, then `Err(Error::Execution)`
|
||||
/// will be returned.
|
||||
///
|
||||
/// [`EnvironmentDefinitionBuilder`]: struct.EnvironmentDefinitionBuilder.html
|
||||
pub fn new(
|
||||
@@ -188,8 +188,8 @@ impl<T> Instance<T> {
|
||||
///
|
||||
/// - An export function name isn't a proper utf8 byte sequence,
|
||||
/// - This module doesn't have an exported function with the given name,
|
||||
/// - If types of the arguments passed to the function doesn't match function signature
|
||||
/// then trap occurs (as if the exported function was called via call_indirect),
|
||||
/// - If types of the arguments passed to the function doesn't match function signature then
|
||||
/// trap occurs (as if the exported function was called via call_indirect),
|
||||
/// - Trap occurred at the execution time.
|
||||
pub fn invoke(
|
||||
&mut self,
|
||||
|
||||
@@ -147,8 +147,8 @@ where
|
||||
|mut map: BTreeMap<&[u8], (ExtrinsicIndex<Number>, Vec<u32>)>, (k, extrinsics)| {
|
||||
match map.entry(k) {
|
||||
Entry::Vacant(entry) => {
|
||||
// ignore temporary values (values that have null value at the end of operation
|
||||
// AND are not in storage at the beginning of operation
|
||||
// ignore temporary values (values that have null value at the end of
|
||||
// operation AND are not in storage at the beginning of operation
|
||||
if let Some(child_info) = child_info.as_ref() {
|
||||
if !overlay
|
||||
.child_storage(child_info, k)
|
||||
@@ -177,8 +177,8 @@ where
|
||||
));
|
||||
},
|
||||
Entry::Occupied(mut entry) => {
|
||||
// we do not need to check for temporary values here, because entry is Occupied
|
||||
// AND we are checking it before insertion
|
||||
// we do not need to check for temporary values here, because entry is
|
||||
// Occupied AND we are checking it before insertion
|
||||
let entry_extrinsics = &mut entry.get_mut().1;
|
||||
entry_extrinsics.extend(extrinsics.into_iter());
|
||||
entry_extrinsics.sort();
|
||||
@@ -246,11 +246,12 @@ where
|
||||
));
|
||||
},
|
||||
Entry::Occupied(mut entry) => {
|
||||
// DigestIndexValue must be sorted. Here we are relying on the fact that digest_build_iterator()
|
||||
// returns blocks in ascending order => we only need to check for duplicates
|
||||
// DigestIndexValue must be sorted. Here we are relying on the fact that
|
||||
// digest_build_iterator() returns blocks in ascending order => we only
|
||||
// need to check for duplicates
|
||||
//
|
||||
// is_dup_block could be true when key has been changed in both digest block
|
||||
// AND other blocks that it covers
|
||||
// is_dup_block could be true when key has been changed in both digest
|
||||
// block AND other blocks that it covers
|
||||
let is_dup_block = entry.get().1.last() == Some(&digest_build_block);
|
||||
if !is_dup_block {
|
||||
entry.get_mut().1.push(digest_build_block.clone());
|
||||
|
||||
@@ -39,7 +39,8 @@ pub struct BuildCache<H, N> {
|
||||
/// Map of changes trie root => set of storage keys that are in this trie.
|
||||
/// The `Option<Vec<u8>>` in inner `HashMap` stands for the child storage key.
|
||||
/// If it is `None`, then the `HashSet` contains keys changed in top-level storage.
|
||||
/// If it is `Some`, then the `HashSet` contains keys changed in child storage, identified by the key.
|
||||
/// If it is `Some`, then the `HashSet` contains keys changed in child storage, identified by
|
||||
/// the key.
|
||||
changed_keys: HashMap<H, HashMap<Option<PrefixedStorageKey>, HashSet<StorageKey>>>,
|
||||
}
|
||||
|
||||
|
||||
@@ -50,11 +50,12 @@ pub fn digest_build_iterator<'a, Number: BlockNumber>(
|
||||
/// required for inclusion into changes trie of given block.
|
||||
#[derive(Debug)]
|
||||
pub struct DigestBuildIterator<Number: BlockNumber> {
|
||||
/// Block we're building changes trie for. It could (logically) be a post-end block if we are creating
|
||||
/// skewed digest.
|
||||
/// Block we're building changes trie for. It could (logically) be a post-end block if we are
|
||||
/// creating skewed digest.
|
||||
block: Number,
|
||||
/// Block that is a last block where current configuration is active. We have never yet created anything
|
||||
/// after this block => digest that we're creating can't reference any blocks that are >= end.
|
||||
/// Block that is a last block where current configuration is active. We have never yet created
|
||||
/// anything after this block => digest that we're creating can't reference any blocks that are
|
||||
/// >= end.
|
||||
end: Number,
|
||||
/// Interval of L1 digest blocks.
|
||||
digest_interval: u32,
|
||||
@@ -445,7 +446,8 @@ mod tests {
|
||||
256, 512, 768, 1024, 1280,
|
||||
// level3 MUST point to previous 16-1 level1 digests, BUT there are only 3:
|
||||
1296, 1312, 1328,
|
||||
// level3 MUST be a level1 digest of 16-1 previous blocks, BUT there are only 9:
|
||||
// level3 MUST be a level1 digest of 16-1 previous blocks, BUT there are only
|
||||
// 9:
|
||||
1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337,
|
||||
]
|
||||
.iter()
|
||||
@@ -467,8 +469,9 @@ mod tests {
|
||||
[
|
||||
// level3 MUST point to previous 16-1 level2 digests, BUT there are only 5:
|
||||
256, 512, 768, 1024, 1280,
|
||||
// level3 MUST point to previous 16-1 level1 digests, BUT there are NO ANY L1-digests:
|
||||
// level3 MUST be a level1 digest of 16-1 previous blocks, BUT there are only 3:
|
||||
// level3 MUST point to previous 16-1 level1 digests, BUT there are NO ANY
|
||||
// L1-digests: level3 MUST be a level1 digest of 16-1 previous blocks, BUT
|
||||
// there are only 3:
|
||||
1281, 1282, 1283,
|
||||
]
|
||||
.iter()
|
||||
|
||||
@@ -279,7 +279,8 @@ where
|
||||
if let Some(blocks) = blocks? {
|
||||
if let Ok(blocks) = <DigestIndexValue<Number>>::decode(&mut &blocks[..]) {
|
||||
// filter level0 blocks here because we tend to use digest blocks,
|
||||
// AND digest block changes could also include changes for out-of-range blocks
|
||||
// AND digest block changes could also include changes for out-of-range
|
||||
// blocks
|
||||
let begin = self.begin.clone();
|
||||
let end = self.end.number.clone();
|
||||
let config = self.config.clone();
|
||||
|
||||
@@ -63,9 +63,11 @@ pub type ChildIndexValue = Vec<u8>;
|
||||
pub enum InputPair<Number: BlockNumber> {
|
||||
/// Element of { key => set of extrinsics where key has been changed } element mapping.
|
||||
ExtrinsicIndex(ExtrinsicIndex<Number>, ExtrinsicIndexValue),
|
||||
/// Element of { key => set of blocks/digest blocks where key has been changed } element mapping.
|
||||
/// Element of { key => set of blocks/digest blocks where key has been changed } element
|
||||
/// mapping.
|
||||
DigestIndex(DigestIndex<Number>, DigestIndexValue<Number>),
|
||||
/// Element of { childtrie key => Childchange trie } where key has been changed } element mapping.
|
||||
/// Element of { childtrie key => Childchange trie } where key has been changed } element
|
||||
/// mapping.
|
||||
ChildIndex(ChildIndex<Number>, ChildIndexValue),
|
||||
}
|
||||
|
||||
|
||||
@@ -153,8 +153,8 @@ pub struct State<'a, H, Number> {
|
||||
/// Configuration that is active at given block.
|
||||
pub config: Configuration,
|
||||
/// Configuration activation block number. Zero if it is the first configuration on the chain,
|
||||
/// or number of the block that have emit NewConfiguration signal (thus activating configuration
|
||||
/// starting from the **next** block).
|
||||
/// or number of the block that have emit NewConfiguration signal (thus activating
|
||||
/// configuration starting from the **next** block).
|
||||
pub zero: Number,
|
||||
/// Underlying changes tries storage reference.
|
||||
pub storage: &'a dyn Storage<H, Number>,
|
||||
@@ -276,8 +276,8 @@ where
|
||||
let parent = state.storage.build_anchor(parent_hash).map_err(|_| ())?;
|
||||
let block = parent.number.clone() + One::one();
|
||||
|
||||
// prepare configuration range - we already know zero block. Current block may be the end block if configuration
|
||||
// has been changed in this block
|
||||
// prepare configuration range - we already know zero block. Current block may be the end block
|
||||
// if configuration has been changed in this block
|
||||
let is_config_changed =
|
||||
match changes.storage(sp_core::storage::well_known_keys::CHANGES_TRIE_CONFIG) {
|
||||
Some(Some(new_config)) => new_config != &state.config.encode()[..],
|
||||
@@ -290,7 +290,8 @@ where
|
||||
end: if is_config_changed { Some(block.clone()) } else { None },
|
||||
};
|
||||
|
||||
// storage errors are considered fatal (similar to situations when runtime fetches values from storage)
|
||||
// storage errors are considered fatal (similar to situations when runtime fetches values from
|
||||
// storage)
|
||||
let (input_pairs, child_input_pairs, digest_input_blocks) = maybe_panic(
|
||||
prepare_input::<B, H, Number>(
|
||||
backend,
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The best way to understand how this iterator works is to imagine some 2D terrain that have some mountains
|
||||
//! (digest changes tries) and valleys (changes tries for regular blocks). There are gems (blocks) beneath the
|
||||
//! terrain. Given the request to find all gems in the range [X1; X2] this iterator will return **minimal set**
|
||||
//! of points at the terrain (mountains and valleys) inside this range that have to be drilled down to
|
||||
//! search for gems.
|
||||
//! The best way to understand how this iterator works is to imagine some 2D terrain that have some
|
||||
//! mountains (digest changes tries) and valleys (changes tries for regular blocks). There are gems
|
||||
//! (blocks) beneath the terrain. Given the request to find all gems in the range [X1; X2] this
|
||||
//! iterator will return **minimal set** of points at the terrain (mountains and valleys) inside
|
||||
//! this range that have to be drilled down to search for gems.
|
||||
|
||||
use crate::changes_trie::{BlockNumber, ConfigurationRange};
|
||||
use num_traits::One;
|
||||
@@ -50,9 +50,9 @@ pub fn surface_iterator<'a, Number: BlockNumber>(
|
||||
/// Surface iterator - only traverses top-level digests from given range and tries to find
|
||||
/// all valid digest changes.
|
||||
///
|
||||
/// Iterator item is the tuple of (last block of the current point + digest level of the current point).
|
||||
/// Digest level is Some(0) when it is regular block, is Some(non-zero) when it is digest block and None
|
||||
/// if it is skewed digest block.
|
||||
/// Iterator item is the tuple of (last block of the current point + digest level of the current
|
||||
/// point). Digest level is Some(0) when it is regular block, is Some(non-zero) when it is digest
|
||||
/// block and None if it is skewed digest block.
|
||||
pub struct SurfaceIterator<'a, Number: BlockNumber> {
|
||||
config: ConfigurationRange<'a, Number>,
|
||||
begin: Number,
|
||||
|
||||
@@ -573,9 +573,9 @@ where
|
||||
|
||||
if let Some((root, is_empty, _)) = root {
|
||||
let root = root.encode();
|
||||
// We store update in the overlay in order to be able to use 'self.storage_transaction'
|
||||
// cache. This is brittle as it rely on Ext only querying the trie backend for
|
||||
// storage root.
|
||||
// We store update in the overlay in order to be able to use
|
||||
// 'self.storage_transaction' cache. This is brittle as it rely on Ext only querying
|
||||
// the trie backend for storage root.
|
||||
// A better design would be to manage 'child_storage_transaction' in a
|
||||
// similar way as 'storage_transaction' but for each child trie.
|
||||
if is_empty {
|
||||
|
||||
@@ -206,7 +206,8 @@ mod execution {
|
||||
NativeWhenPossible,
|
||||
/// Use the given wasm module.
|
||||
AlwaysWasm,
|
||||
/// Run with both the wasm and the native variant (if compatible). Report any discrepancy as an error.
|
||||
/// Run with both the wasm and the native variant (if compatible). Report any discrepancy
|
||||
/// as an error.
|
||||
Both,
|
||||
/// First native, then if that fails or is not possible, wasm.
|
||||
NativeElseWasm,
|
||||
@@ -230,10 +231,12 @@ mod execution {
|
||||
/// otherwise fall back to the wasm.
|
||||
NativeWhenPossible,
|
||||
/// Use the given wasm module. The backend on which code is executed code could be
|
||||
/// trusted to provide all storage or not (i.e. the light client cannot be trusted to provide
|
||||
/// for all storage queries since the storage entries it has come from an external node).
|
||||
/// trusted to provide all storage or not (i.e. the light client cannot be trusted to
|
||||
/// provide for all storage queries since the storage entries it has come from an external
|
||||
/// node).
|
||||
AlwaysWasm(BackendTrustLevel),
|
||||
/// Run with both the wasm and the native variant (if compatible). Call `F` in the case of any discrepancy.
|
||||
/// Run with both the wasm and the native variant (if compatible). Call `F` in the case of
|
||||
/// any discrepancy.
|
||||
Both(F),
|
||||
/// First native, then if that fails or is not possible, wasm.
|
||||
NativeElseWasm,
|
||||
@@ -278,12 +281,14 @@ mod execution {
|
||||
ExecutionManager::NativeElseWasm
|
||||
}
|
||||
|
||||
/// Evaluate to ExecutionManager::AlwaysWasm with trusted backend, without having to figure out the type.
|
||||
/// Evaluate to ExecutionManager::AlwaysWasm with trusted backend, without having to figure out
|
||||
/// the type.
|
||||
fn always_wasm<E, R: Decode>() -> ExecutionManager<DefaultHandler<R, E>> {
|
||||
ExecutionManager::AlwaysWasm(BackendTrustLevel::Trusted)
|
||||
}
|
||||
|
||||
/// Evaluate ExecutionManager::AlwaysWasm with untrusted backend, without having to figure out the type.
|
||||
/// Evaluate ExecutionManager::AlwaysWasm with untrusted backend, without having to figure out
|
||||
/// the type.
|
||||
fn always_untrusted_wasm<E, R: Decode>() -> ExecutionManager<DefaultHandler<R, E>> {
|
||||
ExecutionManager::AlwaysWasm(BackendTrustLevel::Untrusted)
|
||||
}
|
||||
@@ -390,8 +395,8 @@ mod execution {
|
||||
///
|
||||
/// Returns the SCALE encoded result of the executed function.
|
||||
pub fn execute(&mut self, strategy: ExecutionStrategy) -> Result<Vec<u8>, Box<dyn Error>> {
|
||||
// We are not giving a native call and thus we are sure that the result can never be a native
|
||||
// value.
|
||||
// We are not giving a native call and thus we are sure that the result can never be a
|
||||
// native value.
|
||||
self.execute_using_consensus_failure_handler::<_, NeverNativeValue, fn() -> _>(
|
||||
strategy.get_manager(),
|
||||
None,
|
||||
|
||||
@@ -21,7 +21,8 @@ use super::changeset::OverlayedMap;
|
||||
use sp_core::offchain::OffchainOverlayedChange;
|
||||
use sp_std::prelude::Vec;
|
||||
|
||||
/// In-memory storage for offchain workers recoding changes for the actual offchain storage implementation.
|
||||
/// In-memory storage for offchain workers recoding changes for the actual offchain storage
|
||||
/// implementation.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct OffchainOverlayedChanges(OverlayedMap<(Vec<u8>, Vec<u8>), OffchainOverlayedChange>);
|
||||
|
||||
|
||||
@@ -198,8 +198,8 @@ impl InherentDataProvider {
|
||||
/// By default the maximum drift is 60 seconds.
|
||||
///
|
||||
/// The maximum drift is used when checking the inherents of a runtime. If the current timestamp
|
||||
/// plus the maximum drift is smaller than the timestamp in the block, the block will be rejected
|
||||
/// as being too far in the future.
|
||||
/// plus the maximum drift is smaller than the timestamp in the block, the block will be
|
||||
/// rejected as being too far in the future.
|
||||
pub fn with_max_drift(mut self, max_drift: std::time::Duration) -> Self {
|
||||
self.max_drift = max_drift.into();
|
||||
self
|
||||
|
||||
@@ -465,9 +465,9 @@ mod std_features {
|
||||
|
||||
// Implementation Note:
|
||||
// the original `tracing` crate generates these static metadata entries at every `span!` and
|
||||
// `event!` location to allow for highly optimised filtering. For us to allow level-based emitting
|
||||
// of wasm events we need these static metadata entries to inject into that system. We then provide
|
||||
// generic `From`-implementations picking the right metadata to refer to.
|
||||
// `event!` location to allow for highly optimised filtering. For us to allow level-based
|
||||
// emitting of wasm events we need these static metadata entries to inject into that system. We
|
||||
// then provide generic `From`-implementations picking the right metadata to refer to.
|
||||
|
||||
static SPAN_ERROR_METADATA: tracing_core::Metadata<'static> = tracing::Metadata::new(
|
||||
WASM_TRACE_IDENTIFIER,
|
||||
|
||||
@@ -72,8 +72,8 @@ impl StorageProof {
|
||||
}
|
||||
|
||||
/// Merges multiple storage proofs covering potentially different sets of keys into one proof
|
||||
/// covering all keys. The merged proof output may be smaller than the aggregate size of the input
|
||||
/// proofs due to deduplication of trie nodes.
|
||||
/// covering all keys. The merged proof output may be smaller than the aggregate size of the
|
||||
/// input proofs due to deduplication of trie nodes.
|
||||
pub fn merge<I>(proofs: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = Self>,
|
||||
|
||||
@@ -27,7 +27,8 @@
|
||||
//! and `UnboundedReceiver<T>` to register every `send`/`received`/`dropped` action happened on
|
||||
//! the channel.
|
||||
//!
|
||||
//! Also this feature creates and registers a prometheus vector with name `unbounded_channel_len` and labels:
|
||||
//! Also this feature creates and registers a prometheus vector with name `unbounded_channel_len`
|
||||
//! and labels:
|
||||
//!
|
||||
//! | Label | Description |
|
||||
//! | ------------ | --------------------------------------------- |
|
||||
|
||||
@@ -86,8 +86,8 @@ impl<T> StatusSinks<T> {
|
||||
let inner = &mut *inner;
|
||||
|
||||
loop {
|
||||
// Future that produces the next ready entry in `entries`, or doesn't produce anything if
|
||||
// the list is empty.
|
||||
// Future that produces the next ready entry in `entries`, or doesn't produce anything
|
||||
// if the list is empty.
|
||||
let next_ready_entry = {
|
||||
let entries = &mut inner.entries;
|
||||
async move {
|
||||
|
||||
@@ -25,9 +25,10 @@ use syn::{
|
||||
Expr, ExprLit, FieldValue, ItemConst, Lit,
|
||||
};
|
||||
|
||||
/// This macro accepts a `const` item that has a struct initializer expression of `RuntimeVersion`-like type.
|
||||
/// The macro will pass through this declaration and append an item declaration that will
|
||||
/// lead to emitting a wasm custom section with the contents of `RuntimeVersion`.
|
||||
/// This macro accepts a `const` item that has a struct initializer expression of
|
||||
/// `RuntimeVersion`-like type. The macro will pass through this declaration and append an item
|
||||
/// declaration that will lead to emitting a wasm custom section with the contents of
|
||||
/// `RuntimeVersion`.
|
||||
pub fn decl_runtime_version_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
let item = parse_macro_input!(input as ItemConst);
|
||||
decl_runtime_version_impl_inner(item)
|
||||
@@ -125,8 +126,8 @@ impl ParseRuntimeVersion {
|
||||
// Intentionally ignored
|
||||
//
|
||||
// The definition will pass through for the declaration, however, it won't get into
|
||||
// the "runtime_version" custom section. `impl_runtime_apis` is responsible for generating
|
||||
// a custom section with the supported runtime apis descriptor.
|
||||
// the "runtime_version" custom section. `impl_runtime_apis` is responsible for
|
||||
// generating a custom section with the supported runtime apis descriptor.
|
||||
} else {
|
||||
return Err(Error::new(field_name.span(), "unknown field"))
|
||||
}
|
||||
|
||||
@@ -38,15 +38,15 @@ use sp_runtime::{generic::BlockId, traits::Block as BlockT};
|
||||
#[cfg(feature = "std")]
|
||||
pub mod embed;
|
||||
|
||||
/// An attribute that accepts a version declaration of a runtime and generates a custom wasm section
|
||||
/// with the equivalent contents.
|
||||
/// An attribute that accepts a version declaration of a runtime and generates a custom wasm
|
||||
/// section with the equivalent contents.
|
||||
///
|
||||
/// The custom section allows to read the version of the runtime without having to execute any code.
|
||||
/// Instead, the generated custom section can be relatively easily parsed from the wasm binary. The
|
||||
/// identifier of the custom section is "runtime_version".
|
||||
/// The custom section allows to read the version of the runtime without having to execute any
|
||||
/// code. Instead, the generated custom section can be relatively easily parsed from the wasm
|
||||
/// binary. The identifier of the custom section is "runtime_version".
|
||||
///
|
||||
/// A shortcoming of this macro is that it is unable to embed information regarding supported APIs.
|
||||
/// This is supported by the `construct_runtime!` macro.
|
||||
/// A shortcoming of this macro is that it is unable to embed information regarding supported
|
||||
/// APIs. This is supported by the `construct_runtime!` macro.
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
@@ -69,32 +69,33 @@ pub mod embed;
|
||||
/// # const RUNTIME_API_VERSIONS: sp_version::ApisVec = sp_version::create_apis_vec!([]);
|
||||
/// ```
|
||||
///
|
||||
/// It will pass it through and add code required for emitting a custom section. The information that
|
||||
/// will go into the custom section is parsed from the item declaration. Due to that, the macro is
|
||||
/// somewhat rigid in terms of the code it accepts. There are the following considerations:
|
||||
/// It will pass it through and add code required for emitting a custom section. The
|
||||
/// information that will go into the custom section is parsed from the item declaration. Due
|
||||
/// to that, the macro is somewhat rigid in terms of the code it accepts. There are the
|
||||
/// following considerations:
|
||||
///
|
||||
/// - The `spec_name` and `impl_name` must be set by a macro-like expression. The name of the macro
|
||||
/// doesn't matter though.
|
||||
/// - The `spec_name` and `impl_name` must be set by a macro-like expression. The name of the
|
||||
/// macro doesn't matter though.
|
||||
///
|
||||
/// - `authoring_version`, `spec_version`, `impl_version` and `transaction_version` must be set
|
||||
/// by a literal. Literal must be an integer. No other expressions are allowed there. In particular,
|
||||
/// you can't supply a constant variable.
|
||||
/// by a literal. Literal must be an integer. No other expressions are allowed there. In
|
||||
/// particular, you can't supply a constant variable.
|
||||
///
|
||||
/// - `apis` doesn't have any specific constraints. This is because this information doesn't get into
|
||||
/// the custom section and is not parsed.
|
||||
/// - `apis` doesn't have any specific constraints. This is because this information doesn't
|
||||
/// get into the custom section and is not parsed.
|
||||
///
|
||||
/// # Compilation Target & "std" feature
|
||||
///
|
||||
/// This macro assumes it will be used within a runtime. By convention, a runtime crate defines a
|
||||
/// feature named "std". This feature is enabled when the runtime is compiled to native code and
|
||||
/// disabled when it is compiled to the wasm code.
|
||||
/// This macro assumes it will be used within a runtime. By convention, a runtime crate defines
|
||||
/// a feature named "std". This feature is enabled when the runtime is compiled to native code
|
||||
/// and disabled when it is compiled to the wasm code.
|
||||
///
|
||||
/// The custom section can only be emitted while compiling to wasm. In order to detect the compilation
|
||||
/// target we use the "std" feature. This macro will emit the custom section only if the "std" feature
|
||||
/// is **not** enabled.
|
||||
/// The custom section can only be emitted while compiling to wasm. In order to detect the
|
||||
/// compilation target we use the "std" feature. This macro will emit the custom section only
|
||||
/// if the "std" feature is **not** enabled.
|
||||
///
|
||||
/// Including this macro in the context where there is no "std" feature and the code is not compiled
|
||||
/// to wasm can lead to cryptic linking errors.
|
||||
/// Including this macro in the context where there is no "std" feature and the code is not
|
||||
/// compiled to wasm can lead to cryptic linking errors.
|
||||
pub use sp_version_proc_macro::runtime_version;
|
||||
|
||||
/// The identity of a particular API interface that the runtime might provide.
|
||||
@@ -119,8 +120,9 @@ macro_rules! create_apis_vec {
|
||||
/// Runtime version.
|
||||
/// This should not be thought of as classic Semver (major/minor/tiny).
|
||||
/// This triplet have different semantics and mis-interpretation could cause problems.
|
||||
/// In particular: bug fixes should result in an increment of `spec_version` and possibly `authoring_version`,
|
||||
/// absolutely not `impl_version` since they change the semantics of the runtime.
|
||||
/// In particular: bug fixes should result in an increment of `spec_version` and possibly
|
||||
/// `authoring_version`, absolutely not `impl_version` since they change the semantics of the
|
||||
/// runtime.
|
||||
#[derive(Clone, PartialEq, Eq, Encode, Decode, Default, sp_runtime::RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
|
||||
@@ -168,9 +170,9 @@ pub struct RuntimeVersion {
|
||||
/// number changes, then `spec_version` must change, also.
|
||||
///
|
||||
/// This number must change when an existing dispatchable (module ID, dispatch ID) is changed,
|
||||
/// either through an alteration in its user-level semantics, a parameter added/removed/changed,
|
||||
/// a dispatchable being removed, a module being removed, or a dispatchable/module changing its
|
||||
/// index.
|
||||
/// either through an alteration in its user-level semantics, a parameter
|
||||
/// added/removed/changed, a dispatchable being removed, a module being removed, or a
|
||||
/// dispatchable/module changing its index.
|
||||
///
|
||||
/// It need *not* change when a new module is added or when a dispatchable is added.
|
||||
pub transaction_version: u32,
|
||||
|
||||
@@ -143,7 +143,8 @@ impl<T: PointerType> Pointer<T> {
|
||||
|
||||
/// Calculate the offset from this pointer.
|
||||
///
|
||||
/// `offset` is in units of `T`. So, `3` means `3 * mem::size_of::<T>()` as offset to the pointer.
|
||||
/// `offset` is in units of `T`. So, `3` means `3 * mem::size_of::<T>()` as offset to the
|
||||
/// pointer.
|
||||
///
|
||||
/// Returns an `Option` to respect that the pointer could probably overflow.
|
||||
pub fn offset(self, offset: u32) -> Option<Self> {
|
||||
|
||||
Reference in New Issue
Block a user