Files
pezkuwi-subxt/substrate/primitives/inherents/src/lib.rs
T
Gavin Wood fd5f9292f5 FRAME: Create TransactionExtension as a replacement for SignedExtension (#2280)
Closes #2160

First part of [Extrinsic
Horizon](https://github.com/paritytech/polkadot-sdk/issues/2415)

Introduces a new trait `TransactionExtension` to replace
`SignedExtension`. Introduce the idea of transactions which obey the
runtime's extensions and have according Extension data (né Extra data)
yet do not have hard-coded signatures.

Deprecate the terminology of "Unsigned" when used for
transactions/extrinsics owing to there now being "proper" unsigned
transactions which obey the extension framework and "old-style" unsigned
which do not. Instead we have __*General*__ for the former and
__*Bare*__ for the latter. (Ultimately, the latter will be phased out as
a type of transaction, and Bare will only be used for Inherents.)

Types of extrinsic are now therefore:
- Bare (no hardcoded signature, no Extra data; used to be known as
"Unsigned")
- Bare transactions (deprecated): Gossiped, validated with
`ValidateUnsigned` (deprecated) and the `_bare_compat` bits of
`TransactionExtension` (deprecated).
  - Inherents: Not gossiped, validated with `ProvideInherent`.
- Extended (Extra data): Gossiped, validated via `TransactionExtension`.
  - Signed transactions (with a hardcoded signature).
  - General transactions (without a hardcoded signature).

`TransactionExtension` differs from `SignedExtension` because:
- A signature on the underlying transaction may validly not be present.
- It may alter the origin during validation.
- `pre_dispatch` is renamed to `prepare` and need not contain the checks
present in `validate`.
- `validate` and `prepare` is passed an `Origin` rather than a
`AccountId`.
- `validate` may pass arbitrary information into `prepare` via a new
user-specifiable type `Val`.
- `AdditionalSigned`/`additional_signed` is renamed to
`Implicit`/`implicit`. It is encoded *for the entire transaction* and
passed in to each extension as a new argument to `validate`. This
facilitates the ability of extensions to acts as underlying crypto.

There is a new `DispatchTransaction` trait which contains only default
function impls and is impl'ed for any `TransactionExtension` impler. It
provides several utility functions which reduce some of the tedium from
using `TransactionExtension` (indeed, none of its regular functions
should now need to be called directly).

Three transaction version discriminator ("versions") are now
permissible:
- 0b000000100: Bare (used to be called "Unsigned"): contains Signature
or Extra (extension data). After bare transactions are no longer
supported, this will strictly identify an Inherents only.
- 0b100000100: Old-school "Signed" Transaction: contains Signature and
Extra (extension data).
- 0b010000100: New-school "General" Transaction: contains Extra
(extension data), but no Signature.

For the New-school General Transaction, it becomes trivial for authors
to publish extensions to the mechanism for authorizing an Origin, e.g.
through new kinds of key-signing schemes, ZK proofs, pallet state,
mutations over pre-authenticated origins or any combination of the
above.

## Code Migration

### NOW: Getting it to build

Wrap your `SignedExtension`s in `AsTransactionExtension`. This should be
accompanied by renaming your aggregate type in line with the new
terminology. E.g. Before:

```rust
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
	/* snip */
	MySpecialSignedExtension,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
```

After:

```rust
/// The extension to the basic transaction logic.
pub type TxExtension = (
	/* snip */
	AsTransactionExtension<MySpecialSignedExtension>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
```

You'll also need to alter any transaction building logic to add a
`.into()` to make the conversion happen. E.g. Before:

```rust
fn construct_extrinsic(
		/* snip */
) -> UncheckedExtrinsic {
	let extra: SignedExtra = (
		/* snip */
		MySpecialSignedExtension::new(/* snip */),
	);
	let payload = SignedPayload::new(call.clone(), extra.clone()).unwrap();
	let signature = payload.using_encoded(|e| sender.sign(e));
	UncheckedExtrinsic::new_signed(
		/* snip */
		Signature::Sr25519(signature),
		extra,
	)
}
```

After:

```rust
fn construct_extrinsic(
		/* snip */
) -> UncheckedExtrinsic {
	let tx_ext: TxExtension = (
		/* snip */
		MySpecialSignedExtension::new(/* snip */).into(),
	);
	let payload = SignedPayload::new(call.clone(), tx_ext.clone()).unwrap();
	let signature = payload.using_encoded(|e| sender.sign(e));
	UncheckedExtrinsic::new_signed(
		/* snip */
		Signature::Sr25519(signature),
		tx_ext,
	)
}
```

### SOON: Migrating to `TransactionExtension`

Most `SignedExtension`s can be trivially converted to become a
`TransactionExtension`. There are a few things to know.

- Instead of a single trait like `SignedExtension`, you should now
implement two traits individually: `TransactionExtensionBase` and
`TransactionExtension`.
- Weights are now a thing and must be provided via the new function `fn
weight`.

#### `TransactionExtensionBase`

This trait takes care of anything which is not dependent on types
specific to your runtime, most notably `Call`.

- `AdditionalSigned`/`additional_signed` is renamed to
`Implicit`/`implicit`.
- Weight must be returned by implementing the `weight` function. If your
extension is associated with a pallet, you'll probably want to do this
via the pallet's existing benchmarking infrastructure.

#### `TransactionExtension`

Generally:
- `pre_dispatch` is now `prepare` and you *should not reexecute the
`validate` functionality in there*!
- You don't get an account ID any more; you get an origin instead. If
you need to presume an account ID, then you can use the trait function
`AsSystemOriginSigner::as_system_origin_signer`.
- You get an additional ticket, similar to `Pre`, called `Val`. This
defines data which is passed from `validate` into `prepare`. This is
important since you should not be duplicating logic from `validate` to
`prepare`, you need a way of passing your working from the former into
the latter. This is it.
- This trait takes two type parameters: `Call` and `Context`. `Call` is
the runtime call type which used to be an associated type; you can just
move it to become a type parameter for your trait impl. `Context` is not
currently used and you can safely implement over it as an unbounded
type.
- There's no `AccountId` associated type any more. Just remove it.

Regarding `validate`:
- You get three new parameters in `validate`; all can be ignored when
migrating from `SignedExtension`.
- `validate` returns a tuple on success; the second item in the tuple is
the new ticket type `Self::Val` which gets passed in to `prepare`. If
you use any information extracted during `validate` (off-chain and
on-chain, non-mutating) in `prepare` (on-chain, mutating) then you can
pass it through with this. For the tuple's last item, just return the
`origin` argument.

Regarding `prepare`:
- This is renamed from `pre_dispatch`, but there is one change:
- FUNCTIONALITY TO VALIDATE THE TRANSACTION NEED NOT BE DUPLICATED FROM
`validate`!!
- (This is different to `SignedExtension` which was required to run the
same checks in `pre_dispatch` as in `validate`.)

Regarding `post_dispatch`:
- Since there are no unsigned transactions handled by
`TransactionExtension`, `Pre` is always defined, so the first parameter
is `Self::Pre` rather than `Option<Self::Pre>`.

If you make use of `SignedExtension::validate_unsigned` or
`SignedExtension::pre_dispatch_unsigned`, then:
- Just use the regular versions of these functions instead.
- Have your logic execute in the case that the `origin` is `None`.
- Ensure your transaction creation logic creates a General Transaction
rather than a Bare Transaction; this means having to include all
`TransactionExtension`s' data.
- `ValidateUnsigned` can still be used (for now) if you need to be able
to construct transactions which contain none of the extension data,
however these will be phased out in stage 2 of the Transactions Horizon,
so you should consider moving to an extension-centric design.

## TODO

- [x] Introduce `CheckSignature` impl of `TransactionExtension` to
ensure it's possible to have crypto be done wholly in a
`TransactionExtension`.
- [x] Deprecate `SignedExtension` and move all uses in codebase to
`TransactionExtension`.
  - [x] `ChargeTransactionPayment`
  - [x] `DummyExtension`
  - [x] `ChargeAssetTxPayment` (asset-tx-payment)
  - [x] `ChargeAssetTxPayment` (asset-conversion-tx-payment)
  - [x] `CheckWeight`
  - [x] `CheckTxVersion`
  - [x] `CheckSpecVersion`
  - [x] `CheckNonce`
  - [x] `CheckNonZeroSender`
  - [x] `CheckMortality`
  - [x] `CheckGenesis`
  - [x] `CheckOnlySudoAccount`
  - [x] `WatchDummy`
  - [x] `PrevalidateAttests`
  - [x] `GenericSignedExtension`
  - [x] `SignedExtension` (chain-polkadot-bulletin)
  - [x] `RefundSignedExtensionAdapter`
- [x] Implement `fn weight` across the board.
- [ ] Go through all pre-existing extensions which assume an account
signer and explicitly handle the possibility of another kind of origin.
- [x] `CheckNonce` should probably succeed in the case of a non-account
origin.
- [x] `CheckNonZeroSender` should succeed in the case of a non-account
origin.
- [x] `ChargeTransactionPayment` and family should fail in the case of a
non-account origin.
  - [ ] 
- [x] Fix any broken tests.

---------

Signed-off-by: georgepisaltu <george.pisaltu@parity.io>
Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Signed-off-by: Alexandru Gheorghe <alexandru.gheorghe@parity.io>
Signed-off-by: Andrei Sandu <andrei-mihail@parity.io>
Co-authored-by: Nikhil Gupta <17176722+gupnik@users.noreply.github.com>
Co-authored-by: georgepisaltu <52418509+georgepisaltu@users.noreply.github.com>
Co-authored-by: Chevdor <chevdor@users.noreply.github.com>
Co-authored-by: Bastian Köcher <git@kchr.de>
Co-authored-by: Maciej <maciej.zyszkiewicz@parity.io>
Co-authored-by: Javier Viola <javier@parity.io>
Co-authored-by: Marcin S. <marcin@realemail.net>
Co-authored-by: Tsvetomir Dimitrov <tsvetomir@parity.io>
Co-authored-by: Javier Bullrich <javier@bullrich.dev>
Co-authored-by: Koute <koute@users.noreply.github.com>
Co-authored-by: Adrian Catangiu <adrian@parity.io>
Co-authored-by: Vladimir Istyufeev <vladimir@parity.io>
Co-authored-by: Ross Bulat <ross@parity.io>
Co-authored-by: Gonçalo Pestana <g6pestana@gmail.com>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
Co-authored-by: Svyatoslav Nikolsky <svyatonik@gmail.com>
Co-authored-by: André Silva <123550+andresilva@users.noreply.github.com>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: s0me0ne-unkn0wn <48632512+s0me0ne-unkn0wn@users.noreply.github.com>
Co-authored-by: ordian <write@reusable.software>
Co-authored-by: Sebastian Kunert <skunert49@gmail.com>
Co-authored-by: Aaro Altonen <48052676+altonen@users.noreply.github.com>
Co-authored-by: Dmitry Markin <dmitry@markin.tech>
Co-authored-by: Alexandru Vasile <60601340+lexnv@users.noreply.github.com>
Co-authored-by: Alexander Samusev <41779041+alvicsam@users.noreply.github.com>
Co-authored-by: Julian Eager <eagr@tutanota.com>
Co-authored-by: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com>
Co-authored-by: Davide Galassi <davxy@datawok.net>
Co-authored-by: Dónal Murray <donal.murray@parity.io>
Co-authored-by: yjh <yjh465402634@gmail.com>
Co-authored-by: Tom Mi <tommi@niemi.lol>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Will | Paradox | ParaNodes.io <79228812+paradox-tt@users.noreply.github.com>
Co-authored-by: Bastian Köcher <info@kchr.de>
Co-authored-by: Joshy Orndorff <JoshOrndorff@users.noreply.github.com>
Co-authored-by: Joshy Orndorff <git-user-email.h0ly5@simplelogin.com>
Co-authored-by: PG Herveou <pgherveou@gmail.com>
Co-authored-by: Alexander Theißen <alex.theissen@me.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: Juan Girini <juangirini@gmail.com>
Co-authored-by: bader y <ibnbassem@gmail.com>
Co-authored-by: James Wilson <james@jsdw.me>
Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com>
Co-authored-by: asynchronous rob <rphmeier@gmail.com>
Co-authored-by: Parth <desaiparth08@gmail.com>
Co-authored-by: Andrew Jones <ascjones@gmail.com>
Co-authored-by: Jonathan Udd <jonathan@dwellir.com>
Co-authored-by: Serban Iorga <serban@parity.io>
Co-authored-by: Egor_P <egor@parity.io>
Co-authored-by: Branislav Kontur <bkontur@gmail.com>
Co-authored-by: Evgeny Snitko <evgeny@parity.io>
Co-authored-by: Just van Stam <vstam1@users.noreply.github.com>
Co-authored-by: Francisco Aguirre <franciscoaguirreperez@gmail.com>
Co-authored-by: gupnik <nikhilgupta.iitk@gmail.com>
Co-authored-by: dzmitry-lahoda <dzmitry@lahoda.pro>
Co-authored-by: zhiqiangxu <652732310@qq.com>
Co-authored-by: Nazar Mokrynskyi <nazar@mokrynskyi.com>
Co-authored-by: Anwesh <anweshknayak@gmail.com>
Co-authored-by: cheme <emericchevalier.pro@gmail.com>
Co-authored-by: Sam Johnson <sam@durosoft.com>
Co-authored-by: kianenigma <kian@parity.io>
Co-authored-by: Jegor Sidorenko <5252494+jsidorenko@users.noreply.github.com>
Co-authored-by: Muharem <ismailov.m.h@gmail.com>
Co-authored-by: joepetrowski <joe@parity.io>
Co-authored-by: Alexandru Gheorghe <49718502+alexggh@users.noreply.github.com>
Co-authored-by: Gabriel Facco de Arruda <arrudagates@gmail.com>
Co-authored-by: Squirrel <gilescope@gmail.com>
Co-authored-by: Andrei Sandu <54316454+sandreim@users.noreply.github.com>
Co-authored-by: georgepisaltu <george.pisaltu@parity.io>
Co-authored-by: command-bot <>
2024-03-04 19:12:43 +00:00

507 lines
16 KiB
Rust

// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Substrate Inherent Extrinsics
//!
//! Inherent extrinsics are extrinsics that are inherently added to each block. However, it is up to
//! the 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.
//!
//! The process of constructing and applying inherents is the following:
//!
//! 1. The block producer first creates the [`InherentData`] by using the inherent data providers
//! that are created by [`CreateInherentDataProviders`].
//!
//! 2. The [`InherentData`] is passed to the `inherent_extrinsics` function of the `BlockBuilder`
//! runtime api. This will call the runtime which will create all the inherents that should be
//! applied to the block.
//!
//! 3. Apply each inherent to the block like any normal extrinsic.
//!
//! On block import the inherents in the block are checked by calling the `check_inherents` runtime
//! API. This will also pass an instance of [`InherentData`] which the runtime can use to validate
//! all inherents. If some inherent data isn't required for validating an inherent, it can be
//! omitted when providing the inherent data providers for block import.
//!
//! # Providing inherent data
//!
//! To provide inherent data from the client side, [`InherentDataProvider`] should be implemented.
//!
//! ```
//! use codec::Decode;
//! use sp_inherents::{InherentIdentifier, InherentData};
//!
//! // This needs to be unique for the runtime.
//! const INHERENT_IDENTIFIER: InherentIdentifier = *b"testinh0";
//!
//! /// Some custom inherent data provider
//! struct InherentDataProvider;
//!
//! #[async_trait::async_trait]
//! impl sp_inherents::InherentDataProvider for InherentDataProvider {
//! async fn provide_inherent_data(
//! &self,
//! inherent_data: &mut InherentData,
//! ) -> Result<(), sp_inherents::Error> {
//! // We can insert any data that implements [`codec::Encode`].
//! inherent_data.put_data(INHERENT_IDENTIFIER, &"hello")
//! }
//!
//! /// When validating the inherents, the runtime implementation can throw errors. We support
//! /// two error modes, fatal and non-fatal errors. A fatal error means that the block is invalid
//! /// and this function here should return `Err(_)` to not import the block. Non-fatal errors
//! /// are allowed to be handled here in this function and the function should return `Ok(())`
//! /// if it could be handled. A non-fatal error is for example that a block is in the future
//! /// from the point of view of the local node. In such a case the block import for example
//! /// should be delayed until the block is valid.
//! ///
//! /// If this functions returns `None`, it means that it is not responsible for this error or
//! /// that the error could not be interpreted.
//! async fn try_handle_error(
//! &self,
//! identifier: &InherentIdentifier,
//! mut error: &[u8],
//! ) -> Option<Result<(), sp_inherents::Error>> {
//! // Check if this error belongs to us.
//! if *identifier != INHERENT_IDENTIFIER {
//! return None;
//! }
//!
//! // For demonstration purposes we are using a `String` as error type. In real
//! // implementations it is advised to not use `String`.
//! Some(Err(
//! sp_inherents::Error::Application(Box::from(String::decode(&mut error).ok()?))
//! ))
//! }
//! }
//! ```
//!
//! In the service the relevant inherent data providers need to be passed the block production and
//! the block import. As already highlighted above, the providers can be different between import
//! and production.
//!
//! ```
//! # use sp_runtime::{generic::UncheckedExtrinsic, testing::MockCallU64};
//! # use sp_inherents::{InherentIdentifier, InherentData};
//! # use futures::FutureExt;
//! # type Block = sp_runtime::testing::Block<UncheckedExtrinsic<u64, MockCallU64, (), ()>>;
//! # const INHERENT_IDENTIFIER: InherentIdentifier = *b"testinh0";
//! # struct InherentDataProvider;
//! # #[async_trait::async_trait]
//! # impl sp_inherents::InherentDataProvider for InherentDataProvider {
//! # async fn provide_inherent_data(&self, inherent_data: &mut InherentData) -> Result<(), sp_inherents::Error> {
//! # inherent_data.put_data(INHERENT_IDENTIFIER, &"hello")
//! # }
//! # async fn try_handle_error(
//! # &self,
//! # _: &InherentIdentifier,
//! # _: &[u8],
//! # ) -> Option<Result<(), sp_inherents::Error>> {
//! # None
//! # }
//! # }
//!
//! async fn cool_consensus_block_production(
//! // The second parameter to the trait are parameters that depend on what the caller
//! // can provide on extra data.
//! _: impl sp_inherents::CreateInherentDataProviders<Block, ()>,
//! ) {
//! // do cool stuff
//! }
//!
//! async fn cool_consensus_block_import(
//! _: impl sp_inherents::CreateInherentDataProviders<Block, ()>,
//! ) {
//! // do cool stuff
//! }
//!
//! async fn build_service(is_validator: bool) {
//! // For block import we don't pass any inherent data provider, because our runtime
//! // does not need any inherent data to validate the inherents.
//! let block_import = cool_consensus_block_import(|_parent, ()| async { Ok(()) });
//!
//! let block_production = if is_validator {
//! // For block production we want to provide our inherent data provider
//! cool_consensus_block_production(|_parent, ()| async {
//! Ok(InherentDataProvider)
//! }).boxed()
//! } else {
//! futures::future::pending().boxed()
//! };
//!
//! futures::pin_mut!(block_import);
//!
//! futures::future::select(block_import, block_production).await;
//! }
//! ```
//!
//! # Creating the inherent
//!
//! As the inherents are created by the runtime, it depends on the runtime implementation on how
//! to create the inherents. As already described above the client side passes the [`InherentData`]
//! and expects the runtime to construct the inherents out of it. When validating the inherents,
//! [`CheckInherentsResult`] is used to communicate the result client side.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
use codec::{Decode, Encode};
use sp_std::{
collections::btree_map::{BTreeMap, Entry, IntoIter},
vec::Vec,
};
#[cfg(feature = "std")]
mod client_side;
#[cfg(feature = "std")]
pub use client_side::*;
/// Errors that occur in context of inherents.
#[derive(Debug)]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
#[allow(missing_docs)]
pub enum Error {
#[cfg_attr(
feature = "std",
error("Inherent data already exists for identifier: {}", "String::from_utf8_lossy(_0)")
)]
InherentDataExists(InherentIdentifier),
#[cfg_attr(
feature = "std",
error("Failed to decode inherent data for identifier: {}", "String::from_utf8_lossy(_1)")
)]
DecodingFailed(#[cfg_attr(feature = "std", source)] codec::Error, InherentIdentifier),
#[cfg_attr(
feature = "std",
error("There was already a fatal error reported and no other errors are allowed")
)]
FatalErrorReported,
#[cfg(feature = "std")]
#[error(transparent)]
Application(#[from] Box<dyn std::error::Error + Send + Sync>),
}
/// An identifier for an inherent.
pub type InherentIdentifier = [u8; 8];
/// Inherent data to include in a block.
#[derive(Clone, Default, Encode, Decode, scale_info::TypeInfo)]
pub struct InherentData {
/// All inherent data encoded with parity-scale-codec and an identifier.
data: BTreeMap<InherentIdentifier, Vec<u8>>,
}
impl InherentData {
/// Create a new instance.
pub fn new() -> Self {
Self::default()
}
/// Put data for an inherent into the internal storage.
///
/// # Return
///
/// Returns `Ok(())` if the data could be inserted and no data for an inherent with the same
/// identifier existed, otherwise an error is returned.
///
/// Inherent identifiers need to be unique, otherwise decoding of these values will not work!
pub fn put_data<I: codec::Encode>(
&mut self,
identifier: InherentIdentifier,
inherent: &I,
) -> Result<(), Error> {
match self.data.entry(identifier) {
Entry::Vacant(entry) => {
entry.insert(inherent.encode());
Ok(())
},
Entry::Occupied(_) => Err(Error::InherentDataExists(identifier)),
}
}
/// Replace the data for an inherent.
///
/// If it does not exist, the data is just inserted.
pub fn replace_data<I: codec::Encode>(&mut self, identifier: InherentIdentifier, inherent: &I) {
self.data.insert(identifier, inherent.encode());
}
/// Returns the data for the requested inherent.
///
/// # Return
///
/// - `Ok(Some(I))` if the data could be found and deserialized.
/// - `Ok(None)` if the data could not be found.
/// - `Err(_)` if the data could be found, but deserialization did not work.
pub fn get_data<I: codec::Decode>(
&self,
identifier: &InherentIdentifier,
) -> Result<Option<I>, Error> {
match self.data.get(identifier) {
Some(inherent) => I::decode(&mut &inherent[..])
.map_err(|e| Error::DecodingFailed(e, *identifier))
.map(Some),
None => Ok(None),
}
}
/// Get the number of inherents in this instance
pub fn len(&self) -> usize {
self.data.len()
}
}
/// The result of checking inherents.
///
/// It either returns okay for all checks, stores all occurred errors or just one fatal error.
///
/// When a fatal error occurs, all other errors are removed and the implementation needs to
/// abort checking inherents.
#[derive(Encode, Decode, Clone, scale_info::TypeInfo)]
pub struct CheckInherentsResult {
/// Did the check succeed?
okay: bool,
/// Did we encounter a fatal error?
fatal_error: bool,
/// We use the `InherentData` to store our errors.
errors: InherentData,
}
impl Default for CheckInherentsResult {
fn default() -> Self {
Self { okay: true, errors: InherentData::new(), fatal_error: false }
}
}
impl CheckInherentsResult {
/// Create a new instance.
pub fn new() -> Self {
Self::default()
}
/// Put an error into the result.
///
/// This makes this result resolve to `ok() == false`.
///
/// # Parameters
///
/// - identifier - The identifier of the inherent that generated the error.
/// - error - The error that will be encoded.
pub fn put_error<E: codec::Encode + IsFatalError>(
&mut self,
identifier: InherentIdentifier,
error: &E,
) -> Result<(), Error> {
// Don't accept any other error
if self.fatal_error {
return Err(Error::FatalErrorReported)
}
if error.is_fatal_error() {
// remove the other errors.
self.errors.data.clear();
}
self.errors.put_data(identifier, error)?;
self.okay = false;
self.fatal_error = error.is_fatal_error();
Ok(())
}
/// Get an error out of the result.
///
/// # Return
///
/// - `Ok(Some(I))` if the error could be found and deserialized.
/// - `Ok(None)` if the error could not be found.
/// - `Err(_)` if the error could be found, but deserialization did not work.
pub fn get_error<E: codec::Decode>(
&self,
identifier: &InherentIdentifier,
) -> Result<Option<E>, Error> {
self.errors.get_data(identifier)
}
/// Convert into an iterator over all contained errors.
pub fn into_errors(self) -> IntoIter<InherentIdentifier, Vec<u8>> {
self.errors.data.into_iter()
}
/// Is this result ok?
pub fn ok(&self) -> bool {
self.okay
}
/// Is this a fatal error?
pub fn fatal_error(&self) -> bool {
self.fatal_error
}
}
#[cfg(feature = "std")]
impl PartialEq for CheckInherentsResult {
fn eq(&self, other: &Self) -> bool {
self.fatal_error == other.fatal_error &&
self.okay == other.okay &&
self.errors.data == other.errors.data
}
}
/// Did we encounter a fatal error while checking an inherent?
///
/// A fatal error is everything that fails while checking an inherent error, e.g. the inherent
/// was not found, could not be decoded etc.
/// Then there are cases where you not want the inherent check to fail, but report that there is an
/// action required. For example a timestamp of a block is in the future, the timestamp is still
/// correct, but it is required to verify the block at a later time again and then the inherent
/// check will succeed.
pub trait IsFatalError {
/// Is this a fatal error?
fn is_fatal_error(&self) -> bool;
}
/// Auxiliary to make any given error resolve to `is_fatal_error() == true` for [`IsFatalError`].
#[derive(codec::Encode)]
pub struct MakeFatalError<E>(E);
impl<E: codec::Encode> From<E> for MakeFatalError<E> {
fn from(err: E) -> Self {
MakeFatalError(err)
}
}
impl<E: codec::Encode> IsFatalError for MakeFatalError<E> {
fn is_fatal_error(&self) -> bool {
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use codec::{Decode, Encode};
const TEST_INHERENT_0: InherentIdentifier = *b"testinh0";
const TEST_INHERENT_1: InherentIdentifier = *b"testinh1";
#[derive(Encode)]
struct NoFatalError<E: codec::Encode>(E);
impl<E: codec::Encode> IsFatalError for NoFatalError<E> {
fn is_fatal_error(&self) -> bool {
false
}
}
#[test]
fn inherent_data_encodes_and_decodes() {
let inherent_0 = vec![1, 2, 3];
let inherent_1: u32 = 7;
let mut data = InherentData::new();
data.put_data(TEST_INHERENT_0, &inherent_0).unwrap();
data.put_data(TEST_INHERENT_1, &inherent_1).unwrap();
let encoded = data.encode();
let decoded = InherentData::decode(&mut &encoded[..]).unwrap();
assert_eq!(decoded.get_data::<Vec<u32>>(&TEST_INHERENT_0).unwrap().unwrap(), inherent_0);
assert_eq!(decoded.get_data::<u32>(&TEST_INHERENT_1).unwrap().unwrap(), inherent_1);
}
#[test]
fn adding_same_inherent_returns_an_error() {
let mut data = InherentData::new();
data.put_data(TEST_INHERENT_0, &8).unwrap();
assert!(data.put_data(TEST_INHERENT_0, &10).is_err());
}
#[derive(Clone)]
struct TestInherentDataProvider;
const ERROR_TO_STRING: &str = "Found error!";
#[async_trait::async_trait]
impl InherentDataProvider for TestInherentDataProvider {
async fn provide_inherent_data(&self, data: &mut InherentData) -> Result<(), Error> {
data.put_data(TEST_INHERENT_0, &42)
}
async fn try_handle_error(
&self,
_: &InherentIdentifier,
_: &[u8],
) -> Option<Result<(), Error>> {
Some(Err(Error::Application(Box::from(ERROR_TO_STRING))))
}
}
#[test]
fn create_inherent_data() {
let provider = TestInherentDataProvider;
let inherent_data = futures::executor::block_on(provider.create_inherent_data()).unwrap();
assert_eq!(inherent_data.get_data::<u32>(&TEST_INHERENT_0).unwrap().unwrap(), 42u32);
}
#[test]
fn check_inherents_result_encodes_and_decodes() {
let mut result = CheckInherentsResult::new();
assert!(result.ok());
result.put_error(TEST_INHERENT_0, &NoFatalError(2u32)).unwrap();
assert!(!result.ok());
assert!(!result.fatal_error());
let encoded = result.encode();
let decoded = CheckInherentsResult::decode(&mut &encoded[..]).unwrap();
assert_eq!(decoded.get_error::<u32>(&TEST_INHERENT_0).unwrap().unwrap(), 2);
assert!(!decoded.ok());
assert!(!decoded.fatal_error());
}
#[test]
fn check_inherents_result_removes_other_errors_on_fatal_error() {
let mut result = CheckInherentsResult::new();
assert!(result.ok());
result.put_error(TEST_INHERENT_0, &NoFatalError(2u32)).unwrap();
assert!(!result.ok());
assert!(!result.fatal_error());
result.put_error(TEST_INHERENT_1, &MakeFatalError(4u32)).unwrap();
assert!(!result.ok());
assert!(result.fatal_error());
assert!(result.put_error(TEST_INHERENT_0, &NoFatalError(5u32)).is_err());
result.into_errors().for_each(|(i, e)| match i {
TEST_INHERENT_1 => assert_eq!(u32::decode(&mut &e[..]).unwrap(), 4),
_ => panic!("There should be no other error!"),
});
}
}