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

Commit ff45239

Browse files
authored
Merge branch 'master' into wasmtime-real
2 parents 812b6f9 + 7389b73 commit ff45239

File tree

80 files changed

+2029
-556
lines changed

Some content is hidden

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

80 files changed

+2029
-556
lines changed

Cargo.lock

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

Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ members = [
8282
"srml/aura",
8383
"srml/balances",
8484
"srml/contracts",
85+
"srml/contracts/rpc",
8586
"srml/collective",
8687
"srml/democracy",
8788
"srml/elections",
@@ -96,6 +97,7 @@ members = [
9697
"srml/indices",
9798
"srml/membership",
9899
"srml/metadata",
100+
"srml/nicks",
99101
"srml/offences",
100102
"srml/randomness-collective-flip",
101103
"srml/scored-pool",
@@ -108,6 +110,7 @@ members = [
108110
"srml/timestamp",
109111
"srml/treasury",
110112
"srml/transaction-payment",
113+
"srml/transaction-payment/rpc",
111114
"srml/utility",
112115
"node/cli",
113116
"node/executor",

core/client/src/runtime_api.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ pub use state_machine::OverlayedChanges;
2323
#[cfg(feature = "std")]
2424
pub use primitives::NativeOrEncoded;
2525
#[doc(hidden)]
26+
#[cfg(not(feature = "std"))]
27+
pub use primitives::to_substrate_wasm_fn_return_value;
28+
#[doc(hidden)]
2629
pub use sr_primitives::{
2730
traits::{
2831
Block as BlockT, GetNodeBlockType, GetRuntimeBlockType,

core/finality-grandpa/src/communication/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -683,7 +683,7 @@ impl<B: BlockT, N: Network<B>> Clone for NetworkBridge<B, N> {
683683
}
684684
}
685685

686-
fn localized_payload<E: Encode>(round: RoundNumber, set_id: SetIdNumber, message: &E) -> Vec<u8> {
686+
pub(crate) fn localized_payload<E: Encode>(round: RoundNumber, set_id: SetIdNumber, message: &E) -> Vec<u8> {
687687
(message, round, set_id).encode()
688688
}
689689

core/finality-grandpa/src/import.rs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -465,17 +465,15 @@ impl<B, E, Block: BlockT<Hash=H256>, RA, SC> BlockImport<Block>
465465
_ => {},
466466
}
467467

468-
if !needs_justification && !enacts_consensus_change {
469-
return Ok(ImportResult::Imported(imported_aux));
470-
}
471-
472468
match justification {
473469
Some(justification) => {
474470
self.import_justification(hash, number, justification, needs_justification).unwrap_or_else(|err| {
475-
debug!(target: "finality", "Imported block #{} that enacts authority set change with \
476-
invalid justification: {:?}, requesting justification from peers.", number, err);
477-
imported_aux.bad_justification = true;
478-
imported_aux.needs_justification = true;
471+
if needs_justification || enacts_consensus_change {
472+
debug!(target: "finality", "Imported block #{} that enacts authority set change with \
473+
invalid justification: {:?}, requesting justification from peers.", number, err);
474+
imported_aux.bad_justification = true;
475+
imported_aux.needs_justification = true;
476+
}
479477
});
480478
},
481479
None => {

core/finality-grandpa/src/justification.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ use crate::communication;
3939
/// This is meant to be stored in the db and passed around the network to other
4040
/// nodes, and are used by syncing nodes to prove authority set handoffs.
4141
#[derive(Encode, Decode)]
42-
pub(crate) struct GrandpaJustification<Block: BlockT> {
42+
pub struct GrandpaJustification<Block: BlockT> {
4343
round: u64,
4444
pub(crate) commit: Commit<Block>,
4545
votes_ancestries: Vec<Block::Header>,

core/finality-grandpa/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ mod voting_rule;
9696

9797
pub use communication::Network;
9898
pub use finality_proof::FinalityProofProvider;
99+
pub use justification::GrandpaJustification;
99100
pub use light_import::light_block_import;
100101
pub use observer::run_grandpa_observer;
101102
pub use voting_rule::{

core/finality-grandpa/src/tests.rs

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1627,3 +1627,84 @@ fn grandpa_environment_respects_voting_rules() {
16271627
19,
16281628
);
16291629
}
1630+
1631+
#[test]
1632+
fn imports_justification_for_regular_blocks_on_import() {
1633+
// NOTE: this is a regression test since initially we would only import
1634+
// justifications for authority change blocks, and would discard any
1635+
// existing justification otherwise.
1636+
let peers = &[Ed25519Keyring::Alice];
1637+
let voters = make_ids(peers);
1638+
let api = TestApi::new(voters);
1639+
let mut net = GrandpaTestNet::new(api.clone(), 1);
1640+
1641+
let client = net.peer(0).client().clone();
1642+
let (mut block_import, ..) = net.make_block_import(client.clone());
1643+
1644+
let full_client = client.as_full().expect("only full clients are used in test");
1645+
let builder = full_client.new_block_at(&BlockId::Number(0), Default::default()).unwrap();
1646+
let block = builder.bake().unwrap();
1647+
1648+
let block_hash = block.hash();
1649+
1650+
// create a valid justification, with one precommit targeting the block
1651+
let justification = {
1652+
let round = 1;
1653+
let set_id = 0;
1654+
1655+
let precommit = grandpa::Precommit {
1656+
target_hash: block_hash,
1657+
target_number: *block.header.number(),
1658+
};
1659+
1660+
let msg = grandpa::Message::Precommit(precommit.clone());
1661+
let encoded = communication::localized_payload(round, set_id, &msg);
1662+
let signature = peers[0].sign(&encoded[..]).into();
1663+
1664+
let precommit = grandpa::SignedPrecommit {
1665+
precommit,
1666+
signature,
1667+
id: peers[0].public().into(),
1668+
};
1669+
1670+
let commit = grandpa::Commit {
1671+
target_hash: block_hash,
1672+
target_number: *block.header.number(),
1673+
precommits: vec![precommit],
1674+
};
1675+
1676+
GrandpaJustification::from_commit(
1677+
&full_client,
1678+
round,
1679+
commit,
1680+
).unwrap()
1681+
};
1682+
1683+
// we import the block with justification attached
1684+
let block = BlockImportParams {
1685+
origin: BlockOrigin::File,
1686+
header: block.header,
1687+
justification: Some(justification.encode()),
1688+
post_digests: Vec::new(),
1689+
body: Some(block.extrinsics),
1690+
finalized: false,
1691+
auxiliary: Vec::new(),
1692+
fork_choice: ForkChoiceStrategy::LongestChain,
1693+
};
1694+
1695+
assert_eq!(
1696+
block_import.import_block(block, HashMap::new()).unwrap(),
1697+
ImportResult::Imported(ImportedAux {
1698+
needs_justification: false,
1699+
clear_justification_requests: false,
1700+
bad_justification: false,
1701+
is_new_best: true,
1702+
..Default::default()
1703+
}),
1704+
);
1705+
1706+
// the justification should be imported and available from the client
1707+
assert!(
1708+
client.justification(&BlockId::Hash(block_hash)).unwrap().is_some(),
1709+
);
1710+
}

core/network/src/behaviour.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use libp2p::core::{Multiaddr, PeerId, PublicKey};
2626
use libp2p::kad::record;
2727
use libp2p::swarm::{NetworkBehaviourAction, NetworkBehaviourEventProcess};
2828
use libp2p::core::{nodes::Substream, muxing::StreamMuxerBox};
29-
use log::warn;
29+
use log::{debug, warn};
3030
use sr_primitives::traits::Block as BlockT;
3131
use std::iter;
3232
use void;
@@ -133,7 +133,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> NetworkBehaviourEventPr
133133
warn!(target: "sub-libp2p", "Connected to a non-Substrate node: {:?}", info);
134134
}
135135
if info.listen_addrs.len() > 30 {
136-
warn!(target: "sub-libp2p", "Node {:?} has reported more than 30 addresses; \
136+
debug!(target: "sub-libp2p", "Node {:?} has reported more than 30 addresses; \
137137
it is identified by {:?} and {:?}", peer_id, info.protocol_version,
138138
info.agent_version
139139
);

core/phragmen/src/lib.rs

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,9 @@ pub fn elect<AccountId, Balance, FS, C>(
290290
let mut assignment = (n.who.clone(), vec![]);
291291
for e in &mut n.edges {
292292
if let Some(c) = elected_candidates.iter().cloned().find(|(c, _)| *c == e.who) {
293-
if c.0 != n.who {
293+
// if self_vote == false, this branch should always be executed as we want to
294+
// collect all nominations
295+
if c.0 != n.who || !self_vote {
294296
let per_bill_parts =
295297
{
296298
if n.load == e.load {
@@ -360,6 +362,47 @@ pub fn elect<AccountId, Balance, FS, C>(
360362
})
361363
}
362364

365+
/// Build the support map from the given phragmen result.
366+
pub fn build_support_map<Balance, AccountId, FS, C>(
367+
elected_stashes: &Vec<AccountId>,
368+
assignments: &Vec<(AccountId, Vec<PhragmenAssignment<AccountId>>)>,
369+
stake_of: FS,
370+
assume_self_vote: bool,
371+
) -> SupportMap<AccountId> where
372+
AccountId: Default + Ord + Member,
373+
Balance: Default + Copy + SimpleArithmetic,
374+
C: Convert<Balance, u64> + Convert<u128, Balance>,
375+
for<'r> FS: Fn(&'r AccountId) -> Balance,
376+
{
377+
let to_votes = |b: Balance| <C as Convert<Balance, u64>>::convert(b) as ExtendedBalance;
378+
// Initialize the support of each candidate.
379+
let mut supports = <SupportMap<AccountId>>::new();
380+
elected_stashes
381+
.iter()
382+
.map(|e| (e, if assume_self_vote { to_votes(stake_of(e)) } else { Zero::zero() } ))
383+
.for_each(|(e, s)| {
384+
let item = Support { own: s, total: s, ..Default::default() };
385+
supports.insert(e.clone(), item);
386+
});
387+
388+
// build support struct.
389+
for (n, assignment) in assignments.iter() {
390+
for (c, per_thing) in assignment.iter() {
391+
let nominator_stake = to_votes(stake_of(n));
392+
// AUDIT: it is crucially important for the `Mul` implementation of all
393+
// per-things to be sound.
394+
let other_stake = *per_thing * nominator_stake;
395+
if let Some(support) = supports.get_mut(c) {
396+
// For an astronomically rich validator with more astronomically rich
397+
// set of nominators, this might saturate.
398+
support.total = support.total.saturating_add(other_stake);
399+
support.others.push((n.clone(), other_stake));
400+
}
401+
}
402+
}
403+
supports
404+
}
405+
363406
/// Performs equalize post-processing to the output of the election algorithm. This happens in
364407
/// rounds. The number of rounds and the maximum diff-per-round tolerance can be tuned through input
365408
/// parameters.

core/primitives/src/lib.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,3 +287,25 @@ impl From<LogLevel> for log::Level {
287287
}
288288
}
289289
}
290+
291+
/// Encodes the given value into a buffer and returns the pointer and the length as a single `u64`.
292+
///
293+
/// When Substrate calls into Wasm it expects a fixed signature for functions exported
294+
/// from the Wasm blob. The return value of this signature is always a `u64`.
295+
/// This `u64` stores the pointer to the encoded return value and the length of this encoded value.
296+
/// The low `32bits` are reserved for the pointer, followed by `32bit` for the length.
297+
#[cfg(not(feature = "std"))]
298+
pub fn to_substrate_wasm_fn_return_value(value: &impl Encode) -> u64 {
299+
let encoded = value.encode();
300+
301+
let ptr = encoded.as_ptr() as u64;
302+
let length = encoded.len() as u64;
303+
let res = ptr | (length << 32);
304+
305+
// Leak the output vector to avoid it being freed.
306+
// This is fine in a WASM context since the heap
307+
// will be discarded after the call.
308+
rstd::mem::forget(encoded);
309+
310+
res
311+
}

core/primitives/src/sr25519.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,6 @@ impl std::fmt::Display for Public {
129129
}
130130
}
131131

132-
#[cfg(not(feature = "std"))]
133-
use core as std;
134-
135132
impl rstd::fmt::Debug for Public {
136133
#[cfg(feature = "std")]
137134
fn fmt(&self, f: &mut rstd::fmt::Formatter) -> rstd::fmt::Result {

core/primitives/src/testing.rs

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -196,15 +196,7 @@ macro_rules! wasm_export_functions {
196196
$( $fn_impl )*
197197
}
198198

199-
// We need to return *something*
200-
let output = Vec::<u8>::new();
201-
let res = output.as_ptr() as u64 + ((output.len() as u64) << 32);
202-
203-
// Leak the output vector to avoid it being freed.
204-
// This is fine in a WASM context since the heap
205-
// will be discarded after the call.
206-
$crate::rstd::mem::forget(output);
207-
res
199+
$crate::to_substrate_wasm_fn_return_value(&())
208200
}
209201
};
210202
(@IMPL
@@ -232,14 +224,7 @@ macro_rules! wasm_export_functions {
232224
$( $fn_impl )*
233225
};
234226

235-
let output = $crate::Encode::encode(&output);
236-
let res = output.as_ptr() as u64 + ((output.len() as u64) << 32);
237-
238-
// Leak the output vector to avoid it being freed.
239-
// This is fine in a WASM context since the heap
240-
// will be discarded after the call.
241-
$crate::rstd::mem::forget(output);
242-
res
227+
$crate::to_substrate_wasm_fn_return_value(&output)
243228
}
244229
};
245230
}

core/rpc-servers/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,9 @@ pub fn rpc_handler<M: PubSubMetadata>(
6060
mod inner {
6161
use super::*;
6262

63+
/// Type alias for http server
6364
pub type HttpServer = http::Server;
65+
/// Type alias for ws server
6466
pub type WsServer = ws::Server;
6567

6668
/// Start HTTP server listening on given address.

core/service/Cargo.toml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,12 @@ client = { package = "substrate-client", path = "../../core/client" }
3232
client_db = { package = "substrate-client-db", path = "../../core/client/db", features = ["kvdb-rocksdb"] }
3333
codec = { package = "parity-scale-codec", version = "1.0.0" }
3434
substrate-executor = { path = "../../core/executor" }
35-
substrate-authority-discovery = { path = "../../core/authority-discovery"}
3635
transaction_pool = { package = "substrate-transaction-pool", path = "../../core/transaction-pool" }
3736
rpc-servers = { package = "substrate-rpc-servers", path = "../../core/rpc-servers" }
3837
rpc = { package = "substrate-rpc", path = "../../core/rpc" }
3938
tel = { package = "substrate-telemetry", path = "../../core/telemetry" }
4039
offchain = { package = "substrate-offchain", path = "../../core/offchain" }
4140
parity-multiaddr = { package = "parity-multiaddr", version = "0.5.0" }
42-
authority-discovery-primitives = { package = "substrate-authority-discovery-primitives", path = "../authority-discovery/primitives", default-features = false }
4341

4442
[dev-dependencies]
4543
substrate-test-runtime-client = { path = "../test-runtime/client" }

core/sr-api-macros/Cargo.toml

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,17 @@ state_machine = { package = "substrate-state-machine", path = "../state-machine"
2121
sr-primitives = { path = "../sr-primitives" }
2222
sr-version = { path = "../sr-version" }
2323
primitives = { package = "substrate-primitives", path = "../primitives" }
24-
criterion = "0.2.11"
24+
criterion = "0.3.0"
2525
consensus_common = { package = "substrate-consensus-common", path = "../consensus/common" }
2626
codec = { package = "parity-scale-codec", version = "1.0.0" }
27-
trybuild = "1.0.14"
28-
rustversion = "0.1.4"
27+
trybuild = "1.0.17"
28+
rustversion = "1.0.0"
2929

3030
[[bench]]
3131
name = "bench"
3232
harness = false
33+
34+
# We actually don't need the `std` feature in this crate, but the tests require it.
35+
[features]
36+
default = [ "std" ]
37+
std = []

core/sr-api-macros/src/impl_runtime_apis.rs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,7 @@ fn generate_impl_call(
8383
)*
8484

8585
#[allow(deprecated)]
86-
let output = <#runtime as #impl_trait>::#fn_name(#( #pborrow #pnames2 ),*);
87-
#c::runtime_api::Encode::encode(&output)
86+
<#runtime as #impl_trait>::#fn_name(#( #pborrow #pnames2 ),*)
8887
)
8988
)
9089
}
@@ -175,11 +174,12 @@ fn generate_impl_calls(
175174
/// Generate the dispatch function that is used in native to call into the runtime.
176175
fn generate_dispatch_function(impls: &[ItemImpl]) -> Result<TokenStream> {
177176
let data = Ident::new("data", Span::call_site());
177+
let c = generate_crate_access(HIDDEN_INCLUDES_ID);
178178
let impl_calls = generate_impl_calls(impls, &data)?
179179
.into_iter()
180180
.map(|(trait_, fn_name, impl_)| {
181181
let name = prefix_function_with_trait(&trait_, &fn_name);
182-
quote!( #name => Some({ #impl_ }), )
182+
quote!( #name => Some(#c::runtime_api::Encode::encode(&{ #impl_ })), )
183183
});
184184

185185
Ok(quote!(
@@ -218,13 +218,7 @@ fn generate_wasm_interface(impls: &[ItemImpl]) -> Result<TokenStream> {
218218
};
219219

220220
let output = { #impl_ };
221-
let res = output.as_ptr() as u64 + ((output.len() as u64) << 32);
222-
223-
// Leak the output vector to avoid it being freed.
224-
// This is fine in a WASM context since the heap
225-
// will be discarded after the call.
226-
#c::runtime_api::mem::forget(output);
227-
res
221+
#c::runtime_api::to_substrate_wasm_fn_return_value(&output)
228222
}
229223
)
230224
});

0 commit comments

Comments
 (0)