mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-04-27 17:28:00 +00:00
Rename folder: primitives/sr-primitives -> primitives/runtime (#4280)
* primitives/sr-primitives -> primitives/runtime * update
This commit is contained in:
committed by
Bastian Köcher
parent
94b6921d03
commit
04fcc71809
@@ -0,0 +1,112 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Generic implementation of a block and associated items.
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use std::fmt;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use rstd::prelude::*;
|
||||
use primitives::RuntimeDebug;
|
||||
use crate::codec::{Codec, Encode, Decode};
|
||||
use crate::traits::{self, Member, Block as BlockT, Header as HeaderT, MaybeSerialize};
|
||||
use crate::Justification;
|
||||
|
||||
/// Something to identify a block.
|
||||
#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize))]
|
||||
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
|
||||
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
|
||||
pub enum BlockId<Block: BlockT> {
|
||||
/// Identify by block header hash.
|
||||
Hash(<<Block as BlockT>::Header as HeaderT>::Hash),
|
||||
/// Identify by block number.
|
||||
Number(<<Block as BlockT>::Header as HeaderT>::Number),
|
||||
}
|
||||
|
||||
impl<Block: BlockT> BlockId<Block> {
|
||||
/// Create a block ID from a hash.
|
||||
pub fn hash(hash: Block::Hash) -> Self {
|
||||
BlockId::Hash(hash)
|
||||
}
|
||||
|
||||
/// Create a block ID from a number.
|
||||
pub fn number(number: <Block::Header as HeaderT>::Number) -> Self {
|
||||
BlockId::Number(number)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Block: BlockT> Copy for BlockId<Block> {}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<Block: BlockT> fmt::Display for BlockId<Block> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{:?}", self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Abstraction over a substrate block.
|
||||
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
|
||||
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
|
||||
pub struct Block<Header, Extrinsic: MaybeSerialize> {
|
||||
/// The block header.
|
||||
pub header: Header,
|
||||
/// The accompanying extrinsics.
|
||||
pub extrinsics: Vec<Extrinsic>,
|
||||
}
|
||||
|
||||
impl<Header, Extrinsic: MaybeSerialize> traits::Block for Block<Header, Extrinsic>
|
||||
where
|
||||
Header: HeaderT,
|
||||
Extrinsic: Member + Codec + traits::Extrinsic,
|
||||
{
|
||||
type Extrinsic = Extrinsic;
|
||||
type Header = Header;
|
||||
type Hash = <Self::Header as traits::Header>::Hash;
|
||||
|
||||
fn header(&self) -> &Self::Header {
|
||||
&self.header
|
||||
}
|
||||
fn extrinsics(&self) -> &[Self::Extrinsic] {
|
||||
&self.extrinsics[..]
|
||||
}
|
||||
fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>) {
|
||||
(self.header, self.extrinsics)
|
||||
}
|
||||
fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self {
|
||||
Block { header, extrinsics }
|
||||
}
|
||||
fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8> {
|
||||
(header, extrinsics).encode()
|
||||
}
|
||||
}
|
||||
|
||||
/// Abstraction over a substrate block and justification.
|
||||
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
|
||||
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
|
||||
pub struct SignedBlock<Block> {
|
||||
/// Full block.
|
||||
pub block: Block,
|
||||
/// Block justification.
|
||||
pub justification: Option<Justification>,
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Generic implementation of an extrinsic that has passed the verification
|
||||
//! stage.
|
||||
|
||||
use crate::traits::{
|
||||
self, Member, MaybeDisplay, SignedExtension, Dispatchable,
|
||||
};
|
||||
#[allow(deprecated)]
|
||||
use crate::traits::ValidateUnsigned;
|
||||
use crate::transaction_validity::TransactionValidity;
|
||||
|
||||
/// Definition of something that the external world might want to say; its
|
||||
/// existence implies that it has been checked and is good, particularly with
|
||||
/// regards to the signature.
|
||||
#[derive(PartialEq, Eq, Clone, primitives::RuntimeDebug)]
|
||||
pub struct CheckedExtrinsic<AccountId, Call, Extra> {
|
||||
/// Who this purports to be from and the number of extrinsics have come before
|
||||
/// from the same signer, if anyone (note this is not a signature).
|
||||
pub signed: Option<(AccountId, Extra)>,
|
||||
|
||||
/// The function that should be called.
|
||||
pub function: Call,
|
||||
}
|
||||
|
||||
impl<AccountId, Call, Extra, Origin, Info> traits::Applyable for
|
||||
CheckedExtrinsic<AccountId, Call, Extra>
|
||||
where
|
||||
AccountId: Member + MaybeDisplay,
|
||||
Call: Member + Dispatchable<Origin=Origin>,
|
||||
Extra: SignedExtension<AccountId=AccountId, Call=Call, DispatchInfo=Info>,
|
||||
Origin: From<Option<AccountId>>,
|
||||
Info: Clone,
|
||||
{
|
||||
type AccountId = AccountId;
|
||||
type Call = Call;
|
||||
type DispatchInfo = Info;
|
||||
|
||||
fn sender(&self) -> Option<&Self::AccountId> {
|
||||
self.signed.as_ref().map(|x| &x.0)
|
||||
}
|
||||
|
||||
#[allow(deprecated)] // Allow ValidateUnsigned
|
||||
fn validate<U: ValidateUnsigned<Call = Self::Call>>(
|
||||
&self,
|
||||
info: Self::DispatchInfo,
|
||||
len: usize,
|
||||
) -> TransactionValidity {
|
||||
if let Some((ref id, ref extra)) = self.signed {
|
||||
Extra::validate(extra, id, &self.function, info.clone(), len)
|
||||
} else {
|
||||
let valid = Extra::validate_unsigned(&self.function, info, len)?;
|
||||
let unsigned_validation = U::validate_unsigned(&self.function)?;
|
||||
Ok(valid.combine_with(unsigned_validation))
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(deprecated)] // Allow ValidateUnsigned
|
||||
fn apply<U: ValidateUnsigned<Call=Self::Call>>(
|
||||
self,
|
||||
info: Self::DispatchInfo,
|
||||
len: usize,
|
||||
) -> 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)
|
||||
} else {
|
||||
let pre = Extra::pre_dispatch_unsigned(&self.function, info.clone(), len)?;
|
||||
U::pre_dispatch(&self.function)?;
|
||||
(None, pre)
|
||||
};
|
||||
let res = self.function.dispatch(Origin::from(maybe_who));
|
||||
Extra::post_dispatch(pre, info.clone(), len);
|
||||
Ok(res.map_err(Into::into))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Generic implementation of a digest.
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use rstd::prelude::*;
|
||||
|
||||
use crate::ConsensusEngineId;
|
||||
use crate::codec::{Decode, Encode, Input, Error};
|
||||
use primitives::RuntimeDebug;
|
||||
|
||||
/// Generic header digest.
|
||||
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct Digest<Hash: Encode + Decode> {
|
||||
/// A list of logs in the digest.
|
||||
pub logs: Vec<DigestItem<Hash>>,
|
||||
}
|
||||
|
||||
impl<Item: Encode + Decode> Default for Digest<Item> {
|
||||
fn default() -> Self {
|
||||
Digest { logs: Vec::new(), }
|
||||
}
|
||||
}
|
||||
|
||||
impl<Hash: Encode + Decode> Digest<Hash> {
|
||||
/// Get reference to all digest items.
|
||||
pub fn logs(&self) -> &[DigestItem<Hash>] {
|
||||
&self.logs
|
||||
}
|
||||
|
||||
/// Push new digest item.
|
||||
pub fn push(&mut self, item: DigestItem<Hash>) {
|
||||
self.logs.push(item);
|
||||
}
|
||||
|
||||
/// Pop a digest item.
|
||||
pub fn pop(&mut self) -> Option<DigestItem<Hash>> {
|
||||
self.logs.pop()
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
self.logs().iter()
|
||||
.filter_map(predicate)
|
||||
.next()
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
self.logs().iter()
|
||||
.filter_map(predicate)
|
||||
.next()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Digest item that is able to encode/decode 'system' digest items and
|
||||
/// provide opaque access to other items.
|
||||
#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
|
||||
pub enum DigestItem<Hash> {
|
||||
/// System digest item that contains the root of changes trie at given
|
||||
/// block. It is created for every block iff runtime supports changes
|
||||
/// trie creation.
|
||||
ChangesTrieRoot(Hash),
|
||||
|
||||
/// A pre-runtime digest.
|
||||
///
|
||||
/// These are messages from the consensus engine to the runtime, although
|
||||
/// the consensus engine can (and should) read them itself to avoid
|
||||
/// code and state duplication. It is erroneous for a runtime to produce
|
||||
/// these, but this is not (yet) checked.
|
||||
PreRuntime(ConsensusEngineId, Vec<u8>),
|
||||
|
||||
/// A message from the runtime to the consensus engine. This should *never*
|
||||
/// be generated by the native code of any consensus engine, but this is not
|
||||
/// checked (yet).
|
||||
Consensus(ConsensusEngineId, Vec<u8>),
|
||||
|
||||
/// Put a Seal on it. This is only used by native code, and is never seen
|
||||
/// by runtimes.
|
||||
Seal(ConsensusEngineId, Vec<u8>),
|
||||
|
||||
/// Some other thing. Unsupported and experimental.
|
||||
Other(Vec<u8>),
|
||||
}
|
||||
|
||||
#[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| {
|
||||
primitives::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
|
||||
D: serde::Deserializer<'a>,
|
||||
{
|
||||
let r = primitives::bytes::deserialize(de)?;
|
||||
Decode::decode(&mut &r[..])
|
||||
.map_err(|e| serde::de::Error::custom(format!("Decode error: {}", e)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A 'referencing view' for digest item. Does not own its contents. Used by
|
||||
/// final runtime implementations for encoding/decoding its log items.
|
||||
#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
|
||||
pub enum DigestItemRef<'a, Hash: 'a> {
|
||||
/// Reference to `DigestItem::ChangesTrieRoot`.
|
||||
ChangesTrieRoot(&'a Hash),
|
||||
/// A pre-runtime digest.
|
||||
///
|
||||
/// These are messages from the consensus engine to the runtime, although
|
||||
/// the consensus engine can (and should) read them itself to avoid
|
||||
/// code and state duplication. It is erroneous for a runtime to produce
|
||||
/// these, but this is not (yet) checked.
|
||||
PreRuntime(&'a ConsensusEngineId, &'a Vec<u8>),
|
||||
/// A message from the runtime to the consensus engine. This should *never*
|
||||
/// be generated by the native code of any consensus engine, but this is not
|
||||
/// checked (yet).
|
||||
Consensus(&'a ConsensusEngineId, &'a Vec<u8>),
|
||||
/// Put a Seal on it. This is only used by native code, and is never seen
|
||||
/// by runtimes.
|
||||
Seal(&'a ConsensusEngineId, &'a Vec<u8>),
|
||||
/// Any 'non-system' digest item, opaque to the native code.
|
||||
Other(&'a Vec<u8>),
|
||||
}
|
||||
|
||||
/// Type of the digest item. Used to gain explicit control over `DigestItem` encoding
|
||||
/// process. We need an explicit control, because final runtimes are encoding their own
|
||||
/// digest items using `DigestItemRef` type and we can't auto-derive `Decode`
|
||||
/// trait for `DigestItemRef`.
|
||||
#[repr(u32)]
|
||||
#[derive(Encode, Decode)]
|
||||
pub enum DigestItemType {
|
||||
ChangesTrieRoot = 2,
|
||||
PreRuntime = 6,
|
||||
Consensus = 4,
|
||||
Seal = 5,
|
||||
Other = 0,
|
||||
}
|
||||
|
||||
/// Type of a digest item that contains raw data; this also names the consensus engine ID where
|
||||
/// applicable. Used to identify one or more digest items of interest.
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
|
||||
pub enum OpaqueDigestItemId<'a> {
|
||||
/// Type corresponding to DigestItem::PreRuntime.
|
||||
PreRuntime(&'a ConsensusEngineId),
|
||||
/// Type corresponding to DigestItem::Consensus.
|
||||
Consensus(&'a ConsensusEngineId),
|
||||
/// Type corresponding to DigestItem::Seal.
|
||||
Seal(&'a ConsensusEngineId),
|
||||
/// Some other (non-prescribed) type.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl<Hash> DigestItem<Hash> {
|
||||
/// Returns a 'referencing view' for this digest item.
|
||||
pub fn dref<'a>(&'a self) -> DigestItemRef<'a, Hash> {
|
||||
match *self {
|
||||
DigestItem::ChangesTrieRoot(ref v) => DigestItemRef::ChangesTrieRoot(v),
|
||||
DigestItem::PreRuntime(ref v, ref s) => DigestItemRef::PreRuntime(v, s),
|
||||
DigestItem::Consensus(ref v, ref s) => DigestItemRef::Consensus(v, s),
|
||||
DigestItem::Seal(ref v, ref s) => DigestItemRef::Seal(v, s),
|
||||
DigestItem::Other(ref v) => DigestItemRef::Other(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `Some` if the entry is the `ChangesTrieRoot` entry.
|
||||
pub fn as_changes_trie_root(&self) -> Option<&Hash> {
|
||||
self.dref().as_changes_trie_root()
|
||||
}
|
||||
|
||||
/// Returns `Some` if this entry is the `PreRuntime` entry.
|
||||
pub fn as_pre_runtime(&self) -> Option<(ConsensusEngineId, &[u8])> {
|
||||
self.dref().as_pre_runtime()
|
||||
}
|
||||
|
||||
/// Returns `Some` if this entry is the `Consensus` entry.
|
||||
pub fn as_consensus(&self) -> Option<(ConsensusEngineId, &[u8])> {
|
||||
self.dref().as_consensus()
|
||||
}
|
||||
|
||||
/// Returns `Some` if this entry is the `Seal` entry.
|
||||
pub fn as_seal(&self) -> Option<(ConsensusEngineId, &[u8])> {
|
||||
self.dref().as_seal()
|
||||
}
|
||||
|
||||
/// Returns Some if `self` is a `DigestItem::Other`.
|
||||
pub fn as_other(&self) -> Option<&[u8]> {
|
||||
match *self {
|
||||
DigestItem::Other(ref v) => Some(&v[..]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the opaque data contained in the item if `Some` if this entry has the id given.
|
||||
pub fn try_as_raw(&self, id: OpaqueDigestItemId) -> Option<&[u8]> {
|
||||
self.dref().try_as_raw(id)
|
||||
}
|
||||
|
||||
/// Returns the data contained in the item if `Some` if this entry has the id given, decoded
|
||||
/// to the type provided `T`.
|
||||
pub fn try_to<T: Decode>(&self, id: OpaqueDigestItemId) -> Option<T> {
|
||||
self.dref().try_to::<T>(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Hash: Encode> Encode for DigestItem<Hash> {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
self.dref().encode()
|
||||
}
|
||||
}
|
||||
|
||||
impl<Hash: Encode> codec::EncodeLike for DigestItem<Hash> {}
|
||||
|
||||
impl<Hash: Decode> Decode for DigestItem<Hash> {
|
||||
#[allow(deprecated)]
|
||||
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
|
||||
let item_type: DigestItemType = Decode::decode(input)?;
|
||||
match item_type {
|
||||
DigestItemType::ChangesTrieRoot => Ok(DigestItem::ChangesTrieRoot(
|
||||
Decode::decode(input)?,
|
||||
)),
|
||||
DigestItemType::PreRuntime => {
|
||||
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
|
||||
Ok(DigestItem::PreRuntime(vals.0, vals.1))
|
||||
},
|
||||
DigestItemType::Consensus => {
|
||||
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
|
||||
Ok(DigestItem::Consensus(vals.0, vals.1))
|
||||
}
|
||||
DigestItemType::Seal => {
|
||||
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
|
||||
Ok(DigestItem::Seal(vals.0, vals.1))
|
||||
},
|
||||
DigestItemType::Other => Ok(DigestItem::Other(
|
||||
Decode::decode(input)?,
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Hash> DigestItemRef<'a, Hash> {
|
||||
/// Cast this digest item into `ChangesTrieRoot`.
|
||||
pub fn as_changes_trie_root(&self) -> Option<&'a Hash> {
|
||||
match *self {
|
||||
DigestItemRef::ChangesTrieRoot(ref changes_trie_root) => Some(changes_trie_root),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast this digest item into `PreRuntime`
|
||||
pub fn as_pre_runtime(&self) -> Option<(ConsensusEngineId, &'a [u8])> {
|
||||
match *self {
|
||||
DigestItemRef::PreRuntime(consensus_engine_id, ref data) => Some((*consensus_engine_id, data)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast this digest item into `Consensus`
|
||||
pub fn as_consensus(&self) -> Option<(ConsensusEngineId, &'a [u8])> {
|
||||
match *self {
|
||||
DigestItemRef::Consensus(consensus_engine_id, ref data) => Some((*consensus_engine_id, data)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast this digest item into `Seal`
|
||||
pub fn as_seal(&self) -> Option<(ConsensusEngineId, &'a [u8])> {
|
||||
match *self {
|
||||
DigestItemRef::Seal(consensus_engine_id, ref data) => Some((*consensus_engine_id, data)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Cast this digest item into `PreRuntime`
|
||||
pub fn as_other(&self) -> Option<&'a [u8]> {
|
||||
match *self {
|
||||
DigestItemRef::Other(ref data) => Some(data),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to match this digest item to the given opaque item identifier; if it matches, then
|
||||
/// return the opaque data it contains.
|
||||
pub fn try_as_raw(&self, id: OpaqueDigestItemId) -> Option<&'a [u8]> {
|
||||
match (id, self) {
|
||||
(OpaqueDigestItemId::Consensus(w), &DigestItemRef::Consensus(v, s)) |
|
||||
(OpaqueDigestItemId::Seal(w), &DigestItemRef::Seal(v, s)) |
|
||||
(OpaqueDigestItemId::PreRuntime(w), &DigestItemRef::PreRuntime(v, s))
|
||||
if v == w => Some(&s[..]),
|
||||
(OpaqueDigestItemId::Other, &DigestItemRef::Other(s)) => Some(&s[..]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to match this digest item to the given opaque item identifier; if it matches, then
|
||||
/// try to cast to the given datatype; if that works, return it.
|
||||
pub fn try_to<T: Decode>(&self, id: OpaqueDigestItemId) -> Option<T> {
|
||||
self.try_as_raw(id).and_then(|mut x| Decode::decode(&mut x).ok())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Hash: Encode> Encode for DigestItemRef<'a, Hash> {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
|
||||
match *self {
|
||||
DigestItemRef::ChangesTrieRoot(changes_trie_root) => {
|
||||
DigestItemType::ChangesTrieRoot.encode_to(&mut v);
|
||||
changes_trie_root.encode_to(&mut v);
|
||||
},
|
||||
DigestItemRef::Consensus(val, data) => {
|
||||
DigestItemType::Consensus.encode_to(&mut v);
|
||||
(val, data).encode_to(&mut v);
|
||||
},
|
||||
DigestItemRef::Seal(val, sig) => {
|
||||
DigestItemType::Seal.encode_to(&mut v);
|
||||
(val, sig).encode_to(&mut v);
|
||||
},
|
||||
DigestItemRef::PreRuntime(val, data) => {
|
||||
DigestItemType::PreRuntime.encode_to(&mut v);
|
||||
(val, data).encode_to(&mut v);
|
||||
},
|
||||
DigestItemRef::Other(val) => {
|
||||
DigestItemType::Other.encode_to(&mut v);
|
||||
val.encode_to(&mut v);
|
||||
},
|
||||
}
|
||||
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Hash: Encode> codec::EncodeLike for DigestItemRef<'a, Hash> {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn should_serialize_digest() {
|
||||
let digest = Digest {
|
||||
logs: vec![
|
||||
DigestItem::ChangesTrieRoot(4),
|
||||
DigestItem::Other(vec![1, 2, 3]),
|
||||
DigestItem::Seal(*b"test", vec![1, 2, 3])
|
||||
],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
::serde_json::to_string(&digest).unwrap(),
|
||||
r#"{"logs":["0x0204000000","0x000c010203","0x05746573740c010203"]}"#
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Generic implementation of an unchecked (pre-verification) extrinsic.
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
use crate::codec::{Decode, Encode, Input, Output, Error};
|
||||
|
||||
/// Era period
|
||||
pub type Period = u64;
|
||||
|
||||
/// Era phase
|
||||
pub type Phase = u64;
|
||||
|
||||
/// An era to describe the longevity of a transaction.
|
||||
#[derive(PartialEq, Eq, Clone, Copy, primitives::RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub enum Era {
|
||||
/// The transaction is valid forever. The genesis hash must be present in the signed content.
|
||||
Immortal,
|
||||
|
||||
/// Period and phase are encoded:
|
||||
/// - The period of validity from the block hash found in the signing material.
|
||||
/// - The phase in the period that this transaction's lifetime begins (and, importantly,
|
||||
/// implies which block hash is included in the signature material). If the `period` is
|
||||
/// greater than 1 << 12, then it will be a factor of the times greater than 1<<12 that
|
||||
/// `period` is.
|
||||
Mortal(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).
|
||||
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 phase = current % period;
|
||||
let quantize_factor = (period >> 12).max(1);
|
||||
let quantized_phase = phase / quantize_factor * quantize_factor;
|
||||
|
||||
Era::Mortal(period, quantized_phase)
|
||||
}
|
||||
|
||||
/// Create an "immortal" transaction.
|
||||
pub fn immortal() -> Self {
|
||||
Era::Immortal
|
||||
}
|
||||
|
||||
/// `true` if this is an immortal transaction.
|
||||
pub fn is_immortal(&self) -> bool {
|
||||
match self {
|
||||
Era::Immortal => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the block number of the start of the era whose properties this object
|
||||
/// describes that `current` belongs to.
|
||||
pub fn birth(self, current: u64) -> u64 {
|
||||
match self {
|
||||
Era::Immortal => 0,
|
||||
Era::Mortal(period, phase) => (current.max(phase) - phase) / period * period + phase,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the block number of the first block at which the era has ended.
|
||||
pub fn death(self, current: u64) -> u64 {
|
||||
match self {
|
||||
Era::Immortal => u64::max_value(),
|
||||
Era::Mortal(period, _) => self.birth(current) + period,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode for Era {
|
||||
fn encode_to<T: Output>(&self, output: &mut T) {
|
||||
match self {
|
||||
Era::Immortal => output.push_byte(0),
|
||||
Era::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;
|
||||
output.push(&encoded);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl codec::EncodeLike for Era {}
|
||||
|
||||
impl Decode for Era {
|
||||
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
|
||||
let first = input.read_byte()?;
|
||||
if first == 0 {
|
||||
Ok(Era::Immortal)
|
||||
} else {
|
||||
let encoded = first as u64 + ((input.read_byte()? as u64) << 8);
|
||||
let period = 2 << (encoded % (1 << 4));
|
||||
let quantize_factor = (period >> 12).max(1);
|
||||
let phase = (encoded >> 4) * quantize_factor;
|
||||
if period >= 4 && phase < period {
|
||||
Ok(Era::Mortal(period, phase))
|
||||
} else {
|
||||
Err("Invalid period and phase".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn immortal_works() {
|
||||
let e = Era::immortal();
|
||||
assert_eq!(e.birth(0), 0);
|
||||
assert_eq!(e.death(0), u64::max_value());
|
||||
assert_eq!(e.birth(1), 0);
|
||||
assert_eq!(e.death(1), u64::max_value());
|
||||
assert_eq!(e.birth(u64::max_value()), 0);
|
||||
assert_eq!(e.death(u64::max_value()), u64::max_value());
|
||||
assert!(e.is_immortal());
|
||||
|
||||
assert_eq!(e.encode(), vec![0u8]);
|
||||
assert_eq!(e, Era::decode(&mut&[0u8][..]).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mortal_codec_works() {
|
||||
let e = Era::mortal(64, 42);
|
||||
assert!(!e.is_immortal());
|
||||
|
||||
let expected = vec![5 + 42 % 16 * 16, 42 / 16];
|
||||
assert_eq!(e.encode(), expected);
|
||||
assert_eq!(e, Era::decode(&mut&expected[..]).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_period_mortal_codec_works() {
|
||||
let e = Era::mortal(32768, 20000);
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn era_initialization_works() {
|
||||
assert_eq!(Era::mortal(64, 42), Era::Mortal(64, 42));
|
||||
assert_eq!(Era::mortal(32768, 20000), Era::Mortal(32768, 20000));
|
||||
assert_eq!(Era::mortal(200, 513), Era::Mortal(256, 1));
|
||||
assert_eq!(Era::mortal(2, 1), Era::Mortal(4, 1));
|
||||
assert_eq!(Era::mortal(4, 5), Era::Mortal(4, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantized_clamped_era_initialization_works() {
|
||||
// clamp 1000000 to 65536, quantize 1000001 % 65536 to the nearest 4
|
||||
assert_eq!(Era::mortal(1000000, 1000001), Era::Mortal(65536, 1000001 % 65536 / 4 * 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mortal_birth_death_works() {
|
||||
let e = Era::mortal(4, 6);
|
||||
for i in 6..10 {
|
||||
assert_eq!(e.birth(i), 6);
|
||||
assert_eq!(e.death(i), 10);
|
||||
}
|
||||
|
||||
// wrong because it's outside of the (current...current + period) range
|
||||
assert_ne!(e.birth(10), 6);
|
||||
assert_ne!(e.birth(5), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_less_than_phase() {
|
||||
// should not panic
|
||||
Era::mortal(4, 3).birth(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Generic implementation of a block header.
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::codec::{Decode, Encode, Codec, Input, Output, HasCompact, EncodeAsRef, Error};
|
||||
use crate::traits::{
|
||||
self, Member, SimpleArithmetic, SimpleBitOps, Hash as HashT,
|
||||
MaybeSerializeDeserialize, MaybeSerialize, MaybeDisplay,
|
||||
};
|
||||
use crate::generic::Digest;
|
||||
use primitives::U256;
|
||||
use rstd::{
|
||||
convert::TryFrom,
|
||||
fmt::Debug,
|
||||
};
|
||||
|
||||
/// Abstraction over a block header for a substrate chain.
|
||||
#[derive(PartialEq, Eq, Clone, primitives::RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
|
||||
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
|
||||
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"))]
|
||||
pub number: Number,
|
||||
/// The state trie merkle root
|
||||
pub state_root: Hash::Output,
|
||||
/// The merkle root of the extrinsics.
|
||||
pub extrinsics_root: Hash::Output,
|
||||
/// A chain-specific digest of data useful for light clients or referencing auxiliary data.
|
||||
pub digest: Digest<Hash::Output>,
|
||||
}
|
||||
|
||||
#[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 {
|
||||
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> {
|
||||
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
|
||||
Number: HasCompact + Copy + Into<U256> + TryFrom<U256>,
|
||||
Hash: HashT,
|
||||
Hash::Output: Decode,
|
||||
{
|
||||
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
|
||||
Ok(Header {
|
||||
parent_hash: Decode::decode(input)?,
|
||||
number: <<Number as HasCompact>::Type>::decode(input)?.into(),
|
||||
state_root: Decode::decode(input)?,
|
||||
extrinsics_root: Decode::decode(input)?,
|
||||
digest: Decode::decode(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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>(&self, dest: &mut T) {
|
||||
dest.push(&self.parent_hash);
|
||||
dest.push(&<<<Number as HasCompact>::Type as EncodeAsRef<_>>::RefType>::from(&self.number));
|
||||
dest.push(&self.state_root);
|
||||
dest.push(&self.extrinsics_root);
|
||||
dest.push(&self.digest);
|
||||
}
|
||||
}
|
||||
|
||||
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 + rstd::hash::Hash + MaybeDisplay +
|
||||
SimpleArithmetic + Codec + Copy + Into<U256> + TryFrom<U256>,
|
||||
Hash: HashT,
|
||||
Hash::Output: Default + rstd::hash::Hash + Copy + Member +
|
||||
MaybeSerialize + Debug + MaybeDisplay + SimpleBitOps + Codec,
|
||||
{
|
||||
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 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 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_mut(&mut self) -> &mut Digest<Self::Hash> {
|
||||
#[cfg(feature = "std")]
|
||||
log::debug!(target: "header", "Retrieving mutable reference to digest");
|
||||
&mut self.digest
|
||||
}
|
||||
|
||||
fn new(
|
||||
number: Self::Number,
|
||||
extrinsics_root: Self::Hash,
|
||||
state_root: Self::Hash,
|
||||
parent_hash: Self::Hash,
|
||||
digest: Digest<Self::Hash>,
|
||||
) -> Self {
|
||||
Header {
|
||||
number,
|
||||
extrinsics_root,
|
||||
state_root,
|
||||
parent_hash,
|
||||
digest,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Number, Hash> Header<Number, Hash> where
|
||||
Number: Member + rstd::hash::Hash + Copy + MaybeDisplay + SimpleArithmetic + Codec + Into<U256> + TryFrom<U256>,
|
||||
Hash: HashT,
|
||||
Hash::Output: Default + rstd::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 {
|
||||
Hash::hash_of(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "std"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn should_serialize_numbers() {
|
||||
fn serialize(num: u128) -> String {
|
||||
let mut v = vec![];
|
||||
{
|
||||
let mut ser = serde_json::Serializer::new(std::io::Cursor::new(&mut v));
|
||||
serialize_number(&num, &mut ser).unwrap();
|
||||
}
|
||||
String::from_utf8(v).unwrap()
|
||||
}
|
||||
|
||||
assert_eq!(serialize(0), "\"0x0\"".to_owned());
|
||||
assert_eq!(serialize(1), "\"0x1\"".to_owned());
|
||||
assert_eq!(serialize(u64::max_value() as u128), "\"0xffffffffffffffff\"".to_owned());
|
||||
assert_eq!(serialize(u64::max_value() as u128 + 1), "\"0x10000000000000000\"".to_owned());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_deserialize_number() {
|
||||
fn deserialize(num: &str) -> u128 {
|
||||
let mut der = serde_json::Deserializer::new(serde_json::de::StrRead::new(num));
|
||||
deserialize_number(&mut der).unwrap()
|
||||
}
|
||||
|
||||
assert_eq!(deserialize("\"0x0\""), 0);
|
||||
assert_eq!(deserialize("\"0x1\""), 1);
|
||||
assert_eq!(deserialize("\"0xffffffffffffffff\""), u64::max_value() as u128);
|
||||
assert_eq!(deserialize("\"0x10000000000000000\""), u64::max_value() as u128 + 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// tag::description[]
|
||||
//! Generic implementations of Extrinsic/Header/Block.
|
||||
// end::description[]
|
||||
|
||||
mod unchecked_extrinsic;
|
||||
mod era;
|
||||
mod checked_extrinsic;
|
||||
mod header;
|
||||
mod block;
|
||||
mod digest;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
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
|
||||
};
|
||||
|
||||
use crate::codec::Encode;
|
||||
use rstd::prelude::*;
|
||||
|
||||
fn encode_with_vec_prefix<T: Encode, F: Fn(&mut Vec<u8>)>(encoder: F) -> Vec<u8> {
|
||||
let size = ::rstd::mem::size_of::<T>();
|
||||
let reserve = match size {
|
||||
0..=0b00111111 => 1,
|
||||
0..=0b00111111_11111111 => 2,
|
||||
_ => 4,
|
||||
};
|
||||
let mut v = Vec::with_capacity(reserve + size);
|
||||
v.resize(reserve, 0);
|
||||
encoder(&mut v);
|
||||
|
||||
// need to prefix with the total length to ensure it's binary compatible with
|
||||
// Vec<u8>.
|
||||
let mut length: Vec<()> = Vec::new();
|
||||
length.resize(v.len() - reserve, ());
|
||||
length.using_encoded(|s| {
|
||||
v.splice(0..reserve, s.iter().cloned());
|
||||
});
|
||||
|
||||
v
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Tests for the generic implementations of Extrinsic/Header/Block.
|
||||
|
||||
use crate::codec::{Decode, Encode};
|
||||
use primitives::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,
|
||||
]);
|
||||
|
||||
let decoded: DigestItem<H256> = Decode::decode(&mut &encoded[..]).unwrap();
|
||||
assert_eq!(item, decoded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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,
|
||||
]);
|
||||
|
||||
let decoded: DigestItem<H256> = Decode::decode(&mut &encoded[..]).unwrap();
|
||||
assert_eq!(item, decoded);
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Generic implementation of an unchecked (pre-verification) extrinsic.
|
||||
|
||||
use rstd::{fmt, prelude::*};
|
||||
use runtime_io::hashing::blake2_256;
|
||||
use codec::{Decode, Encode, EncodeLike, Input, Error};
|
||||
use crate::{
|
||||
traits::{self, Member, MaybeDisplay, SignedExtension, Checkable, Extrinsic, IdentifyAccount},
|
||||
generic::CheckedExtrinsic, transaction_validity::{TransactionValidityError, InvalidTransaction},
|
||||
};
|
||||
|
||||
const TRANSACTION_VERSION: u8 = 4;
|
||||
|
||||
/// A extrinsic right from the external world. This is unchecked and so
|
||||
/// can contain a signature.
|
||||
#[derive(PartialEq, Eq, Clone)]
|
||||
pub struct UncheckedExtrinsic<Address, Call, Signature, Extra>
|
||||
where
|
||||
Extra: SignedExtension
|
||||
{
|
||||
/// The signature, address, number of extrinsics have come before from
|
||||
/// the same signer and an era describing the longevity of this transaction,
|
||||
/// if this is a signed extrinsic.
|
||||
pub signature: Option<(Address, Signature, Extra)>,
|
||||
/// The function that should be called.
|
||||
pub function: Call,
|
||||
}
|
||||
|
||||
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 {
|
||||
UncheckedExtrinsic {
|
||||
signature: Some((signed, signature, extra)),
|
||||
function,
|
||||
}
|
||||
}
|
||||
|
||||
/// New instance of an unsigned extrinsic aka "inherent".
|
||||
pub fn new_unsigned(function: Call) -> Self {
|
||||
UncheckedExtrinsic {
|
||||
signature: None,
|
||||
function,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Address, Call, Signature, Extra: SignedExtension> Extrinsic
|
||||
for UncheckedExtrinsic<Address, Call, Signature, Extra>
|
||||
{
|
||||
type Call = Call;
|
||||
|
||||
type SignaturePayload = (
|
||||
Address,
|
||||
Signature,
|
||||
Extra,
|
||||
);
|
||||
|
||||
fn is_signed(&self) -> Option<bool> {
|
||||
Some(self.signature.is_some())
|
||||
}
|
||||
|
||||
fn new(function: Call, signed_data: Option<Self::SignaturePayload>) -> Option<Self> {
|
||||
Some(if let Some((address, signature, extra)) = signed_data {
|
||||
UncheckedExtrinsic::new_signed(function, address, signature, extra)
|
||||
} else {
|
||||
UncheckedExtrinsic::new_unsigned(function)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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>,
|
||||
AccountId: Member + MaybeDisplay,
|
||||
Lookup: traits::Lookup<Source=Address, Target=AccountId>,
|
||||
{
|
||||
type Checked = CheckedExtrinsic<AccountId, Call, Extra>;
|
||||
|
||||
fn check(self, lookup: &Lookup) -> Result<Self::Checked, TransactionValidityError> {
|
||||
Ok(match self.signature {
|
||||
Some((signed, signature, extra)) => {
|
||||
let signed = lookup.lookup(signed)?;
|
||||
let raw_payload = SignedPayload::new(self.function, extra)?;
|
||||
if !raw_payload.using_encoded(|payload| {
|
||||
signature.verify(payload, &signed)
|
||||
}) {
|
||||
return Err(InvalidTransaction::BadProof.into())
|
||||
}
|
||||
|
||||
let (function, extra, _) = raw_payload.deconstruct();
|
||||
CheckedExtrinsic {
|
||||
signed: Some((signed, extra)),
|
||||
function,
|
||||
}
|
||||
}
|
||||
None => CheckedExtrinsic {
|
||||
signed: None,
|
||||
function: self.function,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A payload that has been signed for an unchecked extrinsics.
|
||||
///
|
||||
/// 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,
|
||||
));
|
||||
|
||||
impl<Call, Extra> SignedPayload<Call, Extra> where
|
||||
Call: Encode,
|
||||
Extra: SignedExtension,
|
||||
{
|
||||
/// Create new `SignedPayload`.
|
||||
///
|
||||
/// This function may fail if `additional_signed` of `Extra` is not available.
|
||||
pub fn new(call: Call, extra: Extra) -> Result<Self, TransactionValidityError> {
|
||||
let additional_signed = extra.additional_signed()?;
|
||||
let raw_payload = (call, extra, additional_signed);
|
||||
Ok(Self(raw_payload))
|
||||
}
|
||||
|
||||
/// Create new `SignedPayload` from raw components.
|
||||
pub fn from_raw(call: Call, extra: Extra, additional_signed: Extra::AdditionalSigned) -> Self {
|
||||
Self((call, extra, additional_signed))
|
||||
}
|
||||
|
||||
/// Deconstruct the payload into it's components.
|
||||
pub fn deconstruct(self) -> (Call, Extra, Extra::AdditionalSigned) {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<Call, Extra> Encode for SignedPayload<Call, Extra> where
|
||||
Call: Encode,
|
||||
Extra: SignedExtension,
|
||||
{
|
||||
/// Get an encoded version of this payload.
|
||||
///
|
||||
/// Payloads longer than 256 bytes are going to be `blake2_256`-hashed.
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
self.0.using_encoded(|payload| {
|
||||
if payload.len() > 256 {
|
||||
f(&blake2_256(payload)[..])
|
||||
} else {
|
||||
f(payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
where
|
||||
Address: Decode,
|
||||
Signature: Decode,
|
||||
Call: Decode,
|
||||
Extra: SignedExtension,
|
||||
{
|
||||
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
|
||||
// This is a little more complicated than usual since the binary format must be compatible
|
||||
// with substrate's generic `Vec<u8>` type. Basically this just means accepting that there
|
||||
// will be a prefix of vector length (we don't need
|
||||
// to use this).
|
||||
let _length_do_not_remove_me_see_above: Vec<()> = Decode::decode(input)?;
|
||||
|
||||
let version = input.read_byte()?;
|
||||
|
||||
let is_signed = version & 0b1000_0000 != 0;
|
||||
let version = version & 0b0111_1111;
|
||||
if version != TRANSACTION_VERSION {
|
||||
return Err("Invalid transaction version".into());
|
||||
}
|
||||
|
||||
Ok(UncheckedExtrinsic {
|
||||
signature: if is_signed { Some(Decode::decode(input)?) } else { None },
|
||||
function: Decode::decode(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<Address, Call, Signature, Extra> Encode
|
||||
for UncheckedExtrinsic<Address, Call, Signature, Extra>
|
||||
where
|
||||
Address: Encode,
|
||||
Signature: Encode,
|
||||
Call: Encode,
|
||||
Extra: SignedExtension,
|
||||
{
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
super::encode_with_vec_prefix::<Self, _>(|v| {
|
||||
// 1 byte version id.
|
||||
match self.signature.as_ref() {
|
||||
Some(s) => {
|
||||
v.push(TRANSACTION_VERSION | 0b1000_0000);
|
||||
s.encode_to(v);
|
||||
}
|
||||
None => {
|
||||
v.push(TRANSACTION_VERSION & 0b0111_1111);
|
||||
}
|
||||
}
|
||||
self.function.encode_to(v);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<Address, Call, Signature, Extra> EncodeLike
|
||||
for UncheckedExtrinsic<Address, Call, Signature, Extra>
|
||||
where
|
||||
Address: Encode,
|
||||
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 {
|
||||
self.using_encoded(|bytes| seq.serialize_bytes(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
impl<Address, Call, Signature, Extra> fmt::Debug
|
||||
for UncheckedExtrinsic<Address, Call, Signature, Extra>
|
||||
where
|
||||
Address: fmt::Debug,
|
||||
Call: fmt::Debug,
|
||||
Extra: SignedExtension,
|
||||
{
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"UncheckedExtrinsic({:?}, {:?})",
|
||||
self.signature.as_ref().map(|x| (&x.0, &x.2)),
|
||||
self.function,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use runtime_io::hashing::blake2_256;
|
||||
use crate::codec::{Encode, Decode};
|
||||
use crate::traits::{SignedExtension, IdentifyAccount, IdentityLookup};
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
type TestContext = IdentityLookup<u64>;
|
||||
|
||||
#[derive(Eq, PartialEq, Clone, Copy, Debug, Serialize, Deserialize, Encode, Decode)]
|
||||
pub struct TestSigner(pub u64);
|
||||
impl From<u64> for TestSigner { fn from(x: u64) -> Self { Self(x) } }
|
||||
impl From<TestSigner> for u64 { fn from(x: TestSigner) -> Self { x.0 } }
|
||||
impl IdentifyAccount for TestSigner {
|
||||
type AccountId = u64;
|
||||
fn into_account(self) -> u64 { self.into() }
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Encode, Decode)]
|
||||
struct TestSig(u64, Vec<u8>);
|
||||
impl traits::Verify for TestSig {
|
||||
type Signer = TestSigner;
|
||||
fn verify<L: traits::Lazy<[u8]>>(&self, mut msg: L, signer: &u64) -> bool {
|
||||
signer == &self.0 && msg.get() == &self.1[..]
|
||||
}
|
||||
}
|
||||
|
||||
type TestAccountId = u64;
|
||||
type TestCall = Vec<u8>;
|
||||
|
||||
const TEST_ACCOUNT: TestAccountId = 0;
|
||||
|
||||
// NOTE: this is demonstration. One can simply use `()` for testing.
|
||||
#[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct TestExtra;
|
||||
impl SignedExtension for TestExtra {
|
||||
type AccountId = u64;
|
||||
type Call = ();
|
||||
type AdditionalSigned = ();
|
||||
type DispatchInfo = ();
|
||||
type Pre = ();
|
||||
|
||||
fn additional_signed(&self) -> rstd::result::Result<(), TransactionValidityError> { Ok(()) }
|
||||
}
|
||||
|
||||
type Ex = UncheckedExtrinsic<TestAccountId, TestCall, TestSig, TestExtra>;
|
||||
type CEx = CheckedExtrinsic<TestAccountId, TestCall, TestExtra>;
|
||||
|
||||
#[test]
|
||||
fn unsigned_codec_should_work() {
|
||||
let ux = Ex::new_unsigned(vec![0u8; 0]);
|
||||
let encoded = ux.encode();
|
||||
assert_eq!(Ex::decode(&mut &encoded[..]), Ok(ux));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_codec_should_work() {
|
||||
let ux = Ex::new_signed(
|
||||
vec![0u8; 0],
|
||||
TEST_ACCOUNT,
|
||||
TestSig(TEST_ACCOUNT, (vec![0u8; 0], TestExtra).encode()),
|
||||
TestExtra
|
||||
);
|
||||
let encoded = ux.encode();
|
||||
assert_eq!(Ex::decode(&mut &encoded[..]), Ok(ux));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_signed_codec_should_work() {
|
||||
let ux = Ex::new_signed(
|
||||
vec![0u8; 0],
|
||||
TEST_ACCOUNT,
|
||||
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));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_check_should_work() {
|
||||
let ux = Ex::new_unsigned(vec![0u8; 0]);
|
||||
assert!(!ux.is_signed().unwrap_or(false));
|
||||
assert!(<Ex as Checkable<TestContext>>::check(ux, &Default::default()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badly_signed_check_should_fail() {
|
||||
let ux = Ex::new_signed(
|
||||
vec![0u8; 0],
|
||||
TEST_ACCOUNT,
|
||||
TestSig(TEST_ACCOUNT, vec![0u8; 0]),
|
||||
TestExtra,
|
||||
);
|
||||
assert!(ux.is_signed().unwrap_or(false));
|
||||
assert_eq!(
|
||||
<Ex as Checkable<TestContext>>::check(ux, &Default::default()),
|
||||
Err(InvalidTransaction::BadProof.into()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_check_should_work() {
|
||||
let ux = Ex::new_signed(
|
||||
vec![0u8; 0],
|
||||
TEST_ACCOUNT,
|
||||
TestSig(TEST_ACCOUNT, (vec![0u8; 0], TestExtra).encode()),
|
||||
TestExtra,
|
||||
);
|
||||
assert!(ux.is_signed().unwrap_or(false));
|
||||
assert_eq!(
|
||||
<Ex as Checkable<TestContext>>::check(ux, &Default::default()),
|
||||
Ok(CEx { signed: Some((TEST_ACCOUNT, TestExtra)), function: vec![0u8; 0] }),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_matches_vec() {
|
||||
let ex = Ex::new_unsigned(vec![0u8; 0]);
|
||||
let encoded = ex.encode();
|
||||
let decoded = Ex::decode(&mut encoded.as_slice()).unwrap();
|
||||
assert_eq!(decoded, ex);
|
||||
let as_vec: Vec<u8> = Decode::decode(&mut encoded.as_slice()).unwrap();
|
||||
assert_eq!(as_vec.encode(), encoded);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user