Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit a52a23d

Browse files
committed
Merge branch 'master' into td-logging
2 parents a9582b6 + 0cd7260 commit a52a23d

File tree

50 files changed

+2796
-2186
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+2796
-2186
lines changed

Cargo.lock

Lines changed: 141 additions & 86 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ members = [
103103
"srml/staking/reward-curve",
104104
"srml/sudo",
105105
"srml/system",
106+
"srml/system/rpc",
106107
"srml/timestamp",
107108
"srml/treasury",
108109
"srml/utility",

core/chain-spec/src/chain_spec.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use std::borrow::Cow;
2020
use std::collections::HashMap;
2121
use std::fs::File;
2222
use std::path::PathBuf;
23+
use std::rc::Rc;
2324
use serde::{Serialize, Deserialize};
2425
use primitives::storage::{StorageKey, StorageData};
2526
use sr_primitives::{BuildStorage, StorageOverlay, ChildrenStorageOverlay};
@@ -31,15 +32,15 @@ use tel::TelemetryEndpoints;
3132
enum GenesisSource<G> {
3233
File(PathBuf),
3334
Binary(Cow<'static, [u8]>),
34-
Factory(fn() -> G),
35+
Factory(Rc<dyn Fn() -> G>),
3536
}
3637

3738
impl<G> Clone for GenesisSource<G> {
3839
fn clone(&self) -> Self {
3940
match *self {
4041
GenesisSource::File(ref path) => GenesisSource::File(path.clone()),
4142
GenesisSource::Binary(ref d) => GenesisSource::Binary(d.clone()),
42-
GenesisSource::Factory(f) => GenesisSource::Factory(f),
43+
GenesisSource::Factory(ref f) => GenesisSource::Factory(f.clone()),
4344
}
4445
}
4546
}
@@ -187,10 +188,10 @@ impl<G, E> ChainSpec<G, E> {
187188
}
188189

189190
/// Create hardcoded spec.
190-
pub fn from_genesis(
191+
pub fn from_genesis<F: Fn() -> G + 'static>(
191192
name: &str,
192193
id: &str,
193-
constructor: fn() -> G,
194+
constructor: F,
194195
boot_nodes: Vec<String>,
195196
telemetry_endpoints: Option<TelemetryEndpoints>,
196197
protocol_id: Option<&str>,
@@ -211,7 +212,7 @@ impl<G, E> ChainSpec<G, E> {
211212

212213
ChainSpec {
213214
spec,
214-
genesis: GenesisSource::Factory(constructor),
215+
genesis: GenesisSource::Factory(Rc::new(constructor)),
215216
}
216217
}
217218
}

core/client/src/client.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1059,10 +1059,10 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
10591059
}
10601060
};
10611061

1062-
let encoded_block = <Block as BlockT>::new(
1063-
import_headers.pre().clone(),
1064-
body.unwrap_or_default(),
1065-
).encode();
1062+
let encoded_block = <Block as BlockT>::encode_from(
1063+
import_headers.pre(),
1064+
&body.unwrap_or_default()
1065+
);
10661066

10671067
let (_, storage_update, changes_update) = self.executor
10681068
.call_at_state::<_, _, NeverNativeValue, fn() -> _>(

core/executor/src/error.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,12 @@ impl From<String> for Error {
9999
}
100100
}
101101

102+
impl From<WasmError> for Error {
103+
fn from(err: WasmError) -> Error {
104+
Error::Other(err.to_string())
105+
}
106+
}
107+
102108
/// Type for errors occurring during Wasm runtime construction.
103109
#[derive(Debug, derive_more::Display)]
104110
pub enum WasmError {

core/executor/src/lib.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,33 @@ pub use primitives::traits::Externalities;
5050
pub use wasm_interface;
5151
pub use wasm_runtime::WasmExecutionMethod;
5252

53+
/// Call the given `function` in the given wasm `code`.
54+
///
55+
/// The signature of `function` needs to follow the default Substrate function signature.
56+
///
57+
/// - `call_data`: Will be given as input parameters to `function`
58+
/// - `execution_method`: The execution method to use.
59+
/// - `ext`: The externalities that should be set while executing the wasm function.
60+
/// - `heap_pages`: The number of heap pages to allocate.
61+
///
62+
/// Returns the `Vec<u8>` that contains the return value of the function.
63+
pub fn call_in_wasm<E: Externalities>(
64+
function: &str,
65+
call_data: &[u8],
66+
execution_method: WasmExecutionMethod,
67+
ext: &mut E,
68+
code: &[u8],
69+
heap_pages: u64,
70+
) -> error::Result<Vec<u8>> {
71+
let mut instance = wasm_runtime::create_wasm_runtime_with_code(
72+
ext,
73+
execution_method,
74+
heap_pages,
75+
code,
76+
)?;
77+
instance.call(ext, function, call_data)
78+
}
79+
5380
/// Provides runtime information.
5481
pub trait RuntimeInfo {
5582
/// Native runtime information.
@@ -61,3 +88,24 @@ pub trait RuntimeInfo {
6188
ext: &mut E,
6289
) -> Option<RuntimeVersion>;
6390
}
91+
92+
#[cfg(test)]
93+
mod tests {
94+
use super::*;
95+
use runtime_test::WASM_BINARY;
96+
use runtime_io::TestExternalities;
97+
98+
#[test]
99+
fn call_in_interpreted_wasm_works() {
100+
let mut ext = TestExternalities::default();
101+
let res = call_in_wasm(
102+
"test_empty_return",
103+
&[],
104+
WasmExecutionMethod::Interpreted,
105+
&mut ext,
106+
&WASM_BINARY,
107+
8,
108+
).unwrap();
109+
assert_eq!(res, vec![0u8; 0]);
110+
}
111+
}

core/executor/src/wasm_runtime.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,17 +157,27 @@ impl RuntimesCache {
157157
}
158158
}
159159

160-
fn create_wasm_runtime<E: Externalities>(
160+
/// Create a wasm runtime with the given `code`.
161+
pub fn create_wasm_runtime_with_code<E: Externalities>(
161162
ext: &mut E,
162163
wasm_method: WasmExecutionMethod,
163164
heap_pages: u64,
165+
code: &[u8],
164166
) -> Result<Box<dyn WasmRuntime>, WasmError> {
165-
let code = ext
166-
.original_storage(well_known_keys::CODE)
167-
.ok_or(WasmError::CodeNotFound)?;
168167
match wasm_method {
169168
WasmExecutionMethod::Interpreted =>
170-
wasmi_execution::create_instance(ext, &code, heap_pages)
169+
wasmi_execution::create_instance(ext, code, heap_pages)
171170
.map(|runtime| -> Box<dyn WasmRuntime> { Box::new(runtime) }),
172171
}
173172
}
173+
174+
fn create_wasm_runtime<E: Externalities>(
175+
ext: &mut E,
176+
wasm_method: WasmExecutionMethod,
177+
heap_pages: u64,
178+
) -> Result<Box<dyn WasmRuntime>, WasmError> {
179+
let code = ext
180+
.original_storage(well_known_keys::CODE)
181+
.ok_or(WasmError::CodeNotFound)?;
182+
create_wasm_runtime_with_code(ext, wasm_method, heap_pages, &code)
183+
}

core/rpc/api/src/system/helpers.rs

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,14 @@ pub struct Health {
5050
pub should_have_peers: bool,
5151
}
5252

53+
impl fmt::Display for Health {
54+
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
55+
write!(fmt, "{} peers ({})", self.peers, if self.is_syncing {
56+
"syncing"
57+
} else { "idle" })
58+
}
59+
}
60+
5361
/// Network Peer information
5462
#[derive(Debug, PartialEq, Serialize, Deserialize)]
5563
#[serde(rename_all = "camelCase")]
@@ -66,12 +74,17 @@ pub struct PeerInfo<Hash, Number> {
6674
pub best_number: Number,
6775
}
6876

69-
impl fmt::Display for Health {
70-
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
71-
write!(fmt, "{} peers ({})", self.peers, if self.is_syncing {
72-
"syncing"
73-
} else { "idle" })
74-
}
77+
/// The role the node is running as
78+
#[derive(Debug, PartialEq, Serialize, Deserialize)]
79+
pub enum NodeRole {
80+
/// The node is a full node
81+
Full,
82+
/// The node is a light client
83+
LightClient,
84+
/// The node is an authority
85+
Authority,
86+
/// An unknown role with a bit number
87+
UnknownRole(u8)
7588
}
7689

7790
#[cfg(test)]

core/rpc/api/src/system/mod.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use jsonrpc_derive::rpc;
2424

2525
use self::error::Result;
2626

27-
pub use self::helpers::{Properties, SystemInfo, Health, PeerInfo};
27+
pub use self::helpers::{Properties, SystemInfo, Health, PeerInfo, NodeRole};
2828
pub use self::gen_client::Client as SystemClient;
2929

3030
/// Substrate system RPC API
@@ -64,4 +64,8 @@ pub trait SystemApi<Hash, Number> {
6464
// TODO: make this stable and move structs https://github.com/paritytech/substrate/issues/1890
6565
#[rpc(name = "system_networkState", returns = "jsonrpc_core::Value")]
6666
fn system_network_state(&self) -> Receiver<jsonrpc_core::Value>;
67+
68+
/// Returns the roles the node is running as.
69+
#[rpc(name = "system_nodeRoles", returns = "Vec<NodeRole>")]
70+
fn system_node_roles(&self) -> Receiver<Vec<NodeRole>>;
6771
}

core/rpc/src/state/tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ fn should_return_runtime_version() {
282282
\"specVersion\":1,\"implVersion\":1,\"apis\":[[\"0xdf6acb689907609b\",2],\
283283
[\"0x37e397fc7c91f5e4\",1],[\"0xd2bc9897eed08f15\",1],[\"0x40fe3ad401f8959a\",3],\
284284
[\"0xc6e9a76309f39b09\",1],[\"0xdd718d5cc53262d4\",1],[\"0xcbca25e39f142387\",1],\
285-
[\"0xf78b278be53f454c\",1],[\"0xab3c0572291feb8b\",1]]}";
285+
[\"0xf78b278be53f454c\",1],[\"0xab3c0572291feb8b\",1],[\"0xbc9d89904f5b923f\",1]]}";
286286

287287
let runtime_version = api.runtime_version(None.into()).wait().unwrap();
288288
let serialized = serde_json::to_string(&runtime_version).unwrap();

core/rpc/src/system/mod.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use sr_primitives::traits::{self, Header as HeaderT};
2525
use self::error::Result;
2626

2727
pub use api::system::*;
28-
pub use self::helpers::{Properties, SystemInfo, Health, PeerInfo};
28+
pub use self::helpers::{Properties, SystemInfo, Health, PeerInfo, NodeRole};
2929
pub use self::gen_client::Client as SystemClient;
3030

3131
/// System API implementation
@@ -42,6 +42,8 @@ pub enum Request<B: traits::Block> {
4242
Peers(oneshot::Sender<Vec<PeerInfo<B::Hash, <B::Header as HeaderT>::Number>>>),
4343
/// Must return the state of the network.
4444
NetworkState(oneshot::Sender<rpc::Value>),
45+
/// Must return the node role.
46+
NodeRoles(oneshot::Sender<Vec<NodeRole>>)
4547
}
4648

4749
impl<B: traits::Block> System<B> {
@@ -94,4 +96,10 @@ impl<B: traits::Block> SystemApi<B::Hash, <B::Header as HeaderT>::Number> for Sy
9496
let _ = self.send_back.unbounded_send(Request::NetworkState(tx));
9597
Receiver(Compat::new(rx))
9698
}
99+
100+
fn system_node_roles(&self) -> Receiver<Vec<NodeRole>> {
101+
let (tx, rx) = oneshot::channel();
102+
let _ = self.send_back.unbounded_send(Request::NodeRoles(tx));
103+
Receiver(Compat::new(rx))
104+
}
97105
}

core/rpc/src/system/tests.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,9 @@ fn api<T: Into<Option<Status>>>(sync: T) -> System<Block> {
7979
average_upload_per_sec: 0,
8080
peerset: serde_json::Value::Null,
8181
}).unwrap());
82+
},
83+
Request::NodeRoles(sender) => {
84+
let _ = sender.send(vec![NodeRole::Authority]);
8285
}
8386
};
8487

@@ -221,3 +224,11 @@ fn system_network_state() {
221224
}
222225
);
223226
}
227+
228+
#[test]
229+
fn system_node_roles() {
230+
assert_eq!(
231+
wait_receiver(api(None).system_node_roles()),
232+
vec![NodeRole::Authority]
233+
);
234+
}

core/service/src/lib.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,7 @@ macro_rules! new_impl {
368368

369369

370370
let _ = to_spawn_tx.unbounded_send(Box::new(build_network_future(
371+
$config.roles,
371372
network_mut,
372373
client.clone(),
373374
network_status_sinks.clone(),
@@ -662,14 +663,15 @@ fn build_network_future<
662663
S: network::specialization::NetworkSpecialization<B>,
663664
H: network::ExHashT
664665
> (
666+
roles: Roles,
665667
mut network: network::NetworkWorker<B, S, H>,
666668
client: Arc<C>,
667669
status_sinks: Arc<Mutex<Vec<mpsc::UnboundedSender<(NetworkStatus<B>, NetworkState)>>>>,
668670
rpc_rx: futures03::channel::mpsc::UnboundedReceiver<rpc::system::Request<B>>,
669671
should_have_peers: bool,
670672
dht_event_tx: Option<mpsc::Sender<DhtEvent>>,
671673
) -> impl Future<Item = (), Error = ()> {
672-
// Compatibility shim while we're transitionning to stable Futures.
674+
// Compatibility shim while we're transitioning to stable Futures.
673675
// See https://github.com/paritytech/substrate/issues/3099
674676
let mut rpc_rx = futures03::compat::Compat::new(rpc_rx.map(|v| Ok::<_, ()>(v)));
675677

@@ -725,6 +727,21 @@ fn build_network_future<
725727
let _ = sender.send(network_state);
726728
}
727729
}
730+
rpc::system::Request::NodeRoles(sender) => {
731+
use rpc::system::NodeRole;
732+
733+
let node_roles = (0 .. 8)
734+
.filter(|&bit_number| (roles.bits() >> bit_number) & 1 == 1)
735+
.map(|bit_number| match Roles::from_bits(1 << bit_number) {
736+
Some(Roles::AUTHORITY) => NodeRole::Authority,
737+
Some(Roles::LIGHT) => NodeRole::LightClient,
738+
Some(Roles::FULL) => NodeRole::Full,
739+
_ => NodeRole::UnknownRole(bit_number),
740+
})
741+
.collect();
742+
743+
let _ = sender.send(node_roles);
744+
}
728745
};
729746
}
730747

core/sr-primitives/src/generic/block.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,9 @@ where
9494
fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self {
9595
Block { header, extrinsics }
9696
}
97+
fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8> {
98+
(header, extrinsics).encode()
99+
}
97100
}
98101

99102
/// Abstraction over a substrate block and justification.

core/sr-primitives/src/testing.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,9 @@ impl<Xt: 'static + Codec + Sized + Send + Sync + Serialize + Clone + Eq + Debug
259259
fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self {
260260
Block { header, extrinsics }
261261
}
262+
fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8> {
263+
(header, extrinsics).encode()
264+
}
262265
}
263266

264267
impl<'a, Xt> Deserialize<'a> for Block<Xt> where Block<Xt>: Decode {

core/sr-primitives/src/traits.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -684,6 +684,8 @@ pub trait Block: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + 'st
684684
fn hash(&self) -> Self::Hash {
685685
<<Self::Header as Header>::Hashing as Hash>::hash_of(self.header())
686686
}
687+
/// Create an encoded block from the given `header` and `extrinsics` without requiring to create an instance.
688+
fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8>;
687689
}
688690

689691
/// Something that acts like an `Extrinsic`.

core/test-runtime/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ cfg-if = "0.1.10"
3131
srml-babe = { path = "../../srml/babe", default-features = false }
3232
srml-timestamp = { path = "../../srml/timestamp", default-features = false }
3333
srml-system = { path = "../../srml/system", default-features = false }
34+
srml-system-rpc-runtime-api = { path = "../../srml/system/rpc/runtime-api", default-features = false }
3435

3536
[dev-dependencies]
3637
substrate-executor = { path = "../executor" }
@@ -68,6 +69,7 @@ std = [
6869
"srml-babe/std",
6970
"srml-timestamp/std",
7071
"srml-system/std",
72+
"srml-system-rpc-runtime-api/std",
7173
"app-crypto/std",
7274
"session/std",
7375
]

0 commit comments

Comments
 (0)