Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
@@ -23,14 +23,16 @@ use std::fmt;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_std::prelude::*;
use sp_core::RuntimeDebug;
use crate::codec::{Codec, Encode, Decode};
use crate::traits::{
self, Member, Block as BlockT, Header as HeaderT, MaybeSerialize, MaybeMallocSizeOf,
NumberFor,
use crate::{
codec::{Codec, Decode, Encode},
traits::{
self, Block as BlockT, Header as HeaderT, MaybeMallocSizeOf, MaybeSerialize, Member,
NumberFor,
},
Justifications,
};
use crate::Justifications;
use sp_core::RuntimeDebug;
use sp_std::prelude::*;
/// Something to identify a block.
#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
@@ -18,11 +18,13 @@
//! Generic implementation of an extrinsic that has passed the verification
//! stage.
use crate::traits::{
self, Member, MaybeDisplay, SignedExtension, Dispatchable, DispatchInfoOf, PostDispatchInfoOf,
ValidateUnsigned,
use crate::{
traits::{
self, DispatchInfoOf, Dispatchable, MaybeDisplay, Member, PostDispatchInfoOf,
SignedExtension, ValidateUnsigned,
},
transaction_validity::{TransactionSource, TransactionValidity},
};
use crate::transaction_validity::{TransactionValidity, TransactionSource};
/// Definition of something that the external world might want to say; its
/// existence implies that it has been checked and is good, particularly with
@@ -37,12 +39,11 @@ pub struct CheckedExtrinsic<AccountId, Call, Extra> {
pub function: Call,
}
impl<AccountId, Call, Extra, Origin> traits::Applyable for
CheckedExtrinsic<AccountId, Call, Extra>
impl<AccountId, Call, Extra, Origin> traits::Applyable for CheckedExtrinsic<AccountId, Call, Extra>
where
AccountId: Member + MaybeDisplay,
Call: Member + Dispatchable<Origin=Origin>,
Extra: SignedExtension<AccountId=AccountId, Call=Call>,
Call: Member + Dispatchable<Origin = Origin>,
Extra: SignedExtension<AccountId = AccountId, Call = Call>,
Origin: From<Option<AccountId>>,
{
type Call = Call;
@@ -64,7 +65,7 @@ where
}
}
fn apply<U: ValidateUnsigned<Call=Self::Call>>(
fn apply<U: ValidateUnsigned<Call = Self::Call>>(
self,
info: &DispatchInfoOf<Self::Call>,
len: usize,
@@ -22,8 +22,10 @@ use serde::{Deserialize, Serialize};
use sp_std::prelude::*;
use crate::ConsensusEngineId;
use crate::codec::{Decode, Encode, Input, Error};
use crate::{
codec::{Decode, Encode, Error, Input},
ConsensusEngineId,
};
use sp_core::{ChangesTrieConfiguration, RuntimeDebug};
/// Generic header digest.
@@ -40,7 +42,7 @@ pub struct Digest<Hash> {
impl<Item> Default for Digest<Item> {
fn default() -> Self {
Self { logs: Vec::new(), }
Self { logs: Vec::new() }
}
}
@@ -61,12 +63,18 @@ impl<Hash> Digest<Hash> {
}
/// Get reference to the first digest item that matches the passed predicate.
pub fn log<T: ?Sized, F: Fn(&DigestItem<Hash>) -> Option<&T>>(&self, predicate: F) -> Option<&T> {
pub fn log<T: ?Sized, F: Fn(&DigestItem<Hash>) -> Option<&T>>(
&self,
predicate: F,
) -> Option<&T> {
self.logs().iter().find_map(predicate)
}
/// Get a conversion of the first digest item that successfully converts using the function.
pub fn convert_first<T, F: Fn(&DigestItem<Hash>) -> Option<T>>(&self, predicate: F) -> Option<T> {
pub fn convert_first<T, F: Fn(&DigestItem<Hash>) -> Option<T>>(
&self,
predicate: F,
) -> Option<T> {
self.logs().iter().find_map(predicate)
}
}
@@ -132,16 +140,18 @@ pub enum ChangesTrieSignal {
#[cfg(feature = "std")]
impl<Hash: Encode> serde::Serialize for DigestItem<Hash> {
fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
self.using_encoded(|bytes| {
sp_core::bytes::serialize(bytes, seq)
})
fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.using_encoded(|bytes| sp_core::bytes::serialize(bytes, seq))
}
}
#[cfg(feature = "std")]
impl<'a, Hash: Decode> serde::Deserialize<'a> for DigestItem<Hash> {
fn deserialize<D>(de: D) -> Result<Self, D::Error> where
fn deserialize<D>(de: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'a>,
{
let r = sp_core::bytes::deserialize(de)?;
@@ -297,9 +307,7 @@ impl<Hash: Decode> Decode for DigestItem<Hash> {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let item_type: DigestItemType = Decode::decode(input)?;
match item_type {
DigestItemType::ChangesTrieRoot => Ok(Self::ChangesTrieRoot(
Decode::decode(input)?,
)),
DigestItemType::ChangesTrieRoot => Ok(Self::ChangesTrieRoot(Decode::decode(input)?)),
DigestItemType::PreRuntime => {
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
Ok(Self::PreRuntime(vals.0, vals.1))
@@ -307,17 +315,14 @@ impl<Hash: Decode> Decode for DigestItem<Hash> {
DigestItemType::Consensus => {
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
Ok(Self::Consensus(vals.0, vals.1))
}
},
DigestItemType::Seal => {
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
Ok(Self::Seal(vals.0, vals.1))
},
DigestItemType::ChangesTrieSignal => Ok(Self::ChangesTrieSignal(
Decode::decode(input)?,
)),
DigestItemType::Other => Ok(Self::Other(
Decode::decode(input)?,
)),
DigestItemType::ChangesTrieSignal =>
Ok(Self::ChangesTrieSignal(Decode::decode(input)?)),
DigestItemType::Other => Ok(Self::Other(Decode::decode(input)?)),
}
}
}
@@ -376,9 +381,10 @@ impl<'a, Hash> DigestItemRef<'a, Hash> {
pub fn try_as_raw(&self, id: OpaqueDigestItemId) -> Option<&'a [u8]> {
match (id, self) {
(OpaqueDigestItemId::Consensus(w), &Self::Consensus(v, s)) |
(OpaqueDigestItemId::Seal(w), &Self::Seal(v, s)) |
(OpaqueDigestItemId::PreRuntime(w), &Self::PreRuntime(v, s))
if v == w => Some(&s[..]),
(OpaqueDigestItemId::Seal(w), &Self::Seal(v, s)) |
(OpaqueDigestItemId::PreRuntime(w), &Self::PreRuntime(v, s))
if v == w =>
Some(&s[..]),
(OpaqueDigestItemId::Other, &Self::Other(s)) => Some(&s[..]),
_ => None,
}
@@ -395,8 +401,7 @@ impl<'a, Hash> DigestItemRef<'a, Hash> {
/// Returns `None` if this isn't a seal item, the `id` doesn't match or when the decoding fails.
pub fn seal_try_to<T: Decode>(&self, id: &ConsensusEngineId) -> Option<T> {
match self {
Self::Seal(v, s) if *v == id =>
Decode::decode(&mut &s[..]).ok(),
Self::Seal(v, s) if *v == id => Decode::decode(&mut &s[..]).ok(),
_ => None,
}
}
@@ -407,8 +412,7 @@ impl<'a, Hash> DigestItemRef<'a, Hash> {
/// when the decoding fails.
pub fn consensus_try_to<T: Decode>(&self, id: &ConsensusEngineId) -> Option<T> {
match self {
Self::Consensus(v, s) if *v == id =>
Decode::decode(&mut &s[..]).ok(),
Self::Consensus(v, s) if *v == id => Decode::decode(&mut &s[..]).ok(),
_ => None,
}
}
@@ -419,8 +423,7 @@ impl<'a, Hash> DigestItemRef<'a, Hash> {
/// when the decoding fails.
pub fn pre_runtime_try_to<T: Decode>(&self, id: &ConsensusEngineId) -> Option<T> {
match self {
Self::PreRuntime(v, s) if *v == id =>
Decode::decode(&mut &s[..]).ok(),
Self::PreRuntime(v, s) if *v == id => Decode::decode(&mut &s[..]).ok(),
_ => None,
}
}
@@ -482,7 +485,7 @@ mod tests {
logs: vec![
DigestItem::ChangesTrieRoot(4),
DigestItem::Other(vec![1, 2, 3]),
DigestItem::Seal(*b"test", vec![1, 2, 3])
DigestItem::Seal(*b"test", vec![1, 2, 3]),
],
};
+16 -20
View File
@@ -18,9 +18,9 @@
//! Generic implementation of an unchecked (pre-verification) extrinsic.
#[cfg(feature = "std")]
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
use crate::codec::{Decode, Encode, Input, Output, Error};
use crate::codec::{Decode, Encode, Error, Input, Output};
/// Era period
pub type Period = u64;
@@ -47,15 +47,13 @@ pub enum Era {
Mortal(Period, Phase),
}
/*
* E.g. with period == 4:
* 0 10 20 30 40
* 0123456789012345678901234567890123456789012
* |...|
* authored -/ \- expiry
* phase = 1
* n = Q(current - phase, period) + phase
*/
// E.g. with period == 4:
// 0 10 20 30 40
// 0123456789012345678901234567890123456789012
// |...|
// authored -/ \- expiry
// 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).
@@ -64,10 +62,7 @@ impl Era {
/// does not exceed `BlockHashCount` parameter passed to `system` module, since that
/// prunes old blocks and renders transactions immediately invalid.
pub fn mortal(period: u64, current: u64) -> Self {
let period = period.checked_next_power_of_two()
.unwrap_or(1 << 16)
.max(4)
.min(1 << 16);
let period = period.checked_next_power_of_two().unwrap_or(1 << 16).max(4).min(1 << 16);
let phase = current % period;
let quantize_factor = (period >> 12).max(1);
let quantized_phase = phase / quantize_factor * quantize_factor;
@@ -109,9 +104,10 @@ impl Encode for Era {
Self::Immortal => output.push_byte(0),
Self::Mortal(period, phase) => {
let quantize_factor = (*period as u64 >> 12).max(1);
let encoded = (period.trailing_zeros() - 1).max(1).min(15) as u16 | ((phase / quantize_factor) << 4) as u16;
let encoded = (period.trailing_zeros() - 1).max(1).min(15) as u16 |
((phase / quantize_factor) << 4) as u16;
encoded.encode_to(output);
}
},
}
}
}
@@ -153,7 +149,7 @@ mod tests {
assert!(e.is_immortal());
assert_eq!(e.encode(), vec![0u8]);
assert_eq!(e, Era::decode(&mut&[0u8][..]).unwrap());
assert_eq!(e, Era::decode(&mut &[0u8][..]).unwrap());
}
#[test]
@@ -163,7 +159,7 @@ mod tests {
let expected = vec![5 + 42 % 16 * 16, 42 / 16];
assert_eq!(e.encode(), expected);
assert_eq!(e, Era::decode(&mut&expected[..]).unwrap());
assert_eq!(e, Era::decode(&mut &expected[..]).unwrap());
}
#[test]
@@ -172,7 +168,7 @@ mod tests {
let expected = vec![(14 + 2500 % 16 * 16) as u8, (2500 / 16) as u8];
assert_eq!(e.encode(), expected);
assert_eq!(e, Era::decode(&mut&expected[..]).unwrap());
assert_eq!(e, Era::decode(&mut &expected[..]).unwrap());
}
#[test]
@@ -17,20 +17,18 @@
//! Generic implementation of a block header.
use crate::{
codec::{Codec, Decode, Encode, EncodeAsRef, Error, HasCompact, Input, Output},
generic::Digest,
traits::{
self, AtLeast32BitUnsigned, Hash as HashT, MaybeDisplay, MaybeMallocSizeOf, MaybeSerialize,
MaybeSerializeDeserialize, Member, SimpleBitOps,
},
};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use crate::codec::{Decode, Encode, Codec, Input, Output, HasCompact, EncodeAsRef, Error};
use crate::traits::{
self, Member, AtLeast32BitUnsigned, SimpleBitOps, Hash as HashT,
MaybeSerializeDeserialize, MaybeSerialize, MaybeDisplay,
MaybeMallocSizeOf,
};
use crate::generic::Digest;
use sp_core::U256;
use sp_std::{
convert::TryFrom,
fmt::Debug,
};
use sp_std::{convert::TryFrom, fmt::Debug};
/// Abstraction over a block header for a substrate chain.
#[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug)]
@@ -41,9 +39,10 @@ pub struct Header<Number: Copy + Into<U256> + TryFrom<U256>, Hash: HashT> {
/// The parent hash.
pub parent_hash: Hash::Output,
/// The block number.
#[cfg_attr(feature = "std", serde(
serialize_with = "serialize_number",
deserialize_with = "deserialize_number"))]
#[cfg_attr(
feature = "std",
serde(serialize_with = "serialize_number", deserialize_with = "deserialize_number")
)]
pub number: Number,
/// The state trie merkle root
pub state_root: Hash::Output,
@@ -71,21 +70,27 @@ where
#[cfg(feature = "std")]
pub fn serialize_number<S, T: Copy + Into<U256> + TryFrom<U256>>(
val: &T, s: S,
) -> Result<S::Ok, S::Error> where S: serde::Serializer {
val: &T,
s: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let u256: U256 = (*val).into();
serde::Serialize::serialize(&u256, s)
}
#[cfg(feature = "std")]
pub fn deserialize_number<'a, D, T: Copy + Into<U256> + TryFrom<U256>>(
d: D,
) -> Result<T, D::Error> where D: serde::Deserializer<'a> {
pub fn deserialize_number<'a, D, T: Copy + Into<U256> + TryFrom<U256>>(d: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'a>,
{
let u256: U256 = serde::Deserialize::deserialize(d)?;
TryFrom::try_from(u256).map_err(|_| serde::de::Error::custom("Try from failed"))
}
impl<Number, Hash> Decode for Header<Number, Hash> where
impl<Number, Hash> Decode for Header<Number, Hash>
where
Number: HasCompact + Copy + Into<U256> + TryFrom<U256>,
Hash: HashT,
Hash::Output: Decode,
@@ -101,51 +106,92 @@ impl<Number, Hash> Decode for Header<Number, Hash> where
}
}
impl<Number, Hash> Encode for Header<Number, Hash> where
impl<Number, Hash> Encode for Header<Number, Hash>
where
Number: HasCompact + Copy + Into<U256> + TryFrom<U256>,
Hash: HashT,
Hash::Output: Encode,
{
fn encode_to<T: Output + ?Sized>(&self, dest: &mut T) {
self.parent_hash.encode_to(dest);
<<<Number as HasCompact>::Type as EncodeAsRef<_>>::RefType>::from(&self.number).encode_to(dest);
<<<Number as HasCompact>::Type as EncodeAsRef<_>>::RefType>::from(&self.number)
.encode_to(dest);
self.state_root.encode_to(dest);
self.extrinsics_root.encode_to(dest);
self.digest.encode_to(dest);
}
}
impl<Number, Hash> codec::EncodeLike for Header<Number, Hash> where
impl<Number, Hash> codec::EncodeLike for Header<Number, Hash>
where
Number: HasCompact + Copy + Into<U256> + TryFrom<U256>,
Hash: HashT,
Hash::Output: Encode,
{}
{
}
impl<Number, Hash> traits::Header for Header<Number, Hash> where
Number: Member + MaybeSerializeDeserialize + Debug + sp_std::hash::Hash + MaybeDisplay +
AtLeast32BitUnsigned + Codec + Copy + Into<U256> + TryFrom<U256> + sp_std::str::FromStr +
MaybeMallocSizeOf,
impl<Number, Hash> traits::Header for Header<Number, Hash>
where
Number: Member
+ MaybeSerializeDeserialize
+ Debug
+ sp_std::hash::Hash
+ MaybeDisplay
+ AtLeast32BitUnsigned
+ Codec
+ Copy
+ Into<U256>
+ TryFrom<U256>
+ sp_std::str::FromStr
+ MaybeMallocSizeOf,
Hash: HashT,
Hash::Output: Default + sp_std::hash::Hash + Copy + Member + Ord +
MaybeSerialize + Debug + MaybeDisplay + SimpleBitOps + Codec + MaybeMallocSizeOf,
Hash::Output: Default
+ sp_std::hash::Hash
+ Copy
+ Member
+ Ord
+ MaybeSerialize
+ Debug
+ MaybeDisplay
+ SimpleBitOps
+ Codec
+ MaybeMallocSizeOf,
{
type Number = Number;
type Hash = <Hash as HashT>::Output;
type Hashing = Hash;
fn number(&self) -> &Self::Number { &self.number }
fn set_number(&mut self, num: Self::Number) { self.number = num }
fn number(&self) -> &Self::Number {
&self.number
}
fn set_number(&mut self, num: Self::Number) {
self.number = num
}
fn extrinsics_root(&self) -> &Self::Hash { &self.extrinsics_root }
fn set_extrinsics_root(&mut self, root: Self::Hash) { self.extrinsics_root = root }
fn extrinsics_root(&self) -> &Self::Hash {
&self.extrinsics_root
}
fn set_extrinsics_root(&mut self, root: Self::Hash) {
self.extrinsics_root = root
}
fn state_root(&self) -> &Self::Hash { &self.state_root }
fn set_state_root(&mut self, root: Self::Hash) { self.state_root = root }
fn state_root(&self) -> &Self::Hash {
&self.state_root
}
fn set_state_root(&mut self, root: Self::Hash) {
self.state_root = root
}
fn parent_hash(&self) -> &Self::Hash { &self.parent_hash }
fn set_parent_hash(&mut self, hash: Self::Hash) { self.parent_hash = hash }
fn parent_hash(&self) -> &Self::Hash {
&self.parent_hash
}
fn set_parent_hash(&mut self, hash: Self::Hash) {
self.parent_hash = hash
}
fn digest(&self) -> &Digest<Self::Hash> { &self.digest }
fn digest(&self) -> &Digest<Self::Hash> {
&self.digest
}
fn digest_mut(&mut self) -> &mut Digest<Self::Hash> {
#[cfg(feature = "std")]
@@ -160,22 +206,24 @@ impl<Number, Hash> traits::Header for Header<Number, Hash> where
parent_hash: Self::Hash,
digest: Digest<Self::Hash>,
) -> Self {
Self {
number,
extrinsics_root,
state_root,
parent_hash,
digest,
}
Self { number, extrinsics_root, state_root, parent_hash, digest }
}
}
impl<Number, Hash> Header<Number, Hash> where
Number: Member + sp_std::hash::Hash + Copy + MaybeDisplay + AtLeast32BitUnsigned + Codec +
Into<U256> + TryFrom<U256>,
impl<Number, Hash> Header<Number, Hash>
where
Number: Member
+ sp_std::hash::Hash
+ Copy
+ MaybeDisplay
+ AtLeast32BitUnsigned
+ Codec
+ Into<U256>
+ TryFrom<U256>,
Hash: HashT,
Hash::Output: Default + sp_std::hash::Hash + Copy + Member + MaybeDisplay + SimpleBitOps + Codec,
{
Hash::Output:
Default + sp_std::hash::Hash + Copy + Member + MaybeDisplay + SimpleBitOps + Codec,
{
/// Convenience helper for computing the hash of the header without having
/// to import the trait.
pub fn hash(&self) -> Hash::Output {
+11 -11
View File
@@ -19,22 +19,22 @@
//! Generic implementations of Extrinsic/Header/Block.
// end::description[]
mod unchecked_extrinsic;
mod era;
mod checked_extrinsic;
mod header;
mod block;
mod checked_extrinsic;
mod digest;
mod era;
mod header;
#[cfg(test)]
mod tests;
mod unchecked_extrinsic;
pub use self::unchecked_extrinsic::{UncheckedExtrinsic, SignedPayload};
pub use self::era::{Era, Phase};
pub use self::checked_extrinsic::CheckedExtrinsic;
pub use self::header::Header;
pub use self::block::{Block, SignedBlock, BlockId};
pub use self::digest::{
Digest, DigestItem, DigestItemRef, OpaqueDigestItemId, ChangesTrieSignal,
pub use self::{
block::{Block, BlockId, SignedBlock},
checked_extrinsic::CheckedExtrinsic,
digest::{ChangesTrieSignal, Digest, DigestItem, DigestItemRef, OpaqueDigestItemId},
era::{Era, Phase},
header::Header,
unchecked_extrinsic::{SignedPayload, UncheckedExtrinsic},
};
use crate::codec::Encode;
@@ -17,27 +17,23 @@
//! Tests for the generic implementations of Extrinsic/Header/Block.
use super::DigestItem;
use crate::codec::{Decode, Encode};
use sp_core::H256;
use super::DigestItem;
#[test]
fn system_digest_item_encoding() {
let item = DigestItem::ChangesTrieRoot::<H256>(H256::default());
let encoded = item.encode();
assert_eq!(encoded, vec![
// type = DigestItemType::ChangesTrieRoot
2,
// trie root
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
]);
assert_eq!(
encoded,
vec![
// type = DigestItemType::ChangesTrieRoot
2, // trie root
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,
]
);
let decoded: DigestItem<H256> = Decode::decode(&mut &encoded[..]).unwrap();
assert_eq!(item, decoded);
@@ -47,14 +43,15 @@ fn system_digest_item_encoding() {
fn non_system_digest_item_encoding() {
let item = DigestItem::Other::<H256>(vec![10, 20, 30]);
let encoded = item.encode();
assert_eq!(encoded, vec![
// type = DigestItemType::Other
0,
// length of other data
12,
// authorities
10, 20, 30,
]);
assert_eq!(
encoded,
vec![
// type = DigestItemType::Other
0, // length of other data
12, // authorities
10, 20, 30,
]
);
let decoded: DigestItem<H256> = Decode::decode(&mut &encoded[..]).unwrap();
assert_eq!(item, decoded);
@@ -17,18 +17,18 @@
//! Generic implementation of an unchecked (pre-verification) extrinsic.
use sp_std::{fmt, prelude::*};
use sp_io::hashing::blake2_256;
use codec::{Decode, Encode, EncodeLike, Input, Error};
use crate::{
traits::{
self, Member, MaybeDisplay, SignedExtension, Checkable, Extrinsic, ExtrinsicMetadata,
IdentifyAccount,
},
generic::CheckedExtrinsic,
transaction_validity::{TransactionValidityError, InvalidTransaction},
traits::{
self, Checkable, Extrinsic, ExtrinsicMetadata, IdentifyAccount, MaybeDisplay, Member,
SignedExtension,
},
transaction_validity::{InvalidTransaction, TransactionValidityError},
OpaqueExtrinsic,
};
use codec::{Decode, Encode, EncodeLike, Error, Input};
use sp_io::hashing::blake2_256;
use sp_std::{fmt, prelude::*};
/// Current version of the [`UncheckedExtrinsic`] format.
const EXTRINSIC_VERSION: u8 = 4;
@@ -38,7 +38,7 @@ const EXTRINSIC_VERSION: u8 = 4;
#[derive(PartialEq, Eq, Clone)]
pub struct UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Extra: SignedExtension
Extra: SignedExtension,
{
/// The signature, address, number of extrinsics have come before from
/// the same signer and an era describing the longevity of this transaction,
@@ -52,7 +52,7 @@ where
impl<Address, Call, Signature, Extra> parity_util_mem::MallocSizeOf
for UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Extra: SignedExtension
Extra: SignedExtension,
{
fn size_of(&self, _ops: &mut parity_util_mem::MallocSizeOfOps) -> usize {
// Instantiated only in runtime.
@@ -64,24 +64,13 @@ impl<Address, Call, Signature, Extra: SignedExtension>
UncheckedExtrinsic<Address, Call, Signature, Extra>
{
/// New instance of a signed extrinsic aka "transaction".
pub fn new_signed(
function: Call,
signed: Address,
signature: Signature,
extra: Extra
) -> Self {
Self {
signature: Some((signed, signature, extra)),
function,
}
pub fn new_signed(function: Call, signed: Address, signature: Signature, extra: Extra) -> Self {
Self { signature: Some((signed, signature, extra)), function }
}
/// New instance of an unsigned extrinsic aka "inherent".
pub fn new_unsigned(function: Call) -> Self {
Self {
signature: None,
function,
}
Self { signature: None, function }
}
}
@@ -90,11 +79,7 @@ impl<Address, Call, Signature, Extra: SignedExtension> Extrinsic
{
type Call = Call;
type SignaturePayload = (
Address,
Signature,
Extra,
);
type SignaturePayload = (Address, Signature, Extra);
fn is_signed(&self) -> Option<bool> {
Some(self.signature.is_some())
@@ -109,18 +94,16 @@ impl<Address, Call, Signature, Extra: SignedExtension> Extrinsic
}
}
impl<Address, AccountId, Call, Signature, Extra, Lookup>
Checkable<Lookup>
for
UncheckedExtrinsic<Address, Call, Signature, Extra>
impl<Address, AccountId, Call, Signature, Extra, Lookup> Checkable<Lookup>
for UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Address: Member + MaybeDisplay,
Call: Encode + Member,
Signature: Member + traits::Verify,
<Signature as traits::Verify>::Signer: IdentifyAccount<AccountId=AccountId>,
Extra: SignedExtension<AccountId=AccountId>,
<Signature as traits::Verify>::Signer: IdentifyAccount<AccountId = AccountId>,
Extra: SignedExtension<AccountId = AccountId>,
AccountId: Member + MaybeDisplay,
Lookup: traits::Lookup<Source=Address, Target=AccountId>,
Lookup: traits::Lookup<Source = Address, Target = AccountId>,
{
type Checked = CheckedExtrinsic<AccountId, Call, Extra>;
@@ -134,23 +117,17 @@ where
}
let (function, extra, _) = raw_payload.deconstruct();
CheckedExtrinsic {
signed: Some((signed, extra)),
function,
}
}
None => CheckedExtrinsic {
signed: None,
function: self.function,
CheckedExtrinsic { signed: Some((signed, extra)), function }
},
None => CheckedExtrinsic { signed: None, function: self.function },
})
}
}
impl<Address, Call, Signature, Extra> ExtrinsicMetadata
for UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Extra: SignedExtension,
where
Extra: SignedExtension,
{
const VERSION: u8 = EXTRINSIC_VERSION;
type SignedExtensions = Extra;
@@ -161,13 +138,10 @@ impl<Address, Call, Signature, Extra> ExtrinsicMetadata
/// Note that the payload that we sign to produce unchecked extrinsic signature
/// is going to be different than the `SignaturePayload` - so the thing the extrinsic
/// actually contains.
pub struct SignedPayload<Call, Extra: SignedExtension>((
Call,
Extra,
Extra::AdditionalSigned,
));
pub struct SignedPayload<Call, Extra: SignedExtension>((Call, Extra, Extra::AdditionalSigned));
impl<Call, Extra> SignedPayload<Call, Extra> where
impl<Call, Extra> SignedPayload<Call, Extra>
where
Call: Encode,
Extra: SignedExtension,
{
@@ -191,7 +165,8 @@ impl<Call, Extra> SignedPayload<Call, Extra> where
}
}
impl<Call, Extra> Encode for SignedPayload<Call, Extra> where
impl<Call, Extra> Encode for SignedPayload<Call, Extra>
where
Call: Encode,
Extra: SignedExtension,
{
@@ -213,10 +188,10 @@ impl<Call, Extra> EncodeLike for SignedPayload<Call, Extra>
where
Call: Encode,
Extra: SignedExtension,
{}
{
}
impl<Address, Call, Signature, Extra> Decode
for UncheckedExtrinsic<Address, Call, Signature, Extra>
impl<Address, Call, Signature, Extra> Decode for UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Address: Decode,
Signature: Decode,
@@ -235,7 +210,7 @@ where
let is_signed = version & 0b1000_0000 != 0;
let version = version & 0b0111_1111;
if version != EXTRINSIC_VERSION {
return Err("Invalid transaction version".into());
return Err("Invalid transaction version".into())
}
Ok(Self {
@@ -245,8 +220,7 @@ where
}
}
impl<Address, Call, Signature, Extra> Encode
for UncheckedExtrinsic<Address, Call, Signature, Extra>
impl<Address, Call, Signature, Extra> Encode for UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Address: Encode,
Signature: Encode,
@@ -260,10 +234,10 @@ where
Some(s) => {
v.push(EXTRINSIC_VERSION | 0b1000_0000);
s.encode_to(v);
}
},
None => {
v.push(EXTRINSIC_VERSION & 0b0111_1111);
}
},
}
self.function.encode_to(v);
})
@@ -277,22 +251,27 @@ where
Signature: Encode,
Call: Encode,
Extra: SignedExtension,
{}
{
}
#[cfg(feature = "std")]
impl<Address: Encode, Signature: Encode, Call: Encode, Extra: SignedExtension> serde::Serialize
for UncheckedExtrinsic<Address, Call, Signature, Extra>
{
fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer {
fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error>
where
S: ::serde::Serializer,
{
self.using_encoded(|bytes| seq.serialize_bytes(bytes))
}
}
#[cfg(feature = "std")]
impl<'a, Address: Decode, Signature: Decode, Call: Decode, Extra: SignedExtension> serde::Deserialize<'a>
for UncheckedExtrinsic<Address, Call, Signature, Extra>
impl<'a, Address: Decode, Signature: Decode, Call: Decode, Extra: SignedExtension>
serde::Deserialize<'a> for UncheckedExtrinsic<Address, Call, Signature, Extra>
{
fn deserialize<D>(de: D) -> Result<Self, D::Error> where
fn deserialize<D>(de: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'a>,
{
let r = sp_core::bytes::deserialize(de)?;
@@ -327,21 +306,22 @@ where
Extra: SignedExtension,
{
fn from(extrinsic: UncheckedExtrinsic<Address, Call, Signature, Extra>) -> Self {
Self::from_bytes(extrinsic.encode().as_slice())
.expect(
"both OpaqueExtrinsic and UncheckedExtrinsic have encoding that is compatible with \
raw Vec<u8> encoding; qed"
)
Self::from_bytes(extrinsic.encode().as_slice()).expect(
"both OpaqueExtrinsic and UncheckedExtrinsic have encoding that is compatible with \
raw Vec<u8> encoding; qed",
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
codec::{Decode, Encode},
testing::TestSignature as TestSig,
traits::{IdentityLookup, SignedExtension},
};
use sp_io::hashing::blake2_256;
use crate::codec::{Encode, Decode};
use crate::traits::{SignedExtension, IdentityLookup};
use crate::testing::TestSignature as TestSig;
type TestContext = IdentityLookup<u64>;
type TestAccountId = u64;
@@ -359,7 +339,9 @@ mod tests {
type AdditionalSigned = ();
type Pre = ();
fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }
fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {
Ok(())
}
}
type Ex = UncheckedExtrinsic<TestAccountId, TestCall, TestSig, TestExtra>;
@@ -378,7 +360,7 @@ mod tests {
vec![0u8; 0],
TEST_ACCOUNT,
TestSig(TEST_ACCOUNT, (vec![0u8; 0], TestExtra).encode()),
TestExtra
TestExtra,
);
let encoded = ux.encode();
assert_eq!(Ex::decode(&mut &encoded[..]), Ok(ux));
@@ -389,9 +371,11 @@ mod tests {
let ux = Ex::new_signed(
vec![0u8; 0],
TEST_ACCOUNT,
TestSig(TEST_ACCOUNT, (vec![0u8; 257], TestExtra)
.using_encoded(blake2_256)[..].to_owned()),
TestExtra
TestSig(
TEST_ACCOUNT,
(vec![0u8; 257], TestExtra).using_encoded(blake2_256)[..].to_owned(),
),
TestExtra,
);
let encoded = ux.encode();
assert_eq!(Ex::decode(&mut &encoded[..]), Ok(ux));