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 e1c90b573b
commit 1e1ddf61f2
21 changed files with 157 additions and 175 deletions
+3 -3
View File
@@ -93,7 +93,7 @@ impl<B: LocalBackend<Block>> PolkadotApi for Client<B, LocalCallExecutor<B, Nati
fn evaluate_block(&self, at: &BlockId, block: Block) -> Result<bool> { fn evaluate_block(&self, at: &BlockId, block: Block) -> Result<bool> {
use substrate_executor::error::ErrorKind as ExecErrorKind; use substrate_executor::error::ErrorKind as ExecErrorKind;
use codec::Slicable; use codec::{Decode, Encode};
use runtime::Block as RuntimeBlock; use runtime::Block as RuntimeBlock;
let encoded = block.encode(); let encoded = block.encode();
@@ -142,13 +142,13 @@ impl<B: LocalBackend<Block>> PolkadotApi for Client<B, LocalCallExecutor<B, Nati
} }
fn inherent_extrinsics(&self, at: &BlockId, timestamp: Timestamp, new_heads: Vec<CandidateReceipt>) -> Result<Vec<UncheckedExtrinsic>> { fn inherent_extrinsics(&self, at: &BlockId, timestamp: Timestamp, new_heads: Vec<CandidateReceipt>) -> Result<Vec<UncheckedExtrinsic>> {
use codec::Slicable; use codec::{Encode, Decode};
with_runtime!(self, at, || { with_runtime!(self, at, || {
let extrinsics = ::runtime::inherent_extrinsics(timestamp, new_heads); let extrinsics = ::runtime::inherent_extrinsics(timestamp, new_heads);
extrinsics.into_iter() extrinsics.into_iter()
.map(|x| x.encode()) // get encoded representation .map(|x| x.encode()) // get encoded representation
.map(|x| Slicable::decode(&mut &x[..])) // get byte-vec equivalent to extrinsic .map(|x| Decode::decode(&mut &x[..])) // get byte-vec equivalent to extrinsic
.map(|x| x.expect("UncheckedExtrinsic has encoded representation equivalent to Vec<u8>; qed")) .map(|x| x.expect("UncheckedExtrinsic has encoded representation equivalent to Vec<u8>; qed"))
.collect() .collect()
}) })
+1 -1
View File
@@ -19,7 +19,7 @@
use std::sync::Arc; use std::sync::Arc;
use client::backend::{Backend, RemoteBackend}; use client::backend::{Backend, RemoteBackend};
use client::{Client, CallExecutor}; use client::{Client, CallExecutor};
use codec::Slicable; use codec::Decode;
use primitives::{AccountId, Block, BlockId, Hash, Index, SessionKey, Timestamp, UncheckedExtrinsic}; use primitives::{AccountId, Block, BlockId, Hash, Index, SessionKey, Timestamp, UncheckedExtrinsic};
use runtime::Address; use runtime::Address;
use primitives::parachain::{CandidateReceipt, DutyRoster, Id as ParaId}; use primitives::parachain::{CandidateReceipt, DutyRoster, Id as ParaId};
+2 -2
View File
@@ -79,7 +79,7 @@ use std::net::SocketAddr;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use substrate_telemetry::{init_telemetry, TelemetryConfig}; use substrate_telemetry::{init_telemetry, TelemetryConfig};
use polkadot_primitives::BlockId; use polkadot_primitives::BlockId;
use codec::Slicable; use codec::{Decode, Encode};
use client::BlockOrigin; use client::BlockOrigin;
use runtime_primitives::generic::SignedBlock; use runtime_primitives::generic::SignedBlock;
@@ -407,7 +407,7 @@ fn import_blocks<E>(matches: &clap::ArgMatches, exit: E) -> error::Result<()>
}; };
info!("Importing blocks"); info!("Importing blocks");
let count: u32 = Slicable::decode(&mut file).ok_or("Error reading file")?; let count: u32 = Decode::decode(&mut file).ok_or("Error reading file")?;
let mut block = 0; let mut block = 0;
for _ in 0 .. count { for _ in 0 .. count {
if exit_recv.try_recv().is_ok() { if exit_recv.try_recv().is_ok() {
+3 -3
View File
@@ -18,7 +18,7 @@
use super::MAX_TRANSACTIONS_SIZE; use super::MAX_TRANSACTIONS_SIZE;
use codec::Slicable; use codec::{Decode, Encode};
use polkadot_runtime::{Block as PolkadotGenericBlock, CheckedBlock}; use polkadot_runtime::{Block as PolkadotGenericBlock, CheckedBlock};
use polkadot_primitives::{Block, Hash, BlockNumber, Timestamp}; use polkadot_primitives::{Block, Hash, BlockNumber, Timestamp};
use polkadot_primitives::parachain::Id as ParaId; use polkadot_primitives::parachain::Id as ParaId;
@@ -78,13 +78,13 @@ pub fn evaluate_initial(
) -> Result<CheckedBlock> { ) -> Result<CheckedBlock> {
const MAX_TIMESTAMP_DRIFT: Timestamp = 60; const MAX_TIMESTAMP_DRIFT: Timestamp = 60;
let encoded = Slicable::encode(proposal); let encoded = Encode::encode(proposal);
let proposal = PolkadotGenericBlock::decode(&mut &encoded[..]) let proposal = PolkadotGenericBlock::decode(&mut &encoded[..])
.and_then(|b| CheckedBlock::new(b).ok()) .and_then(|b| CheckedBlock::new(b).ok())
.ok_or_else(|| ErrorKind::ProposalNotForPolkadot)?; .ok_or_else(|| ErrorKind::ProposalNotForPolkadot)?;
let transactions_size = proposal.extrinsics.iter().fold(0, |a, tx| { let transactions_size = proposal.extrinsics.iter().fold(0, |a, tx| {
a + Slicable::encode(tx).len() a + Encode::encode(tx).len()
}); });
if transactions_size > MAX_TRANSACTIONS_SIZE { if transactions_size > MAX_TRANSACTIONS_SIZE {
+2 -2
View File
@@ -65,7 +65,7 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc; use std::sync::Arc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use codec::Slicable; use codec::{Decode, Encode};
use polkadot_api::PolkadotApi; use polkadot_api::PolkadotApi;
use polkadot_primitives::{Hash, Block, BlockId, BlockNumber, Header, Timestamp, SessionKey}; use polkadot_primitives::{Hash, Block, BlockId, BlockNumber, Header, Timestamp, SessionKey};
use polkadot_primitives::parachain::{Id as ParaId, Chain, DutyRoster, BlockData, Extrinsic as ParachainExtrinsic, CandidateReceipt, CandidateSignature}; use polkadot_primitives::parachain::{Id as ParaId, Chain, DutyRoster, BlockData, Extrinsic as ParachainExtrinsic, CandidateReceipt, CandidateSignature};
@@ -710,7 +710,7 @@ impl<C> CreateProposal<C> where C: PolkadotApi {
.join(", ") .join(", ")
); );
let substrate_block = Slicable::decode(&mut polkadot_block.encode().as_slice()) let substrate_block = Decode::decode(&mut polkadot_block.encode().as_slice())
.expect("polkadot blocks defined to serialize to substrate blocks correctly; qed"); .expect("polkadot blocks defined to serialize to substrate blocks correctly; qed");
// TODO: full re-evaluation // TODO: full re-evaluation
+10 -10
View File
@@ -47,7 +47,7 @@ mod collator_pool;
mod router; mod router;
pub mod consensus; pub mod consensus;
use codec::Slicable; use codec::{Decode, Encode};
use futures::sync::oneshot; use futures::sync::oneshot;
use parking_lot::Mutex; use parking_lot::Mutex;
use polkadot_consensus::{Statement, SignedStatement, GenericStatement}; use polkadot_consensus::{Statement, SignedStatement, GenericStatement};
@@ -81,25 +81,25 @@ pub struct Status {
collating_for: Option<(AccountId, ParaId)>, collating_for: Option<(AccountId, ParaId)>,
} }
impl Slicable for Status { impl Encode for Status {
fn encode(&self) -> Vec<u8> { fn encode_to<T: codec::Output>(&self, dest: &mut T) {
let mut v = Vec::new();
match self.collating_for { match self.collating_for {
Some(ref details) => { Some(ref details) => {
v.push(1); dest.push_byte(1);
details.using_encoded(|s| v.extend(s)); dest.push(details);
} }
None => { None => {
v.push(0); dest.push_byte(0);
}
} }
} }
v
} }
fn decode<I: ::codec::Input>(input: &mut I) -> Option<Self> { impl Decode for Status {
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> {
let collating_for = match input.read_byte()? { let collating_for = match input.read_byte()? {
0 => None, 0 => None,
1 => Some(Slicable::decode(input)?), 1 => Some(Decode::decode(input)?),
_ => return None, _ => return None,
}; };
Some(Status { collating_for }) Some(Status { collating_for })
+1 -1
View File
@@ -23,7 +23,7 @@ use polkadot_consensus::GenericStatement;
use polkadot_primitives::{Block, Hash, SessionKey}; use polkadot_primitives::{Block, Hash, SessionKey};
use polkadot_primitives::parachain::{CandidateReceipt, HeadData, BlockData}; use polkadot_primitives::parachain::{CandidateReceipt, HeadData, BlockData};
use substrate_primitives::H512; use substrate_primitives::H512;
use codec::Slicable; use codec::Encode;
use substrate_network::{PeerId, PeerInfo, ClientHandle, Context, message::Message as SubstrateMessage, message::Role, specialization::Specialization, generic_message::Message as GenericMessage}; use substrate_network::{PeerId, PeerInfo, ClientHandle, Context, message::Message as SubstrateMessage, message::Role, specialization::Specialization, generic_message::Message as GenericMessage};
use std::sync::Arc; use std::sync::Arc;
+17 -17
View File
@@ -61,7 +61,7 @@ extern crate error_chain;
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
use alloc::vec::Vec; use alloc::vec::Vec;
use codec::Slicable; use codec::{Encode, Decode, Input, Output};
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub mod wasm; pub mod wasm;
@@ -77,20 +77,18 @@ pub struct ValidationParams {
pub parent_head: Vec<u8>, pub parent_head: Vec<u8>,
} }
impl Slicable for ValidationParams { impl Encode for ValidationParams {
fn encode(&self) -> Vec<u8> { fn encode_to<T: Output>(&self, dest: &mut T) {
let mut v = Vec::new(); dest.push(&self.block_data);
dest.push(&self.parent_head);
self.block_data.using_encoded(|s| v.extend(s)); }
self.parent_head.using_encoded(|s| v.extend(s));
v
} }
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> { impl Decode for ValidationParams {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(ValidationParams { Some(ValidationParams {
block_data: Slicable::decode(input)?, block_data: Decode::decode(input)?,
parent_head: Slicable::decode(input)?, parent_head: Decode::decode(input)?,
}) })
} }
} }
@@ -104,14 +102,16 @@ pub struct ValidationResult {
pub head_data: Vec<u8> pub head_data: Vec<u8>
} }
impl Slicable for ValidationResult { impl Encode for ValidationResult {
fn encode(&self) -> Vec<u8> { fn encode_to<T: Output>(&self, dest: &mut T) {
self.head_data.encode() dest.push(&self.head_data);
}
} }
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> { impl Decode for ValidationResult {
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(ValidationResult { Some(ValidationResult {
head_data: Slicable::decode(input)?, head_data: Decode::decode(input)?,
}) })
} }
} }
+1 -1
View File
@@ -20,7 +20,7 @@
//! Assuming the parameters are correct, this module provides a wrapper around //! Assuming the parameters are correct, this module provides a wrapper around
//! a WASM VM for re-execution of a parachain candidate. //! a WASM VM for re-execution of a parachain candidate.
use codec::Slicable; use codec::{Decode, Encode};
use wasmi::{self, Module, ModuleInstance, MemoryInstance, MemoryDescriptor, MemoryRef, ModuleImportResolver}; use wasmi::{self, Module, ModuleInstance, MemoryInstance, MemoryDescriptor, MemoryRef, ModuleImportResolver};
use wasmi::{memory_units, RuntimeValue}; use wasmi::{memory_units, RuntimeValue};
@@ -33,7 +33,7 @@ extern crate wee_alloc;
extern crate tiny_keccak; extern crate tiny_keccak;
extern crate pwasm_libc; extern crate pwasm_libc;
use parachain::codec::{Slicable, Input}; use parachain::codec::{Decode, Encode, Input, Output};
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
mod wasm; mod wasm;
@@ -41,9 +41,6 @@ mod wasm;
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
pub use wasm::*; pub use wasm::*;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
// Define global allocator. // Define global allocator.
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
#[global_allocator] #[global_allocator]
@@ -60,22 +57,20 @@ struct HeadData {
post_state: [u8; 32], post_state: [u8; 32],
} }
impl Slicable for HeadData { impl Encode for HeadData {
fn encode(&self) -> Vec<u8> { fn encode_to<T: Output>(&self, dest: &mut T) {
let mut v = Vec::new(); dest.push(&self.number);
dest.push(&self.parent_hash);
self.number.using_encoded(|s| v.extend(s)); dest.push(&self.post_state);
self.parent_hash.using_encoded(|s| v.extend(s)); }
self.post_state.using_encoded(|s| v.extend(s));
v
} }
impl Decode for HeadData {
fn decode<I: Input>(input: &mut I) -> Option<Self> { fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(HeadData { Some(HeadData {
number: Slicable::decode(input)?, number: Decode::decode(input)?,
parent_hash: Slicable::decode(input)?, parent_hash: Decode::decode(input)?,
post_state: Slicable::decode(input)?, post_state: Decode::decode(input)?,
}) })
} }
} }
@@ -89,20 +84,18 @@ struct BlockData {
add: u64, add: u64,
} }
impl Slicable for BlockData { impl Encode for BlockData {
fn encode(&self) -> Vec<u8> { fn encode_to<T: Output>(&self, dest: &mut T) {
let mut v = Vec::new(); dest.push(&self.state);
dest.push(&self.add);
self.state.using_encoded(|s| v.extend(s)); }
self.add.using_encoded(|s| v.extend(s));
v
} }
impl Decode for BlockData {
fn decode<I: Input>(input: &mut I) -> Option<Self> { fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(BlockData { Some(BlockData {
state: Slicable::decode(input)?, state: Decode::decode(input)?,
add: Slicable::decode(input)?, add: Decode::decode(input)?,
}) })
} }
} }
@@ -18,7 +18,7 @@
use core::{intrinsics, panic, alloc}; use core::{intrinsics, panic, alloc};
use parachain::{self, ValidationResult}; use parachain::{self, ValidationResult};
use parachain::codec::Slicable; use parachain::codec::{Encode, Decode};
use super::{HeadData, BlockData}; use super::{HeadData, BlockData};
#[panic_implementation] #[panic_implementation]
+19 -23
View File
@@ -20,7 +20,7 @@ extern crate polkadot_parachain as parachain;
extern crate tiny_keccak; extern crate tiny_keccak;
use parachain::ValidationParams; use parachain::ValidationParams;
use parachain::codec::{Slicable, Input}; use parachain::codec::{Decode, Encode, Input, Output};
// Head data for this parachain. // Head data for this parachain.
#[derive(Default, Clone)] #[derive(Default, Clone)]
@@ -33,22 +33,20 @@ struct HeadData {
post_state: [u8; 32], post_state: [u8; 32],
} }
impl Slicable for HeadData { impl Encode for HeadData {
fn encode(&self) -> Vec<u8> { fn encode_to<T: Output>(&self, dest: &mut T) {
let mut v = Vec::new(); dest.push(&self.number);
dest.push(&self.parent_hash);
self.number.using_encoded(|s| v.extend(s)); dest.push(&self.post_state);
self.parent_hash.using_encoded(|s| v.extend(s)); }
self.post_state.using_encoded(|s| v.extend(s));
v
} }
impl Decode for HeadData {
fn decode<I: Input>(input: &mut I) -> Option<Self> { fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(HeadData { Some(HeadData {
number: Slicable::decode(input)?, number: Decode::decode(input)?,
parent_hash: Slicable::decode(input)?, parent_hash: Decode::decode(input)?,
post_state: Slicable::decode(input)?, post_state: Decode::decode(input)?,
}) })
} }
} }
@@ -62,20 +60,18 @@ struct BlockData {
add: u64, add: u64,
} }
impl Slicable for BlockData { impl Encode for BlockData {
fn encode(&self) -> Vec<u8> { fn encode_to<T: Output>(&self, dest: &mut T) {
let mut v = Vec::new(); dest.push(&self.state);
dest.push(&self.add);
self.state.using_encoded(|s| v.extend(s)); }
self.add.using_encoded(|s| v.extend(s));
v
} }
impl Decode for BlockData {
fn decode<I: Input>(input: &mut I) -> Option<Self> { fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(BlockData { Some(BlockData {
state: Slicable::decode(input)?, state: Decode::decode(input)?,
add: Slicable::decode(input)?, add: Decode::decode(input)?,
}) })
} }
} }
+6 -4
View File
@@ -42,7 +42,7 @@ use primitives::bytes;
use rstd::prelude::*; use rstd::prelude::*;
use runtime_primitives::traits::BlakeTwo256; use runtime_primitives::traits::BlakeTwo256;
use runtime_primitives::generic; use runtime_primitives::generic;
use codec::{Input, Slicable}; use codec::{Encode, Decode, Input, Output};
pub mod parachain; pub mod parachain;
@@ -109,12 +109,14 @@ pub type BlockId = generic::BlockId<Block>;
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Log(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>); pub struct Log(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
impl Slicable for Log { impl Decode for Log {
fn decode<I: Input>(input: &mut I) -> Option<Self> { fn decode<I: Input>(input: &mut I) -> Option<Self> {
Vec::<u8>::decode(input).map(Log) Vec::<u8>::decode(input).map(Log)
} }
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R { impl Encode for Log {
self.0.using_encoded(f) fn encode_to<T: Output>(&self, dest: &mut T) {
self.0.encode_to(dest)
} }
} }
+44 -52
View File
@@ -16,7 +16,7 @@
//! Polkadot parachain types. //! Polkadot parachain types.
use codec::{Slicable, Input}; use codec::{Encode, Decode, Input, Output};
use rstd::prelude::*; use rstd::prelude::*;
use rstd::cmp::Ordering; use rstd::cmp::Ordering;
use super::Hash; use super::Hash;
@@ -47,11 +47,13 @@ impl Id {
} }
} }
impl Slicable for Id { impl Decode for Id {
fn decode<I: Input>(input: &mut I) -> Option<Self> { fn decode<I: Input>(input: &mut I) -> Option<Self> {
u32::decode(input).map(Id) u32::decode(input).map(Id)
} }
}
impl Encode for Id {
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R { fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.0.using_encoded(f) self.0.using_encoded(f)
} }
@@ -67,30 +69,26 @@ pub enum Chain {
Parachain(Id), Parachain(Id),
} }
impl Slicable for Chain { impl Decode for Chain {
fn decode<I: Input>(input: &mut I) -> Option<Self> { fn decode<I: Input>(input: &mut I) -> Option<Self> {
let disc = input.read_byte()?; let disc = input.read_byte()?;
match disc { match disc {
0 => Some(Chain::Relay), 0 => Some(Chain::Relay),
1 => Some(Chain::Parachain(Slicable::decode(input)?)), 1 => Some(Chain::Parachain(Decode::decode(input)?)),
_ => None, _ => None,
} }
} }
}
fn encode(&self) -> Vec<u8> { impl Encode for Chain {
let mut v = Vec::new(); fn encode_to<T: Output>(&self, dest: &mut T) {
match *self { match *self {
Chain::Relay => { v.push(0); } Chain::Relay => { dest.push_byte(0); }
Chain::Parachain(id) => { Chain::Parachain(id) => {
v.push(1u8); dest.push_byte(1u8);
id.using_encoded(|s| v.extend(s)); dest.push(&id);
} }
} }
v
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(&self.encode().as_slice())
} }
} }
@@ -105,25 +103,19 @@ pub struct DutyRoster {
pub guarantor_duty: Vec<Chain>, pub guarantor_duty: Vec<Chain>,
} }
impl Slicable for DutyRoster { impl Decode for DutyRoster {
fn decode<I: Input>(input: &mut I) -> Option<Self> { fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(DutyRoster { Some(DutyRoster {
validator_duty: Slicable::decode(input)?, validator_duty: Decode::decode(input)?,
guarantor_duty: Slicable::decode(input)?, guarantor_duty: Decode::decode(input)?,
}) })
} }
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
v.extend(self.validator_duty.encode());
v.extend(self.guarantor_duty.encode());
v
} }
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R { impl Encode for DutyRoster {
f(&self.encode().as_slice()) fn encode_to<T: Output>(&self, dest: &mut T) {
dest.push(&self.validator_duty);
dest.push(&self.guarantor_duty);
} }
} }
@@ -158,32 +150,30 @@ pub struct CandidateReceipt {
pub block_data_hash: Hash, pub block_data_hash: Hash,
} }
impl Slicable for CandidateReceipt { impl Encode for CandidateReceipt {
fn encode(&self) -> Vec<u8> { fn encode_to<T: Output>(&self, dest: &mut T) {
let mut v = Vec::new(); dest.push(&self.parachain_index);
dest.push(&self.collator);
self.parachain_index.using_encoded(|s| v.extend(s)); dest.push(&self.signature);
self.collator.using_encoded(|s| v.extend(s)); dest.push(&self.head_data.0);
self.signature.using_encoded(|s| v.extend(s)); dest.push(&self.balance_uploads);
self.head_data.0.using_encoded(|s| v.extend(s)); dest.push(&self.egress_queue_roots);
self.balance_uploads.using_encoded(|s| v.extend(s)); dest.push(&self.fees);
self.egress_queue_roots.using_encoded(|s| v.extend(s)); dest.push(&self.block_data_hash);
self.fees.using_encoded(|s| v.extend(s)); }
self.block_data_hash.using_encoded(|s| v.extend(s));
v
} }
impl Decode for CandidateReceipt {
fn decode<I: Input>(input: &mut I) -> Option<Self> { fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(CandidateReceipt { Some(CandidateReceipt {
parachain_index: Slicable::decode(input)?, parachain_index: Decode::decode(input)?,
collator: Slicable::decode(input)?, collator: Decode::decode(input)?,
signature: Slicable::decode(input)?, signature: Decode::decode(input)?,
head_data: Slicable::decode(input).map(HeadData)?, head_data: Decode::decode(input).map(HeadData)?,
balance_uploads: Slicable::decode(input)?, balance_uploads: Decode::decode(input)?,
egress_queue_roots: Slicable::decode(input)?, egress_queue_roots: Decode::decode(input)?,
fees: Slicable::decode(input)?, fees: Decode::decode(input)?,
block_data_hash: Slicable::decode(input)?, block_data_hash: Decode::decode(input)?,
}) })
} }
} }
@@ -283,13 +273,15 @@ pub struct ValidationCode(#[cfg_attr(feature = "std", serde(with="bytes"))] pub
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Activity(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>); pub struct Activity(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
impl Slicable for Activity { impl Decode for Activity {
fn decode<I: Input>(input: &mut I) -> Option<Self> { fn decode<I: Input>(input: &mut I) -> Option<Self> {
Vec::<u8>::decode(input).map(Activity) Vec::<u8>::decode(input).map(Activity)
} }
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R { impl Encode for Activity {
self.0.using_encoded(f) fn encode_to<T: Output>(&self, dest: &mut T) {
self.0.encode_to(dest)
} }
} }
+3 -3
View File
@@ -257,7 +257,7 @@ pub mod api {
mod tests { mod tests {
use super::*; use super::*;
use substrate_primitives as primitives; use substrate_primitives as primitives;
use ::codec::Slicable; use codec::{Encode, Decode};
use substrate_primitives::hexdisplay::HexDisplay; use substrate_primitives::hexdisplay::HexDisplay;
use substrate_serializer as ser; use substrate_serializer as ser;
use runtime_primitives::traits::{Digest as DigestT, Header as HeaderT}; use runtime_primitives::traits::{Digest as DigestT, Header as HeaderT};
@@ -376,7 +376,7 @@ mod tests {
// df0f0200 // df0f0200
// 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 // 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
let v = Slicable::encode(&tx); let v = Encode::encode(&tx);
assert_eq!(&v[..], &hex!["6f000000ff0101010101010101010101010101010101010101010101010101010101010101e70300000300df0f02000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"][..]); assert_eq!(&v[..], &hex!["6f000000ff0101010101010101010101010101010101010101010101010101010101010101e70300000300df0f02000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"][..]);
println!("{}", HexDisplay::from(&v)); println!("{}", HexDisplay::from(&v));
assert_eq!(UncheckedExtrinsic::decode(&mut &v[..]).unwrap(), tx); assert_eq!(UncheckedExtrinsic::decode(&mut &v[..]).unwrap(), tx);
@@ -393,7 +393,7 @@ mod tests {
)) ))
))), ))),
}; };
let v = Slicable::encode(&xt); let v = Encode::encode(&xt);
assert_eq!(Extrinsic::decode(&mut &v[..]).unwrap(), xt); assert_eq!(Extrinsic::decode(&mut &v[..]).unwrap(), xt);
} }
+2 -2
View File
@@ -17,7 +17,7 @@
//! Main parachains logic. For now this is just the determination of which validators do what. //! Main parachains logic. For now this is just the determination of which validators do what.
use rstd::prelude::*; use rstd::prelude::*;
use codec::Slicable; use codec::Decode;
use runtime_primitives::traits::{Hash, BlakeTwo256, Executable, RefInto, MaybeEmpty}; use runtime_primitives::traits::{Hash, BlakeTwo256, Executable, RefInto, MaybeEmpty};
use primitives::parachain::{Id, Chain, DutyRoster, CandidateReceipt}; use primitives::parachain::{Id, Chain, DutyRoster, CandidateReceipt};
@@ -217,7 +217,7 @@ impl<T: Trait> runtime_primitives::BuildStorage for GenesisConfig<T>
fn build_storage(mut self) -> ::std::result::Result<runtime_io::TestExternalities, String> { fn build_storage(mut self) -> ::std::result::Result<runtime_io::TestExternalities, String> {
use std::collections::HashMap; use std::collections::HashMap;
use runtime_io::twox_128; use runtime_io::twox_128;
use codec::Slicable; use codec::Encode;
self.parachains.sort_unstable_by_key(|&(ref id, _)| id.clone()); self.parachains.sort_unstable_by_key(|&(ref id, _)| id.clone());
self.parachains.dedup_by_key(|&mut (ref id, _)| id.clone()); self.parachains.dedup_by_key(|&mut (ref id, _)| id.clone());
+2 -2
View File
@@ -43,7 +43,7 @@ pub mod chain_spec;
use std::sync::Arc; use std::sync::Arc;
use std::collections::HashMap; use std::collections::HashMap;
use codec::Slicable; use codec::Encode;
use transaction_pool::TransactionPool; use transaction_pool::TransactionPool;
use polkadot_api::{PolkadotApi, light::RemotePolkadotApiWrapper}; use polkadot_api::{PolkadotApi, light::RemotePolkadotApiWrapper};
use polkadot_primitives::{Block, BlockId, Hash}; use polkadot_primitives::{Block, BlockId, Hash};
@@ -265,7 +265,7 @@ impl<B, E, A> network::TransactionPool<Block> for TransactionPoolAdapter<B, E, A
} }
let encoded = transaction.encode(); let encoded = transaction.encode();
if let Some(uxt) = codec::Slicable::decode(&mut &encoded[..]) { if let Some(uxt) = codec::Decode::decode(&mut &encoded[..]) {
let best_block_id = self.best_block_id()?; let best_block_id = self.best_block_id()?;
match self.pool.import_unchecked_extrinsic(best_block_id, uxt) { match self.pool.import_unchecked_extrinsic(best_block_id, uxt) {
Ok(xt) => Some(*xt.hash()), Ok(xt) => Some(*xt.hash()),
+18 -19
View File
@@ -31,7 +31,7 @@ use std::collections::hash_map::{HashMap, Entry};
use std::hash::Hash; use std::hash::Hash;
use std::fmt::Debug; use std::fmt::Debug;
use codec::{Slicable, Input}; use codec::{Decode, Encode, Input, Output};
/// Context for the statement table. /// Context for the statement table.
pub trait Context { pub trait Context {
@@ -97,44 +97,43 @@ enum StatementKind {
Available = 4, Available = 4,
} }
impl<C: Slicable, D: Slicable> Slicable for Statement<C, D> { impl<C: Encode, D: Encode> Encode for Statement<C, D> {
fn encode(&self) -> Vec<u8> { fn encode_to<T: Output>(&self, dest: &mut T) {
let mut v = Vec::new();
match *self { match *self {
Statement::Candidate(ref candidate) => { Statement::Candidate(ref candidate) => {
v.push(StatementKind::Candidate as u8); dest.push_byte(StatementKind::Candidate as u8);
candidate.using_encoded(|s| v.extend(s)); dest.push(candidate);
} }
Statement::Valid(ref digest) => { Statement::Valid(ref digest) => {
v.push(StatementKind::Valid as u8); dest.push_byte(StatementKind::Valid as u8);
digest.using_encoded(|s| v.extend(s)); dest.push(digest);
} }
Statement::Invalid(ref digest) => { Statement::Invalid(ref digest) => {
v.push(StatementKind::Invalid as u8); dest.push_byte(StatementKind::Invalid as u8);
digest.using_encoded(|s| v.extend(s)); dest.push(digest);
} }
Statement::Available(ref digest) => { Statement::Available(ref digest) => {
v.push(StatementKind::Available as u8); dest.push_byte(StatementKind::Available as u8);
digest.using_encoded(|s| v.extend(s)); dest.push(digest);
}
}
} }
} }
v impl<C: Decode, D: Decode> Decode for Statement<C, D> {
}
fn decode<I: Input>(value: &mut I) -> Option<Self> { fn decode<I: Input>(value: &mut I) -> Option<Self> {
match value.read_byte() { match value.read_byte() {
Some(x) if x == StatementKind::Candidate as u8 => { Some(x) if x == StatementKind::Candidate as u8 => {
Slicable::decode(value).map(Statement::Candidate) Decode::decode(value).map(Statement::Candidate)
} }
Some(x) if x == StatementKind::Valid as u8 => { Some(x) if x == StatementKind::Valid as u8 => {
Slicable::decode(value).map(Statement::Valid) Decode::decode(value).map(Statement::Valid)
} }
Some(x) if x == StatementKind::Invalid as u8 => { Some(x) if x == StatementKind::Invalid as u8 => {
Slicable::decode(value).map(Statement::Invalid) Decode::decode(value).map(Statement::Invalid)
} }
Some(x) if x == StatementKind::Available as u8 => { Some(x) if x == StatementKind::Available as u8 => {
Slicable::decode(value).map(Statement::Available) Decode::decode(value).map(Statement::Available)
} }
_ => None, _ => None,
} }
+3 -3
View File
@@ -43,7 +43,7 @@ use std::{
sync::Arc, sync::Arc,
}; };
use codec::Slicable; use codec::{Decode, Encode};
use extrinsic_pool::{Pool, Listener, txpool::{self, Readiness, scoring::{Change, Choice}}}; use extrinsic_pool::{Pool, Listener, txpool::{self, Readiness, scoring::{Change, Choice}}};
use extrinsic_pool::api::{ExtrinsicPool, EventStream}; use extrinsic_pool::api::{ExtrinsicPool, EventStream};
use polkadot_api::PolkadotApi; use polkadot_api::PolkadotApi;
@@ -75,7 +75,7 @@ impl VerifiedTransaction {
/// Convert to primitive unchecked extrinsic. /// Convert to primitive unchecked extrinsic.
pub fn primitive_extrinsic(&self) -> ::primitives::UncheckedExtrinsic { pub fn primitive_extrinsic(&self) -> ::primitives::UncheckedExtrinsic {
Slicable::decode(&mut self.as_transaction().encode().as_slice()) Decode::decode(&mut self.as_transaction().encode().as_slice())
.expect("UncheckedExtrinsic shares repr with Vec<u8>; qed") .expect("UncheckedExtrinsic shares repr with Vec<u8>; qed")
} }
@@ -418,7 +418,7 @@ mod tests {
use std::sync::{atomic::{self, AtomicBool}, Arc}; use std::sync::{atomic::{self, AtomicBool}, Arc};
use super::TransactionPool; use super::TransactionPool;
use substrate_keyring::Keyring::{self, *}; use substrate_keyring::Keyring::{self, *};
use codec::Slicable; use codec::{Decode, Encode};
use polkadot_api::{PolkadotApi, BlockBuilder, Result}; use polkadot_api::{PolkadotApi, BlockBuilder, Result};
use primitives::{AccountId, AccountIndex, Block, BlockId, Hash, Index, SessionKey, Timestamp, use primitives::{AccountId, AccountIndex, Block, BlockId, Hash, Index, SessionKey, Timestamp,
UncheckedExtrinsic as FutureProofUncheckedExtrinsic}; UncheckedExtrinsic as FutureProofUncheckedExtrinsic};