diff --git a/substrate/.gitignore b/substrate/.gitignore index c7a3830779..ea86b1eb14 100644 --- a/substrate/.gitignore +++ b/substrate/.gitignore @@ -1,5 +1,6 @@ /target/ **/*.rs.bk *.swp -wasm-runtime/**/target/ +polkadot-runtime/wasm/target/ +executor/wasm/target/ **/._* diff --git a/substrate/Cargo.lock b/substrate/Cargo.lock index 8f333b159e..b2fca77787 100644 --- a/substrate/Cargo.lock +++ b/substrate/Cargo.lock @@ -821,20 +821,6 @@ dependencies = [ "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "native-runtime" -version = "0.1.0" -dependencies = [ - "hex-literal 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", - "polkadot-primitives 0.1.0", - "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "substrate-codec 0.1.0", - "substrate-primitives 0.1.0", - "substrate-runtime-io 0.1.0", - "substrate-runtime-std 0.1.0", -] - [[package]] name = "net2" version = "0.2.31" @@ -986,30 +972,20 @@ name = "polkadot-cli" version = "0.1.0" dependencies = [ "clap 2.29.4 (registry+https://github.com/rust-lang/crates.io-index)", - "env_logger 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", - "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-rpc-servers 0.1.0", - "substrate-executor 0.1.0", - "substrate-primitives 0.1.0", -] - -[[package]] -name = "polkadot-client" -version = "0.1.0" -dependencies = [ "ed25519 0.1.0", + "env_logger 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", "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", - "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 0.1.0", + "substrate-client 0.1.0", "substrate-codec 0.1.0", "substrate-executor 0.1.0", "substrate-primitives 0.1.0", - "substrate-serializer 0.1.0", + "substrate-rpc-servers 0.1.0", + "substrate-runtime-io 0.1.0", "substrate-state-machine 0.1.0", "triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1023,6 +999,22 @@ dependencies = [ "substrate-primitives 0.1.0", ] +[[package]] +name = "polkadot-executor" +version = "0.1.0" +dependencies = [ + "ed25519 0.1.0", + "hex-literal 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "polkadot-primitives 0.1.0", + "polkadot-runtime 0.1.0", + "substrate-codec 0.1.0", + "substrate-executor 0.1.0", + "substrate-primitives 0.1.0", + "substrate-runtime-io 0.1.0", + "substrate-state-machine 0.1.0", + "triehash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "polkadot-network" version = "0.1.0" @@ -1036,7 +1028,6 @@ dependencies = [ "ipnetwork 0.12.7 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "polkadot-client 0.1.0", "polkadot-primitives 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)", @@ -1044,6 +1035,7 @@ dependencies = [ "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-client 0.1.0", "substrate-primitives 0.1.0", "substrate-serializer 0.1.0", "substrate-state-machine 0.1.0", @@ -1063,26 +1055,17 @@ dependencies = [ ] [[package]] -name = "polkadot-rpc" +name = "polkadot-runtime" version = "0.1.0" dependencies = [ - "assert_matches 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "error-chain 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "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", - "substrate-executor 0.1.0", + "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", + "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-state-machine 0.1.0", -] - -[[package]] -name = "polkadot-rpc-servers" -version = "0.1.0" -dependencies = [ - "jsonrpc-core 8.0.1 (git+https://github.com/paritytech/jsonrpc.git)", - "jsonrpc-http-server 8.0.0 (git+https://github.com/paritytech/jsonrpc.git)", - "polkadot-rpc 0.1.0", + "substrate-runtime-io 0.1.0", + "substrate-runtime-std 0.1.0", ] [[package]] @@ -1413,6 +1396,23 @@ name = "strsim" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "substrate-client" +version = "0.1.0" +dependencies = [ + "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)", + "parking_lot 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "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)", +] + [[package]] name = "substrate-codec" version = "0.1.0" @@ -1430,9 +1430,7 @@ dependencies = [ "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)", @@ -1463,14 +1461,35 @@ dependencies = [ "uint 0.1.2 (git+https://github.com/rphmeier/primitives.git?branch=compile-for-wasm)", ] +[[package]] +name = "substrate-rpc" +version = "0.1.0" +dependencies = [ + "assert_matches 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "error-chain 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "jsonrpc-core 8.0.1 (git+https://github.com/paritytech/jsonrpc.git)", + "jsonrpc-macros 8.0.0 (git+https://github.com/paritytech/jsonrpc.git)", + "substrate-client 0.1.0", + "substrate-executor 0.1.0", + "substrate-primitives 0.1.0", + "substrate-state-machine 0.1.0", +] + +[[package]] +name = "substrate-rpc-servers" +version = "0.1.0" +dependencies = [ + "jsonrpc-core 8.0.1 (git+https://github.com/paritytech/jsonrpc.git)", + "jsonrpc-http-server 8.0.0 (git+https://github.com/paritytech/jsonrpc.git)", + "substrate-rpc 0.1.0", +] + [[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", @@ -1483,6 +1502,8 @@ dependencies = [ name = "substrate-runtime-std" version = "0.1.0" dependencies = [ + "pwasm-alloc 0.1.0", + "pwasm-libc 0.1.0", "rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/substrate/Cargo.toml b/substrate/Cargo.toml index 4780426456..615a00dc05 100644 --- a/substrate/Cargo.toml +++ b/substrate/Cargo.toml @@ -5,29 +5,34 @@ authors = ["Parity Technologies "] [dependencies] error-chain = "0.11" -polkadot-cli = { path = "cli", version = "0.1" } +polkadot-cli = { path = "polkadot-cli", version = "0.1" } polkadot-network = { path = "network" } [workspace] members = [ - "candidate-agreement", "client", - "collator", + "codec", "environmental", "executor", - "native-runtime", "network", - "primitives", - "rpc-servers", - "rpc", - "codec", + "polkadot-candidate-agreement", + "polkadot-cli", + "polkadot-collator", + "polkadot-executor", + "polkadot-runtime", "polkadot-primitives", + "polkadot-validator", + "primitives", + "rpc", + "rpc-servers", "runtime-io", "runtime-std", "serializer", "state-machine", - "validator", ] exclude = [ - "wasm-runtime" + "executor/wasm", + "polkadot-runtime/wasm", + "pwasm-alloc", + "pwasm-libc", ] diff --git a/substrate/build.sh b/substrate/build.sh deleted file mode 100755 index 40a1043226..0000000000 --- a/substrate/build.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh - -cd wasm-runtime -./build.sh -cd .. - diff --git a/substrate/cli/Cargo.toml b/substrate/cli/Cargo.toml deleted file mode 100644 index 74299ec2eb..0000000000 --- a/substrate/cli/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "polkadot-cli" -version = "0.1.0" -authors = ["Parity Technologies "] -description = "Polkadot node implementation in Rust." - -[dependencies] -clap = { version = "2.27", features = ["yaml"] } -env_logger = "0.4" -error-chain = "0.11" -log = "0.3" -polkadot-client = { path = "../client" } -substrate-executor = { path = "../executor" } -substrate-primitives = { path = "../primitives" } -polkadot-rpc-servers = { path = "../rpc-servers" } diff --git a/substrate/client/Cargo.toml b/substrate/client/Cargo.toml index b5ee065dbb..ebe3adba77 100644 --- a/substrate/client/Cargo.toml +++ b/substrate/client/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "polkadot-client" +name = "substrate-client" version = "0.1.0" authors = ["Parity Technologies "] @@ -7,13 +7,11 @@ authors = ["Parity Technologies "] error-chain = "0.11" log = "0.3" parking_lot = "0.4" -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" ed25519 = { path = "../ed25519", version = "0.1" } diff --git a/substrate/client/src/backend.rs b/substrate/client/src/backend.rs index 563dd03699..0eb12cf18b 100644 --- a/substrate/client/src/backend.rs +++ b/substrate/client/src/backend.rs @@ -30,6 +30,8 @@ pub trait BlockImportOperation { fn state(&self) -> error::Result; /// Append block data to the transaction. fn import_block(&mut self, header: block::Header, body: Option, is_new_best: bool) -> error::Result<()>; + /// Inject storage data into the database. + fn reset_storage, Vec)>>(&mut self, iter: I) -> error::Result<()>; } /// Client backend. Manages the data layer. diff --git a/substrate/client/src/in_mem.rs b/substrate/client/src/in_mem.rs index 34475886c4..fe8064c01b 100644 --- a/substrate/client/src/in_mem.rs +++ b/substrate/client/src/in_mem.rs @@ -146,6 +146,11 @@ impl backend::BlockImportOperation for BlockImportOperation { }); Ok(()) } + + fn reset_storage, Vec)>>(&mut self, iter: I) -> error::Result<()> { + self.pending_state = state_machine::backend::InMemory::from(iter.collect()); + Ok(()) + } } /// In-memory backend. Keeps all states and blocks in memory. Useful for testing. diff --git a/substrate/client/src/lib.rs b/substrate/client/src/lib.rs index f0d1fd1a63..983ab2754f 100644 --- a/substrate/client/src/lib.rs +++ b/substrate/client/src/lib.rs @@ -18,13 +18,11 @@ #![warn(missing_docs)] -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; extern crate triehash; @@ -32,19 +30,11 @@ extern crate parking_lot; #[macro_use] extern crate error_chain; #[macro_use] extern crate log; -#[cfg(test)] -#[macro_use] -extern crate hex_literal; - pub mod error; pub mod blockchain; pub mod backend; pub mod in_mem; -mod genesis; - -pub use genesis::construct_genesis_block; - pub use blockchain::Info as ChainInfo; pub use blockchain::BlockId; @@ -109,10 +99,16 @@ pub enum BlockStatus { Unknown, } - /// Create an instance of in-memory client. -pub fn new_in_mem(executor: E) -> error::Result> where E: state_machine::CodeExecutor { - Client::new(in_mem::Backend::new(), executor) +pub fn new_in_mem( + executor: E, + build_genesis: F +) -> error::Result> + where + E: state_machine::CodeExecutor, + F: FnOnce() -> (block::Header, Vec<(Vec, Vec)>) +{ + Client::new(in_mem::Backend::new(), executor, build_genesis) } impl Client where @@ -121,19 +117,19 @@ impl Client where error::Error: From<<::State as state_machine::backend::Backend>::Error>, { /// Creates new Polkadot Client with given blockchain and code executor. - pub fn new(backend: B, executor: E) -> error::Result { + pub fn new( + backend: B, + executor: E, + build_genesis: F + ) -> error::Result + where + F: FnOnce() -> (block::Header, Vec<(Vec, Vec)>) + { if backend.blockchain().header(BlockId::Number(0))?.is_none() { trace!("Empty database, writing genesis block"); - // TODO: spec - let genesis_header = block::Header { - parent_hash: Default::default(), - number: 0, - state_root: Default::default(), - transaction_root: Default::default(), - digest: Default::default(), - }; - + let (genesis_header, genesis_store) = build_genesis(); let mut tx = backend.begin_transaction(BlockId::Hash(block::HeaderHash::default()))?; + tx.reset_storage(genesis_store.into_iter())?; tx.import_block(genesis_header, None, true)?; backend.commit_transaction(tx)?; } diff --git a/substrate/executor/Cargo.toml b/substrate/executor/Cargo.toml index 8d2643d585..7a4a5c8af0 100644 --- a/substrate/executor/Cargo.toml +++ b/substrate/executor/Cargo.toml @@ -19,9 +19,6 @@ rustc-hex = "1.0.0" triehash = "0.1.0" 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" diff --git a/substrate/executor/src/lib.rs b/substrate/executor/src/lib.rs index 88c52c9389..44656fab5b 100644 --- a/substrate/executor/src/lib.rs +++ b/substrate/executor/src/lib.rs @@ -41,10 +41,6 @@ extern crate rustc_hex; 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; @@ -55,14 +51,18 @@ extern crate error_chain; #[cfg(test)] extern crate assert_matches; +// TODO: move into own crate +macro_rules! map { + ($( $name:expr => $value:expr ),*) => ( + vec![ $( ( $name, $value ) ),* ].into_iter().collect() + ) +} + #[macro_use] mod wasm_utils; mod wasm_executor; mod native_executor; pub mod error; - -/// Creates new RustExecutor for contracts. -pub fn executor() -> native_executor::NativeExecutor { - native_executor::NativeExecutor -} +pub use wasm_executor::WasmExecutor; +pub use native_executor::{NativeExecutionDispatch, NativeExecutor}; diff --git a/substrate/executor/src/native_executor.rs b/substrate/executor/src/native_executor.rs index e4812be894..e7c9258063 100644 --- a/substrate/executor/src/native_executor.rs +++ b/substrate/executor/src/native_executor.rs @@ -15,20 +15,33 @@ // along with Substrate. If not, see . use error::{Error, ErrorKind, Result}; -use native_runtime as runtime; use runtime_io; use state_machine::{Externalities, CodeExecutor}; use wasm_executor::WasmExecutor; use std::panic::catch_unwind; -pub struct NativeExecutor; +/// Delegate for dispatching a CodeExecutor call to native code. +pub trait NativeExecutionDispatch { + /// Get the wasm code that the native dispatch will be equivalent to. + fn native_equivalent() -> &'static [u8]; -fn safe_call Vec>(f: F) -> Result> { + /// Dispatch a method and input data to be executed natively. Returns `Some` result or `None` + /// if the `method` is unknown. Panics if there's an unrecoverable error. + fn dispatch(method: &str, data: &[u8]) -> Option>; +} + +/// A generic `CodeExecutor` implementation that uses a delegate to determine wasm code equivalence +/// and dispatch to native code when possible, falling back on `WasmExecutor` when not. +pub struct NativeExecutor { + pub _dummy: ::std::marker::PhantomData, +} + +fn safe_call Option>>(f: F) -> Result>> { catch_unwind(f).map_err(|_| ErrorKind::Runtime.into()) } -impl CodeExecutor for NativeExecutor { +impl CodeExecutor for NativeExecutor { type Error = Error; fn call( @@ -38,240 +51,12 @@ impl CodeExecutor for NativeExecutor { method: &str, data: &[u8], ) -> Result> { - // 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_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()), - }) + if code == D::native_equivalent() { + runtime_io::with_externalities(ext, || safe_call(|| D::dispatch(method, data)))? + .ok_or(ErrorKind::MethodNotFound(method.to_owned()).into()) } else { // call into wasm. WasmExecutor.call(ext, code, method, data) } } } - -#[cfg(test)] -mod tests { - use super::*; - use codec::{KeyedVec, Slicable, Joiner}; - use native_runtime::support::{one, two, Hashable}; - use native_runtime::runtime::staking::balance; - use state_machine::TestExternalities; - 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"); - const COMPACT_CODE: &[u8] = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.compact.wasm"); - - fn tx() -> UncheckedTransaction { - let transaction = Transaction { - signed: one(), - nonce: 0, - function: Function::StakingTransfer(two(), 69), - }; - let signature = secret_for(&transaction.signed).unwrap() - .sign(&transaction.to_vec()); - - UncheckedTransaction { transaction, signature } - } - - #[test] - fn panic_execution_with_foreign_code_gives_error() { - let one = one(); - let mut t = TestExternalities { storage: map![ - 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", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); - assert!(r.is_err()); - } - - #[test] - fn panic_execution_with_native_equivalent_code_gives_error() { - let one = one(); - let mut t = TestExternalities { storage: map![ - 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", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); - assert!(r.is_err()); - } - - #[test] - fn successful_execution_with_native_equivalent_code_gives_ok() { - let one = one(); - let two = two(); - - let mut t = TestExternalities { storage: map![ - 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", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); - assert!(r.is_ok()); - - runtime_io::with_externalities(&mut t, || { - assert_eq!(balance(&one), 42); - assert_eq!(balance(&two), 69); - }); - } - - #[test] - fn successful_execution_with_foreign_code_gives_ok() { - let one = one(); - let two = two(); - - let mut t = TestExternalities { storage: map![ - 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", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); - assert!(r.is_ok()); - - runtime_io::with_externalities(&mut t, || { - assert_eq!(balance(&one), 42); - assert_eq!(balance(&two), 69); - }); - } - - fn new_test_ext() -> TestExternalities { - let one = one(); - let two = two(); - let three = [3u8; 32]; - - TestExternalities { storage: map![ - twox_128(&0u64.to_keyed_vec(b"sys:old:")).to_vec() => [69u8; 32].to_vec(), - twox_128(b"gov:apr").to_vec() => vec![].join(&667u32), - twox_128(b"ses:len").to_vec() => vec![].join(&2u64), - twox_128(b"ses:val:len").to_vec() => vec![].join(&3u32), - twox_128(&0u32.to_keyed_vec(b"ses:val:")).to_vec() => one.to_vec(), - twox_128(&1u32.to_keyed_vec(b"ses:val:")).to_vec() => two.to_vec(), - twox_128(&2u32.to_keyed_vec(b"ses:val:")).to_vec() => three.to_vec(), - twox_128(b"sta:wil:len").to_vec() => vec![].join(&3u32), - twox_128(&0u32.to_keyed_vec(b"sta:wil:")).to_vec() => one.to_vec(), - twox_128(&1u32.to_keyed_vec(b"sta:wil:")).to_vec() => two.to_vec(), - twox_128(&2u32.to_keyed_vec(b"sta:wil:")).to_vec() => three.to_vec(), - twox_128(b"sta:spe").to_vec() => vec![].join(&2u64), - twox_128(b"sta:vac").to_vec() => vec![].join(&3u64), - twox_128(b"sta:era").to_vec() => vec![].join(&0u64), - twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![111u8, 0, 0, 0, 0, 0, 0, 0] - ], } - } - - fn secret_for(who: &AccountId) -> Option { - match who { - x if *x == one() => Some(Pair::from_seed(b"12345678901234567890123456789012")), - x if *x == two() => Some("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60".into()), - _ => None, - } - } - - fn construct_block(number: BlockNumber, parent_hash: Hash, state_root: Hash, txs: Vec) -> (Vec, Hash) { - use triehash::ordered_trie_root; - - let transactions = txs.into_iter().map(|transaction| { - let signature = secret_for(&transaction.signed).unwrap() - .sign(&transaction.to_vec()); - - UncheckedTransaction { transaction, signature } - }).collect::>(); - - let transaction_root = ordered_trie_root(transactions.iter().map(Slicable::to_vec)).0.into(); - - let header = Header { - parent_hash, - number, - state_root, - transaction_root, - digest: Digest { logs: vec![], }, - }; - let hash = header.blake2_256(); - - (Block { header, transactions }.to_vec(), hash.into()) - } - - fn block1() -> (Vec, Hash) { - construct_block( - 1, - [69u8; 32].into(), - hex!("2481853da20b9f4322f34650fea5f240dcbfb266d02db94bfa0153c31f4a29db").into(), - vec![Transaction { - signed: one(), - nonce: 0, - function: Function::StakingTransfer(two(), 69), - }] - ) - } - - fn block2() -> (Vec, Hash) { - construct_block( - 2, - block1().1, - hex!("1feb4d3a2e587079e6ce1685fa79994efd995e33cb289d39cded67aac1bb46a9").into(), - vec![ - Transaction { - signed: two(), - nonce: 0, - function: Function::StakingTransfer(one(), 5), - }, - Transaction { - signed: one(), - nonce: 1, - function: Function::StakingTransfer(two(), 15), - } - ] - ) - } - - #[test] - fn test_execution_works() { - let mut t = new_test_ext(); - println!("Testing Wasm..."); - let r = WasmExecutor.call(&mut t, COMPACT_CODE, "run_tests", &block2().0); - assert!(r.is_ok()); - } - - #[test] - fn full_native_block_import_works() { - let mut t = new_test_ext(); - - NativeExecutor.call(&mut t, COMPACT_CODE, "execute_block", &block1().0).unwrap(); - - runtime_io::with_externalities(&mut t, || { - assert_eq!(balance(&one()), 42); - assert_eq!(balance(&two()), 69); - }); - - NativeExecutor.call(&mut t, COMPACT_CODE, "execute_block", &block2().0).unwrap(); - - runtime_io::with_externalities(&mut t, || { - assert_eq!(balance(&one()), 32); - assert_eq!(balance(&two()), 79); - }); - } - - #[test] - fn full_wasm_block_import_works() { - let mut t = new_test_ext(); - - WasmExecutor.call(&mut t, COMPACT_CODE, "execute_block", &block1().0).unwrap(); - - runtime_io::with_externalities(&mut t, || { - assert_eq!(balance(&one()), 42); - assert_eq!(balance(&two()), 69); - }); - - WasmExecutor.call(&mut t, COMPACT_CODE, "execute_block", &block2().0).unwrap(); - - runtime_io::with_externalities(&mut t, || { - assert_eq!(balance(&one()), 32); - assert_eq!(balance(&two()), 79); - }); - } -} diff --git a/substrate/executor/src/wasm_executor.rs b/substrate/executor/src/wasm_executor.rs index e46991c2c3..0a61a5b099 100644 --- a/substrate/executor/src/wasm_executor.rs +++ b/substrate/executor/src/wasm_executor.rs @@ -37,7 +37,7 @@ struct Heap { impl Heap { fn new() -> Self { Heap { - end: 32768, + end: 262144, } } fn allocate(&mut self, size: u32) -> u32 { @@ -53,6 +53,7 @@ struct FunctionExecutor<'e, E: Externalities + 'e> { heap: Heap, memory: Arc, ext: &'e mut E, + hash_lookup: HashMap, Vec>, } impl<'e, E: Externalities> FunctionExecutor<'e, E> { @@ -61,6 +62,7 @@ impl<'e, E: Externalities> FunctionExecutor<'e, E> { heap: Heap::new(), memory: Arc::clone(m), ext: e, + hash_lookup: HashMap::new(), } } } @@ -89,21 +91,39 @@ impl ReadPrimitive for MemoryInstance { } } +fn ascii_format(asciish: &[u8]) -> String { + let mut r = String::new(); + let mut latch = false; + for c in asciish { + match (latch, *c) { + (false, 32...127) => r.push(*c as char), + _ => { + if !latch { + r.push('#'); + latch = true; + } + r.push_str(&format!("{:02x}", *c)); + } + } + } + r +} + impl_function_executor!(this: FunctionExecutor<'e, E>, ext_print_utf8(utf8_data: *const u8, utf8_len: u32) => { if let Ok(utf8) = this.memory.get(utf8_data, utf8_len as usize) { if let Ok(message) = String::from_utf8(utf8) { - info!(target: "runtime", "{}", message); + println!("{}", message); } } }, ext_print_hex(data: *const u8, len: u32) => { if let Ok(hex) = this.memory.get(data, len as usize) { - info!(target: "runtime", "{}", HexDisplay::from(&hex)); + println!("{}", HexDisplay::from(&hex)); } }, ext_print_num(number: u64) => { - info!(target: "runtime", "{}", number); + println!("{}", number); }, ext_memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32 => { let sl1 = this.memory.get(s1, n as usize).map_err(|_| DummyUserError)?; @@ -144,13 +164,23 @@ impl_function_executor!(this: FunctionExecutor<'e, E>, 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)?; let value = this.memory.get(value_data, value_len as usize).map_err(|_| DummyUserError)?; - info!(target: "runtime", "Setting storage: {} -> {}", HexDisplay::from(&key), HexDisplay::from(&value)); + if let Some(preimage) = this.hash_lookup.get(&key) { + info!(target: "wasm-trace", "*** Setting storage: %{} -> {} [k={}]", ascii_format(&preimage), HexDisplay::from(&value), HexDisplay::from(&key)); + } else { + info!(target: "wasm-trace", "*** Setting storage: {} -> {} [k={}]", ascii_format(&key), HexDisplay::from(&value), HexDisplay::from(&key)); + } this.ext.set_storage(key, value); }, ext_get_allocated_storage(key_data: *const u8, key_len: u32, written_out: *mut u32) -> *mut u8 => { let key = this.memory.get(key_data, key_len as usize).map_err(|_| DummyUserError)?; let value = this.ext.storage(&key).map_err(|_| DummyUserError)?; + if let Some(preimage) = this.hash_lookup.get(&key) { + info!(target: "wasm-trace", " Getting storage: %{} == {} [k={}]", ascii_format(&preimage), HexDisplay::from(&value), HexDisplay::from(&key)); + } else { + info!(target: "wasm-trace", " Getting storage: {} == {} [k={}]", ascii_format(&key), HexDisplay::from(&value), HexDisplay::from(&key)); + } + let offset = this.heap.allocate(value.len() as u32) as u32; this.memory.set(offset, &value).map_err(|_| DummyUserError)?; @@ -160,7 +190,11 @@ impl_function_executor!(this: FunctionExecutor<'e, E>, ext_get_storage_into(key_data: *const u8, key_len: u32, value_data: *mut u8, value_len: u32, value_offset: u32) -> u32 => { let key = this.memory.get(key_data, key_len as usize).map_err(|_| DummyUserError)?; let value = this.ext.storage(&key).map_err(|_| DummyUserError)?; - info!(target: "runtime", "Getting storage: {} ( -> {})", HexDisplay::from(&key), HexDisplay::from(&value)); + if let Some(preimage) = this.hash_lookup.get(&key) { + info!(target: "wasm-trace", " Getting storage: %{} == {} [k={}]", ascii_format(&preimage), HexDisplay::from(&value), HexDisplay::from(&key)); + } else { + info!(target: "wasm-trace", " Getting storage: {} == {} [k={}]", ascii_format(&key), HexDisplay::from(&value), HexDisplay::from(&key)); + } let value = &value[value_offset as usize..]; let written = ::std::cmp::min(value_len as usize, value.len()); this.memory.set(value_data, &value[..written]).map_err(|_| DummyUserError)?; @@ -189,18 +223,22 @@ impl_function_executor!(this: FunctionExecutor<'e, E>, }, ext_twox_128(data: *const u8, len: u32, out: *mut u8) => { let result = if len == 0 { - info!(target: "runtime", "XXhash: ''"); - twox_128(&[0u8; 0]) + let hashed = twox_128(&[0u8; 0]); + trace!(target: "xxhash", "XXhash: '' -> {}", HexDisplay::from(&hashed)); + this.hash_lookup.insert(hashed.to_vec(), vec![]); + hashed } else { let key = this.memory.get(data, len as usize).map_err(|_| DummyUserError)?; let hashed_key = twox_128(&key); if let Ok(skey) = ::std::str::from_utf8(&key) { - info!(target: "runtime", "XXhash: {} -> {}", skey, HexDisplay::from(&hashed_key)); + trace!(target: "xxhash", "XXhash: {} -> {}", skey, HexDisplay::from(&hashed_key)); } else { - info!(target: "runtime", "XXhash: {} -> {}", HexDisplay::from(&key), HexDisplay::from(&hashed_key)); + trace!(target: "xxhash", "XXhash: {} -> {}", HexDisplay::from(&key), HexDisplay::from(&hashed_key)); } + this.hash_lookup.insert(hashed_key.to_vec(), key); hashed_key }; + this.memory.set(out, &result).map_err(|_| DummyUserError)?; }, ext_twox_256(data: *const u8, len: u32, out: *mut u8) => { @@ -252,6 +290,7 @@ impl CodeExecutor for WasmExecutor { data: &[u8], ) -> Result> { // TODO: handle all expects as errors to be returned. + println!("Wasm-Calling {}({})", method, HexDisplay::from(&data)); let program = ProgramInstance::new().expect("this really shouldn't be able to fail; qed"); @@ -276,8 +315,11 @@ impl CodeExecutor for WasmExecutor { })?; if let Some(I64(r)) = returned { - memory.get(r as u32, (r >> 32) as u32 as usize) + let offset = r as u32; + let length = (r >> 32) as u32 as usize; + memory.get(offset, length) .map_err(|_| ErrorKind::Runtime.into()) + .map(|v| { println!("Returned {}", HexDisplay::from(&v)); v }) } else { Err(ErrorKind::InvalidReturn.into()) } @@ -289,38 +331,15 @@ mod tests { use super::*; use rustc_hex::FromHex; use codec::{KeyedVec, Slicable, Joiner}; - use native_runtime::support::{one, two}; - use native_runtime::runtime::staking::balance; use state_machine::TestExternalities; - use primitives::twox_128; - use polkadot_primitives::{Header, Transaction, UncheckedTransaction, Function, AccountId}; + use primitives::{twox_128, Header}; use runtime_io; use ed25519::Pair; - fn secret_for(who: &AccountId) -> Option { - match who { - x if *x == one() => Some(Pair::from_seed(b"12345678901234567890123456789012")), - x if *x == two() => Some("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60".into()), - _ => None, - } - } - - fn tx() -> UncheckedTransaction { - let transaction = Transaction { - signed: one(), - nonce: 0, - function: Function::StakingTransfer(two(), 69), - }; - let signature = secret_for(&transaction.signed).unwrap() - .sign(&transaction.to_vec()); - - UncheckedTransaction { transaction, signature } - } - #[test] fn returning_should_work() { let mut ext = TestExternalities::default(); - let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); + let test_code = include_bytes!("../wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); let output = WasmExecutor.call(&mut ext, &test_code[..], "test_empty_return", &[]).unwrap(); assert_eq!(output, vec![0u8; 0]); @@ -329,7 +348,7 @@ mod tests { #[test] fn panicking_should_work() { let mut ext = TestExternalities::default(); - let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); + let test_code = include_bytes!("../wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); let output = WasmExecutor.call(&mut ext, &test_code[..], "test_panic", &[]); assert!(output.is_err()); @@ -342,7 +361,7 @@ mod tests { fn storage_should_work() { let mut ext = TestExternalities::default(); 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 test_code = include_bytes!("../wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); let output = WasmExecutor.call(&mut ext, &test_code[..], "test_data_in", b"Hello world").unwrap(); @@ -359,7 +378,7 @@ mod tests { #[test] fn blake2_256_should_work() { let mut ext = TestExternalities::default(); - let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); + let test_code = include_bytes!("../wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); assert_eq!( WasmExecutor.call(&mut ext, &test_code[..], "test_blake2_256", &[]).unwrap(), blake2_256(&b""[..]).to_vec() @@ -373,7 +392,7 @@ mod tests { #[test] fn twox_256_should_work() { let mut ext = TestExternalities::default(); - let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); + let test_code = include_bytes!("../wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); assert_eq!( WasmExecutor.call(&mut ext, &test_code[..], "test_twox_256", &[]).unwrap(), FromHex::from_hex("99e9d85137db46ef4bbea33613baafd56f963c64b1f3685a4eb4abd67ff6203a").unwrap() @@ -387,7 +406,7 @@ mod tests { #[test] fn twox_128_should_work() { let mut ext = TestExternalities::default(); - let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); + let test_code = include_bytes!("../wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); assert_eq!( WasmExecutor.call(&mut ext, &test_code[..], "test_twox_128", &[]).unwrap(), FromHex::from_hex("99e9d85137db46ef4bbea33613baafd5").unwrap() @@ -401,7 +420,7 @@ mod tests { #[test] fn ed25519_verify_should_work() { let mut ext = TestExternalities::default(); - let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); + let test_code = include_bytes!("../wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); let key = ::ed25519::Pair::from_seed(&blake2_256(b"test")); let sig = key.sign(b"all ok!"); let mut calldata = vec![]; @@ -416,41 +435,10 @@ mod tests { #[test] fn enumerated_trie_root_should_work() { let mut ext = TestExternalities::default(); - let test_code = include_bytes!("../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); + let test_code = include_bytes!("../wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm"); assert_eq!( 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() ); } - - #[test] - fn panic_execution_gives_error() { - let one = one(); - let mut t = TestExternalities { storage: map![ - twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![68u8, 0, 0, 0, 0, 0, 0, 0] - ], }; - - 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", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); - assert!(r.is_err()); - } - - #[test] - fn successful_execution_gives_ok() { - let one = one(); - let two = two(); - - let mut t = TestExternalities { storage: map![ - twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![111u8, 0, 0, 0, 0, 0, 0, 0] - ], }; - - 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", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); - assert!(r.is_ok()); - - runtime_io::with_externalities(&mut t, || { - assert_eq!(balance(&one), 42); - assert_eq!(balance(&two), 69); - }); - } } diff --git a/substrate/executor/src/wasm_utils.rs b/substrate/executor/src/wasm_utils.rs index 11fc404e2c..0e747b7fe3 100644 --- a/substrate/executor/src/wasm_utils.rs +++ b/substrate/executor/src/wasm_utils.rs @@ -198,10 +198,3 @@ impl AddModuleWithoutFullDependentInstance for interpreter::ProgramInstance $value:expr ),*) => ( - vec![ $( ( $name, $value ) ),* ].into_iter().collect() - ) -} diff --git a/substrate/executor/wasm/Cargo.lock b/substrate/executor/wasm/Cargo.lock new file mode 100644 index 0000000000..5b062eb2d9 --- /dev/null +++ b/substrate/executor/wasm/Cargo.lock @@ -0,0 +1,124 @@ +[[package]] +name = "byteorder" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "crunchy" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "fixed-hash" +version = "0.1.3" +source = "git+https://github.com/rphmeier/primitives.git?branch=compile-for-wasm#8dc457899afdaf968ff7f16140b03d1e37b01d71" + +[[package]] +name = "pwasm-alloc" +version = "0.1.0" +dependencies = [ + "pwasm-libc 0.1.0", + "rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "pwasm-libc" +version = "0.1.0" + +[[package]] +name = "runtime-test" +version = "0.1.0" +dependencies = [ + "substrate-runtime-io 0.1.0", +] + +[[package]] +name = "rustc-hex" +version = "2.0.0" +source = "git+https://github.com/rphmeier/rustc-hex.git#ee2ec40b9062ac7769ccb9dc891d6dc2cc9009d7" + +[[package]] +name = "rustc_version" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "semver" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "serde" +version = "1.0.27" +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 = [ + "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)", + "substrate-codec 0.1.0", + "substrate-runtime-std 0.1.0", + "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 = [ + "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", +] + +[[package]] +name = "substrate-runtime-std" +version = "0.1.0" +dependencies = [ + "pwasm-alloc 0.1.0", + "pwasm-libc 0.1.0", + "rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "uint" +version = "0.1.2" +source = "git+https://github.com/rphmeier/primitives.git?branch=compile-for-wasm#8dc457899afdaf968ff7f16140b03d1e37b01d71" +dependencies = [ + "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[metadata] +"checksum byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "652805b7e73fada9d85e9a6682a4abd490cb52d96aeecc12e33a0de34dfd0d23" +"checksum crunchy 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "a2f4a431c5c9f662e1200b7c7f02c34e91361150e382089a8f2dec3ba680cbda" +"checksum fixed-hash 0.1.3 (git+https://github.com/rphmeier/primitives.git?branch=compile-for-wasm)" = "" +"checksum rustc-hex 2.0.0 (git+https://github.com/rphmeier/rustc-hex.git)" = "" +"checksum rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b9743a7670d88d5d52950408ecdb7c71d8986251ab604d4689dd2ca25c9bca69" +"checksum semver 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a3186ec9e65071a2095434b1f5bb24838d4e8e130f584c790f6033c79943537" +"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" +"checksum serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)" = "db99f3919e20faa51bb2996057f5031d8685019b5a06139b1ce761da671b8526" +"checksum uint 0.1.2 (git+https://github.com/rphmeier/primitives.git?branch=compile-for-wasm)" = "" diff --git a/substrate/wasm-runtime/test/Cargo.toml b/substrate/executor/wasm/Cargo.toml similarity index 80% rename from substrate/wasm-runtime/test/Cargo.toml rename to substrate/executor/wasm/Cargo.toml index 3df27c9c11..d63e04d5fa 100644 --- a/substrate/wasm-runtime/test/Cargo.toml +++ b/substrate/executor/wasm/Cargo.toml @@ -8,3 +8,9 @@ crate-type = ["cdylib"] [dependencies] substrate-runtime-io = { path = "../../runtime-io", version = "0.1", default_features = false } + +[profile.release] +panic = "abort" + +[workspace] +members = [] diff --git a/substrate/executor/wasm/build.sh b/substrate/executor/wasm/build.sh new file mode 100755 index 0000000000..e173ccd36e --- /dev/null +++ b/substrate/executor/wasm/build.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -e + +cargo +nightly build --target=wasm32-unknown-unknown --release +for i in test +do + wasm-gc target/wasm32-unknown-unknown/release/runtime_$i.wasm target/wasm32-unknown-unknown/release/runtime_$i.compact.wasm +done diff --git a/substrate/wasm-runtime/test/src/lib.rs b/substrate/executor/wasm/src/lib.rs similarity index 100% rename from substrate/wasm-runtime/test/src/lib.rs rename to substrate/executor/wasm/src/lib.rs diff --git a/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm b/substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm similarity index 76% rename from substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm rename to substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm index 3c4e94098f..2b8e909b3e 100644 Binary files a/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm and b/substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm differ diff --git a/substrate/native-runtime/src b/substrate/native-runtime/src deleted file mode 120000 index 12e3333860..0000000000 --- a/substrate/native-runtime/src +++ /dev/null @@ -1 +0,0 @@ -../wasm-runtime/polkadot/src \ No newline at end of file diff --git a/substrate/network/Cargo.toml b/substrate/network/Cargo.toml index e1e8310d33..39e88c97db 100644 --- a/substrate/network/Cargo.toml +++ b/substrate/network/Cargo.toml @@ -11,8 +11,7 @@ authors = ["Parity Technologies "] ethcore-network = { git = "https://github.com/paritytech/parity.git" } ethcore-io = { git = "https://github.com/paritytech/parity.git" } substrate-primitives = { path = "../primitives" } -polkadot-primitives = { path = "../polkadot-primitives" } -polkadot-client = { path = "../client" } +substrate-client = { path = "../client" } substrate-state-machine = { path = "../state-machine" } substrate-serializer = { path = "../serializer" } log = "0.3" @@ -28,3 +27,4 @@ bitflags = "1.0" serde = "1.0" serde_derive = "1.0" serde_json = "1.0" +polkadot-primitives = { path = "../polkadot-primitives" } diff --git a/substrate/network/src/lib.rs b/substrate/network/src/lib.rs index 6feabb0b46..bdd7b41ca6 100644 --- a/substrate/network/src/lib.rs +++ b/substrate/network/src/lib.rs @@ -35,7 +35,7 @@ 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; +extern crate substrate_client as client; #[macro_use] extern crate serde_derive; #[macro_use] extern crate log; #[macro_use] extern crate bitflags; diff --git a/substrate/candidate-agreement/Cargo.toml b/substrate/polkadot-candidate-agreement/Cargo.toml similarity index 100% rename from substrate/candidate-agreement/Cargo.toml rename to substrate/polkadot-candidate-agreement/Cargo.toml diff --git a/substrate/candidate-agreement/src/bft/accumulator.rs b/substrate/polkadot-candidate-agreement/src/bft/accumulator.rs similarity index 100% rename from substrate/candidate-agreement/src/bft/accumulator.rs rename to substrate/polkadot-candidate-agreement/src/bft/accumulator.rs diff --git a/substrate/candidate-agreement/src/bft/mod.rs b/substrate/polkadot-candidate-agreement/src/bft/mod.rs similarity index 100% rename from substrate/candidate-agreement/src/bft/mod.rs rename to substrate/polkadot-candidate-agreement/src/bft/mod.rs diff --git a/substrate/candidate-agreement/src/bft/tests.rs b/substrate/polkadot-candidate-agreement/src/bft/tests.rs similarity index 100% rename from substrate/candidate-agreement/src/bft/tests.rs rename to substrate/polkadot-candidate-agreement/src/bft/tests.rs diff --git a/substrate/candidate-agreement/src/handle_incoming.rs b/substrate/polkadot-candidate-agreement/src/handle_incoming.rs similarity index 100% rename from substrate/candidate-agreement/src/handle_incoming.rs rename to substrate/polkadot-candidate-agreement/src/handle_incoming.rs diff --git a/substrate/candidate-agreement/src/lib.rs b/substrate/polkadot-candidate-agreement/src/lib.rs similarity index 100% rename from substrate/candidate-agreement/src/lib.rs rename to substrate/polkadot-candidate-agreement/src/lib.rs diff --git a/substrate/candidate-agreement/src/round_robin.rs b/substrate/polkadot-candidate-agreement/src/round_robin.rs similarity index 100% rename from substrate/candidate-agreement/src/round_robin.rs rename to substrate/polkadot-candidate-agreement/src/round_robin.rs diff --git a/substrate/candidate-agreement/src/table.rs b/substrate/polkadot-candidate-agreement/src/table.rs similarity index 100% rename from substrate/candidate-agreement/src/table.rs rename to substrate/polkadot-candidate-agreement/src/table.rs diff --git a/substrate/candidate-agreement/src/tests/mod.rs b/substrate/polkadot-candidate-agreement/src/tests/mod.rs similarity index 100% rename from substrate/candidate-agreement/src/tests/mod.rs rename to substrate/polkadot-candidate-agreement/src/tests/mod.rs diff --git a/substrate/polkadot-cli/Cargo.toml b/substrate/polkadot-cli/Cargo.toml new file mode 100644 index 0000000000..6ab7915afb --- /dev/null +++ b/substrate/polkadot-cli/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "polkadot-cli" +version = "0.1.0" +authors = ["Parity Technologies "] +description = "Polkadot node implementation in Rust." + +[dependencies] +clap = { version = "2.27", features = ["yaml"] } +env_logger = "0.4" +error-chain = "0.11" +log = "0.3" +hex-literal = "0.1" +ed25519 = { path = "../ed25519" } +triehash = { version = "0.1" } +substrate-client = { path = "../client" } +substrate-codec = { path = "../codec" } +substrate-runtime-io = { path = "../runtime-io" } +substrate-state-machine = { path = "../state-machine" } +substrate-executor = { path = "../executor" } +substrate-primitives = { path = "../primitives" } +substrate-rpc-servers = { path = "../rpc-servers" } +polkadot-primitives = { path = "../polkadot-primitives" } +polkadot-executor = { path = "../polkadot-executor" } +polkadot-runtime = { path = "../polkadot-runtime" } diff --git a/substrate/cli/src/cli.yml b/substrate/polkadot-cli/src/cli.yml similarity index 100% rename from substrate/cli/src/cli.yml rename to substrate/polkadot-cli/src/cli.yml diff --git a/substrate/cli/src/error.rs b/substrate/polkadot-cli/src/error.rs similarity index 100% rename from substrate/cli/src/error.rs rename to substrate/polkadot-cli/src/error.rs diff --git a/substrate/client/src/genesis.rs b/substrate/polkadot-cli/src/genesis.rs similarity index 90% rename from substrate/client/src/genesis.rs rename to substrate/polkadot-cli/src/genesis.rs index 788513ffa6..74e6ff6a3a 100644 --- a/substrate/client/src/genesis.rs +++ b/substrate/polkadot-cli/src/genesis.rs @@ -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 . +// along with Substrate. If not, see . //! Tool for creating the genesis block. @@ -40,12 +40,12 @@ pub fn construct_genesis_block(storage: &HashMap, Vec>) -> Block { mod tests { use super::*; use codec::{Slicable, Joiner}; - use native_runtime::support::{one, two, Hashable}; - use native_runtime::runtime::genesismap::{GenesisConfig, additional_storage_with_genesis}; + use polkadot_runtime::support::{one, two, Hashable}; + use polkadot_runtime::genesismap::{GenesisConfig, additional_storage_with_genesis}; use state_machine::execute; use state_machine::OverlayedChanges; use state_machine::backend::InMemory; - use substrate_executor::executor; + use polkadot_executor::executor; use polkadot_primitives::{AccountId, Hash, BlockNumber, Header, Digest, UncheckedTransaction, Transaction, Function}; use ed25519::Pair; diff --git a/substrate/cli/src/lib.rs b/substrate/polkadot-cli/src/lib.rs similarity index 62% rename from substrate/cli/src/lib.rs rename to substrate/polkadot-cli/src/lib.rs index faad72526e..fdfe35b822 100644 --- a/substrate/cli/src/lib.rs +++ b/substrate/polkadot-cli/src/lib.rs @@ -19,11 +19,19 @@ #![warn(missing_docs)] extern crate env_logger; -extern crate polkadot_client as client; -extern crate substrate_executor as executor; +extern crate ed25519; +extern crate triehash; +extern crate substrate_codec as codec; +extern crate substrate_state_machine as state_machine; +extern crate substrate_client as client; extern crate substrate_primitives as primitives; -extern crate polkadot_rpc_servers as rpc; +extern crate substrate_rpc_servers as rpc; +extern crate polkadot_primitives; +extern crate polkadot_executor; +extern crate polkadot_runtime; +#[macro_use] +extern crate hex_literal; #[macro_use] extern crate clap; #[macro_use] @@ -31,8 +39,12 @@ extern crate error_chain; #[macro_use] extern crate log; +mod genesis; pub mod error; +use codec::Slicable; +use polkadot_runtime::genesismap::{additional_storage_with_genesis, GenesisConfig}; + /// Parse command line arguments and start the node. /// /// IANA unassigned port ranges that we could use: @@ -53,8 +65,27 @@ pub fn run(args: I) -> error::Result<()> where init_logger(log_pattern); // Create client - let executor = executor::executor(); - let client = client::new_in_mem(executor)?; + let executor = polkadot_executor::executor(); + let mut storage = Default::default(); + let god_key = hex!["3d866ec8a9190c8343c2fc593d21d8a6d0c5c4763aaab2349de3a6111d64d124"]; + + let genesis_config = GenesisConfig { + validators: vec![god_key.clone()], + authorities: vec![god_key.clone()], + balances: vec![(god_key.clone(), 1u64 << 63)].into_iter().collect(), + block_time: 5, // 5 second block time. + session_length: 720, // that's 1 hour per session. + sessions_per_era: 24, // 24 hours per era. + bonding_duration: 90, // 90 days per bond. + approval_ratio: 667, // 66.7% approvals required for legislation. + }; + let prepare_genesis = || { + storage = genesis_config.genesis_map(); + let block = genesis::construct_genesis_block(&storage); + storage.extend(additional_storage_with_genesis(&block)); + (primitives::block::Header::from_slice(&mut block.header.to_vec().as_ref()).expect("to_vec() always gives a valid serialisation; qed"), storage.into_iter().collect()) + }; + let client = client::new_in_mem(executor, prepare_genesis)?; let address = "127.0.0.1:9933".parse().unwrap(); let handler = rpc::rpc_handler(client); @@ -94,4 +125,3 @@ fn init_logger(pattern: &str) { builder.init().expect("Logger initialized only once."); } - diff --git a/substrate/collator/Cargo.toml b/substrate/polkadot-collator/Cargo.toml similarity index 100% rename from substrate/collator/Cargo.toml rename to substrate/polkadot-collator/Cargo.toml diff --git a/substrate/collator/src/lib.rs b/substrate/polkadot-collator/src/lib.rs similarity index 100% rename from substrate/collator/src/lib.rs rename to substrate/polkadot-collator/src/lib.rs diff --git a/substrate/polkadot-executor/Cargo.toml b/substrate/polkadot-executor/Cargo.toml new file mode 100644 index 0000000000..fdab366062 --- /dev/null +++ b/substrate/polkadot-executor/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "polkadot-executor" +version = "0.1.0" +authors = ["Parity Technologies "] +description = "Polkadot node implementation in Rust." + +[dependencies] +hex-literal = "0.1" +ed25519 = { path = "../ed25519" } +triehash = { version = "0.1" } +substrate-codec = { path = "../codec" } +substrate-runtime-io = { path = "../runtime-io" } +substrate-state-machine = { path = "../state-machine" } +substrate-executor = { path = "../executor" } +substrate-primitives = { path = "../primitives" } +polkadot-primitives = { path = "../polkadot-primitives", version = "0.1" } +polkadot-runtime = { path = "../polkadot-runtime" } diff --git a/substrate/polkadot-executor/src/lib.rs b/substrate/polkadot-executor/src/lib.rs new file mode 100644 index 0000000000..0c6c0fb37e --- /dev/null +++ b/substrate/polkadot-executor/src/lib.rs @@ -0,0 +1,315 @@ +// 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 . + +//! A `CodeExecutor` specialisation which uses natively compiled runtime when the wasm to be +//! executed is equivalent to the natively compiled code. + +extern crate polkadot_runtime; +extern crate substrate_executor; +extern crate substrate_codec as codec; +extern crate substrate_state_machine as state_machine; +extern crate substrate_runtime_io as runtime_io; +extern crate substrate_primitives as primitives; +extern crate polkadot_primitives as polkadot_primitives; +extern crate ed25519; +extern crate triehash; +#[cfg(test)] +#[macro_use] +extern crate hex_literal; + +use polkadot_runtime as runtime; +use substrate_executor::{NativeExecutionDispatch, NativeExecutor}; + +/// A null struct which implements `NativeExecutionDispatch` feeding in the hard-coded runtime. +pub struct LocalNativeExecutionDispatch; + +impl NativeExecutionDispatch for LocalNativeExecutionDispatch { + fn native_equivalent() -> &'static [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. + include_bytes!("../../polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.compact.wasm") + } + + fn dispatch(method: &str, data: &[u8]) -> Option> { + runtime::dispatch(method, data) + } +} + +/// Creates new RustExecutor for contracts. +pub fn executor() -> NativeExecutor { + NativeExecutor { _dummy: ::std::marker::PhantomData } +} + +#[cfg(test)] +mod tests { + use runtime_io; + use super::*; + use substrate_executor::WasmExecutor; + use codec::{KeyedVec, Slicable, Joiner}; + use polkadot_runtime::support::{one, two, Hashable}; + use polkadot_runtime::runtime::staking::balance; + use state_machine::{CodeExecutor, TestExternalities}; + 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!("../../polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.wasm"); + const COMPACT_CODE: &[u8] = include_bytes!("../../polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.compact.wasm"); + + // TODO: move into own crate. + macro_rules! map { + ($( $name:expr => $value:expr ),*) => ( + vec![ $( ( $name, $value ) ),* ].into_iter().collect() + ) + } + + fn tx() -> UncheckedTransaction { + let transaction = Transaction { + signed: one(), + nonce: 0, + function: Function::StakingTransfer(two(), 69), + }; + let signature = secret_for(&transaction.signed).unwrap() + .sign(&transaction.to_vec()); + + UncheckedTransaction { transaction, signature } + } + + #[test] + fn panic_execution_with_foreign_code_gives_error() { + let one = one(); + let mut t = TestExternalities { storage: map![ + twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![68u8, 0, 0, 0, 0, 0, 0, 0] + ], }; + + let r = executor().call(&mut t, BLOATY_CODE, "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); + assert!(r.is_err()); + } + + #[test] + fn panic_execution_with_native_equivalent_code_gives_error() { + let one = one(); + let mut t = TestExternalities { storage: map![ + twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![68u8, 0, 0, 0, 0, 0, 0, 0] + ], }; + + let r = executor().call(&mut t, COMPACT_CODE, "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); + assert!(r.is_err()); + } + + #[test] + fn successful_execution_with_native_equivalent_code_gives_ok() { + let one = one(); + let two = two(); + + let mut t = TestExternalities { storage: map![ + twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![111u8, 0, 0, 0, 0, 0, 0, 0] + ], }; + + let r = executor().call(&mut t, COMPACT_CODE, "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); + assert!(r.is_ok()); + + runtime_io::with_externalities(&mut t, || { + assert_eq!(balance(&one), 42); + assert_eq!(balance(&two), 69); + }); + } + + #[test] + fn successful_execution_with_foreign_code_gives_ok() { + let one = one(); + let two = two(); + + let mut t = TestExternalities { storage: map![ + twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![111u8, 0, 0, 0, 0, 0, 0, 0] + ], }; + + let r = executor().call(&mut t, BLOATY_CODE, "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); + assert!(r.is_ok()); + + runtime_io::with_externalities(&mut t, || { + assert_eq!(balance(&one), 42); + assert_eq!(balance(&two), 69); + }); + } + + fn new_test_ext() -> TestExternalities { + let one = one(); + let two = two(); + let three = [3u8; 32]; + + TestExternalities { storage: map![ + twox_128(&0u64.to_keyed_vec(b"sys:old:")).to_vec() => [69u8; 32].to_vec(), + twox_128(b"gov:apr").to_vec() => vec![].join(&667u32), + twox_128(b"ses:len").to_vec() => vec![].join(&2u64), + twox_128(b"ses:val:len").to_vec() => vec![].join(&3u32), + twox_128(&0u32.to_keyed_vec(b"ses:val:")).to_vec() => one.to_vec(), + twox_128(&1u32.to_keyed_vec(b"ses:val:")).to_vec() => two.to_vec(), + twox_128(&2u32.to_keyed_vec(b"ses:val:")).to_vec() => three.to_vec(), + twox_128(b"sta:wil:len").to_vec() => vec![].join(&3u32), + twox_128(&0u32.to_keyed_vec(b"sta:wil:")).to_vec() => one.to_vec(), + twox_128(&1u32.to_keyed_vec(b"sta:wil:")).to_vec() => two.to_vec(), + twox_128(&2u32.to_keyed_vec(b"sta:wil:")).to_vec() => three.to_vec(), + twox_128(b"sta:spe").to_vec() => vec![].join(&2u64), + twox_128(b"sta:vac").to_vec() => vec![].join(&3u64), + twox_128(b"sta:era").to_vec() => vec![].join(&0u64), + twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![111u8, 0, 0, 0, 0, 0, 0, 0] + ], } + } + + fn secret_for(who: &AccountId) -> Option { + match who { + x if *x == one() => Some(Pair::from_seed(b"12345678901234567890123456789012")), + x if *x == two() => Some("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60".into()), + _ => None, + } + } + + fn construct_block(number: BlockNumber, parent_hash: Hash, state_root: Hash, txs: Vec) -> (Vec, Hash) { + use triehash::ordered_trie_root; + + let transactions = txs.into_iter().map(|transaction| { + let signature = secret_for(&transaction.signed).unwrap() + .sign(&transaction.to_vec()); + + UncheckedTransaction { transaction, signature } + }).collect::>(); + + let transaction_root = ordered_trie_root(transactions.iter().map(Slicable::to_vec)).0.into(); + + let header = Header { + parent_hash, + number, + state_root, + transaction_root, + digest: Digest { logs: vec![], }, + }; + let hash = header.blake2_256(); + + (Block { header, transactions }.to_vec(), hash.into()) + } + + fn block1() -> (Vec, Hash) { + construct_block( + 1, + [69u8; 32].into(), + hex!("2481853da20b9f4322f34650fea5f240dcbfb266d02db94bfa0153c31f4a29db").into(), + vec![Transaction { + signed: one(), + nonce: 0, + function: Function::StakingTransfer(two(), 69), + }] + ) + } + + fn block2() -> (Vec, Hash) { + construct_block( + 2, + block1().1, + hex!("1feb4d3a2e587079e6ce1685fa79994efd995e33cb289d39cded67aac1bb46a9").into(), + vec![ + Transaction { + signed: two(), + nonce: 0, + function: Function::StakingTransfer(one(), 5), + }, + Transaction { + signed: one(), + nonce: 1, + function: Function::StakingTransfer(two(), 15), + } + ] + ) + } + + #[test] + fn test_execution_works() { + let mut t = new_test_ext(); + println!("Testing Wasm..."); + let r = WasmExecutor.call(&mut t, COMPACT_CODE, "run_tests", &block2().0); + assert!(r.is_ok()); + } + + #[test] + fn full_native_block_import_works() { + let mut t = new_test_ext(); + + executor().call(&mut t, COMPACT_CODE, "execute_block", &block1().0).unwrap(); + + runtime_io::with_externalities(&mut t, || { + assert_eq!(balance(&one()), 42); + assert_eq!(balance(&two()), 69); + }); + + executor().call(&mut t, COMPACT_CODE, "execute_block", &block2().0).unwrap(); + + runtime_io::with_externalities(&mut t, || { + assert_eq!(balance(&one()), 32); + assert_eq!(balance(&two()), 79); + }); + } + + #[test] + fn full_wasm_block_import_works() { + let mut t = new_test_ext(); + + WasmExecutor.call(&mut t, COMPACT_CODE, "execute_block", &block1().0).unwrap(); + + runtime_io::with_externalities(&mut t, || { + assert_eq!(balance(&one()), 42); + assert_eq!(balance(&two()), 69); + }); + + WasmExecutor.call(&mut t, COMPACT_CODE, "execute_block", &block2().0).unwrap(); + + runtime_io::with_externalities(&mut t, || { + assert_eq!(balance(&one()), 32); + assert_eq!(balance(&two()), 79); + }); + } + + #[test] + fn panic_execution_gives_error() { + let one = one(); + let mut t = TestExternalities { storage: map![ + twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![68u8, 0, 0, 0, 0, 0, 0, 0] + ], }; + + let foreign_code = include_bytes!("../../polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.wasm"); + let r = WasmExecutor.call(&mut t, &foreign_code[..], "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); + assert!(r.is_err()); + } + + #[test] + fn successful_execution_gives_ok() { + let one = one(); + let two = two(); + + let mut t = TestExternalities { storage: map![ + twox_128(&one.to_keyed_vec(b"sta:bal:")).to_vec() => vec![111u8, 0, 0, 0, 0, 0, 0, 0] + ], }; + + let foreign_code = include_bytes!("../../polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.compact.wasm"); + let r = WasmExecutor.call(&mut t, &foreign_code[..], "execute_transaction", &vec![].join(&Header::from_block_number(1u64)).join(&tx())); + assert!(r.is_ok()); + + runtime_io::with_externalities(&mut t, || { + assert_eq!(balance(&one), 42); + assert_eq!(balance(&two), 69); + }); + } +} diff --git a/substrate/native-runtime/Cargo.toml b/substrate/polkadot-runtime/Cargo.toml similarity index 96% rename from substrate/native-runtime/Cargo.toml rename to substrate/polkadot-runtime/Cargo.toml index 5666a80ce7..3bb02f1fbb 100644 --- a/substrate/native-runtime/Cargo.toml +++ b/substrate/polkadot-runtime/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "native-runtime" +name = "polkadot-runtime" version = "0.1.0" authors = ["Parity Technologies "] diff --git a/substrate/wasm-runtime/polkadot/src/runtime/genesismap.rs b/substrate/polkadot-runtime/src/genesismap.rs similarity index 95% rename from substrate/wasm-runtime/polkadot/src/runtime/genesismap.rs rename to substrate/polkadot-runtime/src/genesismap.rs index 8f55e0c073..a12086cc47 100644 --- a/substrate/wasm-runtime/polkadot/src/runtime/genesismap.rs +++ b/substrate/polkadot-runtime/src/genesismap.rs @@ -50,7 +50,7 @@ impl GenesisConfig { } pub fn genesis_map(&self) -> HashMap, Vec> { - let wasm_runtime = include_bytes!("../../../../wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.compact.wasm").to_vec(); + let wasm_runtime = include_bytes!("../wasm/genesis.wasm").to_vec(); vec![ (&b"gov:apr"[..], vec![].join(&self.approval_ratio)), (&b"ses:len"[..], vec![].join(&self.session_length)), diff --git a/substrate/wasm-runtime/polkadot/src/lib.rs b/substrate/polkadot-runtime/src/lib.rs similarity index 98% rename from substrate/wasm-runtime/polkadot/src/lib.rs rename to substrate/polkadot-runtime/src/lib.rs index 72e2d23c50..46e4b6c860 100644 --- a/substrate/wasm-runtime/polkadot/src/lib.rs +++ b/substrate/polkadot-runtime/src/lib.rs @@ -38,6 +38,9 @@ extern crate hex_literal; pub mod support; pub mod runtime; +#[cfg(feature = "std")] +pub mod genesismap; + use rstd::prelude::*; use codec::Slicable; use polkadot_primitives::{Header, Block, UncheckedTransaction}; diff --git a/substrate/wasm-runtime/polkadot/src/runtime/consensus.rs b/substrate/polkadot-runtime/src/runtime/consensus.rs similarity index 100% rename from substrate/wasm-runtime/polkadot/src/runtime/consensus.rs rename to substrate/polkadot-runtime/src/runtime/consensus.rs diff --git a/substrate/wasm-runtime/polkadot/src/runtime/governance.rs b/substrate/polkadot-runtime/src/runtime/governance.rs similarity index 100% rename from substrate/wasm-runtime/polkadot/src/runtime/governance.rs rename to substrate/polkadot-runtime/src/runtime/governance.rs diff --git a/substrate/wasm-runtime/polkadot/src/runtime/mod.rs b/substrate/polkadot-runtime/src/runtime/mod.rs similarity index 95% rename from substrate/wasm-runtime/polkadot/src/runtime/mod.rs rename to substrate/polkadot-runtime/src/runtime/mod.rs index ff70fe8928..6a54fa7310 100644 --- a/substrate/wasm-runtime/polkadot/src/runtime/mod.rs +++ b/substrate/polkadot-runtime/src/runtime/mod.rs @@ -32,6 +32,3 @@ pub mod governance; pub mod parachains; // TODO: polkadao - -#[cfg(feature = "std")] -pub mod genesismap; diff --git a/substrate/wasm-runtime/polkadot/src/runtime/parachains.rs b/substrate/polkadot-runtime/src/runtime/parachains.rs similarity index 99% rename from substrate/wasm-runtime/polkadot/src/runtime/parachains.rs rename to substrate/polkadot-runtime/src/runtime/parachains.rs index 222448467a..d0c4f5c845 100644 --- a/substrate/wasm-runtime/polkadot/src/runtime/parachains.rs +++ b/substrate/polkadot-runtime/src/runtime/parachains.rs @@ -17,7 +17,7 @@ //! Main parachains logic. For now this is just the determination of which validators do what. use rstd::prelude::*; -use runtime_io::mem; +use rstd::mem; use codec::{Slicable, Joiner}; use support::{Hashable, with_env, storage}; use runtime::session; diff --git a/substrate/wasm-runtime/polkadot/src/runtime/session.rs b/substrate/polkadot-runtime/src/runtime/session.rs similarity index 100% rename from substrate/wasm-runtime/polkadot/src/runtime/session.rs rename to substrate/polkadot-runtime/src/runtime/session.rs diff --git a/substrate/wasm-runtime/polkadot/src/runtime/staking.rs b/substrate/polkadot-runtime/src/runtime/staking.rs similarity index 99% rename from substrate/wasm-runtime/polkadot/src/runtime/staking.rs rename to substrate/polkadot-runtime/src/runtime/staking.rs index d6d4065dc9..210c518146 100644 --- a/substrate/wasm-runtime/polkadot/src/runtime/staking.rs +++ b/substrate/polkadot-runtime/src/runtime/staking.rs @@ -17,7 +17,7 @@ //! Staking manager: Handles balances and periodically determines the best set of validators. use rstd::prelude::*; -use runtime_io::cell::RefCell; +use rstd::cell::RefCell; use runtime_io::print; use codec::KeyedVec; use support::{storage, StorageVec}; diff --git a/substrate/wasm-runtime/polkadot/src/runtime/system.rs b/substrate/polkadot-runtime/src/runtime/system.rs similarity index 96% rename from substrate/wasm-runtime/polkadot/src/runtime/system.rs rename to substrate/polkadot-runtime/src/runtime/system.rs index 6eb6229470..a82d911ea9 100644 --- a/substrate/wasm-runtime/polkadot/src/runtime/system.rs +++ b/substrate/polkadot-runtime/src/runtime/system.rs @@ -18,7 +18,8 @@ //! and depositing logs. use rstd::prelude::*; -use runtime_io::{mem, storage_root, enumerated_trie_root}; +use rstd::mem; +use runtime_io::{print, storage_root, enumerated_trie_root}; use codec::{KeyedVec, Slicable}; use support::{Hashable, storage, with_env}; use polkadot_primitives::{AccountId, Hash, TxOrder, BlockNumber, Block, Header, @@ -71,6 +72,7 @@ pub mod internal { // execute transactions block.transactions.iter().cloned().for_each(super::execute_transaction); + // post-transactional book-keeping. staking::internal::check_new_era(); session::internal::check_rotate_session(); @@ -103,6 +105,13 @@ pub mod internal { /// Finalise the block - it is up the caller to ensure that all header fields are valid /// except state-root. pub fn finalise_block(mut header: Header) -> Header { + // populate environment from header. + with_env(|e| { + e.block_number = header.number; + e.parent_hash = header.parent_hash; + mem::swap(&mut header.digest, &mut e.digest); + }); + staking::internal::check_new_era(); session::internal::check_rotate_session(); @@ -211,7 +220,13 @@ fn info_expect_equal_hash(given: &Hash, expected: &Hash) { } #[cfg(not(feature = "std"))] -fn info_expect_equal_hash(_given: &Hash, _expected: &Hash) {} +fn info_expect_equal_hash(given: &Hash, expected: &Hash) { + if given != expected { + print("Hash not equal"); + print(&given.0[..]); + print(&expected.0[..]); + } +} #[cfg(test)] mod tests { diff --git a/substrate/wasm-runtime/polkadot/src/runtime/timestamp.rs b/substrate/polkadot-runtime/src/runtime/timestamp.rs similarity index 100% rename from substrate/wasm-runtime/polkadot/src/runtime/timestamp.rs rename to substrate/polkadot-runtime/src/runtime/timestamp.rs diff --git a/substrate/wasm-runtime/polkadot/src/support/environment.rs b/substrate/polkadot-runtime/src/support/environment.rs similarity index 96% rename from substrate/wasm-runtime/polkadot/src/support/environment.rs rename to substrate/polkadot-runtime/src/support/environment.rs index 63ab4277d1..d7651c575a 100644 --- a/substrate/wasm-runtime/polkadot/src/support/environment.rs +++ b/substrate/polkadot-runtime/src/support/environment.rs @@ -16,10 +16,10 @@ //! Environment API: Allows certain information to be accessed throughout the runtime. -use runtime_io::boxed::Box; -use runtime_io::mem; -use runtime_io::cell::RefCell; -use runtime_io::rc::Rc; +use rstd::boxed::Box; +use rstd::mem; +use rstd::cell::RefCell; +use rstd::rc::Rc; use polkadot_primitives::{BlockNumber, Digest, Hash}; diff --git a/substrate/wasm-runtime/polkadot/src/support/hashable.rs b/substrate/polkadot-runtime/src/support/hashable.rs similarity index 100% rename from substrate/wasm-runtime/polkadot/src/support/hashable.rs rename to substrate/polkadot-runtime/src/support/hashable.rs diff --git a/substrate/wasm-runtime/polkadot/src/support/mod.rs b/substrate/polkadot-runtime/src/support/mod.rs similarity index 100% rename from substrate/wasm-runtime/polkadot/src/support/mod.rs rename to substrate/polkadot-runtime/src/support/mod.rs diff --git a/substrate/wasm-runtime/polkadot/src/support/statichex.rs b/substrate/polkadot-runtime/src/support/statichex.rs similarity index 100% rename from substrate/wasm-runtime/polkadot/src/support/statichex.rs rename to substrate/polkadot-runtime/src/support/statichex.rs diff --git a/substrate/wasm-runtime/polkadot/src/support/storage.rs b/substrate/polkadot-runtime/src/support/storage.rs similarity index 100% rename from substrate/wasm-runtime/polkadot/src/support/storage.rs rename to substrate/polkadot-runtime/src/support/storage.rs diff --git a/substrate/wasm-runtime/polkadot/src/support/testing.rs b/substrate/polkadot-runtime/src/support/testing.rs similarity index 100% rename from substrate/wasm-runtime/polkadot/src/support/testing.rs rename to substrate/polkadot-runtime/src/support/testing.rs diff --git a/substrate/wasm-runtime/Cargo.lock b/substrate/polkadot-runtime/wasm/Cargo.lock similarity index 99% rename from substrate/wasm-runtime/Cargo.lock rename to substrate/polkadot-runtime/wasm/Cargo.lock index a6777c28db..506b138461 100644 --- a/substrate/wasm-runtime/Cargo.lock +++ b/substrate/polkadot-runtime/wasm/Cargo.lock @@ -386,6 +386,17 @@ dependencies = [ "substrate-runtime-std 0.1.0", ] +[[package]] +name = "polkadot-runtime" +version = "0.1.0" +dependencies = [ + "polkadot-primitives 0.1.0", + "substrate-codec 0.1.0", + "substrate-primitives 0.1.0", + "substrate-runtime-io 0.1.0", + "substrate-runtime-std 0.1.0", +] + [[package]] name = "proc-macro-hack" version = "0.4.0" @@ -510,24 +521,6 @@ dependencies = [ "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "runtime-polkadot" -version = "0.1.0" -dependencies = [ - "polkadot-primitives 0.1.0", - "substrate-codec 0.1.0", - "substrate-primitives 0.1.0", - "substrate-runtime-io 0.1.0", - "substrate-runtime-std 0.1.0", -] - -[[package]] -name = "runtime-test" -version = "0.1.0" -dependencies = [ - "substrate-runtime-io 0.1.0", -] - [[package]] name = "rustc-hex" version = "1.0.0" @@ -628,8 +621,6 @@ 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", @@ -642,6 +633,8 @@ dependencies = [ name = "substrate-runtime-std" version = "0.1.0" dependencies = [ + "pwasm-alloc 0.1.0", + "pwasm-libc 0.1.0", "rustc_version 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/substrate/polkadot-runtime/wasm/Cargo.toml b/substrate/polkadot-runtime/wasm/Cargo.toml new file mode 100644 index 0000000000..054d05c658 --- /dev/null +++ b/substrate/polkadot-runtime/wasm/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "polkadot-runtime" +version = "0.1.0" +authors = ["Parity Technologies "] + +[lib] +crate-type = ["cdylib"] + +[dependencies] +substrate-codec = { path = "../../codec", default-features = false } +substrate-runtime-std = { path = "../../runtime-std", default-features = false } +substrate-runtime-io = { path = "../../runtime-io", default-features = false } +substrate-primitives = { path = "../../primitives", default-features = false } +polkadot-primitives = { path = "../../polkadot-primitives", default-features = false } + +[features] +default = [] +std = ["substrate-codec/std", "substrate-runtime-io/std", "substrate-runtime-std/std", "substrate-primitives/std", "polkadot-primitives/std"] + +[profile.release] +panic = "abort" + +[workspace] +members = [] diff --git a/substrate/polkadot-runtime/wasm/build.sh b/substrate/polkadot-runtime/wasm/build.sh new file mode 100755 index 0000000000..d48d10a062 --- /dev/null +++ b/substrate/polkadot-runtime/wasm/build.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -e + +cargo +nightly build --target=wasm32-unknown-unknown --release +for i in polkadot_runtime +do + wasm-gc target/wasm32-unknown-unknown/release/$i.wasm target/wasm32-unknown-unknown/release/$i.compact.wasm +done diff --git a/substrate/polkadot-runtime/wasm/genesis.wasm b/substrate/polkadot-runtime/wasm/genesis.wasm new file mode 100644 index 0000000000..91c7b47574 Binary files /dev/null and b/substrate/polkadot-runtime/wasm/genesis.wasm differ diff --git a/substrate/wasm-runtime/init.sh b/substrate/polkadot-runtime/wasm/init.sh similarity index 100% rename from substrate/wasm-runtime/init.sh rename to substrate/polkadot-runtime/wasm/init.sh diff --git a/substrate/polkadot-runtime/wasm/src b/substrate/polkadot-runtime/wasm/src new file mode 120000 index 0000000000..5cd551cf26 --- /dev/null +++ b/substrate/polkadot-runtime/wasm/src @@ -0,0 +1 @@ +../src \ No newline at end of file diff --git a/substrate/polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.compact.wasm b/substrate/polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.compact.wasm new file mode 100644 index 0000000000..325669d0e0 Binary files /dev/null and b/substrate/polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.compact.wasm differ diff --git a/substrate/polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.wasm b/substrate/polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.wasm new file mode 100644 index 0000000000..91c7b47574 Binary files /dev/null and b/substrate/polkadot-runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.wasm differ diff --git a/substrate/validator/Cargo.toml b/substrate/polkadot-validator/Cargo.toml similarity index 100% rename from substrate/validator/Cargo.toml rename to substrate/polkadot-validator/Cargo.toml diff --git a/substrate/validator/src/error.rs b/substrate/polkadot-validator/src/error.rs similarity index 100% rename from substrate/validator/src/error.rs rename to substrate/polkadot-validator/src/error.rs diff --git a/substrate/validator/src/lib.rs b/substrate/polkadot-validator/src/lib.rs similarity index 100% rename from substrate/validator/src/lib.rs rename to substrate/polkadot-validator/src/lib.rs diff --git a/substrate/validator/src/parachains.rs b/substrate/polkadot-validator/src/parachains.rs similarity index 100% rename from substrate/validator/src/parachains.rs rename to substrate/polkadot-validator/src/parachains.rs diff --git a/substrate/validator/src/validator.rs b/substrate/polkadot-validator/src/validator.rs similarity index 100% rename from substrate/validator/src/validator.rs rename to substrate/polkadot-validator/src/validator.rs diff --git a/substrate/primitives/src/lib.rs b/substrate/primitives/src/lib.rs index 452889d74b..3822a77d8c 100644 --- a/substrate/primitives/src/lib.rs +++ b/substrate/primitives/src/lib.rs @@ -43,7 +43,6 @@ extern crate serde_derive; #[cfg(feature = "std")] extern crate core; -#[macro_use] extern crate substrate_runtime_std as rstd; #[cfg(test)] diff --git a/substrate/wasm-runtime/pwasm-alloc/Cargo.toml b/substrate/pwasm-alloc/Cargo.toml similarity index 100% rename from substrate/wasm-runtime/pwasm-alloc/Cargo.toml rename to substrate/pwasm-alloc/Cargo.toml diff --git a/substrate/wasm-runtime/pwasm-alloc/README.md b/substrate/pwasm-alloc/README.md similarity index 100% rename from substrate/wasm-runtime/pwasm-alloc/README.md rename to substrate/pwasm-alloc/README.md diff --git a/substrate/wasm-runtime/pwasm-alloc/build.rs b/substrate/pwasm-alloc/build.rs similarity index 100% rename from substrate/wasm-runtime/pwasm-alloc/build.rs rename to substrate/pwasm-alloc/build.rs diff --git a/substrate/wasm-runtime/pwasm-alloc/src/lib.rs b/substrate/pwasm-alloc/src/lib.rs similarity index 100% rename from substrate/wasm-runtime/pwasm-alloc/src/lib.rs rename to substrate/pwasm-alloc/src/lib.rs diff --git a/substrate/wasm-runtime/pwasm-libc/Cargo.toml b/substrate/pwasm-libc/Cargo.toml similarity index 100% rename from substrate/wasm-runtime/pwasm-libc/Cargo.toml rename to substrate/pwasm-libc/Cargo.toml diff --git a/substrate/wasm-runtime/pwasm-libc/README.md b/substrate/pwasm-libc/README.md similarity index 100% rename from substrate/wasm-runtime/pwasm-libc/README.md rename to substrate/pwasm-libc/README.md diff --git a/substrate/wasm-runtime/pwasm-libc/src/lib.rs b/substrate/pwasm-libc/src/lib.rs similarity index 100% rename from substrate/wasm-runtime/pwasm-libc/src/lib.rs rename to substrate/pwasm-libc/src/lib.rs diff --git a/substrate/rpc-servers/Cargo.toml b/substrate/rpc-servers/Cargo.toml index d47b4d94a1..e242664da3 100644 --- a/substrate/rpc-servers/Cargo.toml +++ b/substrate/rpc-servers/Cargo.toml @@ -1,9 +1,9 @@ [package] -name = "polkadot-rpc-servers" +name = "substrate-rpc-servers" version = "0.1.0" authors = ["Parity Technologies "] [dependencies] -polkadot-rpc = { path = "../rpc", version = "0.1" } +substrate-rpc = { path = "../rpc", version = "0.1" } jsonrpc-core = { git="https://github.com/paritytech/jsonrpc.git" } jsonrpc-http-server = { git="https://github.com/paritytech/jsonrpc.git" } diff --git a/substrate/rpc-servers/src/lib.rs b/substrate/rpc-servers/src/lib.rs index 2bc78a06f2..cf2f6f2dc1 100644 --- a/substrate/rpc-servers/src/lib.rs +++ b/substrate/rpc-servers/src/lib.rs @@ -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 . +// along with Substrate. If not, see . -//! Polkadot RPC servers. +//! Substrate RPC servers. #[warn(missing_docs)] -extern crate polkadot_rpc as apis; +extern crate substrate_rpc as apis; extern crate jsonrpc_core as rpc; extern crate jsonrpc_http_server as http; diff --git a/substrate/rpc/Cargo.toml b/substrate/rpc/Cargo.toml index fdf9f7595b..149199546e 100644 --- a/substrate/rpc/Cargo.toml +++ b/substrate/rpc/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "polkadot-rpc" +name = "substrate-rpc" version = "0.1.0" authors = ["Parity Technologies "] @@ -7,9 +7,10 @@ authors = ["Parity Technologies "] 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" } +substrate-client = { path = "../client" } substrate-primitives = { path = "../primitives" } substrate-state-machine = { path = "../state-machine" } +substrate-executor = { path = "../executor" } [dev-dependencies] assert_matches = "1.1" diff --git a/substrate/rpc/src/chain/error.rs b/substrate/rpc/src/chain/error.rs index a838f30787..fb55a643ea 100644 --- a/substrate/rpc/src/chain/error.rs +++ b/substrate/rpc/src/chain/error.rs @@ -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 . +// along with Substrate. If not, see . use rpc; diff --git a/substrate/rpc/src/chain/mod.rs b/substrate/rpc/src/chain/mod.rs index 519bdefb4a..473b53aff0 100644 --- a/substrate/rpc/src/chain/mod.rs +++ b/substrate/rpc/src/chain/mod.rs @@ -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 . +// along with Substrate. If not, see . -//! Polkadot blockchain API. +//! Substrate blockchain API. use primitives::block; use client; diff --git a/substrate/rpc/src/chain/tests.rs b/substrate/rpc/src/chain/tests.rs index ad629fd41f..c62981094c 100644 --- a/substrate/rpc/src/chain/tests.rs +++ b/substrate/rpc/src/chain/tests.rs @@ -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 . +// along with Substrate. If not, see . use substrate_executor as executor; use client; @@ -20,7 +20,15 @@ use super::*; #[test] fn should_return_header() { - let client = client::new_in_mem(executor::executor()).unwrap(); + let test_genesis_block = block::Header { + parent_hash: 0.into(), + number: 0, + state_root: 0.into(), + transaction_root: Default::default(), + digest: Default::default(), + }; + + let client = client::new_in_mem(executor::WasmExecutor, || (test_genesis_block.clone(), vec![])).unwrap(); assert_matches!( ChainApi::header(&client, "af65e54217fb213853703d57b80fc5b2bb834bf923046294d7a49bff62f0a8b2".into()), diff --git a/substrate/rpc/src/lib.rs b/substrate/rpc/src/lib.rs index 68935fb00b..05d3d94685 100644 --- a/substrate/rpc/src/lib.rs +++ b/substrate/rpc/src/lib.rs @@ -1,25 +1,25 @@ // 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 . +// along with Substrate. If not, see . -//! Polkadot RPC interfaces. +//! Substrate RPC interfaces. #![warn(missing_docs)] extern crate jsonrpc_core as rpc; -extern crate polkadot_client as client; +extern crate substrate_client as client; extern crate substrate_primitives as primitives; extern crate substrate_state_machine as state_machine; diff --git a/substrate/rpc/src/state/error.rs b/substrate/rpc/src/state/error.rs index 827ac9e8ca..57db7d18fe 100644 --- a/substrate/rpc/src/state/error.rs +++ b/substrate/rpc/src/state/error.rs @@ -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 . +// along with Substrate. If not, see . use client; use rpc; diff --git a/substrate/rpc/src/state/mod.rs b/substrate/rpc/src/state/mod.rs index b21b859435..2549f86a85 100644 --- a/substrate/rpc/src/state/mod.rs +++ b/substrate/rpc/src/state/mod.rs @@ -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 . +// along with Substrate. If not, see . //! Polkadot state API. diff --git a/substrate/rpc/src/state/tests.rs b/substrate/rpc/src/state/tests.rs index 8bc0d6ec5f..687c851c5c 100644 --- a/substrate/rpc/src/state/tests.rs +++ b/substrate/rpc/src/state/tests.rs @@ -1,28 +1,35 @@ // 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 . +// along with Substrate. If not, see . use super::*; use substrate_executor as executor; - use self::error::{Error, ErrorKind}; use client; #[test] fn should_return_storage() { - let client = client::new_in_mem(executor::executor()).unwrap(); + let test_genesis_block = block::Header { + parent_hash: 0.into(), + number: 0, + state_root: 0.into(), + transaction_root: Default::default(), + digest: Default::default(), + }; + + let client = client::new_in_mem(executor::WasmExecutor, || (test_genesis_block.clone(), vec![])).unwrap(); let genesis_hash = "af65e54217fb213853703d57b80fc5b2bb834bf923046294d7a49bff62f0a8b2".into(); assert_matches!( @@ -35,7 +42,15 @@ fn should_return_storage() { #[ignore] // TODO: [ToDr] reenable once we can properly mock the wasm executor env fn should_call_contract() { // TODO [ToDr] Fix test after we are able to mock state. - let client = client::new_in_mem(executor::executor()).unwrap(); + let test_genesis_block = block::Header { + parent_hash: 0.into(), + number: 0, + state_root: 0.into(), + transaction_root: Default::default(), + digest: Default::default(), + }; + + let client = client::new_in_mem(executor::WasmExecutor, || (test_genesis_block.clone(), vec![])).unwrap(); let genesis_hash = "af65e54217fb213853703d57b80fc5b2bb834bf923046294d7a49bff62f0a8b2".into(); assert_matches!( diff --git a/substrate/runtime-io/Cargo.toml b/substrate/runtime-io/Cargo.toml index 823ecd00b6..ef82206aad 100644 --- a/substrate/runtime-io/Cargo.toml +++ b/substrate/runtime-io/Cargo.toml @@ -8,8 +8,6 @@ build = "build.rs" 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 } diff --git a/substrate/runtime-io/with_std.rs b/substrate/runtime-io/with_std.rs index 63db356cbd..40c1fe754d 100644 --- a/substrate/runtime-io/with_std.rs +++ b/substrate/runtime-io/with_std.rs @@ -22,13 +22,6 @@ 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}; @@ -131,7 +124,16 @@ pub fn print(value: T) { #[macro_export] macro_rules! impl_stubs { - ($( $name:ident ),*) => {} + ($( $name:ident ),*) => { + pub fn dispatch(method: &str, data: &[u8]) -> Option> { + match method { + $( + stringify!($name) => Some($name(data)), + )* + _ => None, + } + } + } } #[cfg(test)] diff --git a/substrate/runtime-io/without_std.rs b/substrate/runtime-io/without_std.rs index 472b135beb..e5db2c7753 100644 --- a/substrate/runtime-io/without_std.rs +++ b/substrate/runtime-io/without_std.rs @@ -14,24 +14,12 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -#[cfg(feature = "nightly")] -extern crate alloc; - -#[cfg(feature = "nightly")] -extern crate pwasm_libc; -#[cfg(feature = "nightly")] -extern crate pwasm_alloc; - +extern crate substrate_runtime_std as rstd; 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; +use rstd::intrinsics; +use rstd::vec::Vec; +pub use rstd::{mem, slice}; #[lang = "panic_fmt"] #[no_mangle] @@ -40,7 +28,7 @@ pub extern fn panic_fmt(_fmt: ::core::fmt::Arguments, _file: &'static str, _line 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() + intrinsics::abort() } } @@ -83,7 +71,11 @@ pub fn set_storage(key: &[u8], value: &[u8]) { /// 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 + 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 } } @@ -200,7 +192,9 @@ macro_rules! impl_stubs { }; let output = super::$name(input); - output.as_ptr() as u64 + ((output.len() as u64) << 32) + let r = output.as_ptr() as u64 + ((output.len() as u64) << 32); + $crate::mem::forget(output); + r } )* } diff --git a/substrate/runtime-std/Cargo.toml b/substrate/runtime-std/Cargo.toml index e619a9b5d4..42745a0152 100644 --- a/substrate/runtime-std/Cargo.toml +++ b/substrate/runtime-std/Cargo.toml @@ -8,6 +8,8 @@ build = "build.rs" rustc_version = "0.2" [dependencies] +pwasm-alloc = { path = "../pwasm-alloc" } +pwasm-libc = { path = "../pwasm-libc" } [features] default = ["std"] diff --git a/substrate/runtime-std/without_std.rs b/substrate/runtime-std/without_std.rs index ea0f278d37..4aff3153ca 100644 --- a/substrate/runtime-std/without_std.rs +++ b/substrate/runtime-std/without_std.rs @@ -16,6 +16,10 @@ #[cfg(feature = "nightly")] extern crate alloc; +#[cfg(feature = "nightly")] +extern crate pwasm_libc; +#[cfg(feature = "nightly")] +extern crate pwasm_alloc; pub use alloc::vec; pub use alloc::boxed; @@ -26,3 +30,4 @@ pub use core::cell; pub use core::ops; pub use core::iter; pub use core::ptr; +pub use core::intrinsics; diff --git a/substrate/wasm-runtime/Cargo.toml b/substrate/wasm-runtime/Cargo.toml deleted file mode 100644 index 0dc0216fe5..0000000000 --- a/substrate/wasm-runtime/Cargo.toml +++ /dev/null @@ -1,8 +0,0 @@ -[workspace] -members = [ - "test", - "polkadot", -] - -[profile.release] -panic = "abort" diff --git a/substrate/wasm-runtime/build.sh b/substrate/wasm-runtime/build.sh deleted file mode 100755 index 83f46d5a04..0000000000 --- a/substrate/wasm-runtime/build.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -set -e - -cargo +nightly build --target=wasm32-unknown-unknown --release -dirs=`find * -maxdepth 0 -type d | grep -v pwasm- | grep -v std` -for i in $dirs -do - if [[ -e $i/Cargo.toml ]] - then - wasm-gc target/wasm32-unknown-unknown/release/runtime_$i.wasm target/wasm32-unknown-unknown/release/runtime_$i.compact.wasm - fi -done diff --git a/substrate/wasm-runtime/polkadot/Cargo.toml b/substrate/wasm-runtime/polkadot/Cargo.toml deleted file mode 100644 index bde7c47729..0000000000 --- a/substrate/wasm-runtime/polkadot/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "runtime-polkadot" -version = "0.1.0" -authors = ["Parity Technologies "] - -[lib] -crate-type = ["cdylib"] - -[dependencies] -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 = ["substrate-codec/std", "substrate-runtime-io/std", "substrate-runtime-std/std", "substrate-primitives/std", "polkadot-primitives/std"] diff --git a/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.compact.wasm b/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.compact.wasm deleted file mode 100644 index 2af0747ed1..0000000000 Binary files a/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.compact.wasm and /dev/null differ diff --git a/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.wasm b/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.wasm deleted file mode 100644 index f89b2a1d9b..0000000000 Binary files a/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_polkadot.wasm and /dev/null differ diff --git a/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.wasm b/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.wasm deleted file mode 100644 index 6a79823c53..0000000000 Binary files a/substrate/wasm-runtime/target/wasm32-unknown-unknown/release/runtime_test.wasm and /dev/null differ