Renaming and documentation for ApplyResult, ApplyOutcome and et al (#4134)

* Remove superflous errors from the system module

* Rename and document InclusionOutcome

* Rename InclusionError

* Remove unused inclusion errors.

I left the enumeration though since other elements might be used some day.

* Rename and document DispatchOutcome

* Apply suggestions from code review

Co-Authored-By: Tomasz Drwięga <tomusdrw@users.noreply.github.com>

* TransactionValidityError instead of InclusionError

* Rename InclusionOutcome to ApplyExtrinsicResult

* Update docs.

* Update lib.rs

should be → is

* Bump the block builder API version.

* Fix the should_return_runtime_version test

* Clean the evidence
This commit is contained in:
Sergei Pepyakin
2019-11-22 17:15:58 +01:00
committed by GitHub
parent 86b6ac5571
commit 68351da29b
19 changed files with 186 additions and 129 deletions
+1
View File
@@ -5586,6 +5586,7 @@ dependencies = [
name = "substrate-block-builder-runtime-api"
version = "2.0.0"
dependencies = [
"parity-scale-codec 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"sr-api 2.0.0",
"sr-primitives 2.0.0",
"sr-std 2.0.0",
@@ -11,7 +11,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use rstd::prelude::*;
use primitives::OpaqueMetadata;
use sr_primitives::{
ApplyResult, transaction_validity::TransactionValidity, generic, create_runtime_str,
ApplyExtrinsicResult, transaction_validity::TransactionValidity, generic, create_runtime_str,
impl_opaque_keys, MultiSignature
};
use sr_primitives::traits::{
@@ -304,7 +304,7 @@ impl_runtime_apis! {
}
impl block_builder_api::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
+5 -5
View File
@@ -45,7 +45,7 @@ mod tests {
traits::{CodeExecutor, Externalities}, storage::well_known_keys,
};
use sr_primitives::{
Fixed64, traits::{Header as HeaderT, Hash as HashT, Convert}, ApplyResult,
Fixed64, traits::{Header as HeaderT, Hash as HashT, Convert}, ApplyExtrinsicResult,
transaction_validity::InvalidTransaction,
};
use contracts::ContractAddressFor;
@@ -173,7 +173,7 @@ mod tests {
true,
None,
).0.unwrap();
let r = ApplyResult::decode(&mut &v.as_encoded()[..]).unwrap();
let r = ApplyExtrinsicResult::decode(&mut &v.as_encoded()[..]).unwrap();
assert_eq!(r, Err(InvalidTransaction::Payment.into()));
}
@@ -209,7 +209,7 @@ mod tests {
true,
None,
).0.unwrap();
let r = ApplyResult::decode(&mut &v.as_encoded()[..]).unwrap();
let r = ApplyExtrinsicResult::decode(&mut &v.as_encoded()[..]).unwrap();
assert_eq!(r, Err(InvalidTransaction::Payment.into()));
}
@@ -854,7 +854,7 @@ mod tests {
false,
None,
).0.unwrap().into_encoded();
let r = ApplyResult::decode(&mut &r[..]).unwrap();
let r = ApplyExtrinsicResult::decode(&mut &r[..]).unwrap();
assert_eq!(r, Err(InvalidTransaction::Payment.into()));
}
@@ -887,7 +887,7 @@ mod tests {
false,
None,
).0.unwrap().into_encoded();
ApplyResult::decode(&mut &r[..])
ApplyExtrinsicResult::decode(&mut &r[..])
.unwrap()
.expect("Extrinsic could be applied")
.expect("Extrinsic did not fail");
+2 -2
View File
@@ -29,7 +29,7 @@ use support::{
use primitives::u32_trait::{_1, _2, _3, _4};
use node_primitives::{AccountId, AccountIndex, Balance, BlockNumber, Hash, Index, Moment, Signature};
use sr_api::impl_runtime_apis;
use sr_primitives::{Permill, Perbill, ApplyResult, impl_opaque_keys, generic, create_runtime_str};
use sr_primitives::{Permill, Perbill, ApplyExtrinsicResult, impl_opaque_keys, generic, create_runtime_str};
use sr_primitives::curve::PiecewiseLinear;
use sr_primitives::transaction_validity::TransactionValidity;
use sr_primitives::traits::{
@@ -584,7 +584,7 @@ impl_runtime_apis! {
}
impl block_builder_api::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
+10 -5
View File
@@ -18,7 +18,7 @@
use std::{self, error, result};
use state_machine;
use sr_primitives::ApplyError;
use sr_primitives::transaction_validity::TransactionValidityError;
use consensus;
use derive_more::{Display, From};
@@ -37,9 +37,9 @@ pub enum Error {
/// Unknown block.
#[display(fmt = "UnknownBlock: {}", _0)]
UnknownBlock(String),
/// Applying extrinsic error.
#[display(fmt = "Extrinsic error: {:?}", _0)]
ApplyExtrinsicFailed(ApplyError),
/// The `apply_extrinsic` is not valid due to the given `TransactionValidityError`.
#[display(fmt = "Extrinsic is not valid: {:?}", _0)]
ApplyExtrinsicFailed(TransactionValidityError),
/// Execution error.
#[display(fmt = "Execution: {}", _0)]
Execution(Box<dyn state_machine::Error>),
@@ -126,7 +126,12 @@ impl<'a> From<&'a str> for Error {
impl From<block_builder::ApplyExtrinsicFailed> for Error {
fn from(err: block_builder::ApplyExtrinsicFailed) -> Self {
Self::ApplyExtrinsicFailed(err.0)
use block_builder::ApplyExtrinsicFailed;
match err {
ApplyExtrinsicFailed::Validity(tx_validity) => Self::ApplyExtrinsicFailed(tx_validity),
ApplyExtrinsicFailed::Msg(msg) => Self::Msg(msg),
}
}
}
+60 -15
View File
@@ -32,18 +32,41 @@ use sr_primitives::{
Header as HeaderT, Hash, Block as BlockT, HashFor, ProvideRuntimeApi, ApiRef, DigestFor,
NumberFor, One,
},
transaction_validity::TransactionValidityError,
};
use primitives::ExecutionContext;
use state_machine::StorageProof;
use sr_api::{Core, ApiExt, ApiErrorFor};
#[allow(deprecated)]
use runtime_api::compatability_v3;
pub use runtime_api::BlockBuilder as BlockBuilderApi;
/// Error when the runtime failed to apply an extrinsic.
pub struct ApplyExtrinsicFailed(pub sr_primitives::ApplyError);
pub enum ApplyExtrinsicFailed {
/// The transaction cannot be included into the current block.
///
/// This doesn't necessary mean that the transaction itself is invalid, but it might be just
/// unappliable onto the current block.
Validity(TransactionValidityError),
/// This is used for miscelanious errors that can be represented by string and not handleable.
///
/// This will become obsolete with complete migration to v4 APIs.
Msg(String),
}
#[allow(deprecated)]
impl From<compatability_v3::ApplyError> for ApplyExtrinsicFailed {
fn from(e: compatability_v3::ApplyError) -> Self {
use self::compatability_v3::ApplyError::*;
match e {
Validity(tx_validity) => Self::Validity(tx_validity),
e => Self::Msg(format!("Apply extrinsic failed: {:?}", e)),
}
}
}
/// Utility for building new (valid) blocks from a stream of extrinsics.
pub struct BlockBuilder<'a, Block: BlockT, A: ProvideRuntimeApi> {
@@ -107,21 +130,43 @@ where
let block_id = &self.block_id;
let extrinsics = &mut self.extrinsics;
self.api.map_api_result(|api| {
match api.apply_extrinsic_with_context(
if self
.api
.has_api_with::<dyn BlockBuilderApi<Block, Error = ApiErrorFor<A, Block>>, _>(
block_id,
ExecutionContext::BlockConstruction,
xt.clone()
)? {
Ok(_) => {
extrinsics.push(xt);
Ok(())
|version| version < 4,
)?
{
// Run compatibility fallback for v3.
self.api.map_api_result(|api| {
#[allow(deprecated)]
match api.apply_extrinsic_before_version_4_with_context(
block_id,
ExecutionContext::BlockConstruction,
xt.clone(),
)? {
Ok(_) => {
extrinsics.push(xt);
Ok(())
}
Err(e) => Err(ApplyExtrinsicFailed::from(e))?,
}
Err(e) => {
Err(ApplyExtrinsicFailed(e))?
})
} else {
self.api.map_api_result(|api| {
match api.apply_extrinsic_with_context(
block_id,
ExecutionContext::BlockConstruction,
xt.clone(),
)? {
Ok(_) => {
extrinsics.push(xt);
Ok(())
}
Err(tx_validity) => Err(ApplyExtrinsicFailed::Validity(tx_validity))?,
}
}
})
})
}
}
/// Consume the builder to return a valid `Block` containing all pushed extrinsics.
+1 -1
View File
@@ -280,7 +280,7 @@ fn should_return_runtime_version() {
let result = "{\"specName\":\"test\",\"implName\":\"parity-test\",\"authoringVersion\":1,\
\"specVersion\":1,\"implVersion\":1,\"apis\":[[\"0xdf6acb689907609b\",2],\
[\"0x37e397fc7c91f5e4\",1],[\"0xd2bc9897eed08f15\",1],[\"0x40fe3ad401f8959a\",3],\
[\"0x37e397fc7c91f5e4\",1],[\"0xd2bc9897eed08f15\",1],[\"0x40fe3ad401f8959a\",4],\
[\"0xc6e9a76309f39b09\",1],[\"0xdd718d5cc53262d4\",1],[\"0xcbca25e39f142387\",1],\
[\"0xf78b278be53f454c\",1],[\"0xab3c0572291feb8b\",1],[\"0xbc9d89904f5b923f\",1]]}";
+7 -6
View File
@@ -79,7 +79,7 @@
use rstd::{prelude::*, marker::PhantomData};
use support::weights::{GetDispatchInfo, WeighBlock, DispatchInfo};
use sr_primitives::{
generic::Digest, ApplyResult,
generic::Digest, ApplyExtrinsicResult,
traits::{
self, Header, Zero, One, Checkable, Applyable, CheckEqual, OnFinalize, OnInitialize,
NumberFor, Block as BlockT, OffchainWorker, Dispatchable,
@@ -229,9 +229,10 @@ where
}
/// Apply extrinsic outside of the block execution function.
///
/// This doesn't attempt to validate anything regarding the block, but it builds a list of uxt
/// hashes.
pub fn apply_extrinsic(uxt: Block::Extrinsic) -> ApplyResult {
pub fn apply_extrinsic(uxt: Block::Extrinsic) -> ApplyExtrinsicResult {
let encoded = uxt.encode();
let encoded_len = encoded.len();
Self::apply_extrinsic_with_len(uxt, encoded_len, Some(encoded))
@@ -252,7 +253,7 @@ where
uxt: Block::Extrinsic,
encoded_len: usize,
to_note: Option<Vec<u8>>,
) -> ApplyResult {
) -> ApplyExtrinsicResult {
// Verify that the signature is good.
let xt = uxt.check(&Default::default())?;
@@ -322,7 +323,7 @@ mod tests {
use sr_primitives::{
generic::Era, Perbill, DispatchError, testing::{Digest, Header, Block},
traits::{Bounded, Header as HeaderT, BlakeTwo256, IdentityLookup, ConvertInto},
transaction_validity::{InvalidTransaction, UnknownTransaction}, ApplyError,
transaction_validity::{InvalidTransaction, UnknownTransaction, TransactionValidityError},
};
use support::{
impl_outer_event, impl_outer_origin, parameter_types, impl_outer_dispatch,
@@ -448,7 +449,7 @@ mod tests {
impl ValidateUnsigned for Runtime {
type Call = Call;
fn pre_dispatch(_call: &Self::Call) -> Result<(), ApplyError> {
fn pre_dispatch(_call: &Self::Call) -> Result<(), TransactionValidityError> {
Ok(())
}
@@ -701,7 +702,7 @@ mod tests {
} else {
assert_eq!(
Executive::apply_extrinsic(xt),
Err(ApplyError::Validity(InvalidTransaction::Payment.into())),
Err(InvalidTransaction::Payment.into()),
);
assert_eq!(<balances::Module<Runtime>>::total_balance(&1), 111);
}
+4 -4
View File
@@ -18,9 +18,9 @@
#[allow(deprecated)]
pub use crate::sr_primitives::traits::ValidateUnsigned;
#[doc(hidden)]
pub use crate::sr_primitives::transaction_validity::{TransactionValidity, UnknownTransaction};
#[doc(hidden)]
pub use crate::sr_primitives::ApplyError;
pub use crate::sr_primitives::transaction_validity::{
TransactionValidity, UnknownTransaction, TransactionValidityError,
};
/// Implement `ValidateUnsigned` for `Runtime`.
@@ -70,7 +70,7 @@ macro_rules! impl_outer_validate_unsigned {
impl $crate::unsigned::ValidateUnsigned for $runtime {
type Call = Call;
fn pre_dispatch(call: &Self::Call) -> Result<(), $crate::unsigned::ApplyError> {
fn pre_dispatch(call: &Self::Call) -> Result<(), $crate::unsigned::TransactionValidityError> {
#[allow(unreachable_patterns)]
match call {
$( Call::$module(inner_call) => $module::pre_dispatch(inner_call), )*
+4 -6
View File
@@ -98,7 +98,7 @@ use rstd::fmt::Debug;
use sr_version::RuntimeVersion;
use sr_primitives::{
RuntimeDebug,
generic::{self, Era}, Perbill, ApplyError, ApplyOutcome, DispatchError,
generic::{self, Era}, Perbill, DispatchOutcome, DispatchError,
transaction_validity::{
ValidTransaction, TransactionPriority, TransactionLongevity, TransactionValidityError,
InvalidTransaction, TransactionValidity,
@@ -320,8 +320,6 @@ decl_event!(
decl_error! {
/// Error for the System module
pub enum Error {
BadSignature,
BlockFull,
RequireSignedOrigin,
RequireRootOrigin,
RequireNoOrigin,
@@ -754,7 +752,7 @@ impl<T: Trait> Module<T> {
}
/// To be called immediately after an extrinsic has been applied.
pub fn note_applied_extrinsic(r: &ApplyOutcome, _encoded_len: u32, info: DispatchInfo) {
pub fn note_applied_extrinsic(r: &DispatchOutcome, _encoded_len: u32, info: DispatchInfo) {
Self::deposit_event(
match r {
Ok(()) => Event::ExtrinsicSuccess(info),
@@ -865,7 +863,7 @@ impl<T: Trait + Send + Sync> SignedExtension for CheckWeight<T> {
_call: &Self::Call,
info: Self::DispatchInfo,
len: usize,
) -> Result<(), ApplyError> {
) -> Result<(), TransactionValidityError> {
let next_len = Self::check_block_length(info, len)?;
AllExtrinsicsLen::put(next_len);
let next_weight = Self::check_weight(info)?;
@@ -945,7 +943,7 @@ impl<T: Trait> SignedExtension for CheckNonce<T> {
_call: &Self::Call,
_info: Self::DispatchInfo,
_len: usize,
) -> Result<(), ApplyError> {
) -> Result<(), TransactionValidityError> {
let expected = <AccountNonce<T>>::get(who);
if self.0 != expected {
return Err(
@@ -8,12 +8,14 @@ edition = "2018"
sr-primitives = { path = "../../sr-primitives", default-features = false }
sr-api = { path = "../../sr-api", default-features = false }
rstd = { package = "sr-std", path = "../../sr-std", default-features = false }
codec = { package = "parity-scale-codec", version = "1.0.6", default-features = false }
inherents = { package = "substrate-inherents", path = "../../inherents", default-features = false }
[features]
default = [ "std" ]
std = [
"sr-primitives/std",
"codec/std",
"inherents/std",
"sr-api/std",
"rstd/std",
@@ -18,16 +18,46 @@
#![cfg_attr(not(feature = "std"), no_std)]
use sr_primitives::{traits::Block as BlockT, ApplyResult};
use sr_primitives::{traits::Block as BlockT, ApplyExtrinsicResult};
use inherents::{InherentData, CheckInherentsResult};
/// Definitions for supporting the older version of API: v3
///
/// These definitions are taken from the 2c58e30246a029b53d51e5b24c31974ac539ee8b git revision.
#[deprecated(note = "These definitions here are only for compatibility reasons")]
pub mod compatability_v3 {
use sr_primitives::{DispatchOutcome, transaction_validity};
use codec::{Encode, Decode};
#[derive(Eq, PartialEq, Clone, Copy, Decode, Encode, Debug)]
pub enum ApplyError {
NoPermission,
BadState,
Validity(transaction_validity::TransactionValidityError),
}
// `ApplyOutcome` was renamed to `DispatchOutcome` with the layout preserved.
pub type ApplyResult = Result<DispatchOutcome, ApplyError>;
}
sr_api::decl_runtime_apis! {
/// The `BlockBuilder` api trait that provides the required functionality for building a block.
#[api_version(3)]
#[api_version(4)]
pub trait BlockBuilder {
/// Apply the given extrinsics.
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult;
/// Compatibility version of `apply_extrinsic` for v3.
///
/// Only the return type is changed.
#[changed_in(4)]
#[allow(deprecated)]
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic)
-> self::compatability_v3::ApplyResult;
/// Apply the given extrinsic.
///
/// Returns an inclusion outcome which specifies if this extrinsic is included in
/// this block or not.
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult;
/// Finish the current block.
#[renamed("finalise_block", 3)]
fn finalize_block() -> <Block as BlockT>::Header;
@@ -74,7 +74,7 @@ where
self,
info: Self::DispatchInfo,
len: usize,
) -> crate::ApplyResult {
) -> crate::ApplyExtrinsicResult {
let (maybe_who, pre) = if let Some((id, extra)) = self.signed {
let pre = Extra::pre_dispatch(extra, &id, &self.function, info.clone(), len)?;
(Some(id), pre)
+32 -47
View File
@@ -346,58 +346,12 @@ impl From<ed25519::Signature> for AnySignature {
}
}
#[derive(Eq, PartialEq, Clone, Copy, Decode, Encode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize))]
/// Reason why an extrinsic couldn't be applied (i.e. invalid extrinsic).
pub enum ApplyError {
/// General error to do with the permissions of the sender.
NoPermission,
/// General error to do with the state of the system in general.
BadState,
/// Any error to do with the transaction validity.
Validity(transaction_validity::TransactionValidityError),
}
impl ApplyError {
/// Returns if the reason for the error was block resource exhaustion.
pub fn exhausted_resources(&self) -> bool {
match self {
Self::Validity(e) => e.exhausted_resources(),
_ => false,
}
}
}
impl From<ApplyError> for &'static str {
fn from(err: ApplyError) -> &'static str {
match err {
ApplyError::NoPermission => "Transaction does not have required permissions",
ApplyError::BadState => "System state currently prevents this transaction",
ApplyError::Validity(v) => v.into(),
}
}
}
impl From<transaction_validity::TransactionValidityError> for ApplyError {
fn from(err: transaction_validity::TransactionValidityError) -> Self {
ApplyError::Validity(err)
}
}
/// The outcome of applying a transaction.
pub type ApplyOutcome = Result<(), DispatchError>;
impl From<DispatchError> for ApplyOutcome {
impl From<DispatchError> for DispatchOutcome {
fn from(err: DispatchError) -> Self {
Err(err)
}
}
/// Result from attempt to apply an extrinsic.
pub type ApplyResult = Result<ApplyOutcome, ApplyError>;
#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize))]
/// Reason why a dispatch call failed
@@ -451,6 +405,37 @@ impl From<&'static str> for DispatchError {
}
}
/// This type specifies the outcome of dispatching a call to a module.
///
/// In case of failure an error specific to the module is returned.
///
/// Failure of the module call dispatching doesn't invalidate the extrinsic and it is still included
/// in the block, therefore all state changes performed by the dispatched call are still persisted.
///
/// For example, if the dispatching of an extrinsic involves inclusion fee payment then these
/// changes are going to be preserved even if the call dispatched failed.
pub type DispatchOutcome = Result<(), DispatchError>;
/// The result of applying of an extrinsic.
///
/// This type is typically used in the context of `BlockBuilder` to signal that the extrinsic
/// in question cannot be included.
///
/// A block containing extrinsics that have a negative inclusion outcome is invalid. A negative
/// result can only occur during the block production, where such extrinsics are detected and
/// removed from the block that is being created and the transaction pool.
///
/// To rehash: every extrinsic in a valid block must return a positive `ApplyExtrinsicResult`.
///
/// 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 neccessarily 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>;
/// Verify a signature on an encoded value in a lazy manner. This can be
/// an optimization if the signature scheme has an "unsigned" escape hash.
pub fn verify_encoded_lazy<V: Verify, T: codec::Encode>(
@@ -25,7 +25,7 @@ use crate::traits::{
};
#[allow(deprecated)]
use crate::traits::ValidateUnsigned;
use crate::{generic, KeyTypeId, ApplyResult};
use crate::{generic, KeyTypeId, ApplyExtrinsicResult};
pub use primitives::{H256, sr25519};
use primitives::{crypto::{CryptoType, Dummy, key_types, Public}, U256};
use crate::transaction_validity::{TransactionValidity, TransactionValidityError};
@@ -354,7 +354,7 @@ impl<Origin, Call, Extra, Info> Applyable for TestXt<Call, Extra> where
self,
info: Self::DispatchInfo,
len: usize,
) -> ApplyResult {
) -> ApplyExtrinsicResult {
let maybe_who = if let Some((who, extra)) = self.0 {
Extra::pre_dispatch(extra, &who, &self.1, info, len)?;
Some(who)
@@ -754,7 +754,7 @@ pub trait SignedExtension: Codec + Debug + Sync + Send + Clone + Eq + PartialEq
call: &Self::Call,
info: Self::DispatchInfo,
len: usize,
) -> Result<Self::Pre, crate::ApplyError> {
) -> Result<Self::Pre, TransactionValidityError> {
self.validate(who, call, info.clone(), len)
.map(|_| Self::Pre::default())
.map_err(Into::into)
@@ -788,7 +788,7 @@ pub trait SignedExtension: Codec + Debug + Sync + Send + Clone + Eq + PartialEq
call: &Self::Call,
info: Self::DispatchInfo,
len: usize,
) -> Result<Self::Pre, crate::ApplyError> {
) -> Result<Self::Pre, TransactionValidityError> {
Self::validate_unsigned(call, info.clone(), len)
.map(|_| Self::Pre::default())
.map_err(Into::into)
@@ -835,7 +835,7 @@ impl<AccountId, Call, Info: Clone> SignedExtension for Tuple {
}
fn pre_dispatch(self, who: &Self::AccountId, call: &Self::Call, info: Self::DispatchInfo, len: usize)
-> Result<Self::Pre, crate::ApplyError>
-> Result<Self::Pre, TransactionValidityError>
{
Ok(for_tuples!( ( #( Tuple.pre_dispatch(who, call, info.clone(), len)? ),* ) ))
}
@@ -854,7 +854,7 @@ impl<AccountId, Call, Info: Clone> SignedExtension for Tuple {
call: &Self::Call,
info: Self::DispatchInfo,
len: usize,
) -> Result<Self::Pre, crate::ApplyError> {
) -> Result<Self::Pre, TransactionValidityError> {
Ok(for_tuples!( ( #( Tuple::pre_dispatch_unsigned(call, info.clone(), len)? ),* ) ))
}
@@ -912,7 +912,7 @@ pub trait Applyable: Sized + Send + Sync {
self,
info: Self::DispatchInfo,
len: usize,
) -> crate::ApplyResult;
) -> crate::ApplyExtrinsicResult;
}
/// Auxiliary wrapper that holds an api instance and binds it to the given lifetime.
@@ -992,7 +992,7 @@ pub trait ValidateUnsigned {
/// this function again to make sure we never include an invalid transaction.
///
/// Changes made to storage WILL be persisted if the call returns `Ok`.
fn pre_dispatch(call: &Self::Call) -> Result<(), crate::ApplyError> {
fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
Self::validate_unsigned(call)
.map(|_| ())
.map_err(Into::into)
@@ -146,18 +146,6 @@ impl From<UnknownTransaction> for TransactionValidityError {
}
}
impl From<InvalidTransaction> for crate::ApplyError {
fn from(invalid: InvalidTransaction) -> crate::ApplyError {
TransactionValidityError::from(invalid).into()
}
}
impl From<UnknownTransaction> for crate::ApplyError {
fn from(unknown: UnknownTransaction) -> crate::ApplyError {
TransactionValidityError::from(unknown).into()
}
}
/// Information on a transaction's validity and, if valid, on how it relates to other transactions.
pub type TransactionValidity = Result<ValidTransaction, TransactionValidityError>;
+3 -3
View File
@@ -34,7 +34,7 @@ use substrate_trie::trie_types::{TrieDB, TrieDBMut};
use sr_api::{decl_runtime_apis, impl_runtime_apis};
use sr_primitives::{
ApplyResult, create_runtime_str, Perbill, impl_opaque_keys,
ApplyExtrinsicResult, create_runtime_str, Perbill, impl_opaque_keys,
transaction_validity::{
TransactionValidity, ValidTransaction, TransactionValidityError, InvalidTransaction,
},
@@ -494,7 +494,7 @@ cfg_if! {
}
impl block_builder_api::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
system::execute_transaction(extrinsic)
}
@@ -679,7 +679,7 @@ cfg_if! {
}
impl block_builder_api::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
system::execute_transaction(extrinsic)
}
+10 -8
View File
@@ -25,8 +25,10 @@ use runtime_io::{
use runtime_support::storage;
use runtime_support::{decl_storage, decl_module};
use sr_primitives::{
traits::{Hash as HashT, BlakeTwo256, Header as _}, generic, ApplyError, ApplyResult,
transaction_validity::{TransactionValidity, ValidTransaction, InvalidTransaction},
traits::{Hash as HashT, BlakeTwo256, Header as _}, generic, ApplyExtrinsicResult,
transaction_validity::{
TransactionValidity, ValidTransaction, InvalidTransaction, TransactionValidityError,
},
};
use codec::{KeyedVec, Encode};
use palette_system::Trait;
@@ -204,7 +206,7 @@ pub fn validate_transaction(utx: Extrinsic) -> TransactionValidity {
/// Execute a transaction outside of the block execution function.
/// This doesn't attempt to validate anything regarding the block.
pub fn execute_transaction(utx: Extrinsic) -> ApplyResult {
pub fn execute_transaction(utx: Extrinsic) -> ApplyExtrinsicResult {
let extrinsic_index: u32 = storage::unhashed::get(well_known_keys::EXTRINSIC_INDEX).unwrap();
let result = execute_transaction_backend(&utx);
ExtrinsicData::insert(extrinsic_index, utx.encode());
@@ -246,12 +248,12 @@ pub fn finalize_block() -> Header {
}
#[inline(always)]
fn check_signature(utx: &Extrinsic) -> Result<(), ApplyError> {
fn check_signature(utx: &Extrinsic) -> Result<(), TransactionValidityError> {
use sr_primitives::traits::BlindCheckable;
utx.clone().check().map_err(|_| InvalidTransaction::BadProof.into()).map(|_| ())
}
fn execute_transaction_backend(utx: &Extrinsic) -> ApplyResult {
fn execute_transaction_backend(utx: &Extrinsic) -> ApplyExtrinsicResult {
check_signature(utx)?;
match utx {
Extrinsic::Transfer(ref transfer, _) => execute_transfer_backend(transfer),
@@ -261,7 +263,7 @@ fn execute_transaction_backend(utx: &Extrinsic) -> ApplyResult {
}
}
fn execute_transfer_backend(tx: &Transfer) -> ApplyResult {
fn execute_transfer_backend(tx: &Transfer) -> ApplyExtrinsicResult {
// check nonce
let nonce_key = tx.from.to_keyed_vec(NONCE_OF);
let expected_nonce: u64 = storage::hashed::get_or(&blake2_256, &nonce_key, 0);
@@ -287,12 +289,12 @@ fn execute_transfer_backend(tx: &Transfer) -> ApplyResult {
Ok(Ok(()))
}
fn execute_new_authorities_backend(new_authorities: &[AuthorityId]) -> ApplyResult {
fn execute_new_authorities_backend(new_authorities: &[AuthorityId]) -> ApplyExtrinsicResult {
NewAuthorities::put(new_authorities.to_vec());
Ok(Ok(()))
}
fn execute_storage_change(key: &[u8], value: Option<&[u8]>) -> ApplyResult {
fn execute_storage_change(key: &[u8], value: Option<&[u8]>) -> ApplyExtrinsicResult {
match value {
Some(value) => storage::unhashed::put_raw(key, value),
None => storage::unhashed::kill(key),