mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-09 21:21:11 +00:00
Refactored Slicable (#324)
* Refactored Slicable * Docs * Wasm build * Wasm build * Renamed traits * Review nits * Renamed Slicable as well
This commit is contained in:
committed by
Gav Wood
parent
b45020175a
commit
1aeb2825af
@@ -42,7 +42,7 @@ mod tests {
|
||||
use runtime_io;
|
||||
use super::Executor;
|
||||
use substrate_executor::WasmExecutor;
|
||||
use codec::{Slicable, Joiner};
|
||||
use codec::{Encode, Decode, Joiner};
|
||||
use keyring::Keyring;
|
||||
use runtime_support::{Hashable, StorageValue, StorageMap};
|
||||
use state_machine::{CodeExecutor, TestExternalities};
|
||||
@@ -229,7 +229,7 @@ mod tests {
|
||||
UncheckedExtrinsic::new(extrinsic, signature)
|
||||
}).collect::<Vec<_>>();
|
||||
|
||||
let extrinsics_root = ordered_trie_root(extrinsics.iter().map(Slicable::encode)).0.into();
|
||||
let extrinsics_root = ordered_trie_root(extrinsics.iter().map(Encode::encode)).0.into();
|
||||
|
||||
let header = Header {
|
||||
parent_hash,
|
||||
|
||||
BIN
Binary file not shown.
Binary file not shown.
@@ -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> {
|
||||
use substrate_executor::error::ErrorKind as ExecErrorKind;
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use runtime::Block as RuntimeBlock;
|
||||
|
||||
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>> {
|
||||
use codec::Slicable;
|
||||
use codec::{Encode, Decode};
|
||||
|
||||
with_runtime!(self, at, || {
|
||||
let extrinsics = ::runtime::inherent_extrinsics(timestamp, new_heads);
|
||||
extrinsics.into_iter()
|
||||
.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"))
|
||||
.collect()
|
||||
})
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
use std::sync::Arc;
|
||||
use client::backend::{Backend, RemoteBackend};
|
||||
use client::{Client, CallExecutor};
|
||||
use codec::Slicable;
|
||||
use codec::Decode;
|
||||
use primitives::{AccountId, Block, BlockId, Hash, Index, SessionKey, Timestamp, UncheckedExtrinsic};
|
||||
use runtime::Address;
|
||||
use primitives::parachain::{CandidateReceipt, DutyRoster, Id as ParaId};
|
||||
|
||||
@@ -79,7 +79,7 @@ use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use substrate_telemetry::{init_telemetry, TelemetryConfig};
|
||||
use polkadot_primitives::BlockId;
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use client::BlockOrigin;
|
||||
use runtime_primitives::generic::SignedBlock;
|
||||
|
||||
@@ -407,7 +407,7 @@ fn import_blocks<E>(matches: &clap::ArgMatches, exit: E) -> error::Result<()>
|
||||
};
|
||||
|
||||
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;
|
||||
for _ in 0 .. count {
|
||||
if exit_recv.try_recv().is_ok() {
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
use super::MAX_TRANSACTIONS_SIZE;
|
||||
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use polkadot_runtime::{Block as PolkadotGenericBlock, CheckedBlock};
|
||||
use polkadot_primitives::{Block, Hash, BlockNumber, Timestamp};
|
||||
use polkadot_primitives::parachain::Id as ParaId;
|
||||
@@ -78,13 +78,13 @@ pub fn evaluate_initial(
|
||||
) -> Result<CheckedBlock> {
|
||||
const MAX_TIMESTAMP_DRIFT: Timestamp = 60;
|
||||
|
||||
let encoded = Slicable::encode(proposal);
|
||||
let encoded = Encode::encode(proposal);
|
||||
let proposal = PolkadotGenericBlock::decode(&mut &encoded[..])
|
||||
.and_then(|b| CheckedBlock::new(b).ok())
|
||||
.ok_or_else(|| ErrorKind::ProposalNotForPolkadot)?;
|
||||
|
||||
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 {
|
||||
|
||||
@@ -65,7 +65,7 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use polkadot_api::PolkadotApi;
|
||||
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};
|
||||
@@ -710,7 +710,7 @@ impl<C> CreateProposal<C> where C: PolkadotApi {
|
||||
.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");
|
||||
|
||||
// TODO: full re-evaluation
|
||||
|
||||
@@ -47,7 +47,7 @@ mod collator_pool;
|
||||
mod router;
|
||||
pub mod consensus;
|
||||
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use futures::sync::oneshot;
|
||||
use parking_lot::Mutex;
|
||||
use polkadot_consensus::{Statement, SignedStatement, GenericStatement};
|
||||
@@ -81,25 +81,25 @@ pub struct Status {
|
||||
collating_for: Option<(AccountId, ParaId)>,
|
||||
}
|
||||
|
||||
impl Slicable for Status {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
impl Encode for Status {
|
||||
fn encode_to<T: codec::Output>(&self, dest: &mut T) {
|
||||
match self.collating_for {
|
||||
Some(ref details) => {
|
||||
v.push(1);
|
||||
details.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(1);
|
||||
dest.push(details);
|
||||
}
|
||||
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()? {
|
||||
0 => None,
|
||||
1 => Some(Slicable::decode(input)?),
|
||||
1 => Some(Decode::decode(input)?),
|
||||
_ => return None,
|
||||
};
|
||||
Some(Status { collating_for })
|
||||
|
||||
@@ -23,7 +23,7 @@ use polkadot_consensus::GenericStatement;
|
||||
use polkadot_primitives::{Block, Hash, SessionKey};
|
||||
use polkadot_primitives::parachain::{CandidateReceipt, HeadData, BlockData};
|
||||
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 std::sync::Arc;
|
||||
|
||||
@@ -61,7 +61,7 @@ extern crate error_chain;
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
use alloc::vec::Vec;
|
||||
use codec::Slicable;
|
||||
use codec::{Encode, Decode, Input, Output};
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub mod wasm;
|
||||
@@ -77,20 +77,18 @@ pub struct ValidationParams {
|
||||
pub parent_head: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Slicable for ValidationParams {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
|
||||
self.block_data.using_encoded(|s| v.extend(s));
|
||||
self.parent_head.using_encoded(|s| v.extend(s));
|
||||
|
||||
v
|
||||
impl Encode for ValidationParams {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
dest.push(&self.block_data);
|
||||
dest.push(&self.parent_head);
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
block_data: Slicable::decode(input)?,
|
||||
parent_head: Slicable::decode(input)?,
|
||||
block_data: Decode::decode(input)?,
|
||||
parent_head: Decode::decode(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -104,14 +102,16 @@ pub struct ValidationResult {
|
||||
pub head_data: Vec<u8>
|
||||
}
|
||||
|
||||
impl Slicable for ValidationResult {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
self.head_data.encode()
|
||||
impl Encode for ValidationResult {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
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 {
|
||||
head_data: Slicable::decode(input)?,
|
||||
head_data: Decode::decode(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
//! Assuming the parameters are correct, this module provides a wrapper around
|
||||
//! 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::{memory_units, RuntimeValue};
|
||||
|
||||
@@ -33,7 +33,7 @@ extern crate wee_alloc;
|
||||
extern crate tiny_keccak;
|
||||
extern crate pwasm_libc;
|
||||
|
||||
use parachain::codec::{Slicable, Input};
|
||||
use parachain::codec::{Decode, Encode, Input, Output};
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
mod wasm;
|
||||
@@ -41,9 +41,6 @@ mod wasm;
|
||||
#[cfg(not(feature = "std"))]
|
||||
pub use wasm::*;
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
use alloc::vec::Vec;
|
||||
|
||||
// Define global allocator.
|
||||
#[cfg(not(feature = "std"))]
|
||||
#[global_allocator]
|
||||
@@ -60,22 +57,20 @@ struct HeadData {
|
||||
post_state: [u8; 32],
|
||||
}
|
||||
|
||||
impl Slicable for HeadData {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
|
||||
self.number.using_encoded(|s| v.extend(s));
|
||||
self.parent_hash.using_encoded(|s| v.extend(s));
|
||||
self.post_state.using_encoded(|s| v.extend(s));
|
||||
|
||||
v
|
||||
impl Encode for HeadData {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
dest.push(&self.number);
|
||||
dest.push(&self.parent_hash);
|
||||
dest.push(&self.post_state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for HeadData {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
Some(HeadData {
|
||||
number: Slicable::decode(input)?,
|
||||
parent_hash: Slicable::decode(input)?,
|
||||
post_state: Slicable::decode(input)?,
|
||||
number: Decode::decode(input)?,
|
||||
parent_hash: Decode::decode(input)?,
|
||||
post_state: Decode::decode(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -89,20 +84,18 @@ struct BlockData {
|
||||
add: u64,
|
||||
}
|
||||
|
||||
impl Slicable for BlockData {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
|
||||
self.state.using_encoded(|s| v.extend(s));
|
||||
self.add.using_encoded(|s| v.extend(s));
|
||||
|
||||
v
|
||||
impl Encode for BlockData {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
dest.push(&self.state);
|
||||
dest.push(&self.add);
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for BlockData {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
Some(BlockData {
|
||||
state: Slicable::decode(input)?,
|
||||
add: Slicable::decode(input)?,
|
||||
state: Decode::decode(input)?,
|
||||
add: Decode::decode(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
use core::{intrinsics, panic, alloc};
|
||||
use parachain::{self, ValidationResult};
|
||||
use parachain::codec::Slicable;
|
||||
use parachain::codec::{Encode, Decode};
|
||||
use super::{HeadData, BlockData};
|
||||
|
||||
#[panic_implementation]
|
||||
|
||||
@@ -20,7 +20,7 @@ extern crate polkadot_parachain as parachain;
|
||||
extern crate tiny_keccak;
|
||||
|
||||
use parachain::ValidationParams;
|
||||
use parachain::codec::{Slicable, Input};
|
||||
use parachain::codec::{Decode, Encode, Input, Output};
|
||||
|
||||
// Head data for this parachain.
|
||||
#[derive(Default, Clone)]
|
||||
@@ -33,22 +33,20 @@ struct HeadData {
|
||||
post_state: [u8; 32],
|
||||
}
|
||||
|
||||
impl Slicable for HeadData {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
|
||||
self.number.using_encoded(|s| v.extend(s));
|
||||
self.parent_hash.using_encoded(|s| v.extend(s));
|
||||
self.post_state.using_encoded(|s| v.extend(s));
|
||||
|
||||
v
|
||||
impl Encode for HeadData {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
dest.push(&self.number);
|
||||
dest.push(&self.parent_hash);
|
||||
dest.push(&self.post_state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for HeadData {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
Some(HeadData {
|
||||
number: Slicable::decode(input)?,
|
||||
parent_hash: Slicable::decode(input)?,
|
||||
post_state: Slicable::decode(input)?,
|
||||
number: Decode::decode(input)?,
|
||||
parent_hash: Decode::decode(input)?,
|
||||
post_state: Decode::decode(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -62,20 +60,18 @@ struct BlockData {
|
||||
add: u64,
|
||||
}
|
||||
|
||||
impl Slicable for BlockData {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
|
||||
self.state.using_encoded(|s| v.extend(s));
|
||||
self.add.using_encoded(|s| v.extend(s));
|
||||
|
||||
v
|
||||
impl Encode for BlockData {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
dest.push(&self.state);
|
||||
dest.push(&self.add);
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for BlockData {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
Some(BlockData {
|
||||
state: Slicable::decode(input)?,
|
||||
add: Slicable::decode(input)?,
|
||||
state: Decode::decode(input)?,
|
||||
add: Decode::decode(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ use primitives::bytes;
|
||||
use rstd::prelude::*;
|
||||
use runtime_primitives::traits::BlakeTwo256;
|
||||
use runtime_primitives::generic;
|
||||
use codec::{Input, Slicable};
|
||||
use codec::{Encode, Decode, Input, Output};
|
||||
|
||||
pub mod parachain;
|
||||
|
||||
@@ -109,12 +109,14 @@ pub type BlockId = generic::BlockId<Block>;
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
|
||||
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> {
|
||||
Vec::<u8>::decode(input).map(Log)
|
||||
}
|
||||
}
|
||||
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
self.0.using_encoded(f)
|
||||
impl Encode for Log {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
self.0.encode_to(dest)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
//! Polkadot parachain types.
|
||||
|
||||
use codec::{Slicable, Input};
|
||||
use codec::{Encode, Decode, Input, Output};
|
||||
use rstd::prelude::*;
|
||||
use rstd::cmp::Ordering;
|
||||
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> {
|
||||
u32::decode(input).map(Id)
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode for Id {
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
self.0.using_encoded(f)
|
||||
}
|
||||
@@ -67,30 +69,26 @@ pub enum Chain {
|
||||
Parachain(Id),
|
||||
}
|
||||
|
||||
impl Slicable for Chain {
|
||||
impl Decode for Chain {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
let disc = input.read_byte()?;
|
||||
match disc {
|
||||
0 => Some(Chain::Relay),
|
||||
1 => Some(Chain::Parachain(Slicable::decode(input)?)),
|
||||
1 => Some(Chain::Parachain(Decode::decode(input)?)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
impl Encode for Chain {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
match *self {
|
||||
Chain::Relay => { v.push(0); }
|
||||
Chain::Relay => { dest.push_byte(0); }
|
||||
Chain::Parachain(id) => {
|
||||
v.push(1u8);
|
||||
id.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(1u8);
|
||||
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>,
|
||||
}
|
||||
|
||||
impl Slicable for DutyRoster {
|
||||
impl Decode for DutyRoster {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
Some(DutyRoster {
|
||||
validator_duty: Slicable::decode(input)?,
|
||||
guarantor_duty: Slicable::decode(input)?,
|
||||
validator_duty: Decode::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 {
|
||||
f(&self.encode().as_slice())
|
||||
impl Encode for DutyRoster {
|
||||
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,
|
||||
}
|
||||
|
||||
impl Slicable for CandidateReceipt {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
|
||||
self.parachain_index.using_encoded(|s| v.extend(s));
|
||||
self.collator.using_encoded(|s| v.extend(s));
|
||||
self.signature.using_encoded(|s| v.extend(s));
|
||||
self.head_data.0.using_encoded(|s| v.extend(s));
|
||||
self.balance_uploads.using_encoded(|s| v.extend(s));
|
||||
self.egress_queue_roots.using_encoded(|s| v.extend(s));
|
||||
self.fees.using_encoded(|s| v.extend(s));
|
||||
self.block_data_hash.using_encoded(|s| v.extend(s));
|
||||
|
||||
v
|
||||
impl Encode for CandidateReceipt {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
dest.push(&self.parachain_index);
|
||||
dest.push(&self.collator);
|
||||
dest.push(&self.signature);
|
||||
dest.push(&self.head_data.0);
|
||||
dest.push(&self.balance_uploads);
|
||||
dest.push(&self.egress_queue_roots);
|
||||
dest.push(&self.fees);
|
||||
dest.push(&self.block_data_hash);
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for CandidateReceipt {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
Some(CandidateReceipt {
|
||||
parachain_index: Slicable::decode(input)?,
|
||||
collator: Slicable::decode(input)?,
|
||||
signature: Slicable::decode(input)?,
|
||||
head_data: Slicable::decode(input).map(HeadData)?,
|
||||
balance_uploads: Slicable::decode(input)?,
|
||||
egress_queue_roots: Slicable::decode(input)?,
|
||||
fees: Slicable::decode(input)?,
|
||||
block_data_hash: Slicable::decode(input)?,
|
||||
parachain_index: Decode::decode(input)?,
|
||||
collator: Decode::decode(input)?,
|
||||
signature: Decode::decode(input)?,
|
||||
head_data: Decode::decode(input).map(HeadData)?,
|
||||
balance_uploads: Decode::decode(input)?,
|
||||
egress_queue_roots: Decode::decode(input)?,
|
||||
fees: Decode::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))]
|
||||
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> {
|
||||
Vec::<u8>::decode(input).map(Activity)
|
||||
}
|
||||
}
|
||||
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
self.0.using_encoded(f)
|
||||
impl Encode for Activity {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
self.0.encode_to(dest)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -257,7 +257,7 @@ pub mod api {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use substrate_primitives as primitives;
|
||||
use ::codec::Slicable;
|
||||
use codec::{Encode, Decode};
|
||||
use substrate_primitives::hexdisplay::HexDisplay;
|
||||
use substrate_serializer as ser;
|
||||
use runtime_primitives::traits::{Digest as DigestT, Header as HeaderT};
|
||||
@@ -376,7 +376,7 @@ mod tests {
|
||||
// df0f0200
|
||||
// 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
|
||||
|
||||
let v = Slicable::encode(&tx);
|
||||
let v = Encode::encode(&tx);
|
||||
assert_eq!(&v[..], &hex!["6f000000ff0101010101010101010101010101010101010101010101010101010101010101e70300000300df0f02000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"][..]);
|
||||
println!("{}", HexDisplay::from(&v));
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! Main parachains logic. For now this is just the determination of which validators do what.
|
||||
|
||||
use rstd::prelude::*;
|
||||
use codec::Slicable;
|
||||
use codec::Decode;
|
||||
|
||||
use runtime_primitives::traits::{Hash, BlakeTwo256, Executable, RefInto, MaybeEmpty};
|
||||
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> {
|
||||
use std::collections::HashMap;
|
||||
use runtime_io::twox_128;
|
||||
use codec::Slicable;
|
||||
use codec::Encode;
|
||||
|
||||
self.parachains.sort_unstable_by_key(|&(ref id, _)| id.clone());
|
||||
self.parachains.dedup_by_key(|&mut (ref id, _)| id.clone());
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -43,7 +43,7 @@ pub mod chain_spec;
|
||||
use std::sync::Arc;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use codec::Slicable;
|
||||
use codec::Encode;
|
||||
use transaction_pool::TransactionPool;
|
||||
use polkadot_api::{PolkadotApi, light::RemotePolkadotApiWrapper};
|
||||
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();
|
||||
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()?;
|
||||
match self.pool.import_unchecked_extrinsic(best_block_id, uxt) {
|
||||
Ok(xt) => Some(*xt.hash()),
|
||||
|
||||
@@ -31,7 +31,7 @@ use std::collections::hash_map::{HashMap, Entry};
|
||||
use std::hash::Hash;
|
||||
use std::fmt::Debug;
|
||||
|
||||
use codec::{Slicable, Input};
|
||||
use codec::{Decode, Encode, Input, Output};
|
||||
|
||||
/// Context for the statement table.
|
||||
pub trait Context {
|
||||
@@ -97,44 +97,43 @@ enum StatementKind {
|
||||
Available = 4,
|
||||
}
|
||||
|
||||
impl<C: Slicable, D: Slicable> Slicable for Statement<C, D> {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
impl<C: Encode, D: Encode> Encode for Statement<C, D> {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
match *self {
|
||||
Statement::Candidate(ref candidate) => {
|
||||
v.push(StatementKind::Candidate as u8);
|
||||
candidate.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(StatementKind::Candidate as u8);
|
||||
dest.push(candidate);
|
||||
}
|
||||
Statement::Valid(ref digest) => {
|
||||
v.push(StatementKind::Valid as u8);
|
||||
digest.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(StatementKind::Valid as u8);
|
||||
dest.push(digest);
|
||||
}
|
||||
Statement::Invalid(ref digest) => {
|
||||
v.push(StatementKind::Invalid as u8);
|
||||
digest.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(StatementKind::Invalid as u8);
|
||||
dest.push(digest);
|
||||
}
|
||||
Statement::Available(ref digest) => {
|
||||
v.push(StatementKind::Available as u8);
|
||||
digest.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(StatementKind::Available as u8);
|
||||
dest.push(digest);
|
||||
}
|
||||
}
|
||||
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Decode, D: Decode> Decode for Statement<C, D> {
|
||||
fn decode<I: Input>(value: &mut I) -> Option<Self> {
|
||||
match value.read_byte() {
|
||||
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 => {
|
||||
Slicable::decode(value).map(Statement::Valid)
|
||||
Decode::decode(value).map(Statement::Valid)
|
||||
}
|
||||
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 => {
|
||||
Slicable::decode(value).map(Statement::Available)
|
||||
Decode::decode(value).map(Statement::Available)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ use std::{
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use extrinsic_pool::{Pool, Listener, txpool::{self, Readiness, scoring::{Change, Choice}}};
|
||||
use extrinsic_pool::api::{ExtrinsicPool, EventStream};
|
||||
use polkadot_api::PolkadotApi;
|
||||
@@ -75,7 +75,7 @@ impl VerifiedTransaction {
|
||||
|
||||
/// Convert to primitive unchecked extrinsic.
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -418,7 +418,7 @@ mod tests {
|
||||
use std::sync::{atomic::{self, AtomicBool}, Arc};
|
||||
use super::TransactionPool;
|
||||
use substrate_keyring::Keyring::{self, *};
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use polkadot_api::{PolkadotApi, BlockBuilder, Result};
|
||||
use primitives::{AccountId, AccountIndex, Block, BlockId, Hash, Index, SessionKey, Timestamp,
|
||||
UncheckedExtrinsic as FutureProofUncheckedExtrinsic};
|
||||
|
||||
@@ -57,7 +57,7 @@ use std::mem;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use codec::Slicable;
|
||||
use codec::Encode;
|
||||
use ed25519::LocalizedSignature;
|
||||
use runtime_primitives::generic::BlockId;
|
||||
use runtime_primitives::traits::{Block, Header};
|
||||
@@ -506,7 +506,7 @@ fn check_justification_signed_message<H>(authorities: &[AuthorityId], message: &
|
||||
pub fn check_justification<B: Block>(authorities: &[AuthorityId], parent: B::Hash, just: UncheckedJustification<B::Hash>)
|
||||
-> Result<Justification<B::Hash>, UncheckedJustification<B::Hash>>
|
||||
{
|
||||
let message = Slicable::encode(&PrimitiveMessage::<B, _> {
|
||||
let message = Encode::encode(&PrimitiveMessage::<B, _> {
|
||||
parent,
|
||||
action: PrimitiveAction::Commit(just.0.round_number as u32, just.0.digest.clone()),
|
||||
});
|
||||
@@ -521,7 +521,7 @@ pub fn check_justification<B: Block>(authorities: &[AuthorityId], parent: B::Has
|
||||
pub fn check_prepare_justification<B: Block>(authorities: &[AuthorityId], parent: B::Hash, just: UncheckedJustification<B::Hash>)
|
||||
-> Result<PrepareJustification<B::Hash>, UncheckedJustification<B::Hash>>
|
||||
{
|
||||
let message = Slicable::encode(&PrimitiveMessage::<B, _> {
|
||||
let message = Encode::encode(&PrimitiveMessage::<B, _> {
|
||||
parent,
|
||||
action: PrimitiveAction::Prepare(just.0.round_number as u32, just.0.digest.clone()),
|
||||
});
|
||||
@@ -573,7 +573,7 @@ fn check_action<B: Block>(action: PrimitiveAction<B, B::Hash>, parent_hash: &B::
|
||||
action,
|
||||
};
|
||||
|
||||
let message = Slicable::encode(&primitive);
|
||||
let message = Encode::encode(&primitive);
|
||||
if ed25519::verify_strong(&sig.signature, &message, &sig.signer) {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -591,7 +591,7 @@ pub fn sign_message<B: Block + Clone>(message: Message<B>, key: &ed25519::Pair,
|
||||
action,
|
||||
};
|
||||
|
||||
let to_sign = Slicable::encode(&primitive);
|
||||
let to_sign = Encode::encode(&primitive);
|
||||
LocalizedSignature {
|
||||
signer: signer.clone(),
|
||||
signature: key.sign(&to_sign),
|
||||
|
||||
@@ -43,7 +43,7 @@ mod utils;
|
||||
use std::sync::Arc;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use kvdb::{KeyValueDB, DBTransaction};
|
||||
use memorydb::MemoryDB;
|
||||
use parking_lot::RwLock;
|
||||
@@ -187,7 +187,7 @@ impl<Block: BlockT> client::blockchain::HeaderBackend<Block> for BlockchainDb<Bl
|
||||
impl<Block: BlockT> client::blockchain::Backend<Block> for BlockchainDb<Block> {
|
||||
fn body(&self, id: BlockId<Block>) -> Result<Option<Vec<Block::Extrinsic>>, client::error::Error> {
|
||||
match read_db(&*self.db, columns::BLOCK_INDEX, columns::BODY, id)? {
|
||||
Some(body) => match Slicable::decode(&mut &body[..]) {
|
||||
Some(body) => match Decode::decode(&mut &body[..]) {
|
||||
Some(body) => Ok(Some(body)),
|
||||
None => return Err(client::error::ErrorKind::Backend("Error decoding body".into()).into()),
|
||||
}
|
||||
@@ -197,7 +197,7 @@ impl<Block: BlockT> client::blockchain::Backend<Block> for BlockchainDb<Block> {
|
||||
|
||||
fn justification(&self, id: BlockId<Block>) -> Result<Option<Justification<Block::Hash>>, client::error::Error> {
|
||||
match read_db(&*self.db, columns::BLOCK_INDEX, columns::JUSTIFICATION, id)? {
|
||||
Some(justification) => match Slicable::decode(&mut &justification[..]) {
|
||||
Some(justification) => match Decode::decode(&mut &justification[..]) {
|
||||
Some(justification) => Ok(Some(justification)),
|
||||
None => return Err(client::error::ErrorKind::Backend("Error decoding justification".into()).into()),
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ use client::blockchain::{BlockStatus, HeaderBackend as BlockchainHeaderBackend,
|
||||
Info as BlockchainInfo};
|
||||
use client::error::{ErrorKind as ClientErrorKind, Result as ClientResult};
|
||||
use client::light::blockchain::Storage as LightBlockchainStorage;
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use primitives::AuthorityId;
|
||||
use runtime_primitives::generic::BlockId;
|
||||
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, Hash, HashFor, Zero};
|
||||
|
||||
@@ -23,7 +23,7 @@ use kvdb::{self, KeyValueDB, DBTransaction};
|
||||
use kvdb_rocksdb::{Database, DatabaseConfig};
|
||||
|
||||
use client;
|
||||
use codec::Slicable;
|
||||
use codec::Decode;
|
||||
use hashdb::DBValue;
|
||||
use runtime_primitives::generic::BlockId;
|
||||
use runtime_primitives::traits::{As, Block as BlockT, Header as HeaderT, Hash, HashFor, Zero};
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! Utility struct to build a block.
|
||||
|
||||
use std::vec::Vec;
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use state_machine::{self, native_when_possible};
|
||||
use runtime_primitives::traits::{Header as HeaderT, Hash, Block as BlockT, One, HashFor};
|
||||
use runtime_primitives::generic::BlockId;
|
||||
@@ -103,12 +103,12 @@ impl<B, E, Block> BlockBuilder<B, E, Block> where
|
||||
&[],
|
||||
native_when_possible(),
|
||||
)?;
|
||||
self.header = <<Block as BlockT>::Header as Slicable>::decode(&mut &output[..])
|
||||
self.header = <<Block as BlockT>::Header as Decode>::decode(&mut &output[..])
|
||||
.expect("Header came straight out of runtime so must be valid");
|
||||
|
||||
debug_assert_eq!(
|
||||
self.header.extrinsics_root().clone(),
|
||||
HashFor::<Block>::ordered_trie_root(self.extrinsics.iter().map(Slicable::encode)),
|
||||
HashFor::<Block>::ordered_trie_root(self.extrinsics.iter().map(Encode::encode)),
|
||||
);
|
||||
|
||||
Ok(<Block as BlockT>::new(self.header, self.extrinsics))
|
||||
|
||||
@@ -24,7 +24,7 @@ use runtime_primitives::{bft::Justification, generic::{BlockId, SignedBlock, Blo
|
||||
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, Zero, One, As};
|
||||
use runtime_primitives::BuildStorage;
|
||||
use primitives::storage::{StorageKey, StorageData};
|
||||
use codec::Slicable;
|
||||
use codec::Decode;
|
||||
use state_machine::{Ext, OverlayedChanges, Backend as StateBackend, CodeExecutor, ExecutionStrategy, ExecutionManager};
|
||||
|
||||
use backend::{self, BlockImportOperation};
|
||||
@@ -523,7 +523,7 @@ impl<B, E, Block> ChainHead<Block> for Client<B, E, Block>
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codec::Slicable;
|
||||
use codec::Encode;
|
||||
use keyring::Keyring;
|
||||
use test_client::{self, TestClient};
|
||||
use test_client::client::BlockOrigin;
|
||||
|
||||
@@ -42,7 +42,7 @@ pub fn construct_genesis_block<
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codec::{Slicable, Joiner};
|
||||
use codec::{Encode, Decode, Joiner};
|
||||
use keyring::Keyring;
|
||||
use executor::WasmExecutor;
|
||||
use state_machine::{execute, OverlayedChanges, ExecutionStrategy};
|
||||
@@ -68,7 +68,7 @@ mod tests {
|
||||
Extrinsic { transfer: tx, signature }
|
||||
}).collect::<Vec<_>>();
|
||||
|
||||
let extrinsics_root = ordered_trie_root(transactions.iter().map(Slicable::encode)).0.into();
|
||||
let extrinsics_root = ordered_trie_root(transactions.iter().map(Encode::encode)).0.into();
|
||||
|
||||
println!("root before: {:?}", extrinsics_root);
|
||||
let mut header = Header {
|
||||
|
||||
@@ -30,7 +30,7 @@ use call_executor::{CallExecutor, CallResult};
|
||||
use error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult};
|
||||
use light::fetcher::{Fetcher, RemoteCallRequest};
|
||||
use executor::RuntimeVersion;
|
||||
use codec::Slicable;
|
||||
use codec::Decode;
|
||||
|
||||
/// Call executor that executes methods on remote node, querying execution proof
|
||||
/// and checking proof by re-executing locally.
|
||||
|
||||
+195
-141
@@ -19,9 +19,7 @@
|
||||
use alloc::vec::Vec;
|
||||
use alloc::boxed::Box;
|
||||
use core::{mem, slice};
|
||||
use super::joiner::Joiner;
|
||||
use arrayvec::ArrayVec;
|
||||
|
||||
/// Trait that allows reading of data into a slice.
|
||||
pub trait Input {
|
||||
/// Read into the provided input slice. Returns the number of bytes read.
|
||||
@@ -55,14 +53,47 @@ impl<R: ::std::io::Read> Input for R {
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait that allows zero-copy read/write of value-references to/from slices in LE format.
|
||||
pub trait Slicable: Sized {
|
||||
/// Attempt to deserialise the value from input.
|
||||
fn decode<I: Input>(value: &mut I) -> Option<Self>;
|
||||
/// Trait that allows writing of data.
|
||||
pub trait Output: Sized {
|
||||
/// Write to the output.
|
||||
fn write(&mut self, bytes: &[u8]);
|
||||
|
||||
fn push_byte(&mut self, byte: u8) {
|
||||
self.write(&[byte]);
|
||||
}
|
||||
|
||||
fn push<V: Encode + ?Sized>(&mut self, value: &V) {
|
||||
value.encode_to(self);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
impl Output for Vec<u8> {
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
self.extend(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<W: ::std::io::Write> Output for W {
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
(self as &mut ::std::io::Write).write(bytes).expect("Codec outputs are infallible");
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait that allows zero-copy write of value-references to slices in LE format.
|
||||
/// Implementations should override `using_encoded` for value types and `encode_to` for allocating types.
|
||||
pub trait Encode {
|
||||
/// Convert self to a slice and append it to the destination.
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
self.using_encoded(|buf| dest.write(buf));
|
||||
}
|
||||
|
||||
/// Convert self to an owned vector.
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
self.using_encoded(|s| s.to_vec())
|
||||
let mut r = Vec::new();
|
||||
self.encode_to(&mut r);
|
||||
r
|
||||
}
|
||||
|
||||
/// Convert self to a slice and then invoke the given closure with it.
|
||||
@@ -71,17 +102,32 @@ pub trait Slicable: Sized {
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a bytes slice as `Slicable` that can be decoded into a vector.
|
||||
pub fn encode_slice(bytes: &[u8]) -> Vec<u8> {
|
||||
let len = bytes.len();
|
||||
assert!(len <= u32::max_value() as usize, "Attempted to serialize a collection with too many elements.");
|
||||
|
||||
let mut r: Vec<u8> = Vec::new().and(&(len as u32));
|
||||
r.extend_from_slice(bytes);
|
||||
r
|
||||
/// Trait that allows zero-copy read of value-references from slices in LE format.
|
||||
pub trait Decode: Sized {
|
||||
/// Attempt to deserialise the value from input.
|
||||
fn decode<I: Input>(value: &mut I) -> Option<Self>;
|
||||
}
|
||||
|
||||
impl<T: Slicable, E: Slicable> Slicable for Result<T, E> {
|
||||
/// Trait that allows zero-copy read/write of value-references to/from slices in LE format.
|
||||
pub trait Codec: Decode + Encode {}
|
||||
impl<S: Decode + Encode> Codec for S {}
|
||||
|
||||
impl<T: Encode, E: Encode> Encode for Result<T, E> {
|
||||
fn encode_to<W: Output>(&self, dest: &mut W) {
|
||||
match *self {
|
||||
Ok(ref t) => {
|
||||
dest.push_byte(0);
|
||||
t.encode_to(dest);
|
||||
}
|
||||
Err(ref e) => {
|
||||
dest.push_byte(1);
|
||||
e.encode_to(dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Decode, E: Decode> Decode for Result<T, E> {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
match input.read_byte()? {
|
||||
0 => Some(Ok(T::decode(input)?)),
|
||||
@@ -89,36 +135,12 @@ impl<T: Slicable, E: Slicable> Slicable for Result<T, E> {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
match *self {
|
||||
Ok(ref t) => {
|
||||
v.push(0);
|
||||
t.using_encoded(|s| v.extend(s));
|
||||
}
|
||||
Err(ref e) => {
|
||||
v.push(1);
|
||||
e.using_encoded(|s| v.extend(s));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
/// Shim type because we can't do a specialised implementation for `Option<bool>` directly.
|
||||
pub struct OptionBool(pub Option<bool>);
|
||||
|
||||
impl Slicable for OptionBool {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
match input.read_byte()? {
|
||||
0 => Some(OptionBool(None)),
|
||||
1 => Some(OptionBool(Some(true))),
|
||||
2 => Some(OptionBool(Some(false))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode for OptionBool {
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
f(&[match *self {
|
||||
OptionBool(None) => 0u8,
|
||||
@@ -128,7 +150,30 @@ impl Slicable for OptionBool {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Slicable> Slicable for Option<T> {
|
||||
impl Decode for OptionBool {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
match input.read_byte()? {
|
||||
0 => Some(OptionBool(None)),
|
||||
1 => Some(OptionBool(Some(true))),
|
||||
2 => Some(OptionBool(Some(false))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Encode> Encode for Option<T> {
|
||||
fn encode_to<W: Output>(&self, dest: &mut W) {
|
||||
match *self {
|
||||
Some(ref t) => {
|
||||
dest.push_byte(1);
|
||||
t.encode_to(dest);
|
||||
}
|
||||
None => dest.push_byte(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Decode> Decode for Option<T> {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
match input.read_byte()? {
|
||||
0 => Some(None),
|
||||
@@ -136,23 +181,19 @@ impl<T: Slicable> Slicable for Option<T> {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
match *self {
|
||||
Some(ref t) => {
|
||||
v.push(1);
|
||||
t.using_encoded(|s| v.extend(s));
|
||||
}
|
||||
None => v.push(0),
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_array {
|
||||
( $( $n:expr )* ) => { $(
|
||||
impl<T: Slicable> Slicable for [T; $n] {
|
||||
impl<T: Encode> Encode for [T; $n] {
|
||||
fn encode_to<W: Output>(&self, dest: &mut W) {
|
||||
for item in self.iter() {
|
||||
item.encode_to(dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Decode> Decode for [T; $n] {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
let mut r = ArrayVec::new();
|
||||
for _ in 0..$n {
|
||||
@@ -160,15 +201,6 @@ macro_rules! impl_array {
|
||||
}
|
||||
r.into_inner().ok()
|
||||
}
|
||||
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
use core::iter::Extend;
|
||||
let mut r = Vec::new();
|
||||
for item in self.iter() {
|
||||
item.using_encoded(|e| r.extend(e));
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
)* }
|
||||
}
|
||||
@@ -176,17 +208,34 @@ macro_rules! impl_array {
|
||||
impl_array!(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
||||
40 48 56 64 72 96 128 160 192 224 256);
|
||||
|
||||
impl<T: Slicable> Slicable for Box<T> {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
Some(Box::new(T::decode(input)?))
|
||||
}
|
||||
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
self.as_ref().using_encoded(f)
|
||||
impl<T: Encode> Encode for Box<T> {
|
||||
fn encode_to<W: Output>(&self, dest: &mut W) {
|
||||
self.as_ref().encode_to(dest)
|
||||
}
|
||||
}
|
||||
|
||||
impl Slicable for Vec<u8> {
|
||||
impl<T: Decode> Decode for Box<T> {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
Some(Box::new(T::decode(input)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode for [u8] {
|
||||
fn encode_to<W: Output>(&self, dest: &mut W) {
|
||||
let len = self.len();
|
||||
assert!(len <= u32::max_value() as usize, "Attempted to serialize a collection with too many elements.");
|
||||
(len as u32).encode_to(dest);
|
||||
dest.write(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode for Vec<u8> {
|
||||
fn encode_to<W: Output>(&self, dest: &mut W) {
|
||||
self.as_slice().encode_to(dest)
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for Vec<u8> {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
u32::decode(input).and_then(move |len| {
|
||||
let len = len as usize;
|
||||
@@ -198,13 +247,26 @@ impl Slicable for Vec<u8> {
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
encode_slice(&self)
|
||||
impl<T: Encode> Encode for [T] {
|
||||
fn encode_to<W: Output>(&self, dest: &mut W) {
|
||||
let len = self.len();
|
||||
assert!(len <= u32::max_value() as usize, "Attempted to serialize a collection with too many elements.");
|
||||
(len as u32).encode_to(dest);
|
||||
for item in self {
|
||||
item.encode_to(dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Slicable> Slicable for Vec<T> {
|
||||
impl<T: Encode> Encode for Vec<T> {
|
||||
fn encode_to<W: Output>(&self, dest: &mut W) {
|
||||
self.as_slice().encode_to(dest)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Decode> Decode for Vec<T> {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
u32::decode(input).and_then(move |len| {
|
||||
let mut r = Vec::with_capacity(len as usize);
|
||||
@@ -214,24 +276,10 @@ impl<T: Slicable> Slicable for Vec<T> {
|
||||
Some(r)
|
||||
})
|
||||
}
|
||||
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
use core::iter::Extend;
|
||||
|
||||
let len = self.len();
|
||||
assert!(len <= u32::max_value() as usize, "Attempted to serialize vec with too many elements.");
|
||||
|
||||
let mut r: Vec<u8> = Vec::new().and(&(len as u32));
|
||||
for item in self {
|
||||
item.using_encoded(|e| r.extend(e))
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
impl Slicable for () {
|
||||
fn decode<I: Input>(_: &mut I) -> Option<()> {
|
||||
Some(())
|
||||
impl Encode for () {
|
||||
fn encode_to<T: Output>(&self, _dest: &mut T) {
|
||||
}
|
||||
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
@@ -243,26 +291,46 @@ impl Slicable for () {
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for () {
|
||||
fn decode<I: Input>(_: &mut I) -> Option<()> {
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! tuple_impl {
|
||||
($one:ident,) => {
|
||||
impl<$one: Slicable> Slicable for ($one,) {
|
||||
impl<$one: Encode> Encode for ($one,) {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
self.0.encode_to(dest);
|
||||
}
|
||||
}
|
||||
|
||||
impl<$one: Decode> Decode for ($one,) {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
match $one::decode(input) {
|
||||
None => None,
|
||||
Some($one) => Some(($one,)),
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
($first:ident, $($rest:ident,)+) => {
|
||||
impl<$first: Encode, $($rest: Encode),+>
|
||||
Encode for
|
||||
($first, $($rest),+) {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
let (
|
||||
ref $first,
|
||||
$(ref $rest),+
|
||||
) = *self;
|
||||
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
self.0.using_encoded(f)
|
||||
$first.encode_to(dest);
|
||||
$($rest.encode_to(dest);)+
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
($first:ident, $($rest:ident,)+) => {
|
||||
impl<$first: Slicable, $($rest: Slicable),+>
|
||||
Slicable for
|
||||
impl<$first: Decode, $($rest: Decode),+>
|
||||
Decode for
|
||||
($first, $($rest),+) {
|
||||
fn decode<INPUT: Input>(input: &mut INPUT) -> Option<Self> {
|
||||
Some((
|
||||
@@ -276,22 +344,6 @@ macro_rules! tuple_impl {
|
||||
},)+
|
||||
))
|
||||
}
|
||||
|
||||
fn using_encoded<RETURN, PROCESS>(&self, f: PROCESS) -> RETURN
|
||||
where PROCESS: FnOnce(&[u8]) -> RETURN
|
||||
{
|
||||
let mut v = Vec::new();
|
||||
|
||||
let (
|
||||
ref $first,
|
||||
$(ref $rest),+
|
||||
) = *self;
|
||||
|
||||
$first.using_encoded(|s| v.extend(s));
|
||||
$($rest.using_encoded(|s| v.extend(s));)+
|
||||
|
||||
f(v.as_slice())
|
||||
}
|
||||
}
|
||||
|
||||
tuple_impl!($($rest,)+);
|
||||
@@ -300,15 +352,13 @@ macro_rules! tuple_impl {
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
mod inner_tuple_impl {
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use super::{Input, Slicable};
|
||||
use super::{Input, Output, Decode, Encode};
|
||||
tuple_impl!(A, B, C, D, E, F, G, H, I, J, K,);
|
||||
}
|
||||
|
||||
/// Trait to allow conversion to a know endian representation when sensitive.
|
||||
/// Types implementing this trait must have a size > 0.
|
||||
// note: the copy bound and static lifetimes are necessary for safety of `Slicable` blanket
|
||||
// note: the copy bound and static lifetimes are necessary for safety of `Codec` blanket
|
||||
// implementation.
|
||||
trait EndianSensitive: Copy + 'static {
|
||||
fn to_le(self) -> Self { self }
|
||||
@@ -330,22 +380,7 @@ macro_rules! impl_endians {
|
||||
fn as_le_then<T, F: FnOnce(&Self) -> T>(&self, f: F) -> T { let d = self.to_le(); f(&d) }
|
||||
}
|
||||
|
||||
impl Slicable for $t {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
let size = mem::size_of::<$t>();
|
||||
assert!(size > 0, "EndianSensitive can never be implemented for a zero-sized type.");
|
||||
let mut val: $t = unsafe { mem::zeroed() };
|
||||
|
||||
unsafe {
|
||||
let raw: &mut [u8] = slice::from_raw_parts_mut(
|
||||
&mut val as *mut $t as *mut u8,
|
||||
size
|
||||
);
|
||||
if input.read(raw) != size { return None }
|
||||
}
|
||||
Some(val.from_le())
|
||||
}
|
||||
|
||||
impl Encode for $t {
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
self.as_le_then(|le| {
|
||||
let size = mem::size_of::<$t>();
|
||||
@@ -362,13 +397,8 @@ macro_rules! impl_endians {
|
||||
})
|
||||
}
|
||||
}
|
||||
)* }
|
||||
}
|
||||
macro_rules! impl_non_endians {
|
||||
( $( $t:ty ),* ) => { $(
|
||||
impl EndianSensitive for $t {}
|
||||
|
||||
impl Slicable for $t {
|
||||
impl Decode for $t {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
let size = mem::size_of::<$t>();
|
||||
assert!(size > 0, "EndianSensitive can never be implemented for a zero-sized type.");
|
||||
@@ -383,7 +413,14 @@ macro_rules! impl_non_endians {
|
||||
}
|
||||
Some(val.from_le())
|
||||
}
|
||||
}
|
||||
)* }
|
||||
}
|
||||
macro_rules! impl_non_endians {
|
||||
( $( $t:ty ),* ) => { $(
|
||||
impl EndianSensitive for $t {}
|
||||
|
||||
impl Encode for $t {
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
self.as_le_then(|le| {
|
||||
let size = mem::size_of::<$t>();
|
||||
@@ -400,6 +437,23 @@ macro_rules! impl_non_endians {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for $t {
|
||||
fn decode<I: Input>(input: &mut I) -> Option<Self> {
|
||||
let size = mem::size_of::<$t>();
|
||||
assert!(size > 0, "EndianSensitive can never be implemented for a zero-sized type.");
|
||||
let mut val: $t = unsafe { mem::zeroed() };
|
||||
|
||||
unsafe {
|
||||
let raw: &mut [u8] = slice::from_raw_parts_mut(
|
||||
&mut val as *mut $t as *mut u8,
|
||||
size
|
||||
);
|
||||
if input.read(raw) != size { return None }
|
||||
}
|
||||
Some(val.from_le())
|
||||
}
|
||||
}
|
||||
)* }
|
||||
}
|
||||
|
||||
@@ -17,16 +17,16 @@
|
||||
//! Trait
|
||||
|
||||
use core::iter::Extend;
|
||||
use super::slicable::Slicable;
|
||||
use super::Codec;
|
||||
|
||||
/// Trait to allow itself to be serialised into a value which can be extended
|
||||
/// by bytes.
|
||||
pub trait Joiner {
|
||||
fn and<V: Slicable + Sized>(self, value: &V) -> Self;
|
||||
fn and<V: Codec + Sized>(self, value: &V) -> Self;
|
||||
}
|
||||
|
||||
impl<T> Joiner for T where T: for<'a> Extend<&'a u8> {
|
||||
fn and<V: Slicable + Sized>(mut self, value: &V) -> Self {
|
||||
fn and<V: Codec + Sized>(mut self, value: &V) -> Self {
|
||||
value.using_encoded(|s| self.extend(s));
|
||||
self
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
//! Serialiser and prepender.
|
||||
|
||||
use slicable::Slicable;
|
||||
use Codec;
|
||||
use core::iter::Extend;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
@@ -25,7 +25,7 @@ pub trait KeyedVec {
|
||||
fn to_keyed_vec(&self, prepend_key: &[u8]) -> Vec<u8>;
|
||||
}
|
||||
|
||||
impl<T: Slicable> KeyedVec for T {
|
||||
impl<T: Codec> KeyedVec for T {
|
||||
fn to_keyed_vec(&self, prepend_key: &[u8]) -> Vec<u8> {
|
||||
self.using_encoded(|slice| {
|
||||
let mut r = prepend_key.to_vec();
|
||||
|
||||
@@ -34,10 +34,10 @@ pub mod alloc {
|
||||
pub use std::vec;
|
||||
}
|
||||
|
||||
mod slicable;
|
||||
mod codec;
|
||||
mod joiner;
|
||||
mod keyedvec;
|
||||
|
||||
pub use self::slicable::{Input, Slicable, encode_slice};
|
||||
pub use self::codec::{Input, Output, Encode, Decode, Codec};
|
||||
pub use self::joiner::Joiner;
|
||||
pub use self::keyedvec::KeyedVec;
|
||||
|
||||
@@ -69,7 +69,7 @@ pub use wasm_executor::WasmExecutor;
|
||||
pub use native_executor::{with_native_environment, NativeExecutor, NativeExecutionDispatch};
|
||||
pub use state_machine::Externalities;
|
||||
pub use runtime_version::RuntimeVersion;
|
||||
pub use codec::Slicable;
|
||||
pub use codec::Codec;
|
||||
|
||||
/// Provides runtime information.
|
||||
pub trait RuntimeInfo {
|
||||
|
||||
@@ -20,7 +20,7 @@ use wasm_executor::WasmExecutor;
|
||||
use wasmi::Module as WasmModule;
|
||||
use runtime_version::RuntimeVersion;
|
||||
use std::collections::HashMap;
|
||||
use codec::Slicable;
|
||||
use codec::Decode;
|
||||
use twox_hash::XxHash;
|
||||
use std::hash::Hasher;
|
||||
use parking_lot::{Mutex, MutexGuard};
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use primitives::sandbox as sandbox_primitives;
|
||||
use wasm_utils::UserError;
|
||||
use wasmi;
|
||||
|
||||
@@ -386,7 +386,7 @@ impl_function_executor!(this: FunctionExecutor<'e, E>,
|
||||
},
|
||||
// TODO: Remove the old 'ext_sandbox_invoke' and rename this to it.
|
||||
ext_sandbox_invoke_poc2(instance_idx: u32, export_ptr: *const u8, export_len: usize, args_ptr: *const u8, args_len: usize, return_val_ptr: *const u8, return_val_len: usize, state: usize) -> u32 => {
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
|
||||
trace!(target: "runtime-sandbox", "invoke, instance_idx={}", instance_idx);
|
||||
let export = this.memory.get(export_ptr, export_len as usize)
|
||||
@@ -555,7 +555,7 @@ impl CodeExecutor for WasmExecutor {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rustc_hex::FromHex;
|
||||
use codec::Slicable;
|
||||
use codec::Encode;
|
||||
use state_machine::TestExternalities;
|
||||
|
||||
// TODO: move into own crate.
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -30,13 +30,13 @@ extern crate substrate_keyring as keyring;
|
||||
#[cfg(test)]
|
||||
extern crate rhododendron;
|
||||
|
||||
use codec::Slicable;
|
||||
use codec::{Codec, Encode};
|
||||
use primitives::{AuthorityId, Signature};
|
||||
|
||||
use runtime_primitives::bft::{Action, Message, MisbehaviorKind};
|
||||
|
||||
// check a message signature. returns true if signed by that authority.
|
||||
fn check_message_sig<B: Slicable, H: Slicable>(
|
||||
fn check_message_sig<B: Codec, H: Codec>(
|
||||
message: Message<B, H>,
|
||||
signature: &Signature,
|
||||
from: &AuthorityId
|
||||
@@ -64,7 +64,7 @@ fn commit<B, H>(parent: H, round_number: u32, hash: H) -> Message<B, H> {
|
||||
/// Doesn't check that the header hash in question is
|
||||
/// valid or whether the misbehaving authority was part of
|
||||
/// the set at that block.
|
||||
pub fn evaluate_misbehavior<B: Slicable, H: Slicable + Copy>(
|
||||
pub fn evaluate_misbehavior<B: Codec, H: Codec + Copy>(
|
||||
misbehaved: &AuthorityId,
|
||||
parent_hash: H,
|
||||
kind: &MisbehaviorKind<H>,
|
||||
|
||||
@@ -166,7 +166,7 @@ pub struct RemoteCallResponse {
|
||||
/// Generic types.
|
||||
pub mod generic {
|
||||
use primitives::AuthorityId;
|
||||
use codec::Slicable;
|
||||
use codec::{Codec, Decode, Encode};
|
||||
use runtime_primitives::bft::Justification;
|
||||
use ed25519;
|
||||
use primitives::Signature;
|
||||
@@ -190,7 +190,7 @@ pub mod generic {
|
||||
Extrinsics(Vec<Extrinsic>),
|
||||
}
|
||||
|
||||
impl<Extrinsic> Body<Extrinsic> where Extrinsic: Slicable {
|
||||
impl<Extrinsic> Body<Extrinsic> where Extrinsic: Codec {
|
||||
/// Extracts extrinsic from the body.
|
||||
pub fn to_extrinsics(self) -> Vec<Extrinsic> {
|
||||
match self {
|
||||
@@ -198,7 +198,7 @@ pub mod generic {
|
||||
Body::V1(e) => {
|
||||
e.into_iter().filter_map(|bytes| {
|
||||
let bytes = bytes.0.encode();
|
||||
Slicable::decode(&mut bytes.as_slice())
|
||||
Decode::decode(&mut bytes.as_slice())
|
||||
}).collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ use config::ProtocolConfig;
|
||||
use service::TransactionPool;
|
||||
use network_libp2p::{PeerId, SessionInfo, Error as NetworkError};
|
||||
use keyring::Keyring;
|
||||
use codec::Slicable;
|
||||
use codec::Encode;
|
||||
use test_client::{self, TestClient};
|
||||
use test_client::runtime::{Block, Hash, Transfer, Extrinsic};
|
||||
use specialization::Specialization;
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Serialize, Serializer, Deserialize, Deserializer};
|
||||
use codec::Slicable;
|
||||
use codec;
|
||||
use H256;
|
||||
|
||||
/// An identifier for an authority in the consensus algorithm. The same size as ed25519::Public.
|
||||
@@ -106,12 +106,15 @@ impl<'de> Deserialize<'de> for AuthorityId {
|
||||
}
|
||||
}
|
||||
|
||||
impl Slicable for AuthorityId {
|
||||
fn decode<I: ::codec::Input>(input: &mut I) -> Option<Self> {
|
||||
<[u8; 32] as ::codec::Slicable>::decode(input).map(AuthorityId)
|
||||
}
|
||||
|
||||
impl codec::Encode for AuthorityId {
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
self.0.using_encoded(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl codec::Decode for AuthorityId {
|
||||
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> {
|
||||
<[u8; 32] as codec::Decode>::decode(input).map(AuthorityId)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,15 +39,16 @@ macro_rules! impl_rest {
|
||||
}
|
||||
}
|
||||
|
||||
impl ::codec::Slicable for $name {
|
||||
fn decode<I: ::codec::Input>(input: &mut I) -> Option<Self> {
|
||||
<[u8; $len] as ::codec::Slicable>::decode(input).map($name)
|
||||
}
|
||||
|
||||
impl ::codec::Encode for $name {
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
self.0.using_encoded(f)
|
||||
}
|
||||
}
|
||||
impl ::codec::Decode for $name {
|
||||
fn decode<I: ::codec::Input>(input: &mut I) -> Option<Self> {
|
||||
<[u8; $len] as ::codec::Decode>::decode(input).map($name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -101,4 +101,4 @@ impl From<Vec<u8>> for Bytes {
|
||||
impl Deref for Bytes {
|
||||
type Target = [u8];
|
||||
fn deref(&self) -> &[u8] { &self.0[..] }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,18 +16,14 @@
|
||||
|
||||
//! Definition of a sandbox environment.
|
||||
|
||||
use codec::{Slicable, Input};
|
||||
use codec::{Encode, Decode, Input, Output};
|
||||
use rstd::vec::Vec;
|
||||
|
||||
/// Error error that can be returned from host function.
|
||||
#[cfg_attr(feature = "std", derive(Debug))]
|
||||
pub struct HostError;
|
||||
|
||||
impl Slicable for HostError {
|
||||
fn decode<I: Input>(_: &mut I) -> Option<Self> {
|
||||
Some(HostError)
|
||||
}
|
||||
|
||||
impl Encode for HostError {
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
f(&[])
|
||||
}
|
||||
@@ -37,6 +33,12 @@ impl Slicable for HostError {
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for HostError {
|
||||
fn decode<I: Input>(_: &mut I) -> Option<Self> {
|
||||
Some(HostError)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "std", derive(Debug))]
|
||||
#[repr(i8)]
|
||||
@@ -101,31 +103,30 @@ impl From<TypedValue> for ::wasmi::RuntimeValue {
|
||||
}
|
||||
}
|
||||
|
||||
impl Slicable for TypedValue {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
impl Encode for TypedValue {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
match *self {
|
||||
TypedValue::I32(i) => {
|
||||
v.push(ValueType::I32 as u8);
|
||||
i.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(ValueType::I32 as u8);
|
||||
dest.push(&i);
|
||||
}
|
||||
TypedValue::I64(i) => {
|
||||
v.push(ValueType::I64 as u8);
|
||||
i.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(ValueType::I64 as u8);
|
||||
dest.push(&i);
|
||||
}
|
||||
TypedValue::F32(f_bits) => {
|
||||
v.push(ValueType::F32 as u8);
|
||||
f_bits.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(ValueType::F32 as u8);
|
||||
dest.push(&f_bits);
|
||||
}
|
||||
TypedValue::F64(f_bits) => {
|
||||
v.push(ValueType::F64 as u8);
|
||||
f_bits.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(ValueType::F64 as u8);
|
||||
dest.push(&f_bits);
|
||||
}
|
||||
}
|
||||
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for TypedValue {
|
||||
fn decode<I: Input>(value: &mut I) -> Option<Self> {
|
||||
let typed_value = match i8::decode(value) {
|
||||
Some(x) if x == ValueType::I32 as i8 => TypedValue::I32(i32::decode(value)?),
|
||||
@@ -157,21 +158,21 @@ impl From<TypedValue> for ReturnValue {
|
||||
}
|
||||
}
|
||||
|
||||
impl Slicable for ReturnValue {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
impl Encode for ReturnValue {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
match *self {
|
||||
ReturnValue::Unit => {
|
||||
v.push(0);
|
||||
dest.push_byte(0);
|
||||
}
|
||||
ReturnValue::Value(ref val) => {
|
||||
v.push(1);
|
||||
val.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(1);
|
||||
dest.push(val);
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for ReturnValue {
|
||||
fn decode<I: Input>(value: &mut I) -> Option<Self> {
|
||||
match i8::decode(value) {
|
||||
Some(0) => Some(ReturnValue::Unit),
|
||||
@@ -183,7 +184,7 @@ impl Slicable for ReturnValue {
|
||||
|
||||
impl ReturnValue {
|
||||
/// Maximum number of bytes `ReturnValue` might occupy when serialized with
|
||||
/// `Slicable`.
|
||||
/// `Codec`.
|
||||
///
|
||||
/// Breakdown:
|
||||
/// 1 byte for encoding unit/value variant
|
||||
@@ -219,23 +220,22 @@ pub enum ExternEntity {
|
||||
Memory(u32),
|
||||
}
|
||||
|
||||
impl Slicable for ExternEntity {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
impl Encode for ExternEntity {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
match *self {
|
||||
ExternEntity::Function(ref index) => {
|
||||
v.push(ExternEntityKind::Function as u8);
|
||||
index.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(ExternEntityKind::Function as u8);
|
||||
dest.push(index);
|
||||
}
|
||||
ExternEntity::Memory(ref mem_id) => {
|
||||
v.push(ExternEntityKind::Memory as u8);
|
||||
mem_id.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte(ExternEntityKind::Memory as u8);
|
||||
dest.push(mem_id);
|
||||
}
|
||||
}
|
||||
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for ExternEntity {
|
||||
fn decode<I: Input>(value: &mut I) -> Option<Self> {
|
||||
match i8::decode(value) {
|
||||
Some(x) if x == ExternEntityKind::Function as i8 => {
|
||||
@@ -266,16 +266,15 @@ pub struct Entry {
|
||||
pub entity: ExternEntity,
|
||||
}
|
||||
|
||||
impl Slicable for Entry {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
self.module_name.using_encoded(|s| v.extend(s));
|
||||
self.field_name.using_encoded(|s| v.extend(s));
|
||||
self.entity.using_encoded(|s| v.extend(s));
|
||||
|
||||
v
|
||||
impl Encode for Entry {
|
||||
fn encode_to<T: ::codec::Output>(&self, dest: &mut T) {
|
||||
dest.push(&self.module_name);
|
||||
dest.push(&self.field_name);
|
||||
dest.push(&self.entity);
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for Entry {
|
||||
fn decode<I: Input>(value: &mut I) -> Option<Self> {
|
||||
let module_name = Vec::decode(value)?;
|
||||
let field_name = Vec::decode(value)?;
|
||||
@@ -297,11 +296,13 @@ pub struct EnvironmentDefinition {
|
||||
pub entries: Vec<Entry>,
|
||||
}
|
||||
|
||||
impl Slicable for EnvironmentDefinition {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
self.entries.encode()
|
||||
impl Encode for EnvironmentDefinition {
|
||||
fn encode_to<T: Output>(&self, dest: &mut T) {
|
||||
self.entries.encode_to(dest)
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for EnvironmentDefinition {
|
||||
fn decode<I: Input>(value: &mut I) -> Option<Self> {
|
||||
let entries = Vec::decode(value)?;
|
||||
|
||||
@@ -340,8 +341,9 @@ pub const ERR_EXECUTION: u32 = -3i32 as u32;
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fmt;
|
||||
use codec::Codec;
|
||||
|
||||
fn roundtrip<S: Slicable + PartialEq + fmt::Debug>(s: S) {
|
||||
fn roundtrip<S: Codec + PartialEq + fmt::Debug>(s: S) {
|
||||
let encoded = s.encode();
|
||||
assert_eq!(S::decode(&mut &encoded[..]).unwrap(), s);
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ use std::sync::Arc;
|
||||
|
||||
use client::{self, Client};
|
||||
use extrinsic_pool::api::{Error, ExtrinsicPool};
|
||||
use codec::Slicable;
|
||||
use codec::Codec;
|
||||
|
||||
use primitives::Bytes;
|
||||
use runtime_primitives::{generic, traits::Block as BlockT};
|
||||
@@ -65,7 +65,7 @@ impl<B, E, Block, P, Ex, Hash> AuthorApi<Hash, Ex> for Author<B, E, Block, P> wh
|
||||
Block: BlockT + 'static,
|
||||
P: ExtrinsicPool<Ex, generic::BlockId<Block>, Hash>,
|
||||
P::Error: 'static,
|
||||
Ex: Slicable,
|
||||
Ex: Codec,
|
||||
{
|
||||
fn submit_extrinsic(&self, xt: Bytes) -> Result<Hash> {
|
||||
self.submit_rich_extrinsic(Ex::decode(&mut &xt[..]).ok_or(error::Error::from(error::ErrorKind::BadFormat))?)
|
||||
|
||||
@@ -20,6 +20,7 @@ use std::{fmt, sync::Arc};
|
||||
use extrinsic_pool::{api, txpool};
|
||||
use test_client;
|
||||
use parking_lot::Mutex;
|
||||
use codec::Encode;
|
||||
|
||||
type Extrinsic = u64;
|
||||
type Hash = u64;
|
||||
|
||||
@@ -168,13 +168,13 @@ macro_rules! impl_stubs {
|
||||
};
|
||||
(@METHOD $data: ident $new_name: ident => $invoke:expr) => {{
|
||||
let mut data = $data;
|
||||
let input = match $crate::codec::Slicable::decode(&mut data) {
|
||||
let input = match $crate::codec::Decode::decode(&mut data) {
|
||||
Some(input) => input,
|
||||
None => panic!("Bad input data provided to {}", stringify!($new_name)),
|
||||
};
|
||||
|
||||
let output = $invoke(input);
|
||||
Some($crate::codec::Slicable::encode(&output))
|
||||
Some($crate::codec::Encode::encode(&output))
|
||||
}}
|
||||
}
|
||||
|
||||
|
||||
@@ -282,13 +282,13 @@ macro_rules! impl_stubs {
|
||||
}
|
||||
};
|
||||
|
||||
let input = match $crate::codec::Slicable::decode(&mut input) {
|
||||
let input = match $crate::codec::Decode::decode(&mut input) {
|
||||
Some(input) => input,
|
||||
None => panic!("Bad input data provided to {}", stringify!($name)),
|
||||
};
|
||||
|
||||
let output = ($invoke)(input);
|
||||
let output = $crate::codec::Slicable::encode(&output);
|
||||
let output = $crate::codec::Encode::encode(&output);
|
||||
let res = output.as_ptr() as u64 + ((output.len() as u64) << 32);
|
||||
|
||||
// Leak the output vector to avoid it being freed.
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
use rstd::prelude::*;
|
||||
use rstd::{slice, marker, mem};
|
||||
use codec::Slicable;
|
||||
use codec::{Decode, Encode};
|
||||
use primitives::sandbox as sandbox_primitives;
|
||||
use super::{Error, TypedValue, ReturnValue, HostFuncType};
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ pub use std::fmt;
|
||||
pub use rstd::result;
|
||||
#[cfg(feature = "std")]
|
||||
use serde;
|
||||
pub use codec::{Slicable, Input};
|
||||
pub use codec::{Codec, Decode, Encode, Input, Output};
|
||||
|
||||
pub type Result = result::Result<(), &'static str>;
|
||||
|
||||
@@ -39,11 +39,11 @@ pub trait AuxDispatchable {
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub trait AuxCallable {
|
||||
type Call: AuxDispatchable + Slicable + ::serde::Serialize + Clone + PartialEq + Eq;
|
||||
type Call: AuxDispatchable + Codec + ::serde::Serialize + Clone + PartialEq + Eq;
|
||||
}
|
||||
#[cfg(not(feature = "std"))]
|
||||
pub trait AuxCallable {
|
||||
type Call: AuxDispatchable + Slicable + Clone + PartialEq + Eq;
|
||||
type Call: AuxDispatchable + Codec + Clone + PartialEq + Eq;
|
||||
}
|
||||
|
||||
// dirty hack to work around serde_derive issue
|
||||
@@ -52,11 +52,11 @@ pub type AuxCallableCallFor<A> = <A as AuxCallable>::Call;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub trait Callable {
|
||||
type Call: Dispatchable + Slicable + ::serde::Serialize + Clone + PartialEq + Eq;
|
||||
type Call: Dispatchable + Codec + ::serde::Serialize + Clone + PartialEq + Eq;
|
||||
}
|
||||
#[cfg(not(feature = "std"))]
|
||||
pub trait Callable {
|
||||
type Call: Dispatchable + Slicable + Clone + PartialEq + Eq;
|
||||
type Call: Dispatchable + Codec + Clone + PartialEq + Eq;
|
||||
}
|
||||
|
||||
// dirty hack to work around serde_derive issue.
|
||||
@@ -64,16 +64,16 @@ pub trait Callable {
|
||||
pub type CallableCallFor<C> = <C as Callable>::Call;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub trait Parameter: Slicable + serde::Serialize + Clone + Eq + fmt::Debug {}
|
||||
pub trait Parameter: Codec + serde::Serialize + Clone + Eq + fmt::Debug {}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl<T> Parameter for T where T: Slicable + serde::Serialize + Clone + Eq + fmt::Debug {}
|
||||
impl<T> Parameter for T where T: Codec + serde::Serialize + Clone + Eq + fmt::Debug {}
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
pub trait Parameter: Slicable + Clone + Eq {}
|
||||
pub trait Parameter: Codec + Clone + Eq {}
|
||||
|
||||
#[cfg(not(feature = "std"))]
|
||||
impl<T> Parameter for T where T: Slicable + Clone + Eq {}
|
||||
impl<T> Parameter for T where T: Codec + Clone + Eq {}
|
||||
|
||||
/// Declare a struct for this module, then implement dispatch logic to create a pairing of several
|
||||
/// dispatch traits and enums.
|
||||
@@ -395,13 +395,13 @@ macro_rules! __decl_dispatch_module_common {
|
||||
}
|
||||
}
|
||||
|
||||
impl<$trait_instance: $trait_name> $crate::dispatch::Slicable for $call_type<$trait_instance> {
|
||||
impl<$trait_instance: $trait_name> $crate::dispatch::Decode for $call_type<$trait_instance> {
|
||||
fn decode<I: $crate::dispatch::Input>(input: &mut I) -> Option<Self> {
|
||||
match input.read_byte()? {
|
||||
$(
|
||||
$id => {
|
||||
$(
|
||||
let $param_name = $crate::dispatch::Slicable::decode(input)?;
|
||||
let $param_name = $crate::dispatch::Decode::decode(input)?;
|
||||
)*
|
||||
Some($call_type:: $fn_name( $( $param_name ),* ))
|
||||
}
|
||||
@@ -409,9 +409,10 @@ macro_rules! __decl_dispatch_module_common {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(&self) -> $crate::dispatch::Vec<u8> {
|
||||
let mut v = $crate::dispatch::Vec::new();
|
||||
impl<$trait_instance: $trait_name> $crate::dispatch::Encode for $call_type<$trait_instance> {
|
||||
fn encode_to<W: $crate::dispatch::Output>(&self, dest: &mut W) {
|
||||
match *self {
|
||||
$(
|
||||
$call_type::$fn_name(
|
||||
@@ -419,19 +420,14 @@ macro_rules! __decl_dispatch_module_common {
|
||||
ref $param_name
|
||||
),*
|
||||
) => {
|
||||
v.push($id as u8);
|
||||
dest.push_byte($id as u8);
|
||||
$(
|
||||
$param_name.using_encoded(|s| v.extend(s));
|
||||
$param_name.encode_to(dest);
|
||||
)*
|
||||
}
|
||||
)*
|
||||
$call_type::__PhantomItem(_) => unreachable!(),
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
f(self.encode().as_slice())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -536,32 +532,28 @@ macro_rules! impl_outer_dispatch_common {
|
||||
(
|
||||
$call_type:ident, $( $camelcase:ident = $id:expr, )*
|
||||
) => {
|
||||
impl $crate::dispatch::Slicable for $call_type {
|
||||
impl $crate::dispatch::Decode for $call_type {
|
||||
fn decode<I: $crate::dispatch::Input>(input: &mut I) -> Option<Self> {
|
||||
match input.read_byte()? {
|
||||
$(
|
||||
$id =>
|
||||
Some($call_type::$camelcase( $crate::dispatch::Slicable::decode(input)? )),
|
||||
Some($call_type::$camelcase( $crate::dispatch::Decode::decode(input)? )),
|
||||
)*
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(&self) -> $crate::dispatch::Vec<u8> {
|
||||
let mut v = $crate::dispatch::Vec::new();
|
||||
impl $crate::dispatch::Encode for $call_type {
|
||||
fn encode_to<W: $crate::dispatch::Output>(&self, dest: &mut W) {
|
||||
match *self {
|
||||
$(
|
||||
$call_type::$camelcase( ref sub ) => {
|
||||
v.push($id as u8);
|
||||
sub.using_encoded(|s| v.extend(s));
|
||||
dest.push_byte($id as u8);
|
||||
sub.encode_to(dest);
|
||||
}
|
||||
)*
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
|
||||
f(self.encode().as_slice())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
//! Hashable trait.
|
||||
|
||||
use codec::Slicable;
|
||||
use codec::Codec;
|
||||
use runtime_io::{blake2_256, twox_128, twox_256};
|
||||
|
||||
pub trait Hashable: Sized {
|
||||
@@ -25,7 +25,7 @@ pub trait Hashable: Sized {
|
||||
fn twox_256(&self) -> [u8; 32];
|
||||
}
|
||||
|
||||
impl<T: Slicable> Hashable for T {
|
||||
impl<T: Codec> Hashable for T {
|
||||
fn blake2_256(&self) -> [u8; 32] {
|
||||
blake2_256(&self.encode())
|
||||
}
|
||||
|
||||
@@ -59,38 +59,38 @@ pub trait Storage {
|
||||
fn exists(&self, key: &[u8]) -> bool;
|
||||
|
||||
/// Load the bytes of a key from storage. Can panic if the type is incorrect.
|
||||
fn get<T: codec::Slicable>(&self, key: &[u8]) -> Option<T>;
|
||||
fn get<T: codec::Codec>(&self, key: &[u8]) -> Option<T>;
|
||||
|
||||
/// Load the bytes of a key from storage. Can panic if the type is incorrect. Will panic if
|
||||
/// it's not there.
|
||||
fn require<T: codec::Slicable>(&self, key: &[u8]) -> T { self.get(key).expect("Required values must be in storage") }
|
||||
fn require<T: codec::Codec>(&self, key: &[u8]) -> T { self.get(key).expect("Required values must be in storage") }
|
||||
|
||||
/// Load the bytes of a key from storage. Can panic if the type is incorrect. The type's
|
||||
/// default is returned if it's not there.
|
||||
fn get_or_default<T: codec::Slicable + Default>(&self, key: &[u8]) -> T { self.get(key).unwrap_or_default() }
|
||||
fn get_or_default<T: codec::Codec + Default>(&self, key: &[u8]) -> T { self.get(key).unwrap_or_default() }
|
||||
|
||||
/// Put a value in under a key.
|
||||
fn put<T: codec::Slicable>(&self, key: &[u8], val: &T);
|
||||
fn put<T: codec::Codec>(&self, key: &[u8], val: &T);
|
||||
|
||||
/// Remove the bytes of a key from storage.
|
||||
fn kill(&self, key: &[u8]);
|
||||
|
||||
/// Take a value from storage, deleting it after reading.
|
||||
fn take<T: codec::Slicable>(&self, key: &[u8]) -> Option<T> {
|
||||
fn take<T: codec::Codec>(&self, key: &[u8]) -> Option<T> {
|
||||
let value = self.get(key);
|
||||
self.kill(key);
|
||||
value
|
||||
}
|
||||
|
||||
/// Take a value from storage, deleting it after reading.
|
||||
fn take_or_panic<T: codec::Slicable>(&self, key: &[u8]) -> T { self.take(key).expect("Required values must be in storage") }
|
||||
fn take_or_panic<T: codec::Codec>(&self, key: &[u8]) -> T { self.take(key).expect("Required values must be in storage") }
|
||||
|
||||
/// Take a value from storage, deleting it after reading.
|
||||
fn take_or_default<T: codec::Slicable + Default>(&self, key: &[u8]) -> T { self.take(key).unwrap_or_default() }
|
||||
fn take_or_default<T: codec::Codec + Default>(&self, key: &[u8]) -> T { self.take(key).unwrap_or_default() }
|
||||
}
|
||||
|
||||
/// A strongly-typed value kept in storage.
|
||||
pub trait StorageValue<T: codec::Slicable> {
|
||||
pub trait StorageValue<T: codec::Codec> {
|
||||
/// The type that get/take returns.
|
||||
type Query;
|
||||
|
||||
@@ -120,7 +120,7 @@ pub trait StorageValue<T: codec::Slicable> {
|
||||
}
|
||||
|
||||
/// A strongly-typed list in storage.
|
||||
pub trait StorageList<T: codec::Slicable> {
|
||||
pub trait StorageList<T: codec::Codec> {
|
||||
/// Get the prefix key in storage.
|
||||
fn prefix() -> &'static [u8];
|
||||
|
||||
@@ -150,7 +150,7 @@ pub trait StorageList<T: codec::Slicable> {
|
||||
}
|
||||
|
||||
/// A strongly-typed map in storage.
|
||||
pub trait StorageMap<K: codec::Slicable, V: codec::Slicable> {
|
||||
pub trait StorageMap<K: codec::Codec, V: codec::Codec> {
|
||||
/// The type that get/take returns.
|
||||
type Query;
|
||||
|
||||
@@ -233,7 +233,7 @@ macro_rules! __storage_items_internal {
|
||||
/// Get the storage key used to fetch a value corresponding to a specific key.
|
||||
fn key_for(x: &$kty) -> Vec<u8> {
|
||||
let mut key = $prefix.to_vec();
|
||||
key.extend($crate::codec::Slicable::encode(x));
|
||||
$crate::codec::Encode::encode_to(x, &mut key);
|
||||
key
|
||||
}
|
||||
|
||||
@@ -284,7 +284,7 @@ macro_rules! __storage_items_internal {
|
||||
/// Get the storage key used to fetch a value at a given index.
|
||||
fn key_for(index: u32) -> Vec<u8> {
|
||||
let mut key = $prefix.to_vec();
|
||||
key.extend($crate::codec::Slicable::encode(&index));
|
||||
$crate::codec::Encode::encode_to(&index, &mut key);
|
||||
key
|
||||
}
|
||||
|
||||
@@ -496,7 +496,7 @@ macro_rules! __decl_storage_item {
|
||||
/// Get the storage key used to fetch a value corresponding to a specific key.
|
||||
fn key_for(x: &$kty) -> Vec<u8> {
|
||||
let mut key = $prefix.to_vec();
|
||||
key.extend($crate::codec::Slicable::encode(x));
|
||||
$crate::codec::Encode::encode_to(x, &mut key);
|
||||
key
|
||||
}
|
||||
|
||||
@@ -991,7 +991,7 @@ macro_rules! __decl_storage_items {
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
use std::cell::RefCell;
|
||||
use codec::Slicable;
|
||||
use codec::Codec;
|
||||
use super::*;
|
||||
|
||||
impl Storage for RefCell<HashMap<Vec<u8>, Vec<u8>>> {
|
||||
@@ -999,11 +999,11 @@ mod tests {
|
||||
self.borrow_mut().get(key).is_some()
|
||||
}
|
||||
|
||||
fn get<T: Slicable>(&self, key: &[u8]) -> Option<T> {
|
||||
fn get<T: Codec>(&self, key: &[u8]) -> Option<T> {
|
||||
self.borrow_mut().get(key).map(|v| T::decode(&mut &v[..]).unwrap())
|
||||
}
|
||||
|
||||
fn put<T: Slicable>(&self, key: &[u8], val: &T) {
|
||||
fn put<T: Codec>(&self, key: &[u8], val: &T) {
|
||||
self.borrow_mut().insert(key.to_owned(), val.encode());
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
use rstd::prelude::*;
|
||||
use rstd::borrow::Borrow;
|
||||
use runtime_io::{self, twox_128};
|
||||
use codec::{Slicable, KeyedVec, Input};
|
||||
use codec::{Codec, Decode, KeyedVec, Input};
|
||||
|
||||
pub mod generator;
|
||||
|
||||
@@ -40,42 +40,42 @@ impl<'a> Input for IncrementalInput<'a> {
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or `None` if there is no explicit entry.
|
||||
pub fn get<T: Slicable + Sized>(key: &[u8]) -> Option<T> {
|
||||
pub fn get<T: Codec + Sized>(key: &[u8]) -> Option<T> {
|
||||
let key = twox_128(key);
|
||||
runtime_io::read_storage(&key[..], &mut [0; 0][..], 0).map(|_| {
|
||||
let mut input = IncrementalInput {
|
||||
key: &key[..],
|
||||
pos: 0,
|
||||
};
|
||||
Slicable::decode(&mut input).expect("storage is not null, therefore must be a valid type")
|
||||
Decode::decode(&mut input).expect("storage is not null, therefore must be a valid type")
|
||||
})
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or the type's default if there is no
|
||||
/// explicit entry.
|
||||
pub fn get_or_default<T: Slicable + Sized + Default>(key: &[u8]) -> T {
|
||||
pub fn get_or_default<T: Codec + Sized + Default>(key: &[u8]) -> T {
|
||||
get(key).unwrap_or_else(Default::default)
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or `default_value` if there is no
|
||||
/// explicit entry.
|
||||
pub fn get_or<T: Slicable + Sized>(key: &[u8], default_value: T) -> T {
|
||||
pub fn get_or<T: Codec + Sized>(key: &[u8], default_value: T) -> T {
|
||||
get(key).unwrap_or(default_value)
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or `default_value()` if there is no
|
||||
/// explicit entry.
|
||||
pub fn get_or_else<T: Slicable + Sized, F: FnOnce() -> T>(key: &[u8], default_value: F) -> T {
|
||||
pub fn get_or_else<T: Codec + Sized, F: FnOnce() -> T>(key: &[u8], default_value: F) -> T {
|
||||
get(key).unwrap_or_else(default_value)
|
||||
}
|
||||
|
||||
/// Put `value` in storage under `key`.
|
||||
pub fn put<T: Slicable>(key: &[u8], value: &T) {
|
||||
pub fn put<T: Codec>(key: &[u8], value: &T) {
|
||||
value.using_encoded(|slice| runtime_io::set_storage(&twox_128(key)[..], slice));
|
||||
}
|
||||
|
||||
/// Remove `key` from storage, returning its value if it had an explicit entry or `None` otherwise.
|
||||
pub fn take<T: Slicable + Sized>(key: &[u8]) -> Option<T> {
|
||||
pub fn take<T: Codec + Sized>(key: &[u8]) -> Option<T> {
|
||||
let r = get(key);
|
||||
if r.is_some() {
|
||||
kill(key);
|
||||
@@ -85,19 +85,19 @@ pub fn take<T: Slicable + Sized>(key: &[u8]) -> Option<T> {
|
||||
|
||||
/// Remove `key` from storage, returning its value, or, if there was no explicit entry in storage,
|
||||
/// the default for its type.
|
||||
pub fn take_or_default<T: Slicable + Sized + Default>(key: &[u8]) -> T {
|
||||
pub fn take_or_default<T: Codec + Sized + Default>(key: &[u8]) -> T {
|
||||
take(key).unwrap_or_else(Default::default)
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or `default_value` if there is no
|
||||
/// explicit entry. Ensure there is no explicit entry on return.
|
||||
pub fn take_or<T: Slicable + Sized>(key: &[u8], default_value: T) -> T {
|
||||
pub fn take_or<T: Codec + Sized>(key: &[u8], default_value: T) -> T {
|
||||
take(key).unwrap_or(default_value)
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or `default_value()` if there is no
|
||||
/// explicit entry. Ensure there is no explicit entry on return.
|
||||
pub fn take_or_else<T: Slicable + Sized, F: FnOnce() -> T>(key: &[u8], default_value: F) -> T {
|
||||
pub fn take_or_else<T: Codec + Sized, F: FnOnce() -> T>(key: &[u8], default_value: F) -> T {
|
||||
take(key).unwrap_or_else(default_value)
|
||||
}
|
||||
|
||||
@@ -131,12 +131,12 @@ impl ::GenericStorage for RuntimeStorage {
|
||||
}
|
||||
|
||||
/// Load the bytes of a key from storage. Can panic if the type is incorrect.
|
||||
fn get<T: Slicable>(&self, key: &[u8]) -> Option<T> {
|
||||
fn get<T: Codec>(&self, key: &[u8]) -> Option<T> {
|
||||
super::storage::get(key)
|
||||
}
|
||||
|
||||
/// Put a value in under a key.
|
||||
fn put<T: Slicable>(&self, key: &[u8], val: &T) {
|
||||
fn put<T: Codec>(&self, key: &[u8], val: &T) {
|
||||
super::storage::put(key, val)
|
||||
}
|
||||
|
||||
@@ -146,13 +146,13 @@ impl ::GenericStorage for RuntimeStorage {
|
||||
}
|
||||
|
||||
/// Take a value from storage, deleting it after reading.
|
||||
fn take<T: Slicable>(&self, key: &[u8]) -> Option<T> {
|
||||
fn take<T: Codec>(&self, key: &[u8]) -> Option<T> {
|
||||
super::storage::take(key)
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait for working with macro-generated storage values under the substrate storage API.
|
||||
pub trait StorageValue<T: Slicable> {
|
||||
pub trait StorageValue<T: Codec> {
|
||||
/// The type that get/take return.
|
||||
type Query;
|
||||
|
||||
@@ -175,7 +175,7 @@ pub trait StorageValue<T: Slicable> {
|
||||
fn take() -> Self::Query;
|
||||
}
|
||||
|
||||
impl<T: Slicable, U> StorageValue<T> for U where U: generator::StorageValue<T> {
|
||||
impl<T: Codec, U> StorageValue<T> for U where U: generator::StorageValue<T> {
|
||||
type Query = U::Query;
|
||||
|
||||
fn key() -> &'static [u8] {
|
||||
@@ -199,7 +199,7 @@ impl<T: Slicable, U> StorageValue<T> for U where U: generator::StorageValue<T> {
|
||||
}
|
||||
|
||||
/// A strongly-typed list in storage.
|
||||
pub trait StorageList<T: Slicable> {
|
||||
pub trait StorageList<T: Codec> {
|
||||
/// Get the prefix key in storage.
|
||||
fn prefix() -> &'static [u8];
|
||||
|
||||
@@ -228,7 +228,7 @@ pub trait StorageList<T: Slicable> {
|
||||
fn clear();
|
||||
}
|
||||
|
||||
impl<T: Slicable, U> StorageList<T> for U where U: generator::StorageList<T> {
|
||||
impl<T: Codec, U> StorageList<T> for U where U: generator::StorageList<T> {
|
||||
fn prefix() -> &'static [u8] {
|
||||
<U as generator::StorageList<T>>::prefix()
|
||||
}
|
||||
@@ -267,7 +267,7 @@ impl<T: Slicable, U> StorageList<T> for U where U: generator::StorageList<T> {
|
||||
}
|
||||
|
||||
/// A strongly-typed map in storage.
|
||||
pub trait StorageMap<K: Slicable, V: Slicable> {
|
||||
pub trait StorageMap<K: Codec, V: Codec> {
|
||||
/// The type that get/take return.
|
||||
type Query;
|
||||
|
||||
@@ -293,7 +293,7 @@ pub trait StorageMap<K: Slicable, V: Slicable> {
|
||||
fn take<KeyArg: Borrow<K>>(key: KeyArg) -> Self::Query;
|
||||
}
|
||||
|
||||
impl<K: Slicable, V: Slicable, U> StorageMap<K, V> for U where U: generator::StorageMap<K, V> {
|
||||
impl<K: Codec, V: Codec, U> StorageMap<K, V> for U where U: generator::StorageMap<K, V> {
|
||||
type Query = U::Query;
|
||||
|
||||
fn prefix() -> &'static [u8] {
|
||||
@@ -327,7 +327,7 @@ impl<K: Slicable, V: Slicable, U> StorageMap<K, V> for U where U: generator::Sto
|
||||
|
||||
/// A trait to conveniently store a vector of storable data.
|
||||
pub trait StorageVec {
|
||||
type Item: Default + Sized + Slicable;
|
||||
type Item: Default + Sized + Codec;
|
||||
const PREFIX: &'static [u8];
|
||||
|
||||
/// Get the current set of items.
|
||||
@@ -386,44 +386,44 @@ pub trait StorageVec {
|
||||
|
||||
pub mod unhashed {
|
||||
use rstd::borrow::Borrow;
|
||||
use super::{runtime_io, Slicable, KeyedVec, Vec, IncrementalInput};
|
||||
use super::{runtime_io, Codec, Decode, KeyedVec, Vec, IncrementalInput};
|
||||
|
||||
/// Return the value of the item in storage under `key`, or `None` if there is no explicit entry.
|
||||
pub fn get<T: Slicable + Sized>(key: &[u8]) -> Option<T> {
|
||||
pub fn get<T: Codec + Sized>(key: &[u8]) -> Option<T> {
|
||||
runtime_io::read_storage(key, &mut [0; 0][..], 0).map(|_| {
|
||||
let mut input = IncrementalInput {
|
||||
key,
|
||||
pos: 0,
|
||||
};
|
||||
Slicable::decode(&mut input).expect("stroage is not null, therefore must be a valid type")
|
||||
Decode::decode(&mut input).expect("storage is not null, therefore must be a valid type")
|
||||
})
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or the type's default if there is no
|
||||
/// explicit entry.
|
||||
pub fn get_or_default<T: Slicable + Sized + Default>(key: &[u8]) -> T {
|
||||
pub fn get_or_default<T: Codec + Sized + Default>(key: &[u8]) -> T {
|
||||
get(key).unwrap_or_else(Default::default)
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or `default_value` if there is no
|
||||
/// explicit entry.
|
||||
pub fn get_or<T: Slicable + Sized>(key: &[u8], default_value: T) -> T {
|
||||
pub fn get_or<T: Codec + Sized>(key: &[u8], default_value: T) -> T {
|
||||
get(key).unwrap_or(default_value)
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or `default_value()` if there is no
|
||||
/// explicit entry.
|
||||
pub fn get_or_else<T: Slicable + Sized, F: FnOnce() -> T>(key: &[u8], default_value: F) -> T {
|
||||
pub fn get_or_else<T: Codec + Sized, F: FnOnce() -> T>(key: &[u8], default_value: F) -> T {
|
||||
get(key).unwrap_or_else(default_value)
|
||||
}
|
||||
|
||||
/// Put `value` in storage under `key`.
|
||||
pub fn put<T: Slicable>(key: &[u8], value: &T) {
|
||||
pub fn put<T: Codec>(key: &[u8], value: &T) {
|
||||
value.using_encoded(|slice| runtime_io::set_storage(key, slice));
|
||||
}
|
||||
|
||||
/// Remove `key` from storage, returning its value if it had an explicit entry or `None` otherwise.
|
||||
pub fn take<T: Slicable + Sized>(key: &[u8]) -> Option<T> {
|
||||
pub fn take<T: Codec + Sized>(key: &[u8]) -> Option<T> {
|
||||
let r = get(key);
|
||||
if r.is_some() {
|
||||
kill(key);
|
||||
@@ -433,19 +433,19 @@ pub mod unhashed {
|
||||
|
||||
/// Remove `key` from storage, returning its value, or, if there was no explicit entry in storage,
|
||||
/// the default for its type.
|
||||
pub fn take_or_default<T: Slicable + Sized + Default>(key: &[u8]) -> T {
|
||||
pub fn take_or_default<T: Codec + Sized + Default>(key: &[u8]) -> T {
|
||||
take(key).unwrap_or_else(Default::default)
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or `default_value` if there is no
|
||||
/// explicit entry. Ensure there is no explicit entry on return.
|
||||
pub fn take_or<T: Slicable + Sized>(key: &[u8], default_value: T) -> T {
|
||||
pub fn take_or<T: Codec + Sized>(key: &[u8], default_value: T) -> T {
|
||||
take(key).unwrap_or(default_value)
|
||||
}
|
||||
|
||||
/// Return the value of the item in storage under `key`, or `default_value()` if there is no
|
||||
/// explicit entry. Ensure there is no explicit entry on return.
|
||||
pub fn take_or_else<T: Slicable + Sized, F: FnOnce() -> T>(key: &[u8], default_value: F) -> T {
|
||||
pub fn take_or_else<T: Codec + Sized, F: FnOnce() -> T>(key: &[u8], default_value: F) -> T {
|
||||
take(key).unwrap_or_else(default_value)
|
||||
}
|
||||
|
||||
@@ -476,7 +476,7 @@ pub mod unhashed {
|
||||
|
||||
/// A trait to conveniently store a vector of storable data.
|
||||
pub trait StorageVec {
|
||||
type Item: Default + Sized + Slicable;
|
||||
type Item: Default + Sized + Codec;
|
||||
const PREFIX: &'static [u8];
|
||||
|
||||
/// Get the current set of items.
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ mod pruning;
|
||||
|
||||
use std::fmt;
|
||||
use parking_lot::RwLock;
|
||||
use codec::Slicable;
|
||||
use codec::Codec;
|
||||
use std::collections::HashSet;
|
||||
use unfinalized::UnfinalizedOverlay;
|
||||
use pruning::RefWindow;
|
||||
@@ -50,8 +50,8 @@ use pruning::RefWindow;
|
||||
pub type DBValue = Vec<u8>;
|
||||
|
||||
/// Basic set of requirements for the Block hash and node key types.
|
||||
pub trait Hash: Send + Sync + Sized + Eq + PartialEq + Clone + Default + fmt::Debug + Slicable + std::hash::Hash + 'static {}
|
||||
impl<T: Send + Sync + Sized + Eq + PartialEq + Clone + Default + fmt::Debug + Slicable + std::hash::Hash + 'static> Hash for T {}
|
||||
pub trait Hash: Send + Sync + Sized + Eq + PartialEq + Clone + Default + fmt::Debug + Codec + std::hash::Hash + 'static {}
|
||||
impl<T: Send + Sync + Sized + Eq + PartialEq + Clone + Default + fmt::Debug + Codec + std::hash::Hash + 'static> Hash for T {}
|
||||
|
||||
/// Backend database trait. Read-only.
|
||||
pub trait MetaDb {
|
||||
@@ -76,7 +76,7 @@ pub trait HashDb {
|
||||
pub enum Error<E: fmt::Debug> {
|
||||
/// Database backend error.
|
||||
Db(E),
|
||||
/// `Slicable` decoding error.
|
||||
/// `Codec` decoding error.
|
||||
Decoding,
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ impl PruningMode {
|
||||
}
|
||||
}
|
||||
|
||||
fn to_meta_key<S: Slicable>(suffix: &[u8], data: &S) -> Vec<u8> {
|
||||
fn to_meta_key<S: Codec>(suffix: &[u8], data: &S) -> Vec<u8> {
|
||||
let mut buffer = data.encode();
|
||||
buffer.extend(suffix);
|
||||
buffer
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
//! The changes are journaled in the DB.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use codec::{Slicable, self};
|
||||
use codec::{Decode, Encode, self};
|
||||
use {CommitSet, Error, MetaDb, to_meta_key, Hash};
|
||||
|
||||
const LAST_PRUNED: &[u8] = b"last_pruned";
|
||||
@@ -49,20 +49,20 @@ struct JournalRecord<BlockHash: Hash, Key: Hash> {
|
||||
deleted: Vec<Key>,
|
||||
}
|
||||
|
||||
impl<BlockHash: Hash, Key: Hash> Slicable for JournalRecord<BlockHash, Key> {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::with_capacity(4096);
|
||||
self.hash.using_encoded(|s| v.extend(s));
|
||||
self.inserted.using_encoded(|s| v.extend(s));
|
||||
self.deleted.using_encoded(|s| v.extend(s));
|
||||
v
|
||||
impl<BlockHash: Hash, Key: Hash> Encode for JournalRecord<BlockHash, Key> {
|
||||
fn encode_to<T: codec::Output>(&self, dest: &mut T) {
|
||||
dest.push(&self.hash);
|
||||
dest.push(&self.inserted);
|
||||
dest.push(&self.deleted);
|
||||
}
|
||||
}
|
||||
|
||||
impl<BlockHash: Hash, Key: Hash> Decode for JournalRecord<BlockHash, Key> {
|
||||
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> {
|
||||
Some(JournalRecord {
|
||||
hash: Slicable::decode(input)?,
|
||||
inserted: Slicable::decode(input)?,
|
||||
deleted: Slicable::decode(input)?,
|
||||
hash: Decode::decode(input)?,
|
||||
inserted: Decode::decode(input)?,
|
||||
deleted: Decode::decode(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ impl<BlockHash: Hash, Key: Hash> RefWindow<BlockHash, Key> {
|
||||
let journal_key = to_journal_key(block);
|
||||
match db.get_meta(&journal_key).map_err(|e| Error::Db(e))? {
|
||||
Some(record) => {
|
||||
let record: JournalRecord<BlockHash, Key> = Slicable::decode(&mut record.as_slice()).ok_or(Error::Decoding)?;
|
||||
let record: JournalRecord<BlockHash, Key> = Decode::decode(&mut record.as_slice()).ok_or(Error::Decoding)?;
|
||||
trace!(target: "state-db", "Pruning journal entry {} ({} inserted, {} deleted)", block, record.inserted.len(), record.deleted.len());
|
||||
pruning.import(&record.hash, journal_key, record.inserted.into_iter(), record.deleted);
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use super::{Error, DBValue, ChangeSet, CommitSet, MetaDb, Hash, to_meta_key};
|
||||
use codec::{self, Slicable};
|
||||
use codec::{self, Decode, Encode};
|
||||
|
||||
const UNFINALIZED_JOURNAL: &[u8] = b"unfinalized_journal";
|
||||
const LAST_FINALIZED: &[u8] = b"last_finalized";
|
||||
@@ -38,22 +38,22 @@ struct JournalRecord<BlockHash: Hash, Key: Hash> {
|
||||
deleted: Vec<Key>,
|
||||
}
|
||||
|
||||
impl<BlockHash: Hash, Key: Hash> Slicable for JournalRecord<BlockHash, Key> {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::with_capacity(4096);
|
||||
self.hash.using_encoded(|s| v.extend(s));
|
||||
self.parent_hash.using_encoded(|s| v.extend(s));
|
||||
self.inserted.using_encoded(|s| v.extend(s));
|
||||
self.deleted.using_encoded(|s| v.extend(s));
|
||||
v
|
||||
impl<BlockHash: Hash, Key: Hash> Encode for JournalRecord<BlockHash, Key> {
|
||||
fn encode_to<T: codec::Output>(&self, dest: &mut T) {
|
||||
dest.push(&self.hash);
|
||||
dest.push(&self.parent_hash);
|
||||
dest.push(&self.inserted);
|
||||
dest.push(&self.deleted);
|
||||
}
|
||||
}
|
||||
|
||||
impl<BlockHash: Hash, Key: Hash> Decode for JournalRecord<BlockHash, Key> {
|
||||
fn decode<I: codec::Input>(input: &mut I) -> Option<Self> {
|
||||
Some(JournalRecord {
|
||||
hash: Slicable::decode(input)?,
|
||||
parent_hash: Slicable::decode(input)?,
|
||||
inserted: Slicable::decode(input)?,
|
||||
deleted: Slicable::decode(input)?,
|
||||
hash: Decode::decode(input)?,
|
||||
parent_hash: Decode::decode(input)?,
|
||||
inserted: Decode::decode(input)?,
|
||||
deleted: Decode::decode(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,7 @@ impl<BlockHash: Hash, Key: Hash> UnfinalizedOverlay<BlockHash, Key> {
|
||||
let journal_key = to_journal_key(block, index);
|
||||
match db.get_meta(&journal_key).map_err(|e| Error::Db(e))? {
|
||||
Some(record) => {
|
||||
let record: JournalRecord<BlockHash, Key> = Slicable::decode(&mut record.as_slice()).ok_or(Error::Decoding)?;
|
||||
let record: JournalRecord<BlockHash, Key> = Decode::decode(&mut record.as_slice()).ok_or(Error::Decoding)?;
|
||||
let overlay = BlockOverlay {
|
||||
hash: record.hash.clone(),
|
||||
journal_key,
|
||||
|
||||
@@ -51,7 +51,7 @@ extern crate substrate_runtime_version as runtime_version;
|
||||
pub mod system;
|
||||
|
||||
use rstd::prelude::*;
|
||||
use codec::Slicable;
|
||||
use codec::{Encode, Decode};
|
||||
|
||||
use runtime_primitives::traits::{BlindCheckable, BlakeTwo256};
|
||||
use runtime_primitives::Ed25519Signature;
|
||||
@@ -81,18 +81,18 @@ pub struct Transfer {
|
||||
pub nonce: u64,
|
||||
}
|
||||
|
||||
impl Slicable for Transfer {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
self.from.using_encoded(|s| v.extend(s));
|
||||
self.to.using_encoded(|s| v.extend(s));
|
||||
self.amount.using_encoded(|s| v.extend(s));
|
||||
self.nonce.using_encoded(|s| v.extend(s));
|
||||
v
|
||||
impl Encode for Transfer {
|
||||
fn encode_to<T: ::codec::Output>(&self, dest: &mut T) {
|
||||
self.from.encode_to(dest);
|
||||
self.to.encode_to(dest);
|
||||
self.amount.encode_to(dest);
|
||||
self.nonce.encode_to(dest);
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for Transfer {
|
||||
fn decode<I: ::codec::Input>(input: &mut I) -> Option<Self> {
|
||||
Slicable::decode(input).map(|(from, to, amount, nonce)| Transfer { from, to, amount, nonce })
|
||||
Decode::decode(input).map(|(from, to, amount, nonce)| Transfer { from, to, amount, nonce })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,16 +104,16 @@ pub struct Extrinsic {
|
||||
pub signature: Ed25519Signature,
|
||||
}
|
||||
|
||||
impl Slicable for Extrinsic {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
self.transfer.using_encoded(|s| v.extend(s));
|
||||
self.signature.using_encoded(|s| v.extend(s));
|
||||
v
|
||||
impl Encode for Extrinsic {
|
||||
fn encode_to<T: ::codec::Output>(&self, dest: &mut T) {
|
||||
self.transfer.encode_to(dest);
|
||||
self.signature.encode_to(dest);
|
||||
}
|
||||
}
|
||||
|
||||
impl Decode for Extrinsic {
|
||||
fn decode<I: ::codec::Input>(input: &mut I) -> Option<Self> {
|
||||
Slicable::decode(input).map(|(transfer, signature)| Extrinsic { transfer, signature })
|
||||
Decode::decode(input).map(|(transfer, signature)| Extrinsic { transfer, signature })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ pub fn run_tests(mut input: &[u8]) -> Vec<u8> {
|
||||
print("run_tests...");
|
||||
let block = Block::decode(&mut input).unwrap();
|
||||
print("deserialised block.");
|
||||
let stxs = block.extrinsics.iter().map(Slicable::encode).collect::<Vec<_>>();
|
||||
let stxs = block.extrinsics.iter().map(Encode::encode).collect::<Vec<_>>();
|
||||
print("reserialised transactions.");
|
||||
[stxs.len() as u8].encode()
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ use rstd::prelude::*;
|
||||
use runtime_io::{storage_root, enumerated_trie_root};
|
||||
use runtime_support::storage::{self, StorageValue, StorageMap};
|
||||
use runtime_primitives::traits::{Hash as HashT, BlakeTwo256};
|
||||
use codec::{KeyedVec, Slicable};
|
||||
use codec::{KeyedVec, Encode};
|
||||
use super::{AccountId, BlockNumber, Extrinsic, H256 as Hash, Block, Header};
|
||||
|
||||
const NONCE_OF: &[u8] = b"nonce:";
|
||||
@@ -65,7 +65,7 @@ pub fn execute_block(block: Block) {
|
||||
let ref header = block.header;
|
||||
|
||||
// check transaction trie root represents the transactions.
|
||||
let txs = block.extrinsics.iter().map(Slicable::encode).collect::<Vec<_>>();
|
||||
let txs = block.extrinsics.iter().map(Encode::encode).collect::<Vec<_>>();
|
||||
let txs = txs.iter().map(Vec::as_slice).collect::<Vec<_>>();
|
||||
let txs_root = enumerated_trie_root(&txs).into();
|
||||
info_expect_equal_hash(&header.extrinsics_root, &txs_root);
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
Reference in New Issue
Block a user