Split out substrate-primitives from polkadot-primitives.

Bottom half minus tests builds.
This commit is contained in:
Gav
2018-02-07 15:24:54 +01:00
parent 26b4b56402
commit 9fe85fc9f4
50 changed files with 1102 additions and 928 deletions
+32 -24
View File
@@ -827,10 +827,12 @@ version = "0.1.0"
dependencies = [
"hex-literal 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-runtime-std 0.1.0",
"polkadot-primitives 0.1.0",
"rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-codec 0.1.0",
"substrate-primitives 0.1.0",
"substrate-runtime-io 0.1.0",
"substrate-runtime-std 0.1.0",
]
[[package]]
@@ -1048,19 +1050,13 @@ dependencies = [
name = "polkadot-primitives"
version = "0.1.0"
dependencies = [
"blake2-rfc 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)",
"byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"crunchy 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"fixed-hash 0.1.3 (git+https://github.com/rphmeier/primitives.git?branch=compile-for-wasm)",
"pretty_assertions 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-hex 2.0.0 (git+https://github.com/rphmeier/rustc-hex.git)",
"serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-codec 0.1.0",
"substrate-primitives 0.1.0",
"substrate-runtime-std 0.1.0",
"substrate-serializer 0.1.0",
"twox-hash 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"uint 0.1.2 (git+https://github.com/rphmeier/primitives.git?branch=compile-for-wasm)",
]
[[package]]
@@ -1086,21 +1082,6 @@ dependencies = [
"polkadot-rpc 0.1.0",
]
[[package]]
name = "polkadot-runtime-std"
version = "0.1.0"
dependencies = [
"ed25519 0.1.0",
"environmental 0.1.0",
"pwasm-alloc 0.1.0",
"pwasm-libc 0.1.0",
"rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-codec 0.1.0",
"substrate-primitives 0.1.0",
"substrate-state-machine 0.1.0",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "polkadot-validator"
version = "0.1.0"
@@ -1431,6 +1412,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "substrate-codec"
version = "0.1.0"
dependencies = [
"substrate-runtime-std 0.1.0",
]
[[package]]
name = "substrate-executor"
@@ -1444,12 +1428,12 @@ dependencies = [
"log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
"native-runtime 0.1.0",
"parity-wasm 0.15.4 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-runtime-std 0.1.0",
"rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-codec 0.1.0",
"substrate-primitives 0.1.0",
"substrate-runtime-io 0.1.0",
"substrate-serializer 0.1.0",
"substrate-state-machine 0.1.0",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -1468,11 +1452,35 @@ dependencies = [
"serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-codec 0.1.0",
"substrate-runtime-std 0.1.0",
"substrate-serializer 0.1.0",
"twox-hash 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"uint 0.1.2 (git+https://github.com/rphmeier/primitives.git?branch=compile-for-wasm)",
]
[[package]]
name = "substrate-runtime-io"
version = "0.1.0"
dependencies = [
"ed25519 0.1.0",
"environmental 0.1.0",
"pwasm-alloc 0.1.0",
"pwasm-libc 0.1.0",
"rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-codec 0.1.0",
"substrate-primitives 0.1.0",
"substrate-runtime-std 0.1.0",
"substrate-state-machine 0.1.0",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "substrate-runtime-std"
version = "0.1.0"
dependencies = [
"rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "substrate-serializer"
version = "0.1.0"
+1
View File
@@ -22,6 +22,7 @@ members = [
"rpc",
"codec",
"polkadot-primitives",
"runtime-io",
"runtime-std",
"serializer",
"state-machine",
+2 -1
View File
@@ -5,7 +5,8 @@ version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
substrate-runtime-std = { path = "../runtime-std", default_features = false }
[features]
std = []
default = ["std"]
std = ["substrate-runtime-std/std"]
+1
View File
@@ -30,6 +30,7 @@ pub use self::slicable::{Slicable, NonTrivialSlicable};
pub use self::joiner::Joiner;
pub use self::keyedvec::KeyedVec;
// TODO: move these into runtime-std and `extern crate runtime_std as std;`
#[cfg(not(feature = "std"))]
mod std {
extern crate alloc;
+1 -1
View File
@@ -6,7 +6,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
error-chain = "0.11"
substrate-codec = { path = "../codec" }
polkadot-runtime-std = { path = "../runtime-std" }
substrate-runtime-io = { path = "../runtime-io" }
substrate-primitives = { path = "../primitives" }
substrate-serializer = { path = "../serializer" }
substrate-state-machine = { path = "../state-machine" }
+1 -1
View File
@@ -28,7 +28,7 @@
#![warn(missing_docs)]
extern crate substrate_codec as codec;
extern crate polkadot_runtime_std as runtime_std;
extern crate substrate_runtime_io as runtime_io;
extern crate substrate_primitives as primitives;
extern crate substrate_serializer as serializer;
extern crate substrate_state_machine as state_machine;
+8 -8
View File
@@ -16,7 +16,7 @@
use error::{Error, ErrorKind, Result};
use native_runtime as runtime;
use runtime_std;
use runtime_io;
use state_machine::{Externalities, CodeExecutor};
use wasm_executor::WasmExecutor;
@@ -42,7 +42,7 @@ impl CodeExecutor for NativeExecutor {
// get a proper build script, this must be strictly adhered to or things will go wrong.
let native_equivalent = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.compact.wasm");
if code == &native_equivalent[..] {
runtime_std::with_externalities(ext, || match method {
runtime_io::with_externalities(ext, || match method {
"execute_block" => safe_call(|| runtime::execute_block(data)),
"execute_transaction" => safe_call(|| runtime::execute_transaction(data)),
"finalise_block" => safe_call(|| runtime::finalise_block(data)),
@@ -116,7 +116,7 @@ mod tests {
let r = NativeExecutor.call(&mut t, COMPACT_CODE, "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx()));
assert!(r.is_ok());
runtime_std::with_externalities(&mut t, || {
runtime_io::with_externalities(&mut t, || {
assert_eq!(balance(&one), 42);
assert_eq!(balance(&two), 69);
});
@@ -134,7 +134,7 @@ mod tests {
let r = NativeExecutor.call(&mut t, BLOATY_CODE, "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx()));
assert!(r.is_ok());
runtime_std::with_externalities(&mut t, || {
runtime_io::with_externalities(&mut t, || {
assert_eq!(balance(&one), 42);
assert_eq!(balance(&two), 69);
});
@@ -243,14 +243,14 @@ mod tests {
NativeExecutor.call(&mut t, COMPACT_CODE, "execute_block", &block1().0).unwrap();
runtime_std::with_externalities(&mut t, || {
runtime_io::with_externalities(&mut t, || {
assert_eq!(balance(&one()), 42);
assert_eq!(balance(&two()), 69);
});
NativeExecutor.call(&mut t, COMPACT_CODE, "execute_block", &block2().0).unwrap();
runtime_std::with_externalities(&mut t, || {
runtime_io::with_externalities(&mut t, || {
assert_eq!(balance(&one()), 32);
assert_eq!(balance(&two()), 79);
});
@@ -262,14 +262,14 @@ mod tests {
WasmExecutor.call(&mut t, COMPACT_CODE, "execute_block", &block1().0).unwrap();
runtime_std::with_externalities(&mut t, || {
runtime_io::with_externalities(&mut t, || {
assert_eq!(balance(&one()), 42);
assert_eq!(balance(&two()), 69);
});
WasmExecutor.call(&mut t, COMPACT_CODE, "execute_block", &block2().0).unwrap();
runtime_std::with_externalities(&mut t, || {
runtime_io::with_externalities(&mut t, || {
assert_eq!(balance(&one()), 32);
assert_eq!(balance(&two()), 79);
});
+7 -7
View File
@@ -117,29 +117,29 @@ impl_function_executor!(this: FunctionExecutor<'e, E>,
ext_memcpy(dest: *mut u8, src: *const u8, count: usize) -> *mut u8 => {
this.memory.copy_nonoverlapping(src as usize, dest as usize, count as usize)
.map_err(|_| DummyUserError)?;
trace!(target: "runtime-std", "memcpy {} from {}, {} bytes", dest, src, count);
trace!(target: "runtime-io", "memcpy {} from {}, {} bytes", dest, src, count);
dest
},
ext_memmove(dest: *mut u8, src: *const u8, count: usize) -> *mut u8 => {
this.memory.copy(src as usize, dest as usize, count as usize)
.map_err(|_| DummyUserError)?;
trace!(target: "runtime-std", "memmove {} from {}, {} bytes", dest, src, count);
trace!(target: "runtime-io", "memmove {} from {}, {} bytes", dest, src, count);
dest
},
ext_memset(dest: *mut u8, val: u32, count: usize) -> *mut u8 => {
this.memory.clear(dest as usize, val as u8, count as usize)
.map_err(|_| DummyUserError)?;
trace!(target: "runtime-std", "memset {} with {}, {} bytes", dest, val, count);
trace!(target: "runtime-io", "memset {} with {}, {} bytes", dest, val, count);
dest
},
ext_malloc(size: usize) -> *mut u8 => {
let r = this.heap.allocate(size);
trace!(target: "runtime-std", "malloc {} bytes at {}", size, r);
trace!(target: "runtime-io", "malloc {} bytes at {}", size, r);
r
},
ext_free(addr: *mut u8) => {
this.heap.deallocate(addr);
trace!(target: "runtime-std", "free {}", addr)
trace!(target: "runtime-io", "free {}", addr)
},
ext_set_storage(key_data: *const u8, key_len: u32, value_data: *const u8, value_len: u32) => {
let key = this.memory.get(key_data, key_len as usize).map_err(|_| DummyUserError)?;
@@ -294,7 +294,7 @@ mod tests {
use state_machine::TestExternalities;
use primitives::twox_128;
use primitives::relay::{Header, Transaction, UncheckedTransaction, Function, AccountId};
use runtime_std;
use runtime_io;
use ed25519::Pair;
fn secret_for(who: &AccountId) -> Option<Pair> {
@@ -448,7 +448,7 @@ mod tests {
let r = WasmExecutor.call(&mut t, &foreign_code[..], "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx()));
assert!(r.is_ok());
runtime_std::with_externalities(&mut t, || {
runtime_io::with_externalities(&mut t, || {
assert_eq!(balance(&one), 42);
assert_eq!(balance(&two), 69);
});
+4 -2
View File
@@ -5,12 +5,14 @@ authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
substrate-codec = { path = "../codec", version = "0.1" }
polkadot-runtime-std = { path = "../runtime-std", version = "0.1" }
substrate-runtime-std = { path = "../runtime-std", version = "0.1" }
substrate-runtime-io = { path = "../runtime-io", version = "0.1" }
substrate-primitives = { path = "../primitives", version = "0.1" }
polkadot-primitives = { path = "../polkadot-primitives", version = "0.1" }
rustc-hex = "1.0"
hex-literal = "0.1.0"
log = { version = "0.3", optional = true }
[features]
default = ["std"]
std = ["substrate-codec/std", "polkadot-runtime-std/std", "substrate-primitives/std", "log"]
std = ["substrate-codec/std", "substrate-runtime-std/std", "substrate-runtime-io/std", "substrate-primitives/std", "polkadot-primitives/std", "log"]
+4 -14
View File
@@ -4,17 +4,11 @@ version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
crunchy = "0.1"
fixed-hash = { git = "https://github.com/rphmeier/primitives.git", branch = "compile-for-wasm", default_features = false }
rustc-hex = { git = "https://github.com/rphmeier/rustc-hex.git", version = "2.0", default_features = false }
serde = { version = "1.0", default_features = false }
serde_derive = { version = "1.0", optional = true }
uint = { git = "https://github.com/rphmeier/primitives.git", branch = "compile-for-wasm" }
twox-hash = { version = "1.1.0", optional = true }
byteorder = { version = "1.1", default_features = false }
blake2-rfc = { version = "0.2.18", optional = true }
substrate-codec = { path = "../codec", default_features = false }
substrate-primitives = { path = "../primitives", default_features = false }
substrate-runtime-std = { path = "../runtime-std", default_features = false }
[dev-dependencies]
substrate-serializer = { path = "../serializer" }
@@ -23,13 +17,9 @@ pretty_assertions = "0.4"
[features]
default = ["std"]
std = [
"uint/std",
"fixed-hash/std",
"substrate-codec/std",
"serde/std",
"rustc-hex/std",
"twox-hash",
"blake2-rfc",
"substrate-primitives/std",
"substrate-runtime-std/std",
"serde_derive",
"byteorder/std"
"serde/std",
]
@@ -17,12 +17,12 @@
//! Block and header type definitions.
#[cfg(feature = "std")]
use bytes;
use bytes::Vec;
use primitives::bytes;
use primitives::H256;
use rstd::vec::Vec;
use codec::Slicable;
use hash::H256;
use parachain;
use relay::transaction::UncheckedTransaction;
use transaction::UncheckedTransaction;
/// Used to refer to a block number.
pub type Number = u64;
@@ -34,8 +34,8 @@ pub type HeaderHash = H256;
pub type TransactionHash = H256;
/// Execution log (event)
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone)]
#[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 {
@@ -51,8 +51,8 @@ impl Slicable for Log {
impl ::codec::NonTrivialSlicable for Log { }
/// The digest of a block, useful for light-clients.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Digest {
/// All logs that have happened in the block.
pub logs: Vec<Log>,
@@ -69,8 +69,8 @@ impl Slicable for Digest {
}
/// A Polkadot relay chain block.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Block {
/// The block header.
pub header: Header,
@@ -103,8 +103,8 @@ impl Slicable for Block {
/// A relay chain block header.
///
/// https://github.com/w3f/polkadot-spec/blob/master/spec.md#header
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
pub struct Header {
@@ -165,8 +165,8 @@ impl Slicable for Header {
///
/// Included candidates should be sorted by parachain ID, and without duplicate
/// IDs.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
pub struct Body {
+45 -23
View File
@@ -21,36 +21,58 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(alloc))]
extern crate rustc_hex;
extern crate serde;
extern crate byteorder;
#[cfg(feature = "std")]
extern crate twox_hash;
#[cfg(feature = "std")]
extern crate blake2_rfc;
#[macro_use]
extern crate crunchy;
#[macro_use]
extern crate fixed_hash;
#[cfg(feature = "std")]
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate uint as uint_crate;
#[cfg(feature = "std")]
extern crate core;
extern crate serde;
extern crate substrate_runtime_std as rstd;
extern crate substrate_codec as codec;
extern crate substrate_primitives as primitives;
#[cfg(test)]
extern crate substrate_serializer;
#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;
#[cfg(not(feature = "std"))]
#[macro_use]
extern crate alloc;
macro_rules! try_opt {
($e: expr) => {
match $e {
Some(x) => x,
None => return None,
}
}
}
pub mod parachain;
pub mod validator;
pub mod block;
pub mod transaction;
pub use self::block::{Header, Block, Log, Digest};
pub use self::block::Number as BlockNumber;
pub use self::transaction::{Transaction, UncheckedTransaction, Function, Proposal};
/// Virtual account ID that represents the idea of a dispatch/statement being signed by everybody
/// (who matters). Essentially this means that a majority of validators have decided it is
/// "correct".
pub const EVERYBODY: AccountId = [255u8; 32];
/// Alias to Ed25519 pubkey that identifies an account on the relay chain. This will almost
/// certainly continue to be the same as the substrate's `AuthorityId`.
pub type AccountId = primitives::AuthorityId;
/// The Ed25519 pub key of an session that belongs to an authority of the relay chain. This is
/// exactly equivalent to what the substrate calls an "authority".
pub type SessionKey = primitives::AuthorityId;
/// Indentifier for a chain.
pub type ChainID = u64;
/// Index of a transaction in the relay chain.
pub type TxOrder = u64;
/// A hash of some data used by the relay chain.
pub type Hash = primitives::H256;
/// Alias to 520-bit hash when used in the context of a signature on the relay chain.
pub type Signature = primitives::hash::H512;
@@ -17,12 +17,13 @@
//! Parachain data types.
#[cfg(feature = "std")]
use bytes;
use bytes::Vec;
use primitives::bytes;
use primitives;
use rstd::vec::Vec;
/// Unique identifier of a parachain.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Id(u64);
impl From<Id> for u64 {
@@ -46,15 +47,15 @@ impl ::codec::Slicable for Id {
/// Candidate parachain block.
///
/// https://github.com/w3f/polkadot-spec/blob/master/spec.md#candidate-para-chain-block
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
pub struct Candidate {
/// The ID of the parachain this is a proposal for.
pub parachain_index: Id,
/// Collator's signature
pub collator_signature: ::relay::Signature,
pub collator_signature: ::Signature,
/// Unprocessed ingress queue.
///
/// Ordered by parachain ID and block number.
@@ -72,55 +73,55 @@ pub struct CandidateReceipt {
/// The ID of the parachain this is a candidate for.
pub parachain_index: Id,
/// The collator's relay-chain account ID
pub collator: ::relay::AccountId,
pub collator: ::AccountId,
/// The head-data
pub head_data: HeadData,
/// Balance uploads to the relay chain.
pub balance_uploads: Vec<(::relay::AccountId, ::uint::U256)>,
pub balance_uploads: Vec<(::AccountId, u64)>,
/// Egress queue roots.
pub egress_queue_roots: Vec<(Id, ::hash::H256)>,
pub egress_queue_roots: Vec<(Id, primitives::H256)>,
/// Fees paid from the chain to the relay chain validators
pub fees: ::uint::U256,
pub fees: u64,
}
/// Parachain ingress queue message.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Message(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
/// Consolidated ingress queue data.
///
/// This is just an ordered vector of other parachains' egress queues,
/// obtained according to the routing rules.
#[derive(Debug, Default, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Default, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct ConsolidatedIngress(pub Vec<(Id, Vec<Message>)>);
/// Parachain block data.
///
/// contains everything required to validate para-block, may contain block and witness data
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct BlockData(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
/// Parachain header raw bytes wrapper type.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Header(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
/// Parachain head data included in the chain.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct HeadData(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
/// Parachain validation code.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct ValidationCode(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
/// Activitiy bit field
#[derive(Debug, PartialEq, Eq, Clone, Default)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone, Default)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Activity(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
impl ::codec::Slicable for Activity {
@@ -16,19 +16,16 @@
//! Transaction type.
use bytes::Vec;
use rstd::vec::Vec;
use codec::Slicable;
#[cfg(feature = "std")]
use std::fmt;
#[cfg(not(feature = "std"))]
use alloc::fmt;
use block::Number as BlockNumber;
use relay::block::Number as BlockNumber;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[repr(u8)]
enum InternalFunctionId {
/// Set the system's code.
@@ -71,9 +68,9 @@ impl InternalFunctionId {
}
/// Internal functions that can be dispatched to.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum InternalFunction {
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub enum Proposal {
/// Set the system's code.
SystemSetCode(Vec<u8>),
/// Set the session length.
@@ -93,67 +90,59 @@ pub enum InternalFunction {
}
/// An internal function.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct Proposal {
/// The privileged function to call.
pub function: InternalFunction,
}
impl Slicable for Proposal {
fn from_slice(value: &mut &[u8]) -> Option<Self> {
let id = try_opt!(u8::from_slice(value).and_then(InternalFunctionId::from_u8));
let function = match id {
InternalFunctionId::SystemSetCode =>
InternalFunction::SystemSetCode(try_opt!(Slicable::from_slice(value))),
Proposal::SystemSetCode(try_opt!(Slicable::from_slice(value))),
InternalFunctionId::SessionSetLength =>
InternalFunction::SessionSetLength(try_opt!(Slicable::from_slice(value))),
InternalFunctionId::SessionForceNewSession => InternalFunction::SessionForceNewSession,
Proposal::SessionSetLength(try_opt!(Slicable::from_slice(value))),
InternalFunctionId::SessionForceNewSession => Proposal::SessionForceNewSession,
InternalFunctionId::StakingSetSessionsPerEra =>
InternalFunction::StakingSetSessionsPerEra(try_opt!(Slicable::from_slice(value))),
Proposal::StakingSetSessionsPerEra(try_opt!(Slicable::from_slice(value))),
InternalFunctionId::StakingSetBondingDuration =>
InternalFunction::StakingSetBondingDuration(try_opt!(Slicable::from_slice(value))),
Proposal::StakingSetBondingDuration(try_opt!(Slicable::from_slice(value))),
InternalFunctionId::StakingSetValidatorCount =>
InternalFunction::StakingSetValidatorCount(try_opt!(Slicable::from_slice(value))),
InternalFunctionId::StakingForceNewEra => InternalFunction::StakingForceNewEra,
Proposal::StakingSetValidatorCount(try_opt!(Slicable::from_slice(value))),
InternalFunctionId::StakingForceNewEra => Proposal::StakingForceNewEra,
InternalFunctionId::GovernanceSetApprovalPpmRequired =>
InternalFunction::GovernanceSetApprovalPpmRequired(try_opt!(Slicable::from_slice(value))),
Proposal::GovernanceSetApprovalPpmRequired(try_opt!(Slicable::from_slice(value))),
};
Some(Proposal { function })
Some(function)
}
fn to_vec(&self) -> Vec<u8> {
let mut v = Vec::new();
match self.function {
InternalFunction::SystemSetCode(ref data) => {
match *self {
Proposal::SystemSetCode(ref data) => {
(InternalFunctionId::SystemSetCode as u8).as_slice_then(|s| v.extend(s));
data.as_slice_then(|s| v.extend(s));
}
InternalFunction::SessionSetLength(ref data) => {
Proposal::SessionSetLength(ref data) => {
(InternalFunctionId::SessionSetLength as u8).as_slice_then(|s| v.extend(s));
data.as_slice_then(|s| v.extend(s));
}
InternalFunction::SessionForceNewSession => {
Proposal::SessionForceNewSession => {
(InternalFunctionId::SessionForceNewSession as u8).as_slice_then(|s| v.extend(s));
}
InternalFunction::StakingSetSessionsPerEra(ref data) => {
Proposal::StakingSetSessionsPerEra(ref data) => {
(InternalFunctionId::StakingSetSessionsPerEra as u8).as_slice_then(|s| v.extend(s));
data.as_slice_then(|s| v.extend(s));
}
InternalFunction::StakingSetBondingDuration(ref data) => {
Proposal::StakingSetBondingDuration(ref data) => {
(InternalFunctionId::StakingSetBondingDuration as u8).as_slice_then(|s| v.extend(s));
data.as_slice_then(|s| v.extend(s));
}
InternalFunction::StakingSetValidatorCount(ref data) => {
Proposal::StakingSetValidatorCount(ref data) => {
(InternalFunctionId::StakingSetValidatorCount as u8).as_slice_then(|s| v.extend(s));
data.as_slice_then(|s| v.extend(s));
}
InternalFunction::StakingForceNewEra => {
Proposal::StakingForceNewEra => {
(InternalFunctionId::StakingForceNewEra as u8).as_slice_then(|s| v.extend(s));
}
InternalFunction::GovernanceSetApprovalPpmRequired(ref data) => {
Proposal::GovernanceSetApprovalPpmRequired(ref data) => {
(InternalFunctionId::GovernanceSetApprovalPpmRequired as u8).as_slice_then(|s| v.extend(s));
data.as_slice_then(|s| v.extend(s));
}
@@ -169,8 +158,8 @@ impl Slicable for Proposal {
/// Public functions that can be dispatched to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[repr(u8)]
enum FunctionId {
/// Set the timestamp.
@@ -201,19 +190,19 @@ impl FunctionId {
}
/// Functions on the runtime.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub enum Function {
/// Set the timestamp.
TimestampSet(u64),
/// Set temporary session key as a validator.
SessionSetKey(::relay::SessionKey),
SessionSetKey(::SessionKey),
/// Staking subsystem: begin staking.
StakingStake,
/// Staking subsystem: stop staking.
StakingUnstake,
/// Staking subsystem: transfer stake.
StakingTransfer(::relay::AccountId, u64),
StakingTransfer(::AccountId, u64),
/// Make a proposal for the governance system.
GovernancePropose(Proposal),
/// Approve a proposal for the governance system.
@@ -284,8 +273,8 @@ impl Slicable for Function {
}
/// A vetted and verified transaction from the external world.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Transaction {
/// Who signed it (note this is not a signature).
pub signed: super::AccountId,
@@ -297,6 +286,12 @@ pub struct Transaction {
impl Slicable for Transaction {
fn from_slice(value: &mut &[u8]) -> Option<Self> {
// This is a little more complicated than usua 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 = try_opt!(Slicable::from_slice(value));
Some(Transaction {
signed: try_opt!(Slicable::from_slice(value)),
nonce: try_opt!(Slicable::from_slice(value)),
@@ -319,6 +314,8 @@ impl Slicable for Transaction {
}
}
impl ::codec::NonTrivialSlicable for Transaction {}
/// A transactions right from the external world. Unchecked.
#[derive(Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
@@ -331,8 +328,14 @@ pub struct UncheckedTransaction {
impl Slicable for UncheckedTransaction {
fn from_slice(value: &mut &[u8]) -> Option<Self> {
// This is a little more complicated than usua 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 = try_opt!(Slicable::from_slice(value));
Some(UncheckedTransaction {
transaction: try_opt!(Transaction::from_slice(value)),
transaction: try_opt!(Slicable::from_slice(value)),
signature: try_opt!(Slicable::from_slice(value)),
})
}
@@ -340,11 +343,18 @@ impl Slicable for UncheckedTransaction {
fn to_vec(&self) -> Vec<u8> {
let mut v = Vec::new();
// need to prefix with the total length as u32 to ensure it's binary comptible with
// Vec<u8>. we'll make room for it here, then overwrite once we know the length.
v.extend(&[0u8; 4]);
self.transaction.signed.as_slice_then(|s| v.extend(s));
self.transaction.nonce.as_slice_then(|s| v.extend(s));
self.transaction.function.as_slice_then(|s| v.extend(s));
self.signature.as_slice_then(|s| v.extend(s));
let length = (v.len() - 4) as u32;
length.as_slice_then(|s| v[0..4].copy_from_slice(s));
v
}
@@ -361,6 +371,7 @@ impl PartialEq for UncheckedTransaction {
}
}
#[cfg(feature = "std")]
impl fmt::Debug for UncheckedTransaction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "UncheckedTransaction({:?})", self.transaction)
@@ -370,6 +381,7 @@ impl fmt::Debug for UncheckedTransaction {
#[cfg(test)]
mod tests {
use ::codec::Slicable;
use primitives;
use super::*;
#[test]
@@ -380,7 +392,7 @@ mod tests {
nonce: 999u64,
function: Function::TimestampSet(135135),
},
signature: ::hash::H512([0; 64]),
signature: primitives::hash::H512([0; 64]),
};
let v = Slicable::to_vec(&tx);
@@ -17,28 +17,28 @@
//! Validator primitives.
#[cfg(feature = "std")]
use bytes;
use bytes::Vec;
use primitives::bytes;
use rstd::vec::Vec;
use parachain;
/// Parachain outgoing message.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct EgressPost(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
/// Balance upload.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct BalanceUpload(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
/// Balance download.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct BalanceDownload(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
/// The result of parachain validation.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
pub struct ValidationResult {
+3 -1
View File
@@ -5,6 +5,8 @@ authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
crunchy = "0.1"
substrate-runtime-std = { path = "../runtime-std", default_features = false }
substrate-codec = { path = "../codec", default_features = false }
fixed-hash = { git = "https://github.com/rphmeier/primitives.git", branch = "compile-for-wasm", default_features = false }
rustc-hex = { git = "https://github.com/rphmeier/rustc-hex.git", version = "2.0", default_features = false }
serde = { version = "1.0", default_features = false }
@@ -13,7 +15,6 @@ uint = { git = "https://github.com/rphmeier/primitives.git", branch = "compile-f
twox-hash = { version = "1.1.0", optional = true }
byteorder = { version = "1.1", default_features = false }
blake2-rfc = { version = "0.2.18", optional = true }
substrate-codec = { path = "../codec", default_features = false }
[dev-dependencies]
substrate-serializer = { path = "../serializer" }
@@ -25,6 +26,7 @@ std = [
"uint/std",
"fixed-hash/std",
"substrate-codec/std",
"substrate-runtime-std/std",
"serde/std",
"rustc-hex/std",
"twox-hash",
+210
View File
@@ -0,0 +1,210 @@
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Block and header type definitions.
#[cfg(feature = "std")]
use bytes;
use rstd::vec::Vec;
use codec::Slicable;
use hash::H256;
/// Used to refer to a block number.
pub type Number = u64;
/// Hash used to refer to a block hash.
pub type HeaderHash = H256;
/// Hash used to refer to a transaction hash.
pub type TransactionHash = H256;
/// Simple generic transaction type.
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Transaction(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
impl Slicable for Transaction {
fn from_slice(value: &mut &[u8]) -> Option<Self> {
Vec::<u8>::from_slice(value).map(Transaction)
}
fn as_slice_then<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.0.as_slice_then(f)
}
}
impl ::codec::NonTrivialSlicable for Transaction { }
/// Execution log (event)
#[derive(PartialEq, Eq, Clone)]
#[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 {
fn from_slice(value: &mut &[u8]) -> Option<Self> {
Vec::<u8>::from_slice(value).map(Log)
}
fn as_slice_then<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.0.as_slice_then(f)
}
}
impl ::codec::NonTrivialSlicable for Log { }
/// The digest of a block, useful for light-clients.
#[derive(Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Digest {
/// All logs that have happened in the block.
pub logs: Vec<Log>,
}
impl Slicable for Digest {
fn from_slice(value: &mut &[u8]) -> Option<Self> {
Vec::<Log>::from_slice(value).map(|logs| Digest { logs })
}
fn as_slice_then<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.logs.as_slice_then(f)
}
}
/// A Substrate relay chain block.
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct Block {
/// The block header.
pub header: Header,
/// All relay-chain transactions.
pub transactions: Vec<Transaction>,
}
impl Slicable for Block {
fn from_slice(value: &mut &[u8]) -> Option<Self> {
Some(Block {
header: try_opt!(Slicable::from_slice(value)),
transactions: try_opt!(Slicable::from_slice(value)),
})
}
fn to_vec(&self) -> Vec<u8> {
let mut v = Vec::new();
v.extend(self.header.to_vec());
v.extend(self.transactions.to_vec());
v
}
fn as_slice_then<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(self.to_vec().as_slice())
}
}
/// A relay chain block header.
///
/// https://github.com/w3f/polkadot-spec/blob/master/spec.md#header
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
pub struct Header {
/// Block parent's hash.
pub parent_hash: HeaderHash,
/// Block number.
pub number: Number,
/// State root after this transition.
pub state_root: H256,
/// The root of the trie that represents this block's transactions, indexed by a 32-byte integer.
pub transaction_root: H256,
/// The digest of activity on the block.
pub digest: Digest,
}
impl Header {
/// Create a new instance with default fields except `number`, which is given as an argument.
pub fn from_block_number(number: Number) -> Self {
Header {
parent_hash: Default::default(),
number,
state_root: Default::default(),
transaction_root: Default::default(),
digest: Default::default(),
}
}
}
impl Slicable for Header {
fn from_slice(value: &mut &[u8]) -> Option<Self> {
Some(Header {
parent_hash: try_opt!(Slicable::from_slice(value)),
number: try_opt!(Slicable::from_slice(value)),
state_root: try_opt!(Slicable::from_slice(value)),
transaction_root: try_opt!(Slicable::from_slice(value)),
digest: try_opt!(Slicable::from_slice(value)),
})
}
fn to_vec(&self) -> Vec<u8> {
let mut v = Vec::new();
self.parent_hash.as_slice_then(|s| v.extend(s));
self.number.as_slice_then(|s| v.extend(s));
self.state_root.as_slice_then(|s| v.extend(s));
self.transaction_root.as_slice_then(|s| v.extend(s));
self.digest.as_slice_then(|s| v.extend(s));
v
}
fn as_slice_then<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(self.to_vec().as_slice())
}
}
#[cfg(test)]
mod tests {
use super::*;
use codec::Slicable;
use substrate_serializer as ser;
#[test]
fn test_header_serialization() {
let header = Header {
parent_hash: 5.into(),
number: 67,
state_root: 3.into(),
transaction_root: 6.into(),
digest: Digest { logs: vec![Log(vec![1])] },
};
assert_eq!(ser::to_string_pretty(&header), r#"{
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000005",
"number": 67,
"stateRoot": "0x0000000000000000000000000000000000000000000000000000000000000003",
"transactionRoot": "0x0000000000000000000000000000000000000000000000000000000000000006",
"digest": {
"logs": [
"0x01"
]
}
}"#);
let v = header.to_vec();
assert_eq!(Header::from_slice(&mut &v[..]).unwrap(), header);
}
}
+4 -1
View File
@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Simply type for representing Vec<u8> with regards to serde.
use core::fmt;
use serde::{de, Serializer, Deserializer};
@@ -60,7 +62,8 @@ pub fn serialize_uint<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
}
/// Expected length of bytes vector.
#[derive(Debug, PartialEq, Eq)]
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum ExpectedLen {
/// Any length in bytes.
#[cfg_attr(not(feature = "std"), allow(unused))]
+8 -4
View File
@@ -16,18 +16,22 @@
//! A fixed hash type.
#[cfg(feature = "std")]
use serde::{Serialize, Serializer, Deserialize, Deserializer};
#[cfg(feature = "std")]
use bytes;
macro_rules! impl_serde {
macro_rules! impl_rest {
($name: ident, $len: expr) => {
#[cfg(feature = "std")]
impl Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
bytes::serialize(&self.0, serializer)
}
}
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
bytes::deserialize_check_len(deserializer, bytes::ExpectedLen::Exact($len))
@@ -48,11 +52,11 @@ macro_rules! impl_serde {
}
construct_hash!(H160, 20);
impl_serde!(H160, 20);
construct_hash!(H256, 32);
impl_serde!(H256, 32);
construct_hash!(H512, 64);
impl_serde!(H512, 64);
impl_rest!(H160, 20);
impl_rest!(H256, 32);
impl_rest!(H512, 64);
#[cfg(test)]
mod tests {
+30 -27
View File
@@ -22,38 +22,37 @@
#![cfg_attr(not(feature = "std"), feature(alloc))]
extern crate rustc_hex;
extern crate serde;
extern crate byteorder;
#[cfg(feature = "std")]
extern crate twox_hash;
#[cfg(feature = "std")]
extern crate blake2_rfc;
#[macro_use]
extern crate crunchy;
#[macro_use]
extern crate fixed_hash;
#[macro_use]
extern crate uint as uint_crate;
extern crate substrate_codec as codec;
#[cfg(feature = "std")]
extern crate serde;
#[cfg(feature = "std")]
extern crate twox_hash;
#[cfg(feature = "std")]
extern crate blake2_rfc;
#[cfg(feature = "std")]
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate uint as uint_crate;
#[cfg(feature = "std")]
extern crate core;
extern crate substrate_codec as codec;
#[macro_use]
extern crate substrate_runtime_std as rstd;
#[cfg(test)]
extern crate substrate_serializer;
#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;
#[cfg(not(feature = "std"))]
#[macro_use]
extern crate alloc;
// TODO: factor out to separate crate.
macro_rules! try_opt {
($e: expr) => {
@@ -64,23 +63,27 @@ macro_rules! try_opt {
}
}
mod bytes;
pub mod contract;
pub mod hash;
#[cfg(feature = "std")]
pub mod bytes;
#[cfg(feature = "std")]
pub mod hashing;
#[cfg(feature = "std")]
pub use hashing::{blake2_256, twox_128, twox_256};
#[cfg(feature = "std")]
pub mod hexdisplay;
pub mod parachain;
pub mod relay;
pub mod storage;
pub mod hash;
pub mod uint;
pub mod validator;
pub mod block;
#[cfg(test)]
mod tests;
#[cfg(feature = "std")]
pub mod hashing;
pub use self::hash::{H160, H256};
pub use self::uint::{U256, U512};
#[cfg(feature = "std")]
pub use hashing::{blake2_256, twox_128, twox_256};
pub use block::{Block, Header};
/// An identifier for an authority in the consensus algorithm. The same as ed25519::Public.
pub type AuthorityId = [u8; 32];
-33
View File
@@ -1,33 +0,0 @@
//! Relay chain primitives.
pub mod block;
pub mod transaction;
pub use self::block::*;
pub use self::transaction::*;
pub use self::block::Number as BlockNumber;
/// Virtual account ID that represents the idea of a dispatch/statement being signed by everybody
/// (who matters). Essentially this means that a majority of validators have decided it is
/// "correct".
pub const EVERYBODY: AccountId = [255u8; 32];
/// Alias to Ed25519 pubkey that identifies an account on the relay chain.
pub type AccountId = [u8; 32];
/// The Ed25519 pub key of an session that belongs to an authority of the relay chain. This is
/// used as what the external environment/consensus algorithm calls an "authority".
pub type SessionKey = AccountId;
/// Indentifier for a chain.
pub type ChainID = u64;
/// Index of a transaction in the relay chain.
pub type TxOrder = u64;
/// A hash of some data used by the relay chain.
pub type Hash = ::hash::H256;
/// Alias to 520-bit hash when used in the context of a signature on the relay chain.
pub type Signature = ::hash::H512;
@@ -18,14 +18,14 @@
#[cfg(feature = "std")]
use bytes;
use bytes::Vec;
use rstd::vec::Vec;
/// Contract storage key.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct StorageKey(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
/// Contract storage entry data.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct StorageData(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
-212
View File
@@ -15,215 +15,3 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Tests.
use codec::Slicable;
use relay::{AccountId, Block, Header, Digest, Log, UncheckedTransaction, Transaction, Function};
#[test]
fn serialise_transaction_works() {
let one: AccountId = [1u8; 32];
let two: AccountId = [2u8; 32];
let tx = Transaction {
signed: one.clone(),
nonce: 69,
function: Function::StakingTransfer(two, 69),
};
let serialised = tx.to_vec();
assert_eq!(serialised, vec![
1u8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
69, 0, 0, 0, 0, 0, 0, 0,
34,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
69, 0, 0, 0, 0, 0, 0, 0
]);
}
#[test]
fn deserialise_transaction_works() {
let one: AccountId = [1u8; 32];
let two: AccountId = [2u8; 32];
let tx = Transaction {
signed: one.clone(),
nonce: 69,
function: Function::StakingTransfer(two, 69),
};
let data = [
1u8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
69, 0, 0, 0, 0, 0, 0, 0,
34,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
69, 0, 0, 0, 0, 0, 0, 0
];
let deserialised = Transaction::from_slice(&mut &data[..]).unwrap();
assert_eq!(deserialised, tx);
}
#[test]
fn serialise_header_works() {
let h = Header {
parent_hash: [4u8; 32].into(),
number: 42,
state_root: [5u8; 32].into(),
transaction_root: [6u8; 32].into(),
digest: Digest { logs: vec![ Log(b"one log".to_vec()), Log(b"another log".to_vec()) ], },
};
let serialised = h.to_vec();
assert_eq!(serialised, vec![
4u8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
42, 0, 0, 0, 0, 0, 0, 0,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
2, 0, 0, 0,
7, 0, 0, 0,
111, 110, 101, 32, 108, 111, 103,
11, 0, 0, 0,
97, 110, 111, 116, 104, 101, 114, 32, 108, 111, 103
]);
}
#[test]
fn deserialise_header_works() {
let h = Header {
parent_hash: [4u8; 32].into(),
number: 42,
state_root: [5u8; 32].into(),
transaction_root: [6u8; 32].into(),
digest: Digest { logs: vec![ Log(b"one log".to_vec()), Log(b"another log".to_vec()) ], },
};
let data = [
4u8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
42, 0, 0, 0, 0, 0, 0, 0,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
2, 0, 0, 0,
7, 0, 0, 0,
111, 110, 101, 32, 108, 111, 103,
11, 0, 0, 0,
97, 110, 111, 116, 104, 101, 114, 32, 108, 111, 103
];
let deserialised = Header::from_slice(&mut &data[..]).unwrap();
assert_eq!(deserialised, h);
}
#[test]
fn serialise_block_works() {
let one: AccountId = [1u8; 32];
let two: AccountId = [2u8; 32];
let tx1 = UncheckedTransaction {
transaction: Transaction {
signed: one.clone(),
nonce: 69,
function: Function::StakingTransfer(two, 69),
},
signature: [1u8; 64].into(),
};
let tx2 = UncheckedTransaction {
transaction: Transaction {
signed: two.clone(),
nonce: 42,
function: Function::StakingStake,
},
signature: [2u8; 64].into(),
};
let h = Header {
parent_hash: [4u8; 32].into(),
number: 42,
state_root: [5u8; 32].into(),
transaction_root: [6u8; 32].into(),
digest: Digest { logs: vec![ Log(b"one log".to_vec()), Log(b"another log".to_vec()) ], },
};
let b = Block {
header: h,
transactions: vec![tx1, tx2],
};
let serialised = b.to_vec();
assert_eq!(serialised, vec![
// header
4u8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
42, 0, 0, 0, 0, 0, 0, 0,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
2, 0, 0, 0,
7, 0, 0, 0,
111, 110, 101, 32, 108, 111, 103,
11, 0, 0, 0,
97, 110, 111, 116, 104, 101, 114, 32, 108, 111, 103,
// transactions
2, 0, 0, 0,
// tx1
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
69, 0, 0, 0, 0, 0, 0, 0,
34,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
69, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
// tx2
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
42, 0, 0, 0, 0, 0, 0, 0,
32,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
]);
}
#[test]
fn deserialise_block_works() {
let one: AccountId = [1u8; 32];
let two: AccountId = [2u8; 32];
let tx1 = UncheckedTransaction {
transaction: Transaction {
signed: one.clone(),
nonce: 69,
function: Function::StakingTransfer(two, 69),
},
signature: [1u8; 64].into(),
};
let tx2 = UncheckedTransaction {
transaction: Transaction {
signed: two.clone(),
nonce: 42,
function: Function::StakingStake,
},
signature: [2u8; 64].into(),
};
let h = Header {
parent_hash: [4u8; 32].into(),
number: 42,
state_root: [5u8; 32].into(),
transaction_root: [6u8; 32].into(),
digest: Digest { logs: vec![ Log(b"one log".to_vec()), Log(b"another log".to_vec()) ], },
};
let b = Block {
header: h,
transactions: vec![tx1, tx2],
};
let data = [
// header
4u8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
42, 0, 0, 0, 0, 0, 0, 0,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
2, 0, 0, 0,
7, 0, 0, 0,
111, 110, 101, 32, 108, 111, 103,
11, 0, 0, 0,
97, 110, 111, 116, 104, 101, 114, 32, 108, 111, 103,
// transactions
2, 0, 0, 0,
// tx1
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
69, 0, 0, 0, 0, 0, 0, 0,
34,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
69, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
// tx2
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
42, 0, 0, 0, 0, 0, 0, 0,
32,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
];
let deserialised = Block::from_slice(&mut &data[..]).unwrap();
assert_eq!(deserialised, b);
}
+5 -1
View File
@@ -16,12 +16,15 @@
//! An unsigned fixed-size integer.
#[cfg(feature = "std")]
use serde::{Serialize, Serializer, Deserialize, Deserializer};
#[cfg(feature = "std")]
use bytes;
macro_rules! impl_serde {
($name: ident, $len: expr) => {
#[cfg(feature = "std")]
impl Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
let mut bytes = [0u8; $len * 8];
@@ -30,6 +33,7 @@ macro_rules! impl_serde {
}
}
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
bytes::deserialize_check_len(deserializer, bytes::ExpectedLen::Between(0, $len * 8))
@@ -40,8 +44,8 @@ macro_rules! impl_serde {
}
construct_uint!(U256, 4);
impl_serde!(U256, 4);
construct_uint!(U512, 8);
impl_serde!(U256, 4);
impl_serde!(U512, 8);
#[cfg(test)]
+33
View File
@@ -0,0 +1,33 @@
[package]
name = "substrate-runtime-io"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
build = "build.rs"
[build-dependencies]
rustc_version = "0.2"
[dependencies]
pwasm-alloc = { path = "../wasm-runtime/pwasm-alloc" }
pwasm-libc = { path = "../wasm-runtime/pwasm-libc" }
substrate-runtime-std = { path = "../runtime-std" }
environmental = { path = "../environmental", optional = true }
substrate-state-machine = { path = "../state-machine", optional = true }
substrate-primitives = { path = "../primitives", default_features = false }
substrate-codec = { path = "../codec", default_features = false }
triehash = { version = "0.1", optional = true }
ed25519 = { path = "../ed25519", optional = true }
[features]
default = ["std"]
std = [
"environmental",
"substrate-state-machine",
"triehash",
"substrate-primitives/std",
"substrate-codec/std",
"substrate-runtime-std/std",
"ed25519",
]
nightly = []
strict = []
+14
View File
@@ -0,0 +1,14 @@
//! Set a nightly feature
extern crate rustc_version;
use rustc_version::{version, version_meta, Channel};
fn main() {
// Assert we haven't travelled back in time
assert!(version().unwrap().major >= 1);
// Set cfg flags depending on release channel
if let Channel::Nightly = version_meta().unwrap().channel {
println!("cargo:rustc-cfg=feature=\"nightly\"");
}
}
+31
View File
@@ -0,0 +1,31 @@
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! This is part of the Substrate runtime.
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(lang_items))]
#![cfg_attr(not(feature = "std"), feature(core_intrinsics))]
#![cfg_attr(not(feature = "std"), feature(alloc))]
#![cfg_attr(feature = "std", doc = "Substrate runtime standard library as compiled when linked with Rust's standard library.")]
#![cfg_attr(not(feature = "std"), doc = "Substrate's runtime standard library as compiled without Rust's standard library.")]
#[cfg(feature = "std")]
include!("../with_std.rs");
#[cfg(not(feature = "std"))]
include!("../without_std.rs");
+183
View File
@@ -0,0 +1,183 @@
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
#[macro_use]
extern crate environmental;
extern crate substrate_state_machine;
extern crate substrate_primitives as primitives;
extern crate triehash;
extern crate ed25519;
pub use std::vec;
pub use std::rc;
pub use std::cell;
pub use std::boxed;
pub use std::slice;
pub use std::mem;
// re-export hashing functions.
pub use primitives::{blake2_256, twox_128, twox_256};
pub use substrate_state_machine::{Externalities, ExternalitiesError, TestExternalities};
use primitives::hexdisplay::HexDisplay;
// TODO: use the real error, not NoError.
environmental!(ext : trait Externalities);
/// Get `key` from storage and return a `Vec`, empty if there's a problem.
pub fn storage(key: &[u8]) -> Vec<u8> {
ext::with(|ext| ext.storage(key).ok().map(|s| s.to_vec()))
.expect("read_storage cannot be called outside of an Externalities-provided environment.")
.unwrap_or_else(Vec::new)
}
/// Get `key` from storage, placing the value into `value_out` (as much as possible) and return
/// the number of bytes that the key in storage was.
pub fn read_storage(key: &[u8], value_out: &mut [u8], value_offset: usize) -> usize {
ext::with(|ext| {
if let Ok(value) = ext.storage(key) {
let value = &value[value_offset..];
let written = ::std::cmp::min(value.len(), value_out.len());
value_out[0..written].copy_from_slice(&value[0..written]);
value.len()
} else {
// no-entry is treated as an empty vector of bytes.
// TODO: consider allowing empty-vector to exist separately to no-entry (i.e. return
// Option<usize>)
0
}
}).expect("read_storage cannot be called outside of an Externalities-provided environment.")
}
/// Set the storage to some particular key.
pub fn set_storage(key: &[u8], value: &[u8]) {
ext::with(|ext|
ext.set_storage(key.to_vec(), value.to_vec())
);
}
/// The current relay chain identifier.
pub fn chain_id() -> u64 {
ext::with(|ext|
ext.chain_id()
).unwrap_or(0)
}
/// "Commit" all existing operations and get the resultant storage root.
pub fn storage_root() -> [u8; 32] {
ext::with(|ext|
ext.storage_root()
).unwrap_or([0u8; 32])
}
/// "Commit" all existing operations and get the resultant storage root.
pub fn enumerated_trie_root(serialised_values: &[&[u8]]) -> [u8; 32] {
triehash::ordered_trie_root(serialised_values.iter().map(|s| s.to_vec())).0
}
/// Verify a ed25519 signature.
pub fn ed25519_verify(sig: &[u8; 64], msg: &[u8], pubkey: &[u8; 32]) -> bool {
ed25519::verify(sig, msg, pubkey)
}
/// Execute the given closure with global function available whose functionality routes into the
/// externalities `ext`. Forwards the value that the closure returns.
pub fn with_externalities<R, F: FnOnce() -> R>(ext: &mut Externalities, f: F) -> R {
ext::using(ext, f)
}
/// Trait for things which can be printed.
pub trait Printable {
fn print(self);
}
impl<'a> Printable for &'a [u8] {
fn print(self) {
println!("Runtime: {}", HexDisplay::from(&self));
}
}
impl<'a> Printable for &'a str {
fn print(self) {
println!("Runtime: {}", self);
}
}
impl Printable for u64 {
fn print(self) {
println!("Runtime: {}", self);
}
}
/// Print a printable value.
pub fn print<T: Printable + Sized>(value: T) {
value.print();
}
#[macro_export]
macro_rules! impl_stubs {
($( $name:ident ),*) => {}
}
#[cfg(test)]
mod std_tests {
use super::*;
macro_rules! map {
($( $name:expr => $value:expr ),*) => (
vec![ $( ( $name, $value ) ),* ].into_iter().collect()
)
}
#[test]
fn storage_works() {
let mut t = TestExternalities { storage: map![], };
assert!(with_externalities(&mut t, || {
assert_eq!(storage(b"hello"), b"".to_vec());
set_storage(b"hello", b"world");
assert_eq!(storage(b"hello"), b"world".to_vec());
assert_eq!(storage(b"foo"), b"".to_vec());
set_storage(b"foo", &[1, 2, 3][..]);
true
}));
t.storage = map![b"foo".to_vec() => b"bar".to_vec()];
assert!(!with_externalities(&mut t, || {
assert_eq!(storage(b"hello"), b"".to_vec());
assert_eq!(storage(b"foo"), b"bar".to_vec());
false
}));
}
#[test]
fn read_storage_works() {
let mut t = TestExternalities { storage: map![
b":test".to_vec() => b"\x0b\0\0\0Hello world".to_vec()
], };
with_externalities(&mut t, || {
let mut v = [0u8; 4];
assert!(read_storage(b":test", &mut v[..], 0) >= 4);
assert_eq!(v, [11u8, 0, 0, 0]);
let mut w = [0u8; 11];
assert!(read_storage(b":test", &mut w[..], 4) >= 11);
assert_eq!(&w, b"Hello world");
});
}
}
+208
View File
@@ -0,0 +1,208 @@
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
#[cfg(feature = "nightly")]
extern crate alloc;
#[cfg(feature = "nightly")]
extern crate pwasm_libc;
#[cfg(feature = "nightly")]
extern crate pwasm_alloc;
extern crate substrate_primitives as primitives;
pub use alloc::vec;
pub use alloc::boxed;
pub use alloc::rc;
pub use core::mem;
pub use core::slice;
pub use core::cell;
use alloc::vec::Vec;
#[lang = "panic_fmt"]
#[no_mangle]
pub extern fn panic_fmt(_fmt: ::core::fmt::Arguments, _file: &'static str, _line: u32, _col: u32) {
unsafe {
ext_print_utf8(_file.as_ptr() as *const u8, _file.len() as u32);
ext_print_num(_line as u64);
ext_print_num(_col as u64);
::core::intrinsics::abort()
}
}
extern "C" {
fn ext_print_utf8(utf8_data: *const u8, utf8_len: u32);
fn ext_print_hex(data: *const u8, len: u32);
fn ext_print_num(value: u64);
fn ext_set_storage(key_data: *const u8, key_len: u32, value_data: *const u8, value_len: u32);
fn ext_get_allocated_storage(key_data: *const u8, key_len: u32, written_out: *mut u32) -> *mut u8;
fn ext_get_storage_into(key_data: *const u8, key_len: u32, value_data: *mut u8, value_len: u32, value_offset: u32) -> u32;
fn ext_storage_root(result: *mut u8);
fn ext_enumerated_trie_root(values_data: *const u8, lens_data: *const u32, lens_len: u32, result: *mut u8);
fn ext_chain_id() -> u64;
fn ext_blake2_256(data: *const u8, len: u32, out: *mut u8);
fn ext_twox_128(data: *const u8, len: u32, out: *mut u8);
fn ext_twox_256(data: *const u8, len: u32, out: *mut u8);
fn ext_ed25519_verify(msg_data: *const u8, msg_len: u32, sig_data: *const u8, pubkey_data: *const u8) -> u32;
}
/// Get `key` from storage and return a `Vec`, empty if there's a problem.
pub fn storage(key: &[u8]) -> Vec<u8> {
let mut length: u32 = 0;
unsafe {
let ptr = ext_get_allocated_storage(key.as_ptr(), key.len() as u32, &mut length);
Vec::from_raw_parts(ptr, length as usize, length as usize)
}
}
/// Set the storage to some particular key.
pub fn set_storage(key: &[u8], value: &[u8]) {
unsafe {
ext_set_storage(
key.as_ptr(), key.len() as u32,
value.as_ptr(), value.len() as u32
);
}
}
/// Get `key` from storage, placing the value into `value_out` (as much as possible) and return
/// the number of bytes that the key in storage was.
pub fn read_storage(key: &[u8], value_out: &mut [u8], value_offset: usize) -> usize {
unsafe {
ext_get_storage_into(key.as_ptr(), key.len() as u32, value_out.as_mut_ptr(), value_out.len() as u32, value_offset as u32) as usize
}
}
/// The current storage's root.
pub fn storage_root() -> [u8; 32] {
let mut result: [u8; 32] = Default::default();
unsafe {
ext_storage_root(result.as_mut_ptr());
}
result
}
/// A trie root calculated from enumerated values.
pub fn enumerated_trie_root(values: &[&[u8]]) -> [u8; 32] {
let lens = values.iter().map(|v| (v.len() as u32).to_le()).collect::<Vec<_>>();
let values = values.iter().fold(Vec::new(), |mut acc, sl| { acc.extend_from_slice(sl); acc });
let mut result: [u8; 32] = Default::default();
unsafe {
ext_enumerated_trie_root(
values.as_ptr(),
lens.as_ptr(), lens.len() as u32,
result.as_mut_ptr()
);
}
result
}
/// The current relay chain identifier.
pub fn chain_id() -> u64 {
unsafe {
ext_chain_id()
}
}
/// Conduct a 256-bit Blake2 hash.
pub fn blake2_256(data: &[u8]) -> [u8; 32] {
let mut result: [u8; 32] = Default::default();
unsafe {
ext_blake2_256(data.as_ptr(), data.len() as u32, result.as_mut_ptr());
}
result
}
/// Conduct four XX hashes to give a 256-bit result.
pub fn twox_256(data: &[u8]) -> [u8; 32] {
let mut result: [u8; 32] = Default::default();
unsafe {
ext_twox_256(data.as_ptr(), data.len() as u32, result.as_mut_ptr());
}
result
}
/// Conduct two XX hashes to give a 128-bit result.
pub fn twox_128(data: &[u8]) -> [u8; 16] {
let mut result: [u8; 16] = Default::default();
unsafe {
ext_twox_128(data.as_ptr(), data.len() as u32, result.as_mut_ptr());
}
result
}
/// Verify a ed25519 signature.
pub fn ed25519_verify(sig: &[u8], msg: &[u8], pubkey: &[u8]) -> bool {
sig.len() == 64 && pubkey.len() == 32 && unsafe {
ext_ed25519_verify(msg.as_ptr(), msg.len() as u32, sig.as_ptr(), pubkey.as_ptr())
} == 0
}
/// Trait for things which can be printed.
pub trait Printable {
fn print(self);
}
impl<'a> Printable for &'a [u8] {
fn print(self) {
unsafe {
ext_print_hex(self.as_ptr(), self.len() as u32);
}
}
}
impl<'a> Printable for &'a str {
fn print(self) {
unsafe {
ext_print_utf8(self.as_ptr() as *const u8, self.len() as u32);
}
}
}
impl Printable for u64 {
fn print(self) {
unsafe { ext_print_num(self); }
}
}
/// Print a printable value.
pub fn print<T: Printable + Sized>(value: T) {
value.print();
}
#[macro_export]
macro_rules! impl_stubs {
( $( $name:ident ),* ) => {
pub mod _internal {
$(
#[no_mangle]
pub fn $name(input_data: *mut u8, input_len: usize) -> u64 {
let input = if input_len == 0 {
&[0u8; 0]
} else {
unsafe {
$crate::slice::from_raw_parts(input_data, input_len)
}
};
let output = super::$name(input);
output.as_ptr() as u64 + ((output.len() as u64) << 32)
}
)*
}
}
}
+2 -17
View File
@@ -1,5 +1,5 @@
[package]
name = "polkadot-runtime-std"
name = "substrate-runtime-std"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
build = "build.rs"
@@ -8,24 +8,9 @@ build = "build.rs"
rustc_version = "0.2"
[dependencies]
pwasm-alloc = { path = "../wasm-runtime/pwasm-alloc", version = "0.1" }
pwasm-libc = { path = "../wasm-runtime/pwasm-libc", version = "0.1" }
environmental = { path = "../environmental", version = "0.1", optional = true }
substrate-state-machine = { path = "../state-machine", version = "0.1", optional = true }
substrate-primitives = { path = "../primitives", version = "0.1", default_features = false }
substrate-codec = { path = "../codec", version = "0.1", default_features = false }
triehash = { version = "0.1", optional = true }
ed25519 = { path = "../ed25519", version = "0.1", optional = true }
[features]
default = ["std"]
std = [
"environmental",
"substrate-state-machine",
"triehash",
"substrate-primitives/std",
"substrate-codec/std",
"ed25519",
]
std = []
nightly = []
strict = []
+6 -5
View File
@@ -1,20 +1,21 @@
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// This file is part of Substrate.
// Polkadot is free software: you can redistribute it and/or modify
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! This is part of the Polkadot runtime.
//! Lowest-abstraction level for the Substrate runtime: just exports useful primitives from std
//! or core/alloc to be used with any code that depends on the runtime.
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(lang_items))]
+5 -165
View File
@@ -1,26 +1,18 @@
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// This file is part of Substrate.
// Polkadot is free software: you can redistribute it and/or modify
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
#[macro_use]
extern crate environmental;
extern crate substrate_state_machine;
extern crate substrate_primitives as primitives;
extern crate triehash;
extern crate ed25519;
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
pub use std::vec;
pub use std::rc;
@@ -28,156 +20,4 @@ pub use std::cell;
pub use std::boxed;
pub use std::slice;
pub use std::mem;
// re-export hashing functions.
pub use primitives::{blake2_256, twox_128, twox_256};
pub use substrate_state_machine::{Externalities, ExternalitiesError, TestExternalities};
use primitives::hexdisplay::HexDisplay;
// TODO: use the real error, not NoError.
environmental!(ext : trait Externalities);
/// Get `key` from storage and return a `Vec`, empty if there's a problem.
pub fn storage(key: &[u8]) -> Vec<u8> {
ext::with(|ext| ext.storage(key).ok().map(|s| s.to_vec()))
.expect("read_storage cannot be called outside of an Externalities-provided environment.")
.unwrap_or_else(Vec::new)
}
/// Get `key` from storage, placing the value into `value_out` (as much as possible) and return
/// the number of bytes that the key in storage was.
pub fn read_storage(key: &[u8], value_out: &mut [u8], value_offset: usize) -> usize {
ext::with(|ext| {
if let Ok(value) = ext.storage(key) {
let value = &value[value_offset..];
let written = ::std::cmp::min(value.len(), value_out.len());
value_out[0..written].copy_from_slice(&value[0..written]);
value.len()
} else {
// no-entry is treated as an empty vector of bytes.
// TODO: consider allowing empty-vector to exist separately to no-entry (i.e. return
// Option<usize>)
0
}
}).expect("read_storage cannot be called outside of an Externalities-provided environment.")
}
/// Set the storage to some particular key.
pub fn set_storage(key: &[u8], value: &[u8]) {
ext::with(|ext|
ext.set_storage(key.to_vec(), value.to_vec())
);
}
/// The current relay chain identifier.
pub fn chain_id() -> u64 {
ext::with(|ext|
ext.chain_id()
).unwrap_or(0)
}
/// "Commit" all existing operations and get the resultant storage root.
pub fn storage_root() -> [u8; 32] {
ext::with(|ext|
ext.storage_root()
).unwrap_or([0u8; 32])
}
/// "Commit" all existing operations and get the resultant storage root.
pub fn enumerated_trie_root(serialised_values: &[&[u8]]) -> [u8; 32] {
triehash::ordered_trie_root(serialised_values.iter().map(|s| s.to_vec())).0
}
/// Verify a ed25519 signature.
pub fn ed25519_verify(sig: &[u8; 64], msg: &[u8], pubkey: &[u8; 32]) -> bool {
ed25519::verify(sig, msg, pubkey)
}
/// Execute the given closure with global function available whose functionality routes into the
/// externalities `ext`. Forwards the value that the closure returns.
pub fn with_externalities<R, F: FnOnce() -> R>(ext: &mut Externalities, f: F) -> R {
ext::using(ext, f)
}
/// Trait for things which can be printed.
pub trait Printable {
fn print(self);
}
impl<'a> Printable for &'a [u8] {
fn print(self) {
println!("Runtime: {}", HexDisplay::from(&self));
}
}
impl<'a> Printable for &'a str {
fn print(self) {
println!("Runtime: {}", self);
}
}
impl Printable for u64 {
fn print(self) {
println!("Runtime: {}", self);
}
}
/// Print a printable value.
pub fn print<T: Printable + Sized>(value: T) {
value.print();
}
#[macro_export]
macro_rules! impl_stubs {
($( $name:ident ),*) => {}
}
#[cfg(test)]
mod std_tests {
use super::*;
macro_rules! map {
($( $name:expr => $value:expr ),*) => (
vec![ $( ( $name, $value ) ),* ].into_iter().collect()
)
}
#[test]
fn storage_works() {
let mut t = TestExternalities { storage: map![], };
assert!(with_externalities(&mut t, || {
assert_eq!(storage(b"hello"), b"".to_vec());
set_storage(b"hello", b"world");
assert_eq!(storage(b"hello"), b"world".to_vec());
assert_eq!(storage(b"foo"), b"".to_vec());
set_storage(b"foo", &[1, 2, 3][..]);
true
}));
t.storage = map![b"foo".to_vec() => b"bar".to_vec()];
assert!(!with_externalities(&mut t, || {
assert_eq!(storage(b"hello"), b"".to_vec());
assert_eq!(storage(b"foo"), b"bar".to_vec());
false
}));
}
#[test]
fn read_storage_works() {
let mut t = TestExternalities { storage: map![
b":test".to_vec() => b"\x0b\0\0\0Hello world".to_vec()
], };
with_externalities(&mut t, || {
let mut v = [0u8; 4];
assert!(read_storage(b":test", &mut v[..], 0) >= 4);
assert_eq!(v, [11u8, 0, 0, 0]);
let mut w = [0u8; 11];
assert!(read_storage(b":test", &mut w[..], 4) >= 11);
assert_eq!(&w, b"Hello world");
});
}
}
pub use std::ops;
+17 -183
View File
@@ -1,192 +1,26 @@
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
#[cfg(feature = "nightly")]
extern crate alloc;
#[cfg(feature = "nightly")]
extern crate pwasm_libc;
#[cfg(feature = "nightly")]
extern crate pwasm_alloc;
extern crate substrate_primitives as primitives;
pub use alloc::vec;
pub use alloc::boxed;
pub use alloc::rc;
pub use core::mem;
pub use core::slice;
pub use core::cell;
use alloc::vec::Vec;
#[lang = "panic_fmt"]
#[no_mangle]
pub extern fn panic_fmt(_fmt: ::core::fmt::Arguments, _file: &'static str, _line: u32, _col: u32) {
unsafe {
ext_print_utf8(_file.as_ptr() as *const u8, _file.len() as u32);
ext_print_num(_line as u64);
ext_print_num(_col as u64);
::core::intrinsics::abort()
}
}
extern "C" {
fn ext_print_utf8(utf8_data: *const u8, utf8_len: u32);
fn ext_print_hex(data: *const u8, len: u32);
fn ext_print_num(value: u64);
fn ext_set_storage(key_data: *const u8, key_len: u32, value_data: *const u8, value_len: u32);
fn ext_get_allocated_storage(key_data: *const u8, key_len: u32, written_out: *mut u32) -> *mut u8;
fn ext_get_storage_into(key_data: *const u8, key_len: u32, value_data: *mut u8, value_len: u32, value_offset: u32) -> u32;
fn ext_storage_root(result: *mut u8);
fn ext_enumerated_trie_root(values_data: *const u8, lens_data: *const u32, lens_len: u32, result: *mut u8);
fn ext_chain_id() -> u64;
fn ext_blake2_256(data: *const u8, len: u32, out: *mut u8);
fn ext_twox_128(data: *const u8, len: u32, out: *mut u8);
fn ext_twox_256(data: *const u8, len: u32, out: *mut u8);
fn ext_ed25519_verify(msg_data: *const u8, msg_len: u32, sig_data: *const u8, pubkey_data: *const u8) -> u32;
}
/// Get `key` from storage and return a `Vec`, empty if there's a problem.
pub fn storage(key: &[u8]) -> Vec<u8> {
let mut length: u32 = 0;
unsafe {
let ptr = ext_get_allocated_storage(key.as_ptr(), key.len() as u32, &mut length);
Vec::from_raw_parts(ptr, length as usize, length as usize)
}
}
/// Set the storage to some particular key.
pub fn set_storage(key: &[u8], value: &[u8]) {
unsafe {
ext_set_storage(
key.as_ptr(), key.len() as u32,
value.as_ptr(), value.len() as u32
);
}
}
/// Get `key` from storage, placing the value into `value_out` (as much as possible) and return
/// the number of bytes that the key in storage was.
pub fn read_storage(key: &[u8], value_out: &mut [u8], value_offset: usize) -> usize {
unsafe {
ext_get_storage_into(key.as_ptr(), key.len() as u32, value_out.as_mut_ptr(), value_out.len() as u32, value_offset as u32) as usize
}
}
/// The current storage's root.
pub fn storage_root() -> [u8; 32] {
let mut result: [u8; 32] = Default::default();
unsafe {
ext_storage_root(result.as_mut_ptr());
}
result
}
/// A trie root calculated from enumerated values.
pub fn enumerated_trie_root(values: &[&[u8]]) -> [u8; 32] {
let lens = values.iter().map(|v| (v.len() as u32).to_le()).collect::<Vec<_>>();
let values = values.iter().fold(Vec::new(), |mut acc, sl| { acc.extend_from_slice(sl); acc });
let mut result: [u8; 32] = Default::default();
unsafe {
ext_enumerated_trie_root(
values.as_ptr(),
lens.as_ptr(), lens.len() as u32,
result.as_mut_ptr()
);
}
result
}
/// The current relay chain identifier.
pub fn chain_id() -> u64 {
unsafe {
ext_chain_id()
}
}
/// Conduct a 256-bit Blake2 hash.
pub fn blake2_256(data: &[u8]) -> [u8; 32] {
let mut result: [u8; 32] = Default::default();
unsafe {
ext_blake2_256(data.as_ptr(), data.len() as u32, result.as_mut_ptr());
}
result
}
/// Conduct four XX hashes to give a 256-bit result.
pub fn twox_256(data: &[u8]) -> [u8; 32] {
let mut result: [u8; 32] = Default::default();
unsafe {
ext_twox_256(data.as_ptr(), data.len() as u32, result.as_mut_ptr());
}
result
}
/// Conduct two XX hashes to give a 128-bit result.
pub fn twox_128(data: &[u8]) -> [u8; 16] {
let mut result: [u8; 16] = Default::default();
unsafe {
ext_twox_128(data.as_ptr(), data.len() as u32, result.as_mut_ptr());
}
result
}
/// Verify a ed25519 signature.
pub fn ed25519_verify(sig: &[u8], msg: &[u8], pubkey: &[u8]) -> bool {
sig.len() == 64 && pubkey.len() == 32 && unsafe {
ext_ed25519_verify(msg.as_ptr(), msg.len() as u32, sig.as_ptr(), pubkey.as_ptr())
} == 0
}
/// Trait for things which can be printed.
pub trait Printable {
fn print(self);
}
impl<'a> Printable for &'a [u8] {
fn print(self) {
unsafe {
ext_print_hex(self.as_ptr(), self.len() as u32);
}
}
}
impl<'a> Printable for &'a str {
fn print(self) {
unsafe {
ext_print_utf8(self.as_ptr() as *const u8, self.len() as u32);
}
}
}
impl Printable for u64 {
fn print(self) {
unsafe { ext_print_num(self); }
}
}
/// Print a printable value.
pub fn print<T: Printable + Sized>(value: T) {
value.print();
}
#[macro_export]
macro_rules! impl_stubs {
( $( $name:ident ),* ) => {
pub mod _internal {
$(
#[no_mangle]
pub fn $name(input_data: *mut u8, input_len: usize) -> u64 {
let input = if input_len == 0 {
&[0u8; 0]
} else {
unsafe {
$crate::slice::from_raw_parts(input_data, input_len)
}
};
let output = super::$name(input);
output.as_ptr() as u64 + ((output.len() as u64) << 32)
}
)*
}
}
}
pub use core::ops;
+35 -10
View File
@@ -376,18 +376,14 @@ dependencies = [
]
[[package]]
name = "polkadot-runtime-std"
name = "polkadot-primitives"
version = "0.1.0"
dependencies = [
"ed25519 0.1.0",
"environmental 0.1.0",
"pwasm-alloc 0.1.0",
"pwasm-libc 0.1.0",
"rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-codec 0.1.0",
"substrate-primitives 0.1.0",
"substrate-state-machine 0.1.0",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-runtime-std 0.1.0",
]
[[package]]
@@ -518,16 +514,18 @@ dependencies = [
name = "runtime-polkadot"
version = "0.1.0"
dependencies = [
"polkadot-runtime-std 0.1.0",
"polkadot-primitives 0.1.0",
"substrate-codec 0.1.0",
"substrate-primitives 0.1.0",
"substrate-runtime-io 0.1.0",
"substrate-runtime-std 0.1.0",
]
[[package]]
name = "runtime-test"
version = "0.1.0"
dependencies = [
"polkadot-runtime-std 0.1.0",
"substrate-runtime-io 0.1.0",
]
[[package]]
@@ -603,6 +601,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "substrate-codec"
version = "0.1.0"
dependencies = [
"substrate-runtime-std 0.1.0",
]
[[package]]
name = "substrate-primitives"
@@ -616,10 +617,34 @@ dependencies = [
"serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-codec 0.1.0",
"substrate-runtime-std 0.1.0",
"twox-hash 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"uint 0.1.2 (git+https://github.com/rphmeier/primitives.git?branch=compile-for-wasm)",
]
[[package]]
name = "substrate-runtime-io"
version = "0.1.0"
dependencies = [
"ed25519 0.1.0",
"environmental 0.1.0",
"pwasm-alloc 0.1.0",
"pwasm-libc 0.1.0",
"rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-codec 0.1.0",
"substrate-primitives 0.1.0",
"substrate-runtime-std 0.1.0",
"substrate-state-machine 0.1.0",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "substrate-runtime-std"
version = "0.1.0"
dependencies = [
"rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "substrate-state-machine"
version = "0.1.0"
+4 -2
View File
@@ -8,9 +8,11 @@ crate-type = ["cdylib"]
[dependencies]
substrate-codec = { path = "../../codec", version = "0.1", default-features = false }
polkadot-runtime-std = { path = "../../runtime-std", version = "0.1", default-features = false }
substrate-runtime-std = { path = "../../runtime-std", version = "0.1", default-features = false }
substrate-runtime-io = { path = "../../runtime-io", version = "0.1", default-features = false }
substrate-primitives = { path = "../../primitives", version = "0.1", default-features = false }
polkadot-primitives = { path = "../../polkadot-primitives", version = "0.1", default-features = false }
[features]
default = []
std = ["substrate-codec/std", "polkadot-runtime-std/std", "substrate-primitives/std"]
std = ["substrate-codec/std", "substrate-runtime-io/std", "substrate-runtime-std/std", "substrate-primitives/std", "polkadot-primitives/std"]
+13 -14
View File
@@ -19,7 +19,10 @@
#![cfg_attr(not(feature = "std"), no_std)]
#[macro_use]
extern crate polkadot_runtime_std as runtime_std;
extern crate substrate_runtime_std as rstd;
#[macro_use]
extern crate substrate_runtime_io as runtime_io;
#[cfg(feature = "std")]
extern crate rustc_hex;
@@ -28,7 +31,8 @@ extern crate rustc_hex;
extern crate log;
extern crate substrate_codec as codec;
extern crate substrate_primitives as primitives;
extern crate substrate_primitives;
extern crate polkadot_primitives;
#[cfg(test)]
#[macro_use]
@@ -38,20 +42,15 @@ extern crate hex_literal;
pub mod support;
pub mod runtime;
use runtime_std::prelude::*;
use rstd::prelude::*;
use codec::Slicable;
use primitives::relay::{Header, Block, UncheckedTransaction};
use polkadot_primitives::{Header, Block, UncheckedTransaction};
/// Type definitions and helpers for transactions.
pub mod transaction {
pub use primitives::relay::{Transaction, UncheckedTransaction};
use primitives::relay::Signature;
#[cfg(feature = "std")]
use std::ops;
#[cfg(not(feature = "std"))]
use core::ops;
use rstd::ops;
use polkadot_primitives::Signature;
pub use polkadot_primitives::{Transaction, UncheckedTransaction};
/// A type-safe indicator that a transaction has been checked.
#[derive(PartialEq, Eq, Clone)]
@@ -78,7 +77,7 @@ pub mod transaction {
/// On failure, return the transaction back.
pub fn check(tx: UncheckedTransaction) -> Result<CheckedTransaction, UncheckedTransaction> {
let msg = ::codec::Slicable::to_vec(&tx.transaction);
if ::runtime_std::ed25519_verify(&tx.signature.0, &msg, &tx.transaction.signed) {
if ::runtime_io::ed25519_verify(&tx.signature.0, &msg, &tx.transaction.signed) {
Ok(CheckedTransaction(tx))
} else {
Err(tx)
@@ -110,7 +109,7 @@ pub fn finalise_block(mut input: &[u8]) -> Vec<u8> {
/// Run whatever tests we have.
pub fn run_tests(mut input: &[u8]) -> Vec<u8> {
use runtime_std::print;
use runtime_io::print;
print("run_tests...");
let block = Block::from_slice(&mut input).unwrap();
@@ -16,9 +16,9 @@
//! Conensus module for runtime; manages the authority set ready for the native code.
use runtime_std::prelude::*;
use rstd::prelude::*;
use support::storage::unhashed::StorageVec;
use primitives::relay::SessionKey;
use polkadot_primitives::SessionKey;
struct AuthorityStorageVec {}
impl StorageVec for AuthorityStorageVec {
@@ -17,10 +17,10 @@
//! Tool for creating the genesis block.
use std::collections::HashMap;
use runtime_std::twox_128;
use runtime_io::twox_128;
use codec::{KeyedVec, Joiner};
use support::Hashable;
use primitives::relay::{Number as BlockNumber, Block, AccountId};
use polkadot_primitives::{BlockNumber, Block, AccountId};
use runtime::staking::Balance;
/// Configuration of a general Polkadot genesis block.
@@ -25,10 +25,10 @@
//! At the end of the era, all validators approvals are tallied and if there are sufficient to pass
//! the proposal then it is enacted. All items in storage concerning the proposal are reset.
use runtime_std::prelude::*;
use rstd::prelude::*;
use codec::KeyedVec;
use support::storage;
use primitives::relay::{Proposal, AccountId, Hash, BlockNumber};
use polkadot_primitives::{Proposal, AccountId, Hash, BlockNumber};
use runtime::{staking, system, session};
const APPROVALS_REQUIRED: &[u8] = b"gov:apr";
@@ -94,7 +94,7 @@ pub mod privileged {
pub mod internal {
use super::*;
use primitives::relay::{Proposal, InternalFunction};
use polkadot_primitives::Proposal;
/// Current era is ending; we should finish up any proposals.
pub fn end_of_an_era() {
@@ -112,29 +112,29 @@ pub mod internal {
}
fn enact_proposal(proposal: Proposal) {
match proposal.function {
InternalFunction::SystemSetCode(code) => {
match proposal {
Proposal::SystemSetCode(code) => {
system::privileged::set_code(&code);
}
InternalFunction::SessionSetLength(value) => {
Proposal::SessionSetLength(value) => {
session::privileged::set_length(value);
}
InternalFunction::SessionForceNewSession => {
Proposal::SessionForceNewSession => {
session::privileged::force_new_session();
}
InternalFunction::StakingSetSessionsPerEra(value) => {
Proposal::StakingSetSessionsPerEra(value) => {
staking::privileged::set_sessions_per_era(value);
}
InternalFunction::StakingSetBondingDuration(value) => {
Proposal::StakingSetBondingDuration(value) => {
staking::privileged::set_bonding_duration(value);
}
InternalFunction::StakingSetValidatorCount(value) => {
Proposal::StakingSetValidatorCount(value) => {
staking::privileged::set_validator_count(value);
}
InternalFunction::StakingForceNewEra => {
Proposal::StakingForceNewEra => {
staking::privileged::force_new_era()
}
InternalFunction::GovernanceSetApprovalPpmRequired(value) => {
Proposal::GovernanceSetApprovalPpmRequired(value) => {
self::privileged::set_approval_ppm_required(value);
}
@@ -145,7 +145,7 @@ pub mod internal {
#[cfg(test)]
mod tests {
use super::*;
use runtime_std::{with_externalities, twox_128, TestExternalities};
use runtime_io::{with_externalities, twox_128, TestExternalities};
use codec::{KeyedVec, Joiner};
use support::{one, two, with_env};
use primitives::relay::{AccountId, InternalFunction};
@@ -190,7 +190,7 @@ mod tests {
// Block 1: Make proposal. Approve it. Era length changes.
with_env(|e| e.block_number = 1);
public::propose(&one, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
function: Proposal::StakingSetSessionsPerEra(2),
});
public::approve(&two, 1);
staking::internal::check_new_era();
@@ -215,7 +215,7 @@ mod tests {
// Block 1: Make proposal. Fail it.
with_env(|e| e.block_number = 1);
public::propose(&one, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
function: Proposal::StakingSetSessionsPerEra(2),
});
staking::internal::check_new_era();
assert_eq!(staking::era_length(), 1);
@@ -223,7 +223,7 @@ mod tests {
// Block 2: Make proposal. Approve it. It should change era length.
with_env(|e| e.block_number = 2);
public::propose(&one, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
function: Proposal::StakingSetSessionsPerEra(2),
});
public::approve(&two, 2);
staking::internal::check_new_era();
@@ -248,7 +248,7 @@ mod tests {
// Block 1: Make proposal. Will have only 1 vote. No change.
with_env(|e| e.block_number = 1);
public::propose(&one, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
function: Proposal::StakingSetSessionsPerEra(2),
});
staking::internal::check_new_era();
assert_eq!(staking::era_length(), 1);
@@ -273,7 +273,7 @@ mod tests {
// Block 1: Make proposal. Will have only 1 vote. No change.
with_env(|e| e.block_number = 1);
public::propose(&one, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
function: Proposal::StakingSetSessionsPerEra(2),
});
public::approve(&two, 0);
staking::internal::check_new_era();
@@ -299,7 +299,7 @@ mod tests {
// Block 1: Make proposal. Will have only 1 vote. No change.
with_env(|e| e.block_number = 1);
public::propose(&one, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
function: Proposal::StakingSetSessionsPerEra(2),
});
public::approve(&two, 1);
public::approve(&two, 1);
@@ -326,10 +326,10 @@ mod tests {
// Block 1: Make proposal. Will have only 1 vote. No change.
with_env(|e| e.block_number = 1);
public::propose(&one, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
function: Proposal::StakingSetSessionsPerEra(2),
});
public::propose(&two, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
function: Proposal::StakingSetSessionsPerEra(2),
});
staking::internal::check_new_era();
assert_eq!(staking::era_length(), 1);
@@ -378,7 +378,7 @@ mod tests {
// Block 1: Make proposal. Will have only 1 vote. No change.
with_env(|e| e.block_number = 1);
public::propose(&one, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
function: Proposal::StakingSetSessionsPerEra(2),
});
public::approve(&four, 1);
staking::internal::check_new_era();
@@ -16,8 +16,8 @@
//! Main parachains logic. For now this is just the determination of which validators do what.
use runtime_std::prelude::*;
use runtime_std::mem;
use rstd::prelude::*;
use runtime_io::mem;
use codec::{Slicable, Joiner};
use support::{Hashable, with_env, storage};
use runtime::session;
@@ -96,7 +96,7 @@ pub fn calculate_duty_roster() -> DutyRoster {
#[cfg(test)]
mod tests {
use super::*;
use runtime_std::{with_externalities, twox_128, TestExternalities};
use runtime_io::{with_externalities, twox_128, TestExternalities};
use codec::{KeyedVec, Joiner};
use support::{one, two, with_env};
use runtime::{consensus, session};
@@ -17,10 +17,10 @@
//! Session manager: is told the validators and allows them to manage their session keys for the
//! consensus module.
use runtime_std::prelude::*;
use rstd::prelude::*;
use codec::KeyedVec;
use support::{storage, StorageVec};
use primitives::relay::{AccountId, SessionKey, BlockNumber};
use polkadot_primitives::{AccountId, SessionKey, BlockNumber};
use runtime::{system, staking, consensus};
const SESSION_LENGTH: &[u8] = b"ses:len";
@@ -137,7 +137,7 @@ mod tests {
use super::public::*;
use super::privileged::*;
use super::internal::*;
use runtime_std::{with_externalities, twox_128, TestExternalities};
use runtime_io::{with_externalities, twox_128, TestExternalities};
use codec::{KeyedVec, Joiner};
use support::{one, two, with_env};
use primitives::relay::AccountId;
@@ -16,12 +16,12 @@
//! Staking manager: Handles balances and periodically determines the best set of validators.
use runtime_std::prelude::*;
use runtime_std::cell::RefCell;
use runtime_std::print;
use rstd::prelude::*;
use runtime_io::cell::RefCell;
use runtime_io::print;
use codec::KeyedVec;
use support::{storage, StorageVec};
use primitives::relay::{BlockNumber, AccountId};
use polkadot_primitives::{BlockNumber, AccountId};
use runtime::{system, session, governance};
/// The balance of an account.
@@ -213,7 +213,7 @@ mod tests {
use super::public::*;
use super::privileged::*;
use runtime_std::{with_externalities, twox_128, TestExternalities};
use runtime_io::{with_externalities, twox_128, TestExternalities};
use codec::{KeyedVec, Joiner};
use support::{one, two, with_env};
use primitives::relay::AccountId;
@@ -17,12 +17,12 @@
//! System manager: Handles all of the top-level stuff; executing block/transaction, setting code
//! and depositing logs.
use runtime_std::prelude::*;
use runtime_std::{mem, storage_root, enumerated_trie_root};
use rstd::prelude::*;
use runtime_io::{mem, storage_root, enumerated_trie_root};
use codec::{KeyedVec, Slicable};
use support::{Hashable, storage, with_env};
use primitives::relay::{AccountId, Hash, TxOrder, BlockNumber, Block, Header, UncheckedTransaction,
Function, Log};
use polkadot_primitives::{AccountId, Hash, TxOrder, BlockNumber, Block, Header,
UncheckedTransaction, Function, Log};
use runtime::{staking, session};
const NONCE_OF: &[u8] = b"sys:non:";
@@ -218,7 +218,7 @@ mod tests {
use super::*;
use super::internal::*;
use runtime_std::{with_externalities, twox_128, TestExternalities};
use runtime_io::{with_externalities, twox_128, TestExternalities};
use codec::{Joiner, KeyedVec, Slicable};
use support::{StaticHexInto, HexDisplay, one, two};
use primitives::relay::{Header, Digest, UncheckedTransaction, Transaction, Function};
@@ -41,7 +41,7 @@ mod tests {
use super::*;
use super::public::*;
use runtime_std::{with_externalities, twox_128, TestExternalities};
use runtime_io::{with_externalities, twox_128, TestExternalities};
use runtime::timestamp;
use codec::{Joiner, KeyedVec};
@@ -16,12 +16,12 @@
//! Environment API: Allows certain information to be accessed throughout the runtime.
use runtime_std::boxed::Box;
use runtime_std::mem;
use runtime_std::cell::RefCell;
use runtime_std::rc::Rc;
use runtime_io::boxed::Box;
use runtime_io::mem;
use runtime_io::cell::RefCell;
use runtime_io::rc::Rc;
use primitives::relay::{BlockNumber, Digest, Hash};
use polkadot_primitives::{BlockNumber, Digest, Hash};
#[derive(Default)]
/// The information that can be accessed globally.
@@ -17,7 +17,7 @@
//! Hashable trait.
use codec::Slicable;
use runtime_std::{blake2_256, twox_128, twox_256};
use runtime_io::{blake2_256, twox_128, twox_256};
pub trait Hashable: Sized {
fn blake2_256(&self) -> [u8; 32];
@@ -16,15 +16,15 @@
//! Stuff to do with the runtime's storage.
use runtime_std::prelude::*;
use runtime_std::{self, twox_128};
use rstd::prelude::*;
use runtime_io::{self, twox_128};
use codec::{Slicable, KeyedVec};
// TODO: consider using blake256 to avoid possible preimage attack.
/// 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> {
let raw = runtime_std::storage(&twox_128(key)[..]);
let raw = runtime_io::storage(&twox_128(key)[..]);
Slicable::from_slice(&mut &raw[..])
}
@@ -48,12 +48,12 @@ pub fn get_or_else<T: Slicable + Sized, F: FnOnce() -> T>(key: &[u8], default_va
/// Please `value` in storage under `key`.
pub fn put<T: Slicable>(key: &[u8], value: &T) {
value.as_slice_then(|slice| runtime_std::set_storage(&twox_128(key)[..], slice));
value.as_slice_then(|slice| runtime_io::set_storage(&twox_128(key)[..], slice));
}
/// Please `value` in storage under `key`.
pub fn place<T: Slicable>(key: &[u8], value: T) {
value.as_slice_then(|slice| runtime_std::set_storage(&twox_128(key)[..], slice));
value.as_slice_then(|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.
@@ -86,22 +86,22 @@ pub fn take_or_else<T: Slicable + Sized, F: FnOnce() -> T>(key: &[u8], default_v
/// Check to see if `key` has an explicit entry in storage.
pub fn exists(key: &[u8]) -> bool {
let mut x = [0u8; 1];
runtime_std::read_storage(&twox_128(key)[..], &mut x[..], 0) >= 1
runtime_io::read_storage(&twox_128(key)[..], &mut x[..], 0) >= 1
}
/// Ensure `key` has no explicit entry in storage.
pub fn kill(key: &[u8]) {
runtime_std::set_storage(&twox_128(key)[..], b"");
runtime_io::set_storage(&twox_128(key)[..], b"");
}
/// Get a Vec of bytes from storage.
pub fn get_raw(key: &[u8]) -> Vec<u8> {
runtime_std::storage(&twox_128(key)[..])
runtime_io::storage(&twox_128(key)[..])
}
/// Put a raw byte slice into storage.
pub fn put_raw(key: &[u8], value: &[u8]) {
runtime_std::set_storage(&twox_128(key)[..], value)
runtime_io::set_storage(&twox_128(key)[..], value)
}
/// A trait to conveniently store a vector of storable data.
@@ -142,11 +142,11 @@ pub trait StorageVec {
}
pub mod unhashed {
use super::{runtime_std, Slicable, KeyedVec, Vec};
use super::{runtime_io, Slicable, KeyedVec, Vec};
/// 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> {
let raw = runtime_std::storage(key);
let raw = runtime_io::storage(key);
T::from_slice(&mut &raw[..])
}
@@ -170,12 +170,12 @@ pub mod unhashed {
/// Please `value` in storage under `key`.
pub fn put<T: Slicable>(key: &[u8], value: &T) {
value.as_slice_then(|slice| runtime_std::set_storage(key, slice));
value.as_slice_then(|slice| runtime_io::set_storage(key, slice));
}
/// Please `value` in storage under `key`.
pub fn place<T: Slicable>(key: &[u8], value: T) {
value.as_slice_then(|slice| runtime_std::set_storage(key, slice));
value.as_slice_then(|slice| runtime_io::set_storage(key, slice));
}
/// Remove `key` from storage, returning its value if it had an explicit entry or `None` otherwise.
@@ -208,22 +208,22 @@ pub mod unhashed {
/// Check to see if `key` has an explicit entry in storage.
pub fn exists(key: &[u8]) -> bool {
let mut x = [0u8; 1];
runtime_std::read_storage(key, &mut x[..], 0) >= 1
runtime_io::read_storage(key, &mut x[..], 0) >= 1
}
/// Ensure `key` has no explicit entry in storage.
pub fn kill(key: &[u8]) {
runtime_std::set_storage(key, b"");
runtime_io::set_storage(key, b"");
}
/// Get a Vec of bytes from storage.
pub fn get_raw(key: &[u8]) -> Vec<u8> {
runtime_std::storage(key)
runtime_io::storage(key)
}
/// Put a raw byte slice into storage.
pub fn put_raw(key: &[u8], value: &[u8]) {
runtime_std::set_storage(key, value)
runtime_io::set_storage(key, value)
}
/// A trait to conveniently store a vector of storable data.
@@ -269,7 +269,7 @@ mod tests {
use super::*;
use std::collections::HashMap;
use support::HexDisplay;
use runtime_std::{storage, twox_128, TestExternalities, with_externalities};
use runtime_io::{storage, twox_128, TestExternalities, with_externalities};
#[test]
fn integers_can_be_stored() {
@@ -310,7 +310,7 @@ mod tests {
fn vecs_can_be_retrieved() {
let mut t = TestExternalities { storage: HashMap::new(), };
with_externalities(&mut t, || {
runtime_std::set_storage(&twox_128(b":test"), b"\x0b\0\0\0Hello world");
runtime_io::set_storage(&twox_128(b":test"), b"\x0b\0\0\0Hello world");
let x = b"Hello world".to_vec();
println!("Hex: {}", HexDisplay::from(&storage(&twox_128(b":test"))));
let y = get::<Vec<u8>>(b":test").unwrap();
@@ -16,7 +16,7 @@
//! Testing helpers.
use primitives::relay::AccountId;
use polkadot_primitives::AccountId;
use super::statichex::StaticHexInto;
#[macro_export]
+1 -1
View File
@@ -7,4 +7,4 @@ authors = ["Parity Technologies <admin@parity.io>"]
crate-type = ["cdylib"]
[dependencies]
polkadot-runtime-std = { path = "../../runtime-std", version = "0.1", default_features = false }
substrate-runtime-io = { path = "../../runtime-io", version = "0.1", default_features = false }
+2 -2
View File
@@ -7,8 +7,8 @@ extern crate alloc;
use alloc::vec::Vec;
#[macro_use]
extern crate polkadot_runtime_std as runtime_std;
use runtime_std::{
extern crate substrate_runtime_io as runtime_io;
use runtime_io::{
set_storage, storage, print, blake2_256,
twox_128, twox_256, ed25519_verify, enumerated_trie_root
};