Merge pull request #60 from paritytech/gav-refactor-primitives

Start isolating Substrate code from Polkadot
This commit is contained in:
Gav Wood
2018-02-07 17:43:34 +01:00
committed by GitHub
97 changed files with 1581 additions and 1373 deletions
+119 -87
View File
@@ -195,9 +195,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
name = "ed25519"
version = "0.1.0"
dependencies = [
"polkadot-primitives 0.1.0",
"ring 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-primitives 0.1.0",
"untrusted 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -828,9 +828,11 @@ 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-primitives 0.1.0",
"polkadot-runtime-codec 0.1.0",
"polkadot-runtime-std 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]]
@@ -988,9 +990,9 @@ dependencies = [
"error-chain 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-client 0.1.0",
"polkadot-executor 0.1.0",
"polkadot-primitives 0.1.0",
"polkadot-rpc-servers 0.1.0",
"substrate-executor 0.1.0",
"substrate-primitives 0.1.0",
]
[[package]]
@@ -1003,11 +1005,12 @@ dependencies = [
"log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
"native-runtime 0.1.0",
"parking_lot 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-executor 0.1.0",
"polkadot-primitives 0.1.0",
"polkadot-runtime-codec 0.1.0",
"polkadot-serializer 0.1.0",
"polkadot-state-machine 0.1.0",
"substrate-codec 0.1.0",
"substrate-executor 0.1.0",
"substrate-primitives 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)",
]
@@ -1017,29 +1020,7 @@ version = "0.1.0"
dependencies = [
"futures 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-primitives 0.1.0",
]
[[package]]
name = "polkadot-executor"
version = "0.1.0"
dependencies = [
"assert_matches 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"ed25519 0.1.0",
"error-chain 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
"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)",
"native-runtime 0.1.0",
"parity-wasm 0.15.4 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-primitives 0.1.0",
"polkadot-runtime-codec 0.1.0",
"polkadot-runtime-std 0.1.0",
"polkadot-serializer 0.1.0",
"polkadot-state-machine 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)",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-primitives 0.1.0",
]
[[package]]
@@ -1057,32 +1038,28 @@ dependencies = [
"parking_lot 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-client 0.1.0",
"polkadot-primitives 0.1.0",
"polkadot-serializer 0.1.0",
"polkadot-state-machine 0.1.0",
"rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)",
"semver 0.6.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)",
"serde_json 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)",
"smallvec 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-primitives 0.1.0",
"substrate-serializer 0.1.0",
"substrate-state-machine 0.1.0",
]
[[package]]
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)",
"polkadot-runtime-codec 0.1.0",
"polkadot-serializer 0.1.0",
"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)",
"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)",
"substrate-codec 0.1.0",
"substrate-primitives 0.1.0",
"substrate-runtime-std 0.1.0",
"substrate-serializer 0.1.0",
]
[[package]]
@@ -1094,9 +1071,9 @@ dependencies = [
"jsonrpc-core 8.0.1 (git+https://github.com/paritytech/jsonrpc.git)",
"jsonrpc-macros 8.0.0 (git+https://github.com/paritytech/jsonrpc.git)",
"polkadot-client 0.1.0",
"polkadot-executor 0.1.0",
"polkadot-primitives 0.1.0",
"polkadot-state-machine 0.1.0",
"substrate-executor 0.1.0",
"substrate-primitives 0.1.0",
"substrate-state-machine 0.1.0",
]
[[package]]
@@ -1108,54 +1085,15 @@ dependencies = [
"polkadot-rpc 0.1.0",
]
[[package]]
name = "polkadot-runtime-codec"
version = "0.1.0"
[[package]]
name = "polkadot-runtime-std"
version = "0.1.0"
dependencies = [
"ed25519 0.1.0",
"environmental 0.1.0",
"polkadot-primitives 0.1.0",
"polkadot-runtime-codec 0.1.0",
"polkadot-state-machine 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)",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "polkadot-serializer"
version = "0.1.0"
dependencies = [
"serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "polkadot-state-machine"
version = "0.1.0"
dependencies = [
"byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"hashdb 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"hex-literal 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"memorydb 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"patricia-trie 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-primitives 0.1.0",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "polkadot-validator"
version = "0.1.0"
dependencies = [
"error-chain 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-primitives 0.1.0",
"polkadot-serializer 0.1.0",
"serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-primitives 0.1.0",
"substrate-serializer 0.1.0",
]
[[package]]
@@ -1475,6 +1413,100 @@ name = "strsim"
version = "0.7.0"
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"
version = "0.1.0"
dependencies = [
"assert_matches 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"ed25519 0.1.0",
"error-chain 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
"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)",
"native-runtime 0.1.0",
"parity-wasm 0.15.4 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-primitives 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)",
]
[[package]]
name = "substrate-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-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"
dependencies = [
"serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "substrate-state-machine"
version = "0.1.0"
dependencies = [
"byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"hashdb 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"hex-literal 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"memorydb 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"patricia-trie 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-primitives 0.1.0",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "subtle"
version = "0.1.0"
+3 -1
View File
@@ -20,7 +20,9 @@ members = [
"primitives",
"rpc-servers",
"rpc",
"runtime-codec",
"codec",
"polkadot-primitives",
"runtime-io",
"runtime-std",
"serializer",
"state-machine",
+4 -4
View File
@@ -9,7 +9,7 @@ clap = { version = "2.27", features = ["yaml"] }
env_logger = "0.4"
error-chain = "0.11"
log = "0.3"
polkadot-client = { path = "../client", version = "0.1" }
polkadot-executor = { path = "../executor", version = "0.1" }
polkadot-primitives = { path = "../primitives", version = "0.1" }
polkadot-rpc-servers = { path = "../rpc-servers", version = "0.1" }
polkadot-client = { path = "../client" }
substrate-executor = { path = "../executor" }
substrate-primitives = { path = "../primitives" }
polkadot-rpc-servers = { path = "../rpc-servers" }
+2 -2
View File
@@ -20,8 +20,8 @@
extern crate env_logger;
extern crate polkadot_client as client;
extern crate polkadot_executor as executor;
extern crate polkadot_primitives as primitives;
extern crate substrate_executor as executor;
extern crate substrate_primitives as primitives;
extern crate polkadot_rpc_servers as rpc;
#[macro_use]
+6 -5
View File
@@ -7,11 +7,12 @@ authors = ["Parity Technologies <admin@parity.io>"]
error-chain = "0.11"
log = "0.3"
parking_lot = "0.4"
polkadot-primitives = { path = "../primitives", version = "0.1" }
polkadot-state-machine = { path = "../state-machine", version = "0.1" }
polkadot-serializer = { path = "../serializer" }
polkadot-executor = { path = "../executor" }
polkadot-runtime-codec = { path = "../runtime-codec", version = "0.1" }
polkadot-primitives = { path = "../polkadot-primitives", version = "0.1" }
substrate-primitives = { path = "../primitives", version = "0.1" }
substrate-state-machine = { path = "../state-machine", version = "0.1" }
substrate-serializer = { path = "../serializer" }
substrate-executor = { path = "../executor" }
substrate-codec = { path = "../codec", version = "0.1" }
native-runtime = { path = "../native-runtime" }
triehash = "0.1"
hex-literal = "0.1"
+1 -2
View File
@@ -18,7 +18,7 @@
use state_machine;
use error;
use primitives::relay::block;
use primitives::block;
use blockchain::{self, BlockId};
/// Block insertion transction. Keeps hold if the inseted block state and data.
@@ -50,4 +50,3 @@ pub trait Backend {
/// Returns state backend for specified block.
fn state_at(&self, block: BlockId) -> error::Result<Self::State>;
}
+1 -2
View File
@@ -17,7 +17,7 @@
//! Polkadot blockchain trait
use std::fmt::{Display, Formatter, Error as FmtError};
use primitives::relay::block;
use primitives::block;
use error::Result;
/// Block indentification.
@@ -83,4 +83,3 @@ pub enum BlockStatus {
/// Not in the queue or the blockchain.
Unknown,
}
+7 -8
View File
@@ -17,7 +17,7 @@
//! Tool for creating the genesis block.
use std::collections::HashMap;
use primitives::relay::{Block, Header};
use polkadot_primitives::{Block, Header};
use triehash::trie_root;
/// Create a genesis block, given the initial storage.
@@ -45,10 +45,9 @@ mod tests {
use state_machine::execute;
use state_machine::OverlayedChanges;
use state_machine::backend::InMemory;
use polkadot_executor::executor;
use primitives::{AccountId, Hash};
use primitives::relay::{BlockNumber, Header, Digest, UncheckedTransaction, Transaction, Function};
use primitives::contract::CallData;
use substrate_executor::executor;
use polkadot_primitives::{AccountId, Hash, BlockNumber, Header, Digest, UncheckedTransaction,
Transaction, Function};
use ed25519::Pair;
fn secret_for(who: &AccountId) -> Option<Pair> {
@@ -88,7 +87,7 @@ mod tests {
&mut overlay,
&executor(),
"execute_transaction",
&CallData(vec![].join(&header).join(tx))
&vec![].join(&header).join(tx)
).unwrap();
header = Header::from_slice(&mut &ret_data[..]).unwrap();
}
@@ -98,7 +97,7 @@ mod tests {
&mut overlay,
&executor(),
"finalise_block",
&CallData(vec![].join(&header))
&vec![].join(&header)
).unwrap();
header = Header::from_slice(&mut &ret_data[..]).unwrap();
@@ -137,7 +136,7 @@ mod tests {
&mut overlay,
&executor(),
"execute_block",
&CallData(b1data)
&b1data
).unwrap();
}
}
+1 -2
View File
@@ -23,7 +23,7 @@ use error;
use backend;
use primitives;
use ser;
use primitives::relay::block::{self, HeaderHash};
use primitives::block::{self, HeaderHash};
use blockchain::{self, BlockId, BlockStatus};
fn header_hash(header: &block::Header) -> block::HeaderHash {
@@ -201,4 +201,3 @@ impl backend::Backend for Backend {
}
}
}
+9 -8
View File
@@ -18,11 +18,12 @@
#![warn(missing_docs)]
extern crate polkadot_primitives as primitives;
extern crate polkadot_state_machine as state_machine;
extern crate polkadot_serializer as ser;
extern crate polkadot_runtime_codec as codec;
extern crate polkadot_executor;
extern crate polkadot_primitives;
extern crate substrate_primitives as primitives;
extern crate substrate_state_machine as state_machine;
extern crate substrate_serializer as ser;
extern crate substrate_codec as codec;
extern crate substrate_executor;
extern crate native_runtime;
extern crate ed25519;
@@ -47,8 +48,8 @@ pub use genesis::construct_genesis_block;
pub use blockchain::Info as ChainInfo;
pub use blockchain::BlockId;
use primitives::relay::block;
use primitives::contract::{CallData, StorageKey, StorageData};
use primitives::block;
use primitives::storage::{StorageKey, StorageData};
use blockchain::Backend as BlockchainBackend;
use backend::BlockImportOperation;
@@ -156,7 +157,7 @@ impl<B, E> Client<B, E> where
/// Execute a call to a contract on top of state in a block of given hash.
///
/// No changes are made.
pub fn call(&self, hash: &block::HeaderHash, method: &str, call_data: &CallData) -> error::Result<CallResult> {
pub fn call(&self, hash: &block::HeaderHash, method: &str, call_data: &[u8]) -> error::Result<CallResult> {
let state = self.state_at(hash)?;
let mut changes = state_machine::OverlayedChanges::default();
@@ -1,11 +1,12 @@
[package]
name = "polkadot-runtime-codec"
name = "substrate-codec"
description = "Serialization and deserialization codec for runtime values"
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,18 +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/>.
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Endian manager.
@@ -1,22 +1,22 @@
// 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/>.
//! Trait
use std::iter::Extend;
use rstd::iter::Extend;
use super::slicable::Slicable;
/// Trait to allow itself to be serialised into a value which can be extended
@@ -1,24 +1,24 @@
// 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/>.
//! Serialiser and prepender.
use slicable::Slicable;
use std::iter::Extend;
use std::vec::Vec;
use rstd::iter::Extend;
use rstd::vec::Vec;
/// Trait to allow itselg to be serialised and prepended by a given slice.
pub trait KeyedVec {
@@ -1,18 +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/>.
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Implements the serialization and deserialization codec for polkadot runtime
//! values.
@@ -20,6 +20,8 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(alloc))]
extern crate substrate_runtime_std as rstd;
mod endiansensitive;
mod slicable;
mod joiner;
@@ -29,11 +31,3 @@ pub use self::endiansensitive::EndianSensitive;
pub use self::slicable::{Slicable, NonTrivialSlicable};
pub use self::joiner::Joiner;
pub use self::keyedvec::KeyedVec;
#[cfg(not(feature = "std"))]
mod std {
extern crate alloc;
pub use core::*;
pub use self::alloc::vec;
}
@@ -1,23 +1,23 @@
// 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/>.
//! Serialisation.
use std::{mem, slice};
use std::vec::Vec;
use rstd::{mem, slice};
use rstd::vec::Vec;
use super::joiner::Joiner;
use super::endiansensitive::EndianSensitive;
@@ -44,7 +44,7 @@ impl<T: EndianSensitive> Slicable for T {
let size = mem::size_of::<T>();
assert!(size > 0, "EndianSensitive can never be implemented for a zero-sized type.");
if value.len() >= size {
let x: T = unsafe { ::std::ptr::read(value.as_ptr() as *const T) };
let x: T = unsafe { ::rstd::ptr::read(value.as_ptr() as *const T) };
*value = &value[size..];
Some(x.from_le())
} else {
@@ -115,7 +115,7 @@ impl<T: NonTrivialSlicable> Slicable for Vec<T> {
}
fn to_vec(&self) -> Vec<u8> {
use std::iter::Extend;
use rstd::iter::Extend;
let len = self.len();
assert!(len <= u32::max_value() as usize, "Attempted to serialize vec with too many elements.");
+2 -1
View File
@@ -5,5 +5,6 @@ authors = ["Parity Technologies <rphmeier@gmail.com>"]
description = "Abstract collation logic"
[dependencies]
polkadot-primitives = { path = "../primitives", version = "0.1" }
substrate-primitives = { path = "../primitives", version = "0.1" }
polkadot-primitives = { path = "../polkadot-primitives", version = "0.1" }
futures = "0.1.17"
+5 -4
View File
@@ -45,12 +45,13 @@
//! to be performed, as the collation logic itself.
extern crate futures;
extern crate polkadot_primitives as primitives;
extern crate substrate_primitives as primitives;
extern crate polkadot_primitives;
use std::collections::{BTreeSet, BTreeMap};
use futures::{stream, Stream, Future, IntoFuture};
use primitives::parachain::{self, ConsolidatedIngress, Message, Id as ParaId};
use polkadot_primitives::parachain::{self, ConsolidatedIngress, Message, Id as ParaId};
/// Parachain context needed for collation.
///
@@ -60,7 +61,7 @@ pub trait ParachainContext {
fn produce_candidate<I: IntoIterator<Item=(ParaId, Message)>>(
&self,
ingress: I,
) -> (parachain::BlockData, primitives::Signature);
) -> (parachain::BlockData, polkadot_primitives::Signature);
}
/// Relay chain context needed to collate.
@@ -150,7 +151,7 @@ mod tests {
use std::collections::{HashMap, BTreeSet};
use futures::Future;
use primitives::parachain::{Message, Id as ParaId};
use polkadot_primitives::parachain::{Message, Id as ParaId};
pub struct DummyRelayChainCtx {
egresses: HashMap<ParaId, Vec<Vec<Message>>>,
+1 -1
View File
@@ -6,5 +6,5 @@ authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
ring = "0.12"
untrusted = "0.5"
polkadot-primitives = { version = "0.1", path = "../primitives" }
substrate-primitives = { version = "0.1", path = "../primitives" }
rustc-hex = "1.0"
+9 -6
View File
@@ -1,30 +1,33 @@
// 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/>.
//! Simple Ed25519 API.
extern crate ring;
extern crate polkadot_primitives as primitives;
extern crate substrate_primitives as primitives;
extern crate untrusted;
extern crate rustc_hex;
use ring::{rand, signature};
use primitives::Signature;
use primitives::hash::H512;
use rustc_hex::FromHex;
/// Alias to 520-bit hash when used in the context of a signature on the relay chain.
pub type Signature = H512;
/// Verify a message without type checking the parameters' types for the right size.
pub fn verify(sig: &[u8], message: &[u8], public: &[u8]) -> bool {
let public_key = untrusted::Input::from(public);
+10 -8
View File
@@ -1,25 +1,27 @@
[package]
name = "polkadot-executor"
name = "substrate-executor"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
error-chain = "0.11"
polkadot-runtime-codec = { path = "../runtime-codec", version = "0.1" }
polkadot-runtime-std = { path = "../runtime-std", version = "0.1" }
polkadot-primitives = { path = "../primitives", version = "0.1" }
polkadot-serializer = { path = "../serializer", version = "0.1" }
polkadot-state-machine = { path = "../state-machine" , version = "0.1" }
substrate-codec = { path = "../codec" }
substrate-runtime-io = { path = "../runtime-io" }
substrate-primitives = { path = "../primitives" }
substrate-serializer = { path = "../serializer" }
substrate-state-machine = { path = "../state-machine" }
ed25519 = { path = "../ed25519" }
serde = "1.0"
serde_derive = "1.0"
parity-wasm = "0.15.0"
byteorder = "1.1"
rustc-hex = "1.0.0"
native-runtime = { path = "../native-runtime", version = "0.1" }
triehash = "0.1.0"
ed25519 = { path = "../ed25519", version = "0.1" }
hex-literal = "0.1.0"
log = "0.3"
# TODO: Remove these and split out tests and a concrete executor.
native-runtime = { path = "../native-runtime" }
polkadot-primitives = { path = "../polkadot-primitives" }
[dev-dependencies]
assert_matches = "1.1"
+4 -4
View File
@@ -1,18 +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/>.
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Rust executor possible errors.
+13 -10
View File
@@ -1,18 +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/>.
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Temporary crate for contracts implementations.
//!
@@ -27,21 +27,24 @@
#![warn(missing_docs)]
extern crate polkadot_runtime_codec as codec;
extern crate polkadot_runtime_std as runtime_std;
extern crate polkadot_primitives as primitives;
extern crate polkadot_serializer as serializer;
extern crate polkadot_state_machine as state_machine;
extern crate substrate_codec as codec;
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;
extern crate ed25519;
extern crate serde;
extern crate parity_wasm;
extern crate byteorder;
extern crate rustc_hex;
extern crate native_runtime;
extern crate triehash;
#[macro_use] extern crate log;
// TODO: Remove and split out into polkadot-specific crate.
extern crate native_runtime;
extern crate polkadot_primitives;
#[cfg(test)]
#[macro_use]
extern crate hex_literal;
+30 -30
View File
@@ -1,23 +1,22 @@
// 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/>.
use error::{Error, ErrorKind, Result};
use native_runtime as runtime;
use primitives::contract::CallData;
use runtime_std;
use runtime_io;
use state_machine::{Externalities, CodeExecutor};
use wasm_executor::WasmExecutor;
@@ -37,16 +36,16 @@ impl CodeExecutor for NativeExecutor {
ext: &mut E,
code: &[u8],
method: &str,
data: &CallData,
data: &[u8],
) -> Result<Vec<u8>> {
// WARNING!!! This assumes that the runtime was built *before* the main project. Until we
// 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 {
"execute_block" => safe_call(|| runtime::execute_block(&data.0)),
"execute_transaction" => safe_call(|| runtime::execute_transaction(&data.0)),
"finalise_block" => safe_call(|| runtime::finalise_block(&data.0)),
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)),
_ => Err(ErrorKind::MethodNotFound(method.to_owned()).into()),
})
} else {
@@ -63,8 +62,9 @@ mod tests {
use native_runtime::support::{one, two, Hashable};
use native_runtime::runtime::staking::balance;
use state_machine::TestExternalities;
use primitives::{twox_128, Hash};
use primitives::relay::{Header, BlockNumber, Block, Digest, Transaction, UncheckedTransaction, Function};
use primitives::twox_128;
use polkadot_primitives::{Hash, Header, BlockNumber, Block, Digest, Transaction,
UncheckedTransaction, Function, AccountId};
use ed25519::Pair;
const BLOATY_CODE: &[u8] = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.wasm");
@@ -89,7 +89,7 @@ mod tests {
twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![68u8, 0, 0, 0, 0, 0, 0, 0]
], };
let r = NativeExecutor.call(&mut t, BLOATY_CODE, "execute_transaction", &CallData(vec![].join(&Header::from_block_number(1u64)).join(&tx())));
let r = NativeExecutor.call(&mut t, BLOATY_CODE, "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx()));
assert!(r.is_err());
}
@@ -100,7 +100,7 @@ mod tests {
twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![68u8, 0, 0, 0, 0, 0, 0, 0]
], };
let r = NativeExecutor.call(&mut t, COMPACT_CODE, "execute_transaction", &CallData(vec![].join(&Header::from_block_number(1u64)).join(&tx())));
let r = NativeExecutor.call(&mut t, COMPACT_CODE, "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx()));
assert!(r.is_err());
}
@@ -113,10 +113,10 @@ mod tests {
twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![111u8, 0, 0, 0, 0, 0, 0, 0]
], };
let r = NativeExecutor.call(&mut t, COMPACT_CODE, "execute_transaction", &CallData(vec![].join(&Header::from_block_number(1u64)).join(&tx())));
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);
});
@@ -131,10 +131,10 @@ mod tests {
twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![111u8, 0, 0, 0, 0, 0, 0, 0]
], };
let r = NativeExecutor.call(&mut t, BLOATY_CODE, "execute_transaction", &CallData(vec![].join(&Header::from_block_number(1u64)).join(&tx())));
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);
});
@@ -164,7 +164,7 @@ mod tests {
], }
}
fn secret_for(who: &::primitives::AccountId) -> Option<Pair> {
fn secret_for(who: &AccountId) -> Option<Pair> {
match who {
x if *x == one() => Some(Pair::from_seed(b"12345678901234567890123456789012")),
x if *x == two() => Some("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60".into()),
@@ -213,7 +213,7 @@ mod tests {
construct_block(
2,
block1().1,
hex!("e2ba57cfb94b870ea6670b012b49dc33cbb70e3aa8d36cf54dfa5e4e69cd0778").into(),
hex!("1feb4d3a2e587079e6ce1685fa79994efd995e33cb289d39cded67aac1bb46a9").into(),
vec![
Transaction {
signed: two(),
@@ -233,7 +233,7 @@ mod tests {
fn test_execution_works() {
let mut t = new_test_ext();
println!("Testing Wasm...");
let r = WasmExecutor.call(&mut t, COMPACT_CODE, "run_tests", &CallData(block2().0));
let r = WasmExecutor.call(&mut t, COMPACT_CODE, "run_tests", &block2().0);
assert!(r.is_ok());
}
@@ -241,16 +241,16 @@ mod tests {
fn full_native_block_import_works() {
let mut t = new_test_ext();
NativeExecutor.call(&mut t, COMPACT_CODE, "execute_block", &CallData(block1().0)).unwrap();
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", &CallData(block2().0)).unwrap();
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);
});
@@ -260,16 +260,16 @@ mod tests {
fn full_wasm_block_import_works() {
let mut t = new_test_ext();
WasmExecutor.call(&mut t, COMPACT_CODE, "execute_block", &CallData(block1().0)).unwrap();
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", &CallData(block2().0)).unwrap();
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);
});
+31 -32
View File
@@ -1,20 +1,20 @@
// 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/>.
//! Rust implementation of Polkadot contracts.
//! Rust implementation of Substrate contracts.
use std::sync::Arc;
use std::cmp::Ordering;
@@ -22,7 +22,6 @@ use std::collections::HashMap;
use parity_wasm::{deserialize_buffer, ModuleInstanceInterface, ProgramInstance};
use parity_wasm::interpreter::{ItemIndex, DummyUserError};
use parity_wasm::RuntimeValue::{I32, I64};
use primitives::contract::CallData;
use state_machine::{Externalities, CodeExecutor};
use error::{Error, ErrorKind, Result};
use wasm_utils::{MemoryInstance, UserDefinedElements,
@@ -118,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)?;
@@ -250,7 +249,7 @@ impl CodeExecutor for WasmExecutor {
ext: &mut E,
code: &[u8],
method: &str,
data: &CallData,
data: &[u8],
) -> Result<Vec<u8>> {
// TODO: handle all expects as errors to be returned.
@@ -262,9 +261,9 @@ impl CodeExecutor for WasmExecutor {
let memory = module.memory(ItemIndex::Internal(0)).expect("all modules compiled with rustc include memory segments; qed");
let mut fec = FunctionExecutor::new(&memory, ext);
let size = data.0.len() as u32;
let size = data.len() as u32;
let offset = fec.heap.allocate(size);
memory.set(offset, &data.0).expect("heap always gives a sensible offset to write");
memory.set(offset, &data).expect("heap always gives a sensible offset to write");
let returned = program
.params_with_external("env", &mut fec)
@@ -293,9 +292,9 @@ mod tests {
use native_runtime::support::{one, two};
use native_runtime::runtime::staking::balance;
use state_machine::TestExternalities;
use primitives::{twox_128, AccountId};
use primitives::relay::{Header, Transaction, UncheckedTransaction, Function};
use runtime_std;
use primitives::twox_128;
use polkadot_primitives::{Header, Transaction, UncheckedTransaction, Function, AccountId};
use runtime_io;
use ed25519::Pair;
fn secret_for(who: &AccountId) -> Option<Pair> {
@@ -323,7 +322,7 @@ mod tests {
let mut ext = TestExternalities::default();
let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm");
let output = WasmExecutor.call(&mut ext, &test_code[..], "test_empty_return", &CallData(vec![])).unwrap();
let output = WasmExecutor.call(&mut ext, &test_code[..], "test_empty_return", &[]).unwrap();
assert_eq!(output, vec![0u8; 0]);
}
@@ -332,10 +331,10 @@ mod tests {
let mut ext = TestExternalities::default();
let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm");
let output = WasmExecutor.call(&mut ext, &test_code[..], "test_panic", &CallData(vec![]));
let output = WasmExecutor.call(&mut ext, &test_code[..], "test_panic", &[]);
assert!(output.is_err());
let output = WasmExecutor.call(&mut ext, &test_code[..], "test_conditional_panic", &CallData(vec![2]));
let output = WasmExecutor.call(&mut ext, &test_code[..], "test_conditional_panic", &[2]);
assert!(output.is_err());
}
@@ -345,7 +344,7 @@ mod tests {
ext.set_storage(b"foo".to_vec(), b"bar".to_vec());
let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm");
let output = WasmExecutor.call(&mut ext, &test_code[..], "test_data_in", &CallData(b"Hello world".to_vec())).unwrap();
let output = WasmExecutor.call(&mut ext, &test_code[..], "test_data_in", b"Hello world").unwrap();
assert_eq!(output, b"all ok!".to_vec());
@@ -362,11 +361,11 @@ mod tests {
let mut ext = TestExternalities::default();
let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm");
assert_eq!(
WasmExecutor.call(&mut ext, &test_code[..], "test_blake2_256", &CallData(b"".to_vec())).unwrap(),
WasmExecutor.call(&mut ext, &test_code[..], "test_blake2_256", &[]).unwrap(),
blake2_256(&b""[..]).to_vec()
);
assert_eq!(
WasmExecutor.call(&mut ext, &test_code[..], "test_blake2_256", &CallData(b"Hello world!".to_vec())).unwrap(),
WasmExecutor.call(&mut ext, &test_code[..], "test_blake2_256", b"Hello world!").unwrap(),
blake2_256(&b"Hello world!"[..]).to_vec()
);
}
@@ -376,11 +375,11 @@ mod tests {
let mut ext = TestExternalities::default();
let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm");
assert_eq!(
WasmExecutor.call(&mut ext, &test_code[..], "test_twox_256", &CallData(b"".to_vec())).unwrap(),
WasmExecutor.call(&mut ext, &test_code[..], "test_twox_256", &[]).unwrap(),
FromHex::from_hex("99e9d85137db46ef4bbea33613baafd56f963c64b1f3685a4eb4abd67ff6203a").unwrap()
);
assert_eq!(
WasmExecutor.call(&mut ext, &test_code[..], "test_twox_256", &CallData(b"Hello world!".to_vec())).unwrap(),
WasmExecutor.call(&mut ext, &test_code[..], "test_twox_256", b"Hello world!").unwrap(),
FromHex::from_hex("b27dfd7f223f177f2a13647b533599af0c07f68bda23d96d059da2b451a35a74").unwrap()
);
}
@@ -390,11 +389,11 @@ mod tests {
let mut ext = TestExternalities::default();
let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm");
assert_eq!(
WasmExecutor.call(&mut ext, &test_code[..], "test_twox_128", &CallData(b"".to_vec())).unwrap(),
WasmExecutor.call(&mut ext, &test_code[..], "test_twox_128", &[]).unwrap(),
FromHex::from_hex("99e9d85137db46ef4bbea33613baafd5").unwrap()
);
assert_eq!(
WasmExecutor.call(&mut ext, &test_code[..], "test_twox_128", &CallData(b"Hello world!".to_vec())).unwrap(),
WasmExecutor.call(&mut ext, &test_code[..], "test_twox_128", b"Hello world!").unwrap(),
FromHex::from_hex("b27dfd7f223f177f2a13647b533599af").unwrap()
);
}
@@ -409,7 +408,7 @@ mod tests {
calldata.extend_from_slice(key.public().as_ref());
calldata.extend_from_slice(sig.as_ref());
assert_eq!(
WasmExecutor.call(&mut ext, &test_code[..], "test_ed25519_verify", &CallData(calldata)).unwrap(),
WasmExecutor.call(&mut ext, &test_code[..], "test_ed25519_verify", &calldata).unwrap(),
vec![0]
);
}
@@ -419,7 +418,7 @@ mod tests {
let mut ext = TestExternalities::default();
let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm");
assert_eq!(
WasmExecutor.call(&mut ext, &test_code[..], "test_enumerated_trie_root", &CallData(vec![])).unwrap(),
WasmExecutor.call(&mut ext, &test_code[..], "test_enumerated_trie_root", &[]).unwrap(),
ordered_trie_root(vec![b"zero".to_vec(), b"one".to_vec(), b"two".to_vec()]).0.to_vec()
);
}
@@ -432,7 +431,7 @@ mod tests {
], };
let foreign_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.wasm");
let r = WasmExecutor.call(&mut t, &foreign_code[..], "execute_transaction", &CallData(vec![].join(&Header::from_block_number(1u64)).join(&tx())));
let r = WasmExecutor.call(&mut t, &foreign_code[..], "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx()));
assert!(r.is_err());
}
@@ -446,10 +445,10 @@ mod tests {
], };
let foreign_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.compact.wasm");
let r = WasmExecutor.call(&mut t, &foreign_code[..], "execute_transaction", &CallData(vec![].join(&Header::from_block_number(1u64)).join(&tx())));
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);
});
+5 -5
View File
@@ -1,20 +1,20 @@
// 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/>.
//! Rust implementation of Polkadot contracts.
//! Rust implementation of Substrate contracts.
use std::sync::{Arc};
use std::collections::HashMap;
+6 -4
View File
@@ -4,13 +4,15 @@ version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
polkadot-runtime-codec = { path = "../runtime-codec", version = "0.1" }
polkadot-runtime-std = { path = "../runtime-std", version = "0.1" }
polkadot-primitives = { path = "../primitives", version = "0.1" }
substrate-codec = { path = "../codec", 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 = ["polkadot-runtime-codec/std", "polkadot-runtime-std/std", "polkadot-primitives/std", "log"]
std = ["substrate-codec/std", "substrate-runtime-std/std", "substrate-runtime-io/std", "substrate-primitives/std", "polkadot-primitives/std", "log"]
+4 -3
View File
@@ -10,10 +10,11 @@ authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
ethcore-network = { git = "https://github.com/paritytech/parity.git" }
ethcore-io = { git = "https://github.com/paritytech/parity.git" }
polkadot-primitives = { path = "../primitives" }
substrate-primitives = { path = "../primitives" }
polkadot-primitives = { path = "../polkadot-primitives" }
polkadot-client = { path = "../client" }
polkadot-state-machine = { path = "../state-machine" }
polkadot-serializer = { path = "../serializer" }
substrate-state-machine = { path = "../state-machine" }
substrate-serializer = { path = "../serializer" }
log = "0.3"
env_logger = "0.4"
rand = "0.3"
+2 -3
View File
@@ -20,7 +20,7 @@ use std::ops::Range;
use std::collections::{HashMap, BTreeMap};
use std::collections::hash_map::Entry;
use network::PeerId;
use primitives::relay::BlockNumber;
use primitives::block::Number as BlockNumber;
use message;
const MAX_PARALLEL_DOWNLOADS: u32 = 1;
@@ -190,7 +190,7 @@ impl BlockCollection {
mod test {
use super::{BlockCollection, BlockData};
use message;
use primitives::relay::{HeaderHash};
use primitives::block::HeaderHash;
fn is_empty(bc: &BlockCollection) -> bool {
bc.blocks.is_empty() &&
@@ -260,4 +260,3 @@ mod test {
assert_eq!(drained[40..], blocks[121..150].iter().map(|b| BlockData { block: b.clone(), origin: 1 }).collect::<Vec<_>>()[..]);
}
}
+1 -3
View File
@@ -19,7 +19,7 @@
use client::{self, Client as PolkadotClient, ImportResult, ClientInfo, BlockStatus};
use client::error::Error;
use state_machine;
use primitives::relay::block;
use primitives::block;
pub trait Client : Send + Sync {
/// Given a hash return a header
@@ -55,5 +55,3 @@ impl<B, E> Client for PolkadotClient<B, E> where
(self as &Client).block_hash(block_number)
}
}
+8 -6
View File
@@ -27,12 +27,15 @@ extern crate semver;
extern crate parking_lot;
extern crate smallvec;
extern crate ipnetwork;
extern crate polkadot_primitives as primitives;
extern crate polkadot_client as client;
extern crate polkadot_state_machine as state_machine;
extern crate polkadot_serializer as ser;
extern crate substrate_primitives as primitives;
extern crate substrate_state_machine as state_machine;
extern crate substrate_serializer as ser;
extern crate serde;
extern crate serde_json;
// TODO: remove these two; split off dependent logic into polkadot-network and rename this crate
// to substrate-network.
extern crate polkadot_primitives as polkadot_primitives;
extern crate polkadot_client as client;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate log;
#[macro_use] extern crate bitflags;
@@ -56,7 +59,6 @@ pub use protocol::{ProtocolStatus};
pub use network::{NonReservedPeerMode, ConnectionFilter, ConnectionDirection, NetworkConfiguration};
// TODO: move it elsewhere
fn header_hash(header: &primitives::relay::Header) -> primitives::relay::HeaderHash {
fn header_hash(header: &primitives::Header) -> primitives::block::HeaderHash {
primitives::hashing::blake2_256(&ser::to_vec(header)).into()
}
+4 -4
View File
@@ -17,10 +17,10 @@
//! Network packet message types. These get serialized and put into the lower level protocol payload.
use std::borrow::Borrow;
use primitives::parachain::Id as ParachainId;
use primitives::AccountId;
use primitives::relay::{BlockNumber, HeaderHash, Header, Body};
use primitives::AuthorityId;
use primitives::block::{Number as BlockNumber, HeaderHash, Header, Body};
use service::Role as RoleFlags;
use polkadot_primitives::parachain::Id as ParachainId;
pub type RequestId = u64;
type Bytes = Vec<u8>;
@@ -150,7 +150,7 @@ pub struct Status {
/// Signatue of `best_hash` made with validator address. Required for the validator role.
pub validator_signature: Option<Signature>,
/// Validator address. Required for the validator role.
pub validator_id: Option<AccountId>,
pub validator_id: Option<AuthorityId>,
/// Parachain id. Required for the collator role.
pub parachain_id: Option<ParachainId>,
}
+1 -4
View File
@@ -20,7 +20,7 @@ use std::sync::Arc;
use parking_lot::RwLock;
use serde_json;
use std::time;
use primitives::relay::{HeaderHash, TransactionHash, BlockNumber, Header};
use primitives::block::{HeaderHash, TransactionHash, Number as BlockNumber, Header};
use network::{PeerId, NodeId};
use message::{self, Message};
@@ -342,6 +342,3 @@ impl Protocol {
&*self.chain
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ use std::collections::{BTreeMap};
use std::io;
use network::{NetworkProtocolHandler, NetworkService, NetworkContext, HostInfo, PeerId, ProtocolId,
NetworkConfiguration , NonReservedPeerMode, ErrorKind};
use primitives::relay::{TransactionHash, Header};
use primitives::block::{TransactionHash, Header};
use core_io::{TimerToken};
use io::NetSyncIo;
use protocol::{Protocol, ProtocolStatus, PeerInfo as ProtocolPeerInfo, TransactionStats};
+1 -5
View File
@@ -19,7 +19,7 @@ use io::SyncIo;
use protocol::Protocol;
use network::PeerId;
use client::{ImportResult, BlockStatus, ClientInfo};
use primitives::relay::{HeaderHash, BlockNumber, Header};
use primitives::block::{HeaderHash, Number as BlockNumber, Header};
use blocks::{self, BlockCollection};
use message::{self, Message};
use super::header_hash;
@@ -366,7 +366,3 @@ impl ChainSync {
protocol.send_message(io, peer_id, Message::BlockRequest(request));
}
}
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "polkadot-primitives"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
serde = { version = "1.0", default_features = false }
serde_derive = { version = "1.0", 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" }
pretty_assertions = "0.4"
[features]
default = ["std"]
std = [
"substrate-codec/std",
"substrate-primitives/std",
"substrate-runtime-std/std",
"serde_derive",
"serde/std",
]
@@ -17,12 +17,11 @@
//! 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 +33,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 +50,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>,
@@ -68,14 +67,17 @@ impl Slicable for Digest {
}
}
/// The block "body": A bunch of transactions.
pub type Body = Vec<UncheckedTransaction>;
/// 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,
/// All relay-chain transactions.
pub transactions: Vec<UncheckedTransaction>,
pub transactions: Body,
}
impl Slicable for Block {
@@ -103,8 +105,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 {
@@ -161,24 +163,11 @@ impl Slicable for Header {
}
}
/// A relay chain block body.
///
/// Included candidates should be sorted by parachain ID, and without duplicate
/// IDs.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
#[cfg_attr(feature = "std", serde(deny_unknown_fields))]
pub struct Body {
/// Parachain proposal blocks.
pub candidates: Vec<parachain::Candidate>,
}
#[cfg(test)]
mod tests {
use super::*;
use codec::Slicable;
use polkadot_serializer as ser;
use substrate_serializer as ser;
#[test]
fn test_header_serialization() {
@@ -205,28 +194,4 @@ mod tests {
let v = header.to_vec();
assert_eq!(Header::from_slice(&mut &v[..]).unwrap(), header);
}
#[test]
fn test_body_serialization() {
assert_eq!(ser::to_string_pretty(&Body {
candidates: vec![
parachain::Candidate {
parachain_index: 10.into(),
collator_signature: Default::default(),
unprocessed_ingress: Default::default(),
block: ::parachain::BlockData(vec![1, 3, 5, 8]),
}
],
}), r#"{
"candidates": [
{
"parachainIndex": 10,
"collatorSignature": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"unprocessedIngress": [],
"block": "0x01030508"
}
]
}"#);
}
}
+78
View File
@@ -0,0 +1,78 @@
// 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/>.
//! Shareable Polkadot types.
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(alloc))]
#[cfg(feature = "std")]
#[macro_use]
extern crate serde_derive;
#[cfg(feature = "std")]
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;
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,8 +47,8 @@ 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 {
@@ -71,56 +72,56 @@ pub struct Candidate {
pub struct CandidateReceipt {
/// The ID of the parachain this is a candidate for.
pub parachain_index: Id,
/// The collator's account ID
/// The collator's relay-chain account ID
pub collator: ::AccountId,
/// The head-data
pub head_data: HeadData,
/// Balance uploads to the relay chain.
pub balance_uploads: Vec<(::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 {
@@ -136,7 +137,7 @@ impl ::codec::Slicable for Activity {
#[cfg(test)]
mod tests {
use super::*;
use polkadot_serializer as ser;
use substrate_serializer as ser;
#[test]
fn test_candidate() {
@@ -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,11 +190,11 @@ 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(::Timestamp),
TimestampSet(u64),
/// Set temporary session key as a validator.
SessionSetKey(::SessionKey),
/// Staking subsystem: begin staking.
@@ -213,7 +202,7 @@ pub enum Function {
/// Staking subsystem: stop staking.
StakingUnstake,
/// Staking subsystem: transfer stake.
StakingTransfer(::AccountId, ::Balance),
StakingTransfer(::AccountId, u64),
/// Make a proposal for the governance system.
GovernancePropose(Proposal),
/// Approve a proposal for the governance system.
@@ -284,13 +273,13 @@ 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: ::AccountId,
pub signed: super::AccountId,
/// The number of transactions have come before from the same signer.
pub nonce: ::TxOrder,
pub nonce: super::TxOrder,
/// The function that should be called.
pub function: Function,
}
@@ -319,6 +308,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))]
@@ -326,13 +317,19 @@ pub struct UncheckedTransaction {
/// The actual transaction information.
pub transaction: Transaction,
/// The signature; should be an Ed25519 signature applied to the serialised `transaction` field.
pub signature: ::Signature,
pub signature: super::Signature,
}
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 +337,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 +365,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)
@@ -369,8 +374,10 @@ impl fmt::Debug for UncheckedTransaction {
#[cfg(test)]
mod tests {
use ::codec::Slicable;
use super::*;
use primitives;
use ::codec::Slicable;
use primitives::hexdisplay::HexDisplay;
#[test]
fn serialize_unchecked() {
@@ -380,10 +387,17 @@ mod tests {
nonce: 999u64,
function: Function::TimestampSet(135135),
},
signature: ::hash::H512([0; 64]),
signature: primitives::hash::H512([0; 64]),
};
// 71000000
// 0101010101010101010101010101010101010101010101010101010101010101
// e703000000000000
// 00
// df0f0200
// 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
let v = Slicable::to_vec(&tx);
println!("{}", HexDisplay::from(&v));
assert_eq!(UncheckedTransaction::from_slice(&mut &v[..]).unwrap(), 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 {
@@ -53,7 +53,7 @@ pub struct ValidationResult {
#[cfg(test)]
mod tests {
use super::*;
use polkadot_serializer as ser;
use substrate_serializer as ser;
#[test]
fn test_validation_result() {
+7 -5
View File
@@ -1,22 +1,23 @@
[package]
name = "polkadot-primitives"
name = "substrate-primitives"
version = "0.1.0"
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 }
serde_derive = { version = "1.0", optional = true }
uint = { git = "https://github.com/rphmeier/primitives.git", branch = "compile-for-wasm" }
uint = { git = "https://github.com/rphmeier/primitives.git", branch = "compile-for-wasm", default_features = false }
twox-hash = { version = "1.1.0", optional = true }
byteorder = { version = "1.1", default_features = false }
blake2-rfc = { version = "0.2.18", optional = true }
polkadot-runtime-codec = { path = "../runtime-codec", version = "0.1", default_features = false }
[dev-dependencies]
polkadot-serializer = { path = "../serializer", version = "0.1" }
substrate-serializer = { path = "../serializer" }
pretty_assertions = "0.4"
[features]
@@ -24,7 +25,8 @@ default = ["std"]
std = [
"uint/std",
"fixed-hash/std",
"polkadot-runtime-codec/std",
"substrate-codec/std",
"substrate-runtime-std/std",
"serde/std",
"rustc-hex/std",
"twox-hash",
+213
View File
@@ -0,0 +1,213 @@
// 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)
}
}
/// The body of a block is just a bunch of transactions.
pub type Body = Vec<Transaction>;
/// 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: Body,
}
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))]
+9 -5
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,16 +52,16 @@ 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 {
use super::*;
use polkadot_serializer as ser;
use substrate_serializer as ser;
#[test]
fn test_h160() {
+30 -58
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 polkadot_runtime_codec as codec;
#[macro_use]
extern crate substrate_runtime_std as rstd;
#[cfg(test)]
extern crate polkadot_serializer;
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,54 +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::relay::BlockNumber;
pub use self::uint::{U256, U512};
#[cfg(feature = "std")]
pub use hashing::{blake2_256, twox_128, twox_256};
pub use block::{Block, Header};
/// 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.
pub type AccountId = [u8; 32];
/// The Ed25519 pub key of an session that belongs to an authority. 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.
pub type TxOrder = u64;
/// A hash of some data.
pub type Hash = hash::H256;
/// Alias to 520-bit hash when used in the context of a signature.
pub type Signature = hash::H512;
/// A balance in the staking subsystem.
pub type Balance = u64;
/// A timestamp.
pub type Timestamp = u64;
/// An identifier for an authority in the consensus algorithm. The same as ed25519::Public.
pub type AuthorityId = [u8; 32];
-9
View File
@@ -1,9 +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;
@@ -18,24 +18,14 @@
#[cfg(feature = "std")]
use bytes;
use bytes::Vec;
/// Contract call data.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct CallData(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
/// Contract output data.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct OutData(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
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>);
-215
View File
@@ -15,218 +15,3 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Tests.
use codec::Slicable;
use ::AccountId;
use relay::block::{Block, Header, Digest, Log};
use relay::transaction::{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);
}
+6 -2
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,14 +44,14 @@ 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)]
mod tests {
use super::*;
use polkadot_serializer as ser;
use substrate_serializer as ser;
macro_rules! test {
($name: ident, $test_name: ident) => {
+4 -4
View File
@@ -7,10 +7,10 @@ authors = ["Parity Technologies <admin@parity.io>"]
error-chain = "0.11"
jsonrpc-core = { git="https://github.com/paritytech/jsonrpc.git" }
jsonrpc-macros = { git="https://github.com/paritytech/jsonrpc.git" }
polkadot-client = { path = "../client", version = "0.1" }
polkadot-primitives = { path = "../primitives", version = "0.1" }
polkadot-state-machine = { path = "../state-machine", version = "0.1" }
polkadot-client = { path = "../client" }
substrate-primitives = { path = "../primitives" }
substrate-state-machine = { path = "../state-machine" }
[dev-dependencies]
assert_matches = "1.1"
polkadot-executor = { path = "../executor", version = "0.1" }
substrate-executor = { path = "../executor" }
+1 -1
View File
@@ -16,7 +16,7 @@
//! Polkadot blockchain API.
use primitives::relay::block;
use primitives::block;
use client;
use state_machine;
+1 -1
View File
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use polkadot_executor as executor;
use substrate_executor as executor;
use client;
use super::*;
+3 -3
View File
@@ -20,8 +20,8 @@
extern crate jsonrpc_core as rpc;
extern crate polkadot_client as client;
extern crate polkadot_primitives as primitives;
extern crate polkadot_state_machine as state_machine;
extern crate substrate_primitives as primitives;
extern crate substrate_state_machine as state_machine;
#[macro_use]
extern crate error_chain;
@@ -29,7 +29,7 @@ extern crate error_chain;
extern crate jsonrpc_macros;
#[cfg(test)]
extern crate polkadot_executor;
extern crate substrate_executor;
#[cfg(test)]
#[macro_use]
extern crate assert_matches;
+4 -4
View File
@@ -22,8 +22,8 @@ mod error;
mod tests;
use client::{self, Client};
use primitives::relay::block;
use primitives::contract::{CallData, StorageKey, StorageData};
use primitives::block;
use primitives::storage::{StorageKey, StorageData};
use state_machine;
use self::error::Result;
@@ -37,7 +37,7 @@ build_rpc_trait! {
/// Call a contract.
#[rpc(name = "state_call")]
fn call(&self, String, CallData, block::HeaderHash) -> Result<Vec<u8>>;
fn call(&self, String, Vec<u8>, block::HeaderHash) -> Result<Vec<u8>>;
}
}
@@ -50,7 +50,7 @@ impl<B, E> StateApi for Client<B, E> where
Ok(self.storage(&block, &key)?)
}
fn call(&self, method: String, data: CallData, block: block::HeaderHash) -> Result<Vec<u8>> {
fn call(&self, method: String, data: Vec<u8>, block: block::HeaderHash) -> Result<Vec<u8>> {
Ok(self.call(&block, &method, &data)?.return_data)
}
}
+2 -2
View File
@@ -15,7 +15,7 @@
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use polkadot_executor as executor;
use substrate_executor as executor;
use self::error::{Error, ErrorKind};
use client;
@@ -39,7 +39,7 @@ fn should_call_contract() {
let genesis_hash = "af65e54217fb213853703d57b80fc5b2bb834bf923046294d7a49bff62f0a8b2".into();
assert_matches!(
StateApi::call(&client, "balanceOf".into(), CallData(vec![1,2,3]), genesis_hash),
StateApi::call(&client, "balanceOf".into(), vec![1,2,3], genesis_hash),
Err(Error(ErrorKind::Client(client::error::ErrorKind::Execution(_)), _))
)
}
+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", default_features = false }
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 }
polkadot-state-machine = { path = "../state-machine", version = "0.1", optional = true }
polkadot-primitives = { path = "../primitives", version = "0.1", default_features = false }
polkadot-runtime-codec = { path = "../runtime-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",
"polkadot-state-machine",
"triehash",
"polkadot-primitives/std",
"polkadot-runtime-codec/std",
"ed25519",
]
std = []
nightly = []
strict = []
+7 -51
View File
@@ -1,18 +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/>.
//! 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))]
@@ -22,8 +25,6 @@
#![cfg_attr(feature = "std", doc = "Polkadot runtime standard library as compiled when linked with Rust's standard library.")]
#![cfg_attr(not(feature = "std"), doc = "Polkadot's runtime standard library as compiled without Rust's standard library.")]
extern crate polkadot_runtime_codec as codec;
#[cfg(feature = "std")]
include!("../with_std.rs");
@@ -37,48 +38,3 @@ pub mod prelude {
pub use ::vec::Vec;
pub use ::boxed::Box;
}
/// Type definitions and helpers for transactions.
pub mod transaction {
pub use primitives::relay::{Transaction, UncheckedTransaction};
use primitives::Signature;
#[cfg(feature = "std")]
use std::ops;
#[cfg(not(feature = "std"))]
use core::ops;
/// A type-safe indicator that a transaction has been checked.
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct CheckedTransaction(UncheckedTransaction);
impl CheckedTransaction {
/// Get a reference to the checked signature.
pub fn signature(&self) -> &Signature {
&self.0.signature
}
}
impl ops::Deref for CheckedTransaction {
type Target = Transaction;
fn deref(&self) -> &Transaction {
&self.0.transaction
}
}
/// Check the signature on a transaction.
///
/// On failure, return the transaction back.
pub fn check(tx: UncheckedTransaction) -> Result<CheckedTransaction, UncheckedTransaction> {
let msg = ::codec::Slicable::to_vec(&tx.transaction);
if ::ed25519_verify(&tx.signature.0, &msg, &tx.transaction.signed) {
Ok(CheckedTransaction(tx))
} else {
Err(tx)
}
}
}
+7 -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 polkadot_state_machine;
extern crate polkadot_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,6 @@ 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 polkadot_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;
pub use std::iter;
pub use std::ptr;
+19 -183
View File
@@ -1,192 +1,28 @@
// 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 polkadot_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;
pub use core::iter;
pub use core::ptr;
+1 -1
View File
@@ -1,5 +1,5 @@
[package]
name = "polkadot-serializer"
name = "substrate-serializer"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
+5 -6
View File
@@ -1,20 +1,20 @@
// 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/>.
//! Polkadot customizable serde serializer.
//! Substrate customizable serde serializer.
//!
//! The idea is that we can later change the implementation
//! to something more compact, but for now we're using JSON.
@@ -42,4 +42,3 @@ pub fn to_vec<T: serde::Serialize + ?Sized>(value: &T) -> Vec<u8> {
pub fn to_writer<W: ::std::io::Write, T: serde::Serialize + ?Sized>(writer: W, value: &T) -> Result<()> {
serde_json::to_writer(writer, value)
}
+3 -3
View File
@@ -1,11 +1,11 @@
[package]
name = "polkadot-state-machine"
name = "substrate-state-machine"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
description = "Polkadot State Machine"
description = "Substrate State Machine"
[dependencies]
polkadot-primitives = { path = "../primitives", version = "0.1.0" }
substrate-primitives = { path = "../primitives", version = "0.1.0" }
hashdb = "0.1.1"
patricia-trie = "0.1.0"
memorydb = "0.1.1"
+4 -4
View File
@@ -1,18 +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/>.
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! State machine backends. These manage the code and storage of contracts.
+4 -4
View File
@@ -1,18 +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/>.
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Conrete externalities implementation.
+8 -10
View File
@@ -1,24 +1,24 @@
// 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/>.
//! Polkadot state machine implementation.
//! Substrate state machine implementation.
#![warn(missing_docs)]
extern crate polkadot_primitives as primitives;
extern crate substrate_primitives as primitives;
#[cfg_attr(test, macro_use)]
extern crate hex_literal;
@@ -34,8 +34,6 @@ extern crate byteorder;
use std::collections::HashMap;
use std::fmt;
use primitives::contract::CallData;
pub mod backend;
mod ext;
mod testing;
@@ -177,7 +175,7 @@ pub trait CodeExecutor: Sized + Send + Sync {
ext: &mut E,
code: &[u8],
method: &str,
data: &CallData,
data: &[u8],
) -> Result<Vec<u8>, Self::Error>;
}
@@ -192,7 +190,7 @@ pub fn execute<B: backend::Backend, Exec: CodeExecutor>(
overlay: &mut OverlayedChanges,
exec: &Exec,
method: &str,
call_data: &CallData,
call_data: &[u8],
) -> Result<Vec<u8>, Box<Error>> {
let result = {
+4 -4
View File
@@ -1,18 +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/>.
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Test implementation for Externalities.
+3 -2
View File
@@ -5,6 +5,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
error-chain = "0.11"
polkadot-primitives = { path = "../primitives", version = "0.1" }
polkadot-serializer = { path = "../serializer", version = "0.1" }
substrate-primitives = { path = "../primitives" }
polkadot-primitives = { path = "../polkadot-primitives" }
substrate-serializer = { path = "../serializer" }
serde = "1.0"
+3 -2
View File
@@ -18,8 +18,9 @@
#[warn(missing_docs)]
extern crate polkadot_primitives as primitives;
extern crate polkadot_serializer as serializer;
extern crate substrate_primitives as primitives;
extern crate substrate_serializer as serializer;
extern crate polkadot_primitives;
extern crate serde;
#[macro_use]
+1 -1
View File
@@ -16,7 +16,7 @@
use std::fmt;
use primitives::validator;
use polkadot_primitives::validator;
use serde::de::DeserializeOwned;
use error::Result;
+1 -2
View File
@@ -16,7 +16,7 @@
use std::fmt;
use primitives::{validator, parachain};
use polkadot_primitives::{validator, parachain};
use serde::de::DeserializeOwned;
use serializer;
@@ -99,4 +99,3 @@ impl<M, B, T, R> Code for T where
Ok(self.check(messages, downloads, block_data, head_data)?.into())
}
}
+69 -44
View File
@@ -92,9 +92,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
name = "ed25519"
version = "0.1.0"
dependencies = [
"polkadot-primitives 0.1.0",
"ring 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-primitives 0.1.0",
"untrusted 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -379,48 +379,11 @@ 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)",
"polkadot-runtime-codec 0.1.0",
"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)",
"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 = "polkadot-runtime-codec"
version = "0.1.0"
[[package]]
name = "polkadot-runtime-std"
version = "0.1.0"
dependencies = [
"ed25519 0.1.0",
"environmental 0.1.0",
"polkadot-primitives 0.1.0",
"polkadot-runtime-codec 0.1.0",
"polkadot-state-machine 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)",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "polkadot-state-machine"
version = "0.1.0"
dependencies = [
"byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"hashdb 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"hex-literal 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"memorydb 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"patricia-trie 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"polkadot-primitives 0.1.0",
"triehash 0.1.0 (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",
]
[[package]]
@@ -552,15 +515,17 @@ name = "runtime-polkadot"
version = "0.1.0"
dependencies = [
"polkadot-primitives 0.1.0",
"polkadot-runtime-codec 0.1.0",
"polkadot-runtime-std 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]]
@@ -633,6 +598,66 @@ name = "stable_deref_trait"
version = "1.0.0"
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"
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)",
"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-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"
dependencies = [
"byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"hashdb 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"hex-literal 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"memorydb 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"patricia-trie 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"substrate-primitives 0.1.0",
"triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "syn"
version = "0.11.11"
+6 -4
View File
@@ -7,10 +7,12 @@ authors = ["Parity Technologies <admin@parity.io>"]
crate-type = ["cdylib"]
[dependencies]
polkadot-runtime-codec = { path = "../../runtime-codec", version = "0.1", default-features = false }
polkadot-runtime-std = { path = "../../runtime-std", version = "0.1", default-features = false }
polkadot-primitives = { path = "../../primitives", version = "0.1", default-features = false }
substrate-codec = { path = "../../codec", 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 = ["polkadot-runtime-codec/std", "polkadot-runtime-std/std", "polkadot-primitives/std"]
std = ["substrate-codec/std", "substrate-runtime-io/std", "substrate-runtime-std/std", "substrate-primitives/std", "polkadot-primitives/std"]
+48 -9
View File
@@ -18,17 +18,17 @@
#![cfg_attr(not(feature = "std"), no_std)]
extern crate substrate_runtime_std as rstd;
#[macro_use]
extern crate polkadot_runtime_std as runtime_std;
extern crate substrate_runtime_io as runtime_io;
#[cfg(feature = "std")]
extern crate rustc_hex;
#[cfg(feature = "with-std")]
#[macro_use]
extern crate log;
extern crate polkadot_runtime_codec as codec;
extern crate polkadot_primitives as primitives;
extern crate substrate_codec as codec;
extern crate substrate_primitives;
extern crate polkadot_primitives;
#[cfg(test)]
#[macro_use]
@@ -38,9 +38,48 @@ 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 {
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)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct CheckedTransaction(UncheckedTransaction);
impl CheckedTransaction {
/// Get a reference to the checked signature.
pub fn signature(&self) -> &Signature {
&self.0.signature
}
}
impl ops::Deref for CheckedTransaction {
type Target = Transaction;
fn deref(&self) -> &Transaction {
&self.0.transaction
}
}
/// Check the signature on a 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_io::ed25519_verify(&tx.signature.0, &msg, &tx.transaction.signed) {
Ok(CheckedTransaction(tx))
} else {
Err(tx)
}
}
}
/// Execute a block, with `input` being the canonical serialisation of the block. Returns the
/// empty vector.
@@ -66,7 +105,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::SessionKey;
use polkadot_primitives::SessionKey;
struct AuthorityStorageVec {}
impl StorageVec for AuthorityStorageVec {
@@ -17,11 +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};
use primitives::AccountId;
use polkadot_primitives::{BlockNumber, Block, AccountId};
use runtime::staking::Balance;
/// Configuration of a general Polkadot genesis block.
@@ -25,11 +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::{AccountId, Hash, BlockNumber};
use primitives::relay::Proposal;
use polkadot_primitives::{Proposal, AccountId, Hash, BlockNumber};
use runtime::{staking, system, session};
const APPROVALS_REQUIRED: &[u8] = b"gov:apr";
@@ -95,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() {
@@ -113,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);
}
@@ -146,11 +145,10 @@ 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::AccountId;
use primitives::relay::InternalFunction;
use polkadot_primitives::{AccountId, Proposal};
use runtime::{staking, session};
fn new_test_ext() -> TestExternalities {
@@ -191,9 +189,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),
});
public::propose(&one, &Proposal::StakingSetSessionsPerEra(2));
public::approve(&two, 1);
staking::internal::check_new_era();
assert_eq!(staking::era_length(), 2);
@@ -216,17 +212,13 @@ mod tests {
// Block 1: Make proposal. Fail it.
with_env(|e| e.block_number = 1);
public::propose(&one, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
});
public::propose(&one, &Proposal::StakingSetSessionsPerEra(2));
staking::internal::check_new_era();
assert_eq!(staking::era_length(), 1);
// 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),
});
public::propose(&one, &Proposal::StakingSetSessionsPerEra(2));
public::approve(&two, 2);
staking::internal::check_new_era();
assert_eq!(staking::era_length(), 2);
@@ -249,9 +241,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),
});
public::propose(&one, &Proposal::StakingSetSessionsPerEra(2));
staking::internal::check_new_era();
assert_eq!(staking::era_length(), 1);
});
@@ -274,9 +264,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),
});
public::propose(&one, &Proposal::StakingSetSessionsPerEra(2));
public::approve(&two, 0);
staking::internal::check_new_era();
assert_eq!(staking::era_length(), 1);
@@ -300,9 +288,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),
});
public::propose(&one, &Proposal::StakingSetSessionsPerEra(2));
public::approve(&two, 1);
public::approve(&two, 1);
staking::internal::check_new_era();
@@ -327,12 +313,8 @@ 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),
});
public::propose(&two, &Proposal {
function: InternalFunction::StakingSetSessionsPerEra(2),
});
public::propose(&one, &Proposal::StakingSetSessionsPerEra(2));
public::propose(&two, &Proposal::StakingSetSessionsPerEra(2));
staking::internal::check_new_era();
assert_eq!(staking::era_length(), 1);
});
@@ -379,9 +361,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),
});
public::propose(&one, &Proposal::StakingSetSessionsPerEra(2));
public::approve(&four, 1);
staking::internal::check_new_era();
assert_eq!(staking::era_length(), 1);
@@ -16,7 +16,8 @@
//! Main parachains logic. For now this is just the determination of which validators do what.
use runtime_std::mem;
use rstd::prelude::*;
use runtime_io::mem;
use codec::{Slicable, Joiner};
use support::{Hashable, with_env, storage};
use runtime::session;
@@ -95,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::{AccountId, SessionKey, BlockNumber};
use polkadot_primitives::{AccountId, SessionKey, BlockNumber};
use runtime::{system, staking, consensus};
const SESSION_LENGTH: &[u8] = b"ses:len";
@@ -137,10 +137,10 @@ 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::AccountId;
use polkadot_primitives::AccountId;
use runtime::{consensus, session};
fn simple_setup() -> TestExternalities {
@@ -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::{BlockNumber, AccountId};
use polkadot_primitives::{BlockNumber, AccountId};
use runtime::{system, session, governance};
/// The balance of an account.
@@ -213,10 +213,10 @@ 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::AccountId;
use polkadot_primitives::AccountId;
use runtime::{staking, session};
#[test]
@@ -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::{AccountId, Hash, TxOrder, BlockNumber};
use primitives::relay::{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:";
@@ -145,7 +145,7 @@ pub mod internal {
}
fn execute_transaction(utx: UncheckedTransaction) {
use runtime_std::transaction;
use ::transaction;
// Verify the signature is good.
let tx = match transaction::check(utx) {
@@ -202,15 +202,15 @@ fn post_finalise(header: &Header) {
storage::put(&header.number.to_keyed_vec(BLOCK_HASH_AT), &header.blake2_256());
}
#[cfg(feature = "with-std")]
#[cfg(feature = "std")]
fn info_expect_equal_hash(given: &Hash, expected: &Hash) {
use support::HexDisplay;
if given != expected {
info!("Hash: given={}, expected={}", HexDisplay::from(given), HexDisplay::from(expected));
println!("Hash: given={}, expected={}", HexDisplay::from(&given.0), HexDisplay::from(&expected.0));
}
}
#[cfg(not(feature = "with-std"))]
#[cfg(not(feature = "std"))]
fn info_expect_equal_hash(_given: &Hash, _expected: &Hash) {}
#[cfg(test)]
@@ -218,10 +218,10 @@ 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};
use polkadot_primitives::{Header, Digest, UncheckedTransaction, Transaction, Function};
use runtime::staking;
#[test]
@@ -17,7 +17,8 @@
//! Timestamp manager: just handles the current timestamp.
use support::storage;
use primitives::Timestamp;
pub type Timestamp = u64;
const CURRENT_TIMESTAMP: &[u8] = b"tim:val";
@@ -40,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,13 +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};
use primitives::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();
@@ -338,12 +338,10 @@ mod tests {
#[test]
fn proposals_can_be_stored() {
use primitives::relay::{Proposal, InternalFunction};
use polkadot_primitives::Proposal;
let mut t = TestExternalities { storage: HashMap::new(), };
with_externalities(&mut t, || {
let x = Proposal {
function: InternalFunction::StakingSetSessionsPerEra(25519),
};
let x = Proposal::StakingSetSessionsPerEra(25519);
put(b":test", &x);
let y: Proposal = get(b":test").unwrap();
assert_eq!(x, y);
@@ -16,7 +16,7 @@
//! Testing helpers.
use primitives::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
};