Refactored Slicable (#324)

* Refactored Slicable

* Docs

* Wasm build

* Wasm build

* Renamed traits

* Review nits

* Renamed Slicable as well
This commit is contained in:
Arkadiy Paronyan
2018-07-15 22:51:21 +02:00
committed by Gav Wood
parent b45020175a
commit 1aeb2825af
84 changed files with 901 additions and 818 deletions
@@ -48,8 +48,8 @@ use primitives::bft::MisbehaviorReport;
pub const AUTHORITY_AT: &'static [u8] = b":auth:";
pub const AUTHORITY_COUNT: &'static [u8] = b":auth:len";
struct AuthorityStorageVec<S: codec::Slicable + Default>(rstd::marker::PhantomData<S>);
impl<S: codec::Slicable + Default> StorageVec for AuthorityStorageVec<S> {
struct AuthorityStorageVec<S: codec::Codec + Default>(rstd::marker::PhantomData<S>);
impl<S: codec::Codec + Default> StorageVec for AuthorityStorageVec<S> {
type Item = S;
const PREFIX: &'static [u8] = AUTHORITY_AT;
}
@@ -147,7 +147,7 @@ impl<T: Trait> Default for GenesisConfig<T> {
impl<T: Trait> primitives::BuildStorage for GenesisConfig<T>
{
fn build_storage(self) -> ::std::result::Result<runtime_io::TestExternalities, String> {
use codec::{Slicable, KeyedVec};
use codec::{Encode, KeyedVec};
let auth_count = self.authorities.len() as u32;
let mut r: runtime_io::TestExternalities = self.authorities.into_iter().enumerate().map(|(i, v)|
((i as u32).to_keyed_vec(AUTHORITY_AT), v.encode())
@@ -37,7 +37,7 @@ extern crate assert_matches;
extern crate wabt;
use rstd::prelude::*;
use codec::Slicable;
use codec::{Codec, Decode};
use parity_wasm::elements::{self, External, MemoryType};
use pwasm_utils::rules;
@@ -49,9 +49,9 @@ use pwasm_utils::rules;
/// operations are implicitly performed on that account.
pub trait Ext {
/// The indentifier of an account.
type AccountId: Slicable + Clone;
type AccountId: Codec + Clone;
/// The balance of an account.
type Balance: Slicable;
type Balance: Codec;
/// Returns the storage entry of the executing account by the given key.
fn get_storage(&self, key: &[u8]) -> Option<Vec<u8>>;
@@ -591,7 +591,7 @@ impl<T: Trait> Default for GenesisConfig<T> {
impl<T: Trait> primitives::BuildStorage for GenesisConfig<T>
{
fn build_storage(self) -> ::std::result::Result<runtime_io::TestExternalities, String> {
use codec::Slicable;
use codec::Encode;
use runtime_io::twox_128;
Ok(map![
@@ -339,7 +339,7 @@ impl<T: Trait> Default for GenesisConfig<T> {
impl<T: Trait> primitives::BuildStorage for GenesisConfig<T>
{
fn build_storage(self) -> ::std::result::Result<runtime_io::TestExternalities, String> {
use codec::Slicable;
use codec::Encode;
use runtime_io::twox_128;
Ok(map![
@@ -17,7 +17,7 @@
//! Voting thresholds.
use primitives::traits::{Zero, IntegerSquareRoot};
use codec::{Input, Slicable};
use codec::{Decode, Encode, Input};
use rstd::ops::{Add, Mul, Div, Rem};
/// A means of determining if a vote is past pass threshold.
@@ -32,7 +32,7 @@ pub enum VoteThreshold {
SimpleMajority,
}
impl Slicable for VoteThreshold {
impl Decode for VoteThreshold {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
input.read_byte().and_then(|v| match v {
0 => Some(VoteThreshold::SuperMajorityApprove),
@@ -41,7 +41,9 @@ impl Slicable for VoteThreshold {
_ => None,
})
}
}
impl Encode for VoteThreshold {
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(&[match *self {
VoteThreshold::SuperMajorityApprove => 0u8,
@@ -55,7 +55,7 @@ use rstd::result;
use runtime_support::StorageValue;
use primitives::traits::{self, Header, Zero, One, Checkable, Applyable, CheckEqual, Executable,
MakePayment, Hash, AuxLookup};
use codec::Slicable;
use codec::{Codec, Encode};
use system::extrinsics_root;
use primitives::{ApplyOutcome, ApplyError};
@@ -89,7 +89,7 @@ impl<
Payment: MakePayment<System::AccountId>,
Finalisation: Executable,
> Executive<System, Block, Lookup, Payment, Finalisation> where
Block::Extrinsic: Checkable<fn(Address) -> Result<System::AccountId, &'static str>> + Slicable,
Block::Extrinsic: Checkable<fn(Address) -> Result<System::AccountId, &'static str>> + Codec,
<Block::Extrinsic as Checkable<fn(Address) -> Result<System::AccountId, &'static str>>>::Checked: Applyable<Index=System::Index, AccountId=System::AccountId>
{
/// Start the execution of a particular block.
@@ -17,7 +17,7 @@
//! Message formats for the BFT consensus layer.
use rstd::prelude::*;
use codec::{Slicable, Input};
use codec::{Decode, Encode, Input, Output};
use substrate_primitives::{AuthorityId, Signature};
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -51,59 +51,58 @@ pub enum Action<Block, H> {
AdvanceRound(u32),
}
impl<Block: Slicable, Hash: Slicable> Slicable for Action<Block, Hash> {
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
impl<Block: Encode, Hash: Encode> Encode for Action<Block, Hash> {
fn encode_to<T: Output>(&self, dest: &mut T) {
match *self {
Action::Propose(ref round, ref block) => {
v.push(ActionKind::Propose as u8);
round.using_encoded(|s| v.extend(s));
block.using_encoded(|s| v.extend(s));
dest.push_byte(ActionKind::Propose as u8);
dest.push(round);
dest.push(block);
}
Action::ProposeHeader(ref round, ref hash) => {
v.push(ActionKind::ProposeHeader as u8);
round.using_encoded(|s| v.extend(s));
hash.using_encoded(|s| v.extend(s));
dest.push_byte(ActionKind::ProposeHeader as u8);
dest.push(round);
dest.push(hash);
}
Action::Prepare(ref round, ref hash) => {
v.push(ActionKind::Prepare as u8);
round.using_encoded(|s| v.extend(s));
hash.using_encoded(|s| v.extend(s));
dest.push_byte(ActionKind::Prepare as u8);
dest.push(round);
dest.push(hash);
}
Action::Commit(ref round, ref hash) => {
v.push(ActionKind::Commit as u8);
round.using_encoded(|s| v.extend(s));
hash.using_encoded(|s| v.extend(s));
dest.push_byte(ActionKind::Commit as u8);
dest.push(round);
dest.push(hash);
}
Action::AdvanceRound(ref round) => {
v.push(ActionKind::AdvanceRound as u8);
round.using_encoded(|s| v.extend(s));
dest.push_byte(ActionKind::AdvanceRound as u8);
dest.push(round);
}
}
v
}
}
impl<Block: Decode, Hash: Decode> Decode for Action<Block, Hash> {
fn decode<I: Input>(value: &mut I) -> Option<Self> {
match i8::decode(value) {
Some(x) if x == ActionKind::Propose as i8 => {
let (round, block) = Slicable::decode(value)?;
let (round, block) = Decode::decode(value)?;
Some(Action::Propose(round, block))
}
Some(x) if x == ActionKind::ProposeHeader as i8 => {
let (round, hash) = Slicable::decode(value)?;
let (round, hash) = Decode::decode(value)?;
Some(Action::ProposeHeader(round, hash))
}
Some(x) if x == ActionKind::Prepare as i8 => {
let (round, hash) = Slicable::decode(value)?;
let (round, hash) = Decode::decode(value)?;
Some(Action::Prepare(round, hash))
}
Some(x) if x == ActionKind::Commit as i8 => {
let (round, hash) = Slicable::decode(value)?;
let (round, hash) = Decode::decode(value)?;
Some(Action::Commit(round, hash))
}
Some(x) if x == ActionKind::AdvanceRound as i8 => {
Slicable::decode(value).map(Action::AdvanceRound)
Decode::decode(value).map(Action::AdvanceRound)
}
_ => None,
}
@@ -123,17 +122,18 @@ pub struct Message<Block, Hash> {
pub action: Action<Block, Hash>,
}
impl<Block: Slicable, Hash: Slicable> Slicable for Message<Block, Hash> {
fn encode(&self) -> Vec<u8> {
let mut v = self.parent.encode();
self.action.using_encoded(|s| v.extend(s));
v
impl<Block: Encode, Hash: Encode> Encode for Message<Block, Hash> {
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.parent);
dest.push(&self.action);
}
}
impl<Block: Decode, Hash: Decode> Decode for Message<Block, Hash> {
fn decode<I: Input>(value: &mut I) -> Option<Self> {
Some(Message {
parent: Slicable::decode(value)?,
action: Slicable::decode(value)?,
parent: Decode::decode(value)?,
action: Decode::decode(value)?,
})
}
}
@@ -150,22 +150,20 @@ pub struct Justification<H> {
pub signatures: Vec<(AuthorityId, Signature)>
}
impl<H: Slicable> Slicable for Justification<H> {
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
self.round_number.using_encoded(|s| v.extend(s));
self.hash.using_encoded(|s| v.extend(s));
self.signatures.using_encoded(|s| v.extend(s));
v
impl<H: Encode> Encode for Justification<H> {
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.round_number);
dest.push(&self.hash);
dest.push(&self.signatures);
}
}
impl<H: Decode> Decode for Justification<H> {
fn decode<I: Input>(value: &mut I) -> Option<Self> {
Some(Justification {
round_number: Slicable::decode(value)?,
hash: Slicable::decode(value)?,
signatures: Slicable::decode(value)?,
round_number: Decode::decode(value)?,
hash: Decode::decode(value)?,
signatures: Decode::decode(value)?,
})
}
}
@@ -213,35 +211,34 @@ pub struct MisbehaviorReport<Hash, Number> {
pub misbehavior: MisbehaviorKind<Hash>,
}
impl<Hash: Slicable, Number: Slicable> Slicable for MisbehaviorReport<Hash, Number> {
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
self.parent_hash.using_encoded(|s| v.extend(s));
self.parent_number.using_encoded(|s| v.extend(s));
self.target.using_encoded(|s| v.extend(s));
impl<Hash: Encode, Number: Encode> Encode for MisbehaviorReport<Hash, Number> {
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.parent_hash);
dest.push(&self.parent_number);
dest.push(&self.target);
match self.misbehavior {
MisbehaviorKind::BftDoublePrepare(ref round, (ref h_a, ref s_a), (ref h_b, ref s_b)) => {
(MisbehaviorCode::BftDoublePrepare as i8).using_encoded(|s| v.extend(s));
round.using_encoded(|s| v.extend(s));
h_a.using_encoded(|s| v.extend(s));
s_a.using_encoded(|s| v.extend(s));
h_b.using_encoded(|s| v.extend(s));
s_b.using_encoded(|s| v.extend(s));
dest.push(&(MisbehaviorCode::BftDoublePrepare as i8));
dest.push(round);
dest.push(h_a);
dest.push(s_a);
dest.push(h_b);
dest.push(s_b);
}
MisbehaviorKind::BftDoubleCommit(ref round, (ref h_a, ref s_a), (ref h_b, ref s_b)) => {
(MisbehaviorCode::BftDoubleCommit as i8).using_encoded(|s| v.extend(s));
round.using_encoded(|s| v.extend(s));
h_a.using_encoded(|s| v.extend(s));
s_a.using_encoded(|s| v.extend(s));
h_b.using_encoded(|s| v.extend(s));
s_b.using_encoded(|s| v.extend(s));
dest.push(&(MisbehaviorCode::BftDoubleCommit as i8));
dest.push(round);
dest.push(h_a);
dest.push(s_a);
dest.push(h_b);
dest.push(s_b);
}
}
v
}
}
impl<Hash: Decode, Number: Decode> Decode for MisbehaviorReport<Hash, Number> {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
let parent_hash = Hash::decode(input)?;
let parent_number = Number::decode(input)?;
@@ -23,7 +23,7 @@ use std::fmt;
use serde::{Deserialize, Deserializer};
use rstd::prelude::*;
use codec::{Slicable, Input};
use codec::{Decode, Encode, Codec, Input, Output};
use runtime_support::AuxDispatchable;
use traits::{self, Member, SimpleArithmetic, SimpleBitOps, MaybeDisplay, Block as BlockT,
Header as HeaderT, Hash as HashT};
@@ -42,27 +42,29 @@ pub struct Extrinsic<Address, Index, Call> {
pub function: Call,
}
impl<Address, Index, Call> Slicable for Extrinsic<Address, Index, Call> where
Address: Member + Slicable + MaybeDisplay,
Index: Member + Slicable + MaybeDisplay + SimpleArithmetic,
Call: Member + Slicable
impl<Address, Index, Call> Decode for Extrinsic<Address, Index, Call> where
Address: Decode,
Index: Decode,
Call: Decode,
{
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(Extrinsic {
signed: Slicable::decode(input)?,
index: Slicable::decode(input)?,
function: Slicable::decode(input)?,
signed: Decode::decode(input)?,
index: Decode::decode(input)?,
function: Decode::decode(input)?,
})
}
}
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
self.signed.using_encoded(|s| v.extend(s));
self.index.using_encoded(|s| v.extend(s));
self.function.using_encoded(|s| v.extend(s));
v
impl<Address, Index, Call> Encode for Extrinsic<Address, Index, Call> where
Address: Encode,
Index: Encode,
Call: Encode,
{
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.signed);
dest.push(&self.index);
dest.push(&self.function);
}
}
@@ -105,7 +107,7 @@ where
Signature: traits::Verify<Signer=AccountId> + Eq + Default,
AccountId: Member + Default + MaybeDisplay,
::MaybeUnsigned<Signature>: Member,
Extrinsic<AccountId, Index, Call>: Slicable,
Extrinsic<AccountId, Index, Call>: Codec,
ThisLookup: FnOnce(Address) -> Result<AccountId, &'static str>,
{
type Checked = CheckedExtrinsic<AccountId, Index, Call>;
@@ -133,23 +135,32 @@ where
}
}
impl<Address, Index, Call, Signature> Slicable for UncheckedExtrinsic<Address, Index, Call, Signature> where
Signature: Slicable,
Extrinsic<Address, Index, Call>: Slicable,
impl<Address, Index, Call, Signature> Decode
for UncheckedExtrinsic<Address, Index, Call, Signature>
where
Signature: Decode,
Extrinsic<Address, Index, Call>: Decode,
{
fn decode<I: Input>(input: &mut I) -> Option<Self> {
// 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 u32, which has the total number of bytes following (we don't need
// to use this).
let _length_do_not_remove_me_see_above: u32 = Slicable::decode(input)?;
let _length_do_not_remove_me_see_above: u32 = Decode::decode(input)?;
Some(UncheckedExtrinsic::new(
Slicable::decode(input)?,
Slicable::decode(input)?
Decode::decode(input)?,
Decode::decode(input)?
))
}
}
impl<Address, Index, Call, Signature> Encode
for UncheckedExtrinsic<Address, Index, Call, Signature>
where
Signature: Encode,
Extrinsic<Address, Index, Call>: Encode,
{
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
@@ -157,9 +168,8 @@ impl<Address, Index, Call, Signature> Slicable for UncheckedExtrinsic<Address, I
// Vec<u8>. we'll make room for it here, then overwrite once we know the length.
v.extend(&[0u8; 4]);
self.extrinsic.using_encoded(|s| v.extend(s));
self.signature.using_encoded(|s| v.extend(s));
self.extrinsic.encode_to(&mut v);
self.signature.encode_to(&mut v);
let length = (v.len() - 4) as u32;
length.using_encoded(|s| v[0..4].copy_from_slice(s));
@@ -230,18 +240,20 @@ pub struct Digest<Item> {
pub logs: Vec<Item>,
}
impl<Item> Slicable for Digest<Item> where
Item: Member + Default + Slicable
{
impl<Item: Decode> Decode for Digest<Item> {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(Digest { logs: Slicable::decode(input)? })
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.logs.using_encoded(f)
Some(Digest { logs: Decode::decode(input)? })
}
}
impl<Item: Encode> Encode for Digest<Item> {
fn encode_to<T: Output>(&self, dest: &mut T) {
self.logs.encode_to(dest)
}
}
impl<Item> traits::Digest for Digest<Item> where
Item: Member + Default + Slicable
Item: Member + Default + Codec
{
type Item = Item;
fn push(&mut self, item: Self::Item) {
@@ -307,38 +319,43 @@ impl<'a, Number: 'a, Hash: 'a + HashT, DigestItem: 'a> Deserialize<'a> for Heade
}
}
impl<Number, Hash, DigestItem> Slicable for Header<Number, Hash, DigestItem> where
Number: Member + Slicable + MaybeDisplay + SimpleArithmetic + Slicable,
impl<Number, Hash, DigestItem> Decode for Header<Number, Hash, DigestItem> where
Number: Decode,
Hash: HashT,
DigestItem: Member + Default + Slicable,
Hash::Output: Default + Member + MaybeDisplay + SimpleBitOps + Slicable,
Hash::Output: Decode,
DigestItem: Decode,
{
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(Header {
parent_hash: Slicable::decode(input)?,
number: Slicable::decode(input)?,
state_root: Slicable::decode(input)?,
extrinsics_root: Slicable::decode(input)?,
digest: Slicable::decode(input)?,
parent_hash: Decode::decode(input)?,
number: Decode::decode(input)?,
state_root: Decode::decode(input)?,
extrinsics_root: Decode::decode(input)?,
digest: Decode::decode(input)?,
})
}
}
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
self.parent_hash.using_encoded(|s| v.extend(s));
self.number.using_encoded(|s| v.extend(s));
self.state_root.using_encoded(|s| v.extend(s));
self.extrinsics_root.using_encoded(|s| v.extend(s));
self.digest.using_encoded(|s| v.extend(s));
v
impl<Number, Hash, DigestItem> Encode for Header<Number, Hash, DigestItem> where
Number: Encode,
Hash: HashT,
Hash::Output: Encode,
DigestItem: Encode,
{
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.parent_hash);
dest.push(&self.number);
dest.push(&self.state_root);
dest.push(&self.extrinsics_root);
dest.push(&self.digest);
}
}
impl<Number, Hash, DigestItem> traits::Header for Header<Number, Hash, DigestItem> where
Number: Member + ::rstd::hash::Hash + Copy + Slicable + MaybeDisplay + SimpleArithmetic + Slicable,
Number: Member + ::rstd::hash::Hash + Copy + Codec + MaybeDisplay + SimpleArithmetic + Codec,
Hash: HashT,
DigestItem: Member + Default + Slicable,
Hash::Output: Default + ::rstd::hash::Hash + Copy + Member + MaybeDisplay + SimpleBitOps + Slicable,
DigestItem: Member + Default + Codec,
Hash::Output: Default + ::rstd::hash::Hash + Copy + Member + MaybeDisplay + SimpleBitOps + Codec,
{
type Number = Number;
type Hash = <Hash as HashT>::Output;
@@ -374,10 +391,10 @@ impl<Number, Hash, DigestItem> traits::Header for Header<Number, Hash, DigestIte
}
impl<Number, Hash, DigestItem> Header<Number, Hash, DigestItem> where
Number: Member + ::rstd::hash::Hash + Copy + Slicable + MaybeDisplay + SimpleArithmetic + Slicable,
Number: Member + ::rstd::hash::Hash + Copy + Codec + MaybeDisplay + SimpleArithmetic + Codec,
Hash: HashT,
DigestItem: Member + Default + Slicable,
Hash::Output: Default + ::rstd::hash::Hash + Copy + Member + MaybeDisplay + SimpleBitOps + Slicable,
DigestItem: Member + Default + Codec,
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.
@@ -431,26 +448,26 @@ pub struct Block<Header, Extrinsic> {
pub extrinsics: Vec<Extrinsic>,
}
impl<Header: Slicable, Extrinsic: Slicable> Slicable for Block<Header, Extrinsic> {
impl<Header: Decode, Extrinsic: Decode> Decode for Block<Header, Extrinsic> {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(Block {
header: Slicable::decode(input)?,
extrinsics: Slicable::decode(input)?,
header: Decode::decode(input)?,
extrinsics: Decode::decode(input)?,
})
}
}
fn encode(&self) -> Vec<u8> {
let mut v: Vec<u8> = Vec::new();
v.extend(self.header.encode());
v.extend(self.extrinsics.encode());
v
impl<Header: Encode, Extrinsic: Encode> Encode for Block<Header, Extrinsic> {
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.header);
dest.push(&self.extrinsics);
}
}
impl<Header, Extrinsic> traits::Block for Block<Header, Extrinsic>
where
Header: HeaderT,
Extrinsic: Member + Slicable,
Extrinsic: Member + Codec,
{
type Extrinsic = Extrinsic;
type Header = Header;
@@ -482,25 +499,29 @@ pub struct SignedBlock<Header, Extrinsic, Hash> {
pub justification: Justification<Hash>,
}
impl<Header: Slicable, Extrinsic: Slicable, Hash: Slicable> Slicable for SignedBlock<Header, Extrinsic, Hash> {
impl<Header: Decode, Extrinsic: Decode, Hash: Decode> Decode
for SignedBlock<Header, Extrinsic, Hash>
{
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(SignedBlock {
block: Slicable::decode(input)?,
justification: Slicable::decode(input)?,
block: Decode::decode(input)?,
justification: Decode::decode(input)?,
})
}
}
fn encode(&self) -> Vec<u8> {
let mut v: Vec<u8> = Vec::new();
v.extend(self.block.encode());
v.extend(self.justification.encode());
v
impl<Header: Encode, Extrinsic: Encode, Hash: Encode> Encode
for SignedBlock<Header, Extrinsic, Hash>
{
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.block);
dest.push(&self.justification);
}
}
#[cfg(test)]
mod tests {
use codec::Slicable;
use codec::{Decode, Encode};
use substrate_primitives::{H256, H512};
use super::{Digest, Header, UncheckedExtrinsic, Extrinsic};
@@ -81,9 +81,16 @@ impl Verify for Ed25519Signature {
}
}
impl codec::Slicable for Ed25519Signature {
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> { Some(Ed25519Signature(codec::Slicable::decode(input)?,)) }
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R { self.0.using_encoded(f) }
impl codec::Decode for Ed25519Signature {
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> {
Some(Ed25519Signature(codec::Decode::decode(input)?,))
}
}
impl codec::Encode for Ed25519Signature {
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.0.using_encoded(f)
}
}
impl From<H512> for Ed25519Signature {
@@ -102,7 +109,7 @@ pub enum ApplyOutcome {
/// Failed application (extrinsic was probably a no-op other than fees).
Fail = 1,
}
impl codec::Slicable for ApplyOutcome {
impl codec::Decode for ApplyOutcome {
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> {
match input.read_byte()? {
x if x == ApplyOutcome::Success as u8 => Some(ApplyOutcome::Success),
@@ -110,6 +117,8 @@ impl codec::Slicable for ApplyOutcome {
_ => None,
}
}
}
impl codec::Encode for ApplyOutcome {
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(&[*self as u8])
}
@@ -129,7 +138,8 @@ pub enum ApplyError {
/// Sending account had too low a balance.
CantPay = 3,
}
impl codec::Slicable for ApplyError {
impl codec::Decode for ApplyError {
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> {
match input.read_byte()? {
x if x == ApplyError::BadSignature as u8 => Some(ApplyError::BadSignature),
@@ -139,6 +149,9 @@ impl codec::Slicable for ApplyError {
_ => None,
}
}
}
impl codec::Encode for ApplyError {
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(&[*self as u8])
}
@@ -179,9 +192,16 @@ impl<T: Verify> Verify for MaybeUnsigned<T> where
}
}
impl<T: codec::Slicable> codec::Slicable for MaybeUnsigned<T> {
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> { Some(MaybeUnsigned(codec::Slicable::decode(input)?)) }
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R { self.0.using_encoded(f) }
impl<T: codec::Decode> codec::Decode for MaybeUnsigned<T> {
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> {
Some(MaybeUnsigned(codec::Decode::decode(input)?))
}
}
impl<T: codec::Encode> codec::Encode for MaybeUnsigned<T> {
fn encode_to<W: codec::Output>(&self, dest: &mut W) {
self.0.encode_to(dest)
}
}
impl<T> From<T> for MaybeUnsigned<T> {
@@ -192,7 +212,7 @@ impl<T> From<T> for MaybeUnsigned<T> {
/// 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::Slicable>(sig: &V, item: &T, signer: &V::Signer) -> bool {
pub fn verify_encoded_lazy<V: Verify, T: codec::Encode>(sig: &V, item: &T, signer: &V::Signer) -> bool {
// The `Lazy<T>` trait expresses something like `X: FnMut<Output = for<'a> &'a T>`.
// unfortunately this is a lifetime relationship that can't
// be expressed without generic associated types, better unification of HRTBs in type position,
@@ -18,7 +18,7 @@
use serde::{Serialize, de::DeserializeOwned};
use std::fmt::Debug;
use codec::{Slicable, Input};
use codec::{Decode, Encode, Codec, Input, Output};
use runtime_support::AuxDispatchable;
use traits::{self, Checkable, Applyable, BlakeTwo256};
@@ -28,14 +28,19 @@ pub use substrate_primitives::H256;
pub struct Digest {
pub logs: Vec<u64>,
}
impl Slicable for Digest {
impl Decode for Digest {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Vec::<u64>::decode(input).map(|logs| Digest { logs })
}
}
impl Encode for Digest {
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.logs.using_encoded(f)
}
}
impl traits::Digest for Digest {
type Item = u64;
fn push(&mut self, item: Self::Item) {
@@ -53,27 +58,29 @@ pub struct Header {
pub extrinsics_root: H256,
pub digest: Digest,
}
impl Slicable for Header {
impl Decode for Header {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(Header {
parent_hash: Slicable::decode(input)?,
number: Slicable::decode(input)?,
state_root: Slicable::decode(input)?,
extrinsics_root: Slicable::decode(input)?,
digest: Slicable::decode(input)?,
parent_hash: Decode::decode(input)?,
number: Decode::decode(input)?,
state_root: Decode::decode(input)?,
extrinsics_root: Decode::decode(input)?,
digest: Decode::decode(input)?,
})
}
}
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
self.parent_hash.using_encoded(|s| v.extend(s));
self.number.using_encoded(|s| v.extend(s));
self.state_root.using_encoded(|s| v.extend(s));
self.extrinsics_root.using_encoded(|s| v.extend(s));
self.digest.using_encoded(|s| v.extend(s));
v
impl Encode for Header {
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.parent_hash);
dest.push(&self.number);
dest.push(&self.state_root);
dest.push(&self.extrinsics_root);
dest.push(&self.digest);
}
}
impl traits::Header for Header {
type Number = u64;
type Hashing = BlakeTwo256;
@@ -109,25 +116,25 @@ impl traits::Header for Header {
}
#[derive(PartialEq, Eq, Clone, Serialize, Deserialize, Debug)]
pub struct Block<Xt: Slicable + Sized + Send + Sync + Serialize + Clone + Eq + Debug> {
pub struct Block<Xt> {
pub header: Header,
pub extrinsics: Vec<Xt>,
}
impl<Xt: Slicable + Sized + Send + Sync + Serialize + DeserializeOwned + Clone + Eq + Debug> Slicable for Block<Xt> {
impl<Xt: Decode> Decode for Block<Xt> {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(Block {
header: Slicable::decode(input)?,
extrinsics: Slicable::decode(input)?,
header: Decode::decode(input)?,
extrinsics: Decode::decode(input)?,
})
}
fn encode(&self) -> Vec<u8> {
let mut v: Vec<u8> = Vec::new();
v.extend(self.header.encode());
v.extend(self.extrinsics.encode());
v
}
impl<Xt: Encode> Encode for Block<Xt> {
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.header);
dest.push(&self.extrinsics);
}
}
impl<Xt: 'static + Slicable + Sized + Send + Sync + Serialize + DeserializeOwned + Clone + Eq + Debug> traits::Block for Block<Xt> {
impl<Xt: 'static + Codec + Sized + Send + Sync + Serialize + DeserializeOwned + Clone + Eq + Debug> traits::Block for Block<Xt> {
type Extrinsic = Xt;
type Header = Header;
type Hash = <Header as traits::Header>::Hash;
@@ -147,21 +154,25 @@ impl<Xt: 'static + Slicable + Sized + Send + Sync + Serialize + DeserializeOwned
}
#[derive(PartialEq, Eq, Clone, Serialize, Deserialize, Debug)]
pub struct TestXt<Call: AuxDispatchable + Slicable + Sized + Send + Sync + Serialize>(pub (u64, u64, Call));
pub struct TestXt<Call>(pub (u64, u64, Call));
impl<Call: AuxDispatchable + Slicable + Sized + Send + Sync + Serialize + DeserializeOwned + Clone + Eq + Debug> Slicable for TestXt<Call> {
impl<Call: Decode> Decode for TestXt<Call> {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(TestXt(Slicable::decode(input)?))
}
fn encode(&self) -> Vec<u8> {
self.0.encode()
Some(TestXt(Decode::decode(input)?))
}
}
impl<Call: Slicable + Sync + Send + Serialize + AuxDispatchable, Context> Checkable<Context> for TestXt<Call> {
impl<Call: Encode> Encode for TestXt<Call> {
fn encode_to<T: Output>(&self, dest: &mut T) {
self.0.encode_to(dest)
}
}
impl<Call: Codec + Sync + Send + Serialize + AuxDispatchable, Context> Checkable<Context> for TestXt<Call> {
type Checked = Self;
fn check_with(self, _: Context) -> Result<Self::Checked, &'static str> { Ok(self) }
}
impl<Call: AuxDispatchable<Aux = u64> + Slicable + Sized + Send + Sync + Serialize + DeserializeOwned + Clone + Eq + Debug> Applyable for TestXt<Call> {
impl<Call: AuxDispatchable<Aux = u64> + Codec + Sized + Send + Sync + Serialize + DeserializeOwned + Clone + Eq + Debug> Applyable for TestXt<Call> {
type AccountId = u64;
type Index = u64;
fn sender(&self) -> &u64 { &(self.0).0 }
@@ -22,7 +22,7 @@ use runtime_io;
#[cfg(feature = "std")] use std::fmt::{Debug, Display};
#[cfg(feature = "std")] use serde::{Serialize, de::DeserializeOwned};
use substrate_primitives;
use codec::Slicable;
use codec::{Codec, Encode};
pub use integer_sqrt::IntegerSquareRoot;
pub use num_traits::{Zero, One, Bounded};
use rstd::ops::{Add, Sub, Mul, Div, Rem, AddAssign, SubAssign, MulAssign, DivAssign, RemAssign};
@@ -194,8 +194,8 @@ pub trait Hash: 'static + MaybeSerializeDebug + Clone + Eq + PartialEq { // Stup
fn hash(s: &[u8]) -> Self::Output;
/// Produce the hash of some codec-encodable value.
fn hash_of<S: Slicable>(s: &S) -> Self::Output {
Slicable::using_encoded(s, Self::hash)
fn hash_of<S: Codec>(s: &S) -> Self::Output {
Encode::using_encoded(s, Self::hash)
}
/// Produce the patricia-trie root of a mapping from indices to byte slices.
@@ -307,7 +307,7 @@ pub trait Member: Send + Sync + Sized + MaybeSerializeDebug + Eq + PartialEq + C
impl<T: Send + Sync + Sized + MaybeSerializeDebug + Eq + PartialEq + Clone + 'static> Member for T {}
/// Something that acts like a `Digest` - it can have `Log`s `push`ed onto it and these `Log`s are
/// each `Slicable`.
/// each `Codec`.
pub trait Digest {
type Item: Member;
fn push(&mut self, item: Self::Item);
@@ -318,9 +318,9 @@ pub trait Digest {
/// `parent_hash`, as well as a `digest` and a block `number`.
///
/// You can also create a `new` one from those fields.
pub trait Header: Clone + Send + Sync + Slicable + Eq + MaybeSerializeDebug + 'static {
type Number: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + SimpleArithmetic + Slicable;
type Hash: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + Default + SimpleBitOps + Slicable + AsRef<[u8]>;
pub trait Header: Clone + Send + Sync + Codec + Eq + MaybeSerializeDebug + 'static {
type Number: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + SimpleArithmetic + Codec;
type Hash: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + Default + SimpleBitOps + Codec + AsRef<[u8]>;
type Hashing: Hash<Output = Self::Hash>;
type Digest: Member + Default;
@@ -356,10 +356,10 @@ pub trait Header: Clone + Send + Sync + Slicable + Eq + MaybeSerializeDebug + 's
/// `Extrinsic` piece of information as well as a `Header`.
///
/// You can get an iterator over each of the `extrinsics` and retrieve the `header`.
pub trait Block: Clone + Send + Sync + Slicable + Eq + MaybeSerializeDebug + 'static {
type Extrinsic: Member + Slicable;
pub trait Block: Clone + Send + Sync + Codec + Eq + MaybeSerializeDebug + 'static {
type Extrinsic: Member + Codec;
type Header: Header<Hash=Self::Hash>;
type Hash: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + Default + SimpleBitOps + Slicable + AsRef<[u8]>;
type Hash: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + Default + SimpleBitOps + Codec + AsRef<[u8]>;
fn header(&self) -> &Self::Header;
fn extrinsics(&self) -> &[Self::Extrinsic];
@@ -246,7 +246,7 @@ impl<T: Trait> primitives::BuildStorage for GenesisConfig<T>
{
fn build_storage(self) -> ::std::result::Result<runtime_io::TestExternalities, String> {
use runtime_io::twox_128;
use codec::Slicable;
use codec::Encode;
use primitives::traits::As;
Ok(map![
twox_128(<SessionLength<T>>::key()).to_vec() => self.session_length.encode(),
@@ -16,10 +16,9 @@
//! Address type that is union of index and id for an account.
use rstd::prelude::*;
#[cfg(feature = "std")]
use std::fmt;
use super::{Member, Slicable, As, Input};
use super::{Member, Decode, Encode, As, Input, Output};
/// A vetted and verified extrinsic from the external world.
#[derive(PartialEq, Eq, Clone)]
@@ -59,45 +58,46 @@ fn need_more_than<T: PartialOrd>(a: T, b: T) -> Option<T> {
if a < b { Some(a) } else { None }
}
impl<AccountId, AccountIndex> Slicable for Address<AccountId, AccountIndex> where
AccountId: Member + Slicable,
AccountIndex: Member + Slicable + PartialOrd<AccountIndex> + Ord + As<u32> + As<u16> + As<u8> + Copy,
impl<AccountId, AccountIndex> Decode for Address<AccountId, AccountIndex> where
AccountId: Member + Decode,
AccountIndex: Member + Decode + PartialOrd<AccountIndex> + Ord + As<u32> + As<u16> + As<u8> + Copy,
{
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(match input.read_byte()? {
x @ 0x00...0xef => Address::Index(As::sa(x)),
0xfc => Address::Index(As::sa(need_more_than(0xef, u16::decode(input)?)?)),
0xfd => Address::Index(As::sa(need_more_than(0xffff, u32::decode(input)?)?)),
0xfe => Address::Index(need_more_than(As::sa(0xffffffffu32), Slicable::decode(input)?)?),
0xff => Address::Id(Slicable::decode(input)?),
0xfe => Address::Index(need_more_than(As::sa(0xffffffffu32), Decode::decode(input)?)?),
0xff => Address::Id(Decode::decode(input)?),
_ => return None,
})
}
}
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
impl<AccountId, AccountIndex> Encode for Address<AccountId, AccountIndex> where
AccountId: Member + Encode,
AccountIndex: Member + Encode + PartialOrd<AccountIndex> + Ord + As<u32> + As<u16> + As<u8> + Copy,
{
fn encode_to<T: Output>(&self, dest: &mut T) {
match *self {
Address::Id(ref i) => {
v.push(255);
i.using_encoded(|s| v.extend(s));
dest.push_byte(255);
dest.push(i);
}
Address::Index(i) if i > As::sa(0xffffffffu32) => {
v.push(254);
i.using_encoded(|s| v.extend(s));
dest.push_byte(254);
dest.push(&i);
}
Address::Index(i) if i > As::sa(0xffffu32) => {
v.push(253);
As::<u32>::as_(i).using_encoded(|s| v.extend(s));
dest.push_byte(253);
dest.push(&As::<u32>::as_(i));
}
Address::Index(i) if i >= As::sa(0xf0u32) => {
v.push(252);
As::<u16>::as_(i).using_encoded(|s| v.extend(s));
dest.push_byte(252);
dest.push(&As::<u16>::as_(i));
}
Address::Index(i) => v.push(As::<u8>::as_(i)),
Address::Index(i) => dest.push_byte(As::<u8>::as_(i)),
}
v
}
}
@@ -19,7 +19,7 @@
//! This implementation is somewhat specialized to the tracking of the storage of accounts.
use rstd::prelude::*;
use codec::Slicable;
use codec::{Codec, Encode};
use runtime_support::storage::unhashed;
use runtime_io::{blake2_256, twox_128};
@@ -29,7 +29,7 @@ use runtime_io::{blake2_256, twox_128};
fn first_part_of_key<M: StorageDoubleMap + ?Sized>(k1: M::Key1) -> [u8; 16] {
let mut raw_prefix = Vec::new();
raw_prefix.extend(M::PREFIX);
raw_prefix.extend(Slicable::encode(&k1));
raw_prefix.extend(Encode::encode(&k1));
twox_128(&raw_prefix)
}
@@ -38,7 +38,7 @@ fn first_part_of_key<M: StorageDoubleMap + ?Sized>(k1: M::Key1) -> [u8; 16] {
/// The first part is hased by XX and then concatenated with a blake2 hash of `k2`.
fn full_key<M: StorageDoubleMap + ?Sized>(k1: M::Key1, k2: M::Key2) -> Vec<u8> {
let first_part = first_part_of_key::<M>(k1);
let second_part = blake2_256(&Slicable::encode(&k2));
let second_part = blake2_256(&Encode::encode(&k2));
let mut k = Vec::new();
k.extend(&first_part);
@@ -60,9 +60,9 @@ fn full_key<M: StorageDoubleMap + ?Sized>(k1: M::Key1, k2: M::Key2) -> Vec<u8> {
/// Blake2 is used for `Key2` is because it will be used as a for a key for contract's storage and
/// thus will be susceptible for a untrusted input.
pub trait StorageDoubleMap {
type Key1: Slicable;
type Key2: Slicable;
type Value: Slicable + Default;
type Key1: Codec;
type Key2: Codec;
type Value: Codec + Default;
const PREFIX: &'static [u8];
@@ -20,7 +20,7 @@
use rstd::prelude::*;
use runtime_io::twox_128;
use codec::Slicable;
use codec::Encode;
use runtime_support::{StorageValue, StorageMap};
use primitives::traits::{Zero, As};
use {runtime_io, primitives};
@@ -50,7 +50,7 @@ use account_db::State;
use rstd::prelude::*;
use rstd::{cmp, result};
use rstd::collections::btree_map::BTreeMap;
use codec::{Input, Slicable};
use codec::{Encode, Decode, Codec, Input, Output};
use runtime_support::{StorageValue, StorageMap, Parameter};
use runtime_support::dispatch::Result;
use session::OnSessionChange;
@@ -110,8 +110,8 @@ impl ContractAddressFor<u64> for DummyContractAddressFor {
impl<Hash, AccountId> ContractAddressFor<AccountId> for Hash where
Hash: HashT,
AccountId: Sized + Slicable + From<Hash::Output>,
Hash::Output: Slicable
AccountId: Sized + Codec + From<Hash::Output>,
Hash::Output: Codec
{
fn contract_address_for(code: &[u8], origin: &AccountId) -> AccountId {
let mut dest_pre = Hash::hash(code).encode();
@@ -122,12 +122,12 @@ impl<Hash, AccountId> ContractAddressFor<AccountId> for Hash where
pub trait Trait: system::Trait + session::Trait {
/// The balance of an account.
type Balance: Parameter + SimpleArithmetic + Slicable + Default + Copy + As<Self::AccountIndex> + As<usize> + As<u64>;
type Balance: Parameter + SimpleArithmetic + Codec + Default + Copy + As<Self::AccountIndex> + As<usize> + As<u64>;
/// Function type to get the contract address given the creator.
type DetermineContractAddress: ContractAddressFor<Self::AccountId>;
/// Type used for storing an account's index; implies the maximum number of accounts the system
/// can hold.
type AccountIndex: Parameter + Member + Slicable + SimpleArithmetic + As<u8> + As<u16> + As<u32> + As<u64> + As<usize> + Copy;
type AccountIndex: Parameter + Member + Codec + SimpleArithmetic + As<u8> + As<u16> + As<u32> + As<u64> + As<usize> + Copy;
}
decl_module! {
@@ -46,14 +46,14 @@ use safe_mix::TripletMix;
#[cfg(any(feature = "std", test))]
use rstd::marker::PhantomData;
#[cfg(any(feature = "std", test))]
use codec::Slicable;
use codec::Encode;
#[cfg(any(feature = "std", test))]
use runtime_io::{twox_128, TestExternalities};
/// Compute the extrinsics root of a list of extrinsics.
pub fn extrinsics_root<H: Hash, E: codec::Slicable>(extrinsics: &[E]) -> H::Output {
extrinsics_data_root::<H>(extrinsics.iter().map(codec::Slicable::encode).collect())
pub fn extrinsics_root<H: Hash, E: codec::Encode>(extrinsics: &[E]) -> H::Output {
extrinsics_data_root::<H>(extrinsics.iter().map(codec::Encode::encode).collect())
}
/// Compute the extrinsics root of a list of extrinsics.
@@ -209,7 +209,7 @@ impl<T: Trait> primitives::BuildStorage for GenesisConfig<T>
{
fn build_storage(self) -> Result<runtime_io::TestExternalities, String> {
use runtime_io::twox_128;
use codec::Slicable;
use codec::Encode;
Ok(map![
twox_128(&<BlockHash<T>>::key_for(T::BlockNumber::zero())).to_vec() => [69u8; 32].encode(),
@@ -128,7 +128,7 @@ impl<T: Trait> runtime_primitives::BuildStorage for GenesisConfig<T>
{
fn build_storage(self) -> ::std::result::Result<runtime_primitives::StorageMap, String> {
use runtime_io::twox_128;
use codec::Slicable;
use codec::Encode;
Ok(map![
twox_128(<BlockPeriod<T>>::key()).to_vec() => self.period.encode(),
twox_128(<Now<T>>::key()).to_vec() => T::Moment::sa(0).encode()
+17 -20
View File
@@ -35,7 +35,9 @@ extern crate substrate_runtime_support as runtime_support;
extern crate substrate_codec as codec;
use rstd::prelude::*;
use codec::Slicable;
use codec::{Encode, Output};
#[cfg(feature = "std")]
use codec::{Decode, Input};
#[cfg(feature = "std")]
use std::borrow::Cow;
@@ -134,30 +136,25 @@ impl RuntimeVersion {
}
}
impl Slicable for RuntimeVersion {
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
v.extend(codec::encode_slice(self.spec_name.as_bytes()));
v.extend(codec::encode_slice(self.impl_name.as_bytes()));
self.authoring_version.using_encoded(|s| v.extend(s));
self.spec_version.using_encoded(|s| v.extend(s));
self.impl_version.using_encoded(|s| v.extend(s));
v
impl Encode for RuntimeVersion {
fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(self.spec_name.as_bytes());
dest.push(self.impl_name.as_bytes());
dest.push(&self.authoring_version);
dest.push(&self.spec_version);
dest.push(&self.impl_version);
}
}
#[cfg(not(feature = "std"))]
fn decode<I: codec::Input>(_value: &mut I) -> Option<Self> {
unreachable!()
}
#[cfg(feature = "std")]
fn decode<I: codec::Input>(value: &mut I) -> Option<Self> {
#[cfg(feature = "std")]
impl Decode for RuntimeVersion {
fn decode<I: Input>(value: &mut I) -> Option<Self> {
Some(RuntimeVersion {
spec_name: Cow::Owned(String::from_utf8_lossy(&Vec::decode(value)?).into()),
impl_name: Cow::Owned(String::from_utf8_lossy(&Vec::decode(value)?).into()),
authoring_version: Slicable::decode(value)?,
spec_version: Slicable::decode(value)?,
impl_version: Slicable::decode(value)?,
authoring_version: Decode::decode(value)?,
spec_version: Decode::decode(value)?,
impl_version: Decode::decode(value)?,
})
}
}