Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
+258 -257
View File
@@ -21,31 +21,37 @@
use super::*;
use assert_matches::assert_matches;
use environment::HasVoted;
use sc_network_test::{
Block, BlockImportAdapter, Hash, PassThroughVerifier, Peer, PeersClient, PeersFullClient,
TestClient, TestNetFactory, FullPeerConfig,
};
use sc_network::config::{ProtocolConfig, Role};
use parking_lot::{RwLock, Mutex};
use futures_timer::Delay;
use futures::executor::block_on;
use tokio::runtime::{Runtime, Handle};
use sp_keyring::Ed25519Keyring;
use sp_blockchain::Result;
use futures_timer::Delay;
use parking_lot::{Mutex, RwLock};
use sc_network::config::{ProtocolConfig, Role};
use sc_network_test::{
Block, BlockImportAdapter, FullPeerConfig, Hash, PassThroughVerifier, Peer, PeersClient,
PeersFullClient, TestClient, TestNetFactory,
};
use sp_api::{ApiRef, ProvideRuntimeApi};
use substrate_test_runtime_client::runtime::BlockNumber;
use sp_blockchain::Result;
use sp_consensus::{
BlockOrigin, ForkChoiceStrategy, ImportedAux, BlockImportParams, ImportResult, BlockImport,
import_queue::BoxJustificationImport,
import_queue::BoxJustificationImport, BlockImport, BlockImportParams, BlockOrigin,
ForkChoiceStrategy, ImportResult, ImportedAux,
};
use std::{collections::{HashMap, HashSet}, pin::Pin};
use sp_runtime::{Justifications, traits::{Block as BlockT, Header as HeaderT}};
use sp_runtime::generic::{BlockId, DigestItem};
use sp_core::H256;
use sp_keystore::{SyncCryptoStorePtr, SyncCryptoStore};
use sp_finality_grandpa::{
GRANDPA_ENGINE_ID, AuthorityList, EquivocationProof, GrandpaApi, OpaqueKeyOwnershipProof,
AuthorityList, EquivocationProof, GrandpaApi, OpaqueKeyOwnershipProof, GRANDPA_ENGINE_ID,
};
use sp_keyring::Ed25519Keyring;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr};
use sp_runtime::{
generic::{BlockId, DigestItem},
traits::{Block as BlockT, Header as HeaderT},
Justifications,
};
use std::{
collections::{HashMap, HashSet},
pin::Pin,
};
use substrate_test_runtime_client::runtime::BlockNumber;
use tokio::runtime::{Handle, Runtime};
use authorities::AuthoritySet;
use sc_block_builder::BlockBuilderProvider;
@@ -61,7 +67,7 @@ type GrandpaBlockImport = crate::GrandpaBlockImport<
substrate_test_runtime_client::Backend,
Block,
PeersFullClient,
LongestChain<substrate_test_runtime_client::Backend, Block>
LongestChain<substrate_test_runtime_client::Backend, Block>,
>;
struct GrandpaTestNet {
@@ -71,10 +77,8 @@ struct GrandpaTestNet {
impl GrandpaTestNet {
fn new(test_config: TestApi, n_authority: usize, n_full: usize) -> Self {
let mut net = GrandpaTestNet {
peers: Vec::with_capacity(n_authority + n_full),
test_config,
};
let mut net =
GrandpaTestNet { peers: Vec::with_capacity(n_authority + n_full), test_config };
for _ in 0..n_authority {
net.add_authority_peer();
@@ -105,10 +109,7 @@ impl TestNetFactory for GrandpaTestNet {
/// Create new test network with peers and given config.
fn from_config(_config: &ProtocolConfig) -> Self {
GrandpaTestNet {
peers: Vec::new(),
test_config: Default::default(),
}
GrandpaTestNet { peers: Vec::new(), test_config: Default::default() }
}
fn default_config() -> ProtocolConfig {
@@ -133,13 +134,10 @@ impl TestNetFactory for GrandpaTestNet {
PassThroughVerifier::new(false) // use non-instant finality.
}
fn make_block_import(&self, client: PeersClient)
-> (
BlockImportAdapter<Self::BlockImport>,
Option<BoxJustificationImport<Block>>,
PeerData,
)
{
fn make_block_import(
&self,
client: PeersClient,
) -> (BlockImportAdapter<Self::BlockImport>, Option<BoxJustificationImport<Block>>, PeerData) {
match client {
PeersClient::Full(ref client, ref backend) => {
let (import, link) = block_import(
@@ -147,7 +145,8 @@ impl TestNetFactory for GrandpaTestNet {
&self.test_config,
LongestChain::new(backend.clone()),
None,
).expect("Could not create block import for fresh peer.");
)
.expect("Could not create block import for fresh peer.");
let justification_import = Box::new(import.clone());
(
BlockImportAdapter::new(import),
@@ -181,9 +180,7 @@ pub(crate) struct TestApi {
impl TestApi {
pub fn new(genesis_authorities: AuthorityList) -> Self {
TestApi {
genesis_authorities,
}
TestApi { genesis_authorities }
}
}
@@ -235,21 +232,24 @@ fn make_ids(keys: &[Ed25519Keyring]) -> AuthorityList {
fn create_keystore(authority: Ed25519Keyring) -> (SyncCryptoStorePtr, tempfile::TempDir) {
let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = Arc::new(LocalKeystore::open(keystore_path.path(), None)
.expect("Creates keystore"));
let keystore =
Arc::new(LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore"));
SyncCryptoStore::ed25519_generate_new(&*keystore, GRANDPA, Some(&authority.to_seed()))
.expect("Creates authority key");
(keystore, keystore_path)
}
fn block_until_complete(future: impl Future + Unpin, net: &Arc<Mutex<GrandpaTestNet>>, runtime: &mut Runtime) {
fn block_until_complete(
future: impl Future + Unpin,
net: &Arc<Mutex<GrandpaTestNet>>,
runtime: &mut Runtime,
) {
let drive_to_completion = futures::future::poll_fn(|cx| {
net.lock().poll(cx); Poll::<()>::Pending
net.lock().poll(cx);
Poll::<()>::Pending
});
runtime.block_on(
future::select(future, drive_to_completion)
);
runtime.block_on(future::select(future, drive_to_completion));
}
// Spawns grandpa voters. Returns a future to spawn on the runtime.
@@ -264,11 +264,9 @@ fn initialize_grandpa(
let (net_service, link) = {
// temporary needed for some reason
let link = net.peers[peer_id].data.lock().take().expect("link initialized at startup; qed");
(
net.peers[peer_id].network_service().clone(),
link,
)
let link =
net.peers[peer_id].data.lock().take().expect("link initialized at startup; qed");
(net.peers[peer_id].network_service().clone(), link)
};
let grandpa_params = GrandpaParams {
@@ -288,9 +286,10 @@ fn initialize_grandpa(
shared_voter_state: SharedVoterState::empty(),
telemetry: None,
};
let voter = run_grandpa_voter(grandpa_params).expect("all in order with client and network");
let voter =
run_grandpa_voter(grandpa_params).expect("all in order with client and network");
fn assert_send<T: Send>(_: &T) { }
fn assert_send<T: Send>(_: &T) {}
assert_send(&voter);
voters.push(voter);
@@ -307,8 +306,9 @@ fn run_to_completion_with<F>(
net: Arc<Mutex<GrandpaTestNet>>,
peers: &[Ed25519Keyring],
with: F,
) -> u64 where
F: FnOnce(Handle) -> Option<Pin<Box<dyn Future<Output = ()>>>>
) -> u64
where
F: FnOnce(Handle) -> Option<Pin<Box<dyn Future<Output = ()>>>>,
{
let mut wait_for = Vec::new();
@@ -322,20 +322,19 @@ fn run_to_completion_with<F>(
let highest_finalized = highest_finalized.clone();
let client = net.lock().peers[peer_id].client().clone();
wait_for.push(
Box::pin(
client.finality_notification_stream()
.take_while(move |n| {
let mut highest_finalized = highest_finalized.write();
if *n.header.number() > *highest_finalized {
*highest_finalized = *n.header.number();
}
future::ready(n.header.number() < &blocks)
})
.collect::<Vec<_>>()
.map(|_| ())
)
);
wait_for.push(Box::pin(
client
.finality_notification_stream()
.take_while(move |n| {
let mut highest_finalized = highest_finalized.write();
if *n.header.number() > *highest_finalized {
*highest_finalized = *n.header.number();
}
future::ready(n.header.number() < &blocks)
})
.collect::<Vec<_>>()
.map(|_| ()),
));
}
// wait for all finalized on each.
@@ -350,7 +349,7 @@ fn run_to_completion(
runtime: &mut Runtime,
blocks: u64,
net: Arc<Mutex<GrandpaTestNet>>,
peers: &[Ed25519Keyring]
peers: &[Ed25519Keyring],
) -> u64 {
run_to_completion_with(runtime, blocks, net, peers, |_| None)
}
@@ -386,8 +385,7 @@ fn finalize_3_voters_no_observers() {
net.block_until_sync();
for i in 0..3 {
assert_eq!(net.peer(i).client().info().best_number, 20,
"Peer #{} failed to sync", i);
assert_eq!(net.peer(i).client().info().best_number, 20, "Peer #{} failed to sync", i);
}
let net = Arc::new(Mutex::new(net));
@@ -395,7 +393,12 @@ fn finalize_3_voters_no_observers() {
// normally there's no justification for finalized blocks
assert!(
net.lock().peer(0).client().justifications(&BlockId::Number(20)).unwrap().is_none(),
net.lock()
.peer(0)
.client()
.justifications(&BlockId::Number(20))
.unwrap()
.is_none(),
"Extra justification for block#1",
);
}
@@ -425,7 +428,7 @@ fn finalize_3_voters_1_full_observer() {
observer_enabled: true,
telemetry: None,
},
link: link,
link,
network: net_service,
voting_rule: (),
prometheus_registry: None,
@@ -444,9 +447,10 @@ fn finalize_3_voters_1_full_observer() {
for peer_id in 0..4 {
let client = net.lock().peers[peer_id].client().clone();
finality_notifications.push(
client.finality_notification_stream()
client
.finality_notification_stream()
.take_while(|n| future::ready(n.header.number() < &20))
.for_each(move |_| future::ready(()))
.for_each(move |_| future::ready(())),
);
}
@@ -458,9 +462,8 @@ fn finalize_3_voters_1_full_observer() {
// all peers should have stored the justification for the best finalized block #20
for peer_id in 0..4 {
let client = net.lock().peers[peer_id].client().as_full().unwrap();
let justification = crate::aux_schema::best_justification::<_, Block>(&*client)
.unwrap()
.unwrap();
let justification =
crate::aux_schema::best_justification::<_, Block>(&*client).unwrap().unwrap();
assert_eq!(justification.commit.target_number, 20);
}
@@ -469,27 +472,16 @@ fn finalize_3_voters_1_full_observer() {
#[test]
fn transition_3_voters_twice_1_full_observer() {
sp_tracing::try_init_simple();
let peers_a = &[
Ed25519Keyring::Alice,
Ed25519Keyring::Bob,
Ed25519Keyring::Charlie,
];
let peers_a = &[Ed25519Keyring::Alice, Ed25519Keyring::Bob, Ed25519Keyring::Charlie];
let peers_b = &[
Ed25519Keyring::Dave,
Ed25519Keyring::Eve,
Ed25519Keyring::Ferdie,
];
let peers_b = &[Ed25519Keyring::Dave, Ed25519Keyring::Eve, Ed25519Keyring::Ferdie];
let peers_c = &[
Ed25519Keyring::Alice,
Ed25519Keyring::Eve,
Ed25519Keyring::Two,
];
let peers_c = &[Ed25519Keyring::Alice, Ed25519Keyring::Eve, Ed25519Keyring::Two];
let observer = &[Ed25519Keyring::One];
let all_peers = peers_a.iter()
let all_peers = peers_a
.iter()
.chain(peers_b)
.chain(peers_c)
.chain(observer)
@@ -511,11 +503,9 @@ fn transition_3_voters_twice_1_full_observer() {
let (net_service, link) = {
let net = net.lock();
let link = net.peers[peer_id].data.lock().take().expect("link initialized at startup; qed");
(
net.peers[peer_id].network_service().clone(),
link,
)
let link =
net.peers[peer_id].data.lock().take().expect("link initialized at startup; qed");
(net.peers[peer_id].network_service().clone(), link)
};
let grandpa_params = GrandpaParams {
@@ -536,7 +526,8 @@ fn transition_3_voters_twice_1_full_observer() {
telemetry: None,
};
voters.push(run_grandpa_voter(grandpa_params).expect("all in order with client and network"));
voters
.push(run_grandpa_voter(grandpa_params).expect("all in order with client and network"));
}
net.lock().peer(0).push_blocks(1, false);
@@ -544,10 +535,10 @@ fn transition_3_voters_twice_1_full_observer() {
for (i, peer) in net.lock().peers().iter().enumerate() {
let full_client = peer.client().as_full().expect("only full clients are used in test");
assert_eq!(full_client.chain_info().best_number, 1,
"Peer #{} failed to sync", i);
assert_eq!(full_client.chain_info().best_number, 1, "Peer #{} failed to sync", i);
let set: AuthoritySet<Hash, BlockNumber> = crate::aux_schema::load_authorities(&*full_client).unwrap();
let set: AuthoritySet<Hash, BlockNumber> =
crate::aux_schema::load_authorities(&*full_client).unwrap();
assert_eq!(set.current(), (0, make_ids(peers_a).as_slice()));
assert_eq!(set.pending_changes().count(), 0);
@@ -559,7 +550,8 @@ fn transition_3_voters_twice_1_full_observer() {
let peers_c = peers_c.clone();
// wait for blocks to be finalized before generating new ones
let block_production = client.finality_notification_stream()
let block_production = client
.finality_notification_stream()
.take_while(|n| future::ready(n.header.number() < &30))
.for_each(move |n| {
match n.header.number() {
@@ -571,10 +563,10 @@ fn transition_3_voters_twice_1_full_observer() {
// generate transition at block 15, applied at 20.
net.lock().peer(0).generate_blocks(1, BlockOrigin::File, |builder| {
let mut block = builder.build().unwrap().block;
add_scheduled_change(&mut block, ScheduledChange {
next_authorities: make_ids(peers_b),
delay: 4,
});
add_scheduled_change(
&mut block,
ScheduledChange { next_authorities: make_ids(peers_b), delay: 4 },
);
block
});
@@ -585,10 +577,10 @@ fn transition_3_voters_twice_1_full_observer() {
// add more until we have 30.
net.lock().peer(0).generate_blocks(1, BlockOrigin::File, |builder| {
let mut block = builder.build().unwrap().block;
add_scheduled_change(&mut block, ScheduledChange {
next_authorities: make_ids(&peers_c),
delay: 0,
});
add_scheduled_change(
&mut block,
ScheduledChange { next_authorities: make_ids(&peers_c), delay: 0 },
);
block
});
@@ -612,16 +604,18 @@ fn transition_3_voters_twice_1_full_observer() {
for (peer_id, _) in all_peers.into_iter().enumerate() {
let client = net.lock().peers[peer_id].client().clone();
finality_notifications.push(
client.finality_notification_stream()
client
.finality_notification_stream()
.take_while(|n| future::ready(n.header.number() < &30))
.for_each(move |_| future::ready(()))
.map(move |()| {
let full_client = client.as_full().expect("only full clients are used in test");
let set: AuthoritySet<Hash, BlockNumber> = crate::aux_schema::load_authorities(&*full_client).unwrap();
let set: AuthoritySet<Hash, BlockNumber> =
crate::aux_schema::load_authorities(&*full_client).unwrap();
assert_eq!(set.current(), (2, make_ids(peers_c).as_slice()));
assert_eq!(set.pending_changes().count(), 0);
})
}),
);
}
@@ -648,7 +642,13 @@ fn justification_is_generated_periodically() {
// when block#32 (justification_period) is finalized, justification
// is required => generated
for i in 0..3 {
assert!(net.lock().peer(i).client().justifications(&BlockId::Number(32)).unwrap().is_some());
assert!(net
.lock()
.peer(i)
.client()
.justifications(&BlockId::Number(32))
.unwrap()
.is_some());
}
}
@@ -670,10 +670,10 @@ fn sync_justifications_on_change_blocks() {
// at block 21 we do add a transition which is instant
net.peer(0).generate_blocks(1, BlockOrigin::File, |builder| {
let mut block = builder.build().unwrap().block;
add_scheduled_change(&mut block, ScheduledChange {
next_authorities: make_ids(peers_b),
delay: 0,
});
add_scheduled_change(
&mut block,
ScheduledChange { next_authorities: make_ids(peers_b), delay: 0 },
);
block
});
@@ -682,8 +682,7 @@ fn sync_justifications_on_change_blocks() {
net.block_until_sync();
for i in 0..4 {
assert_eq!(net.peer(i).client().info().best_number, 25,
"Peer #{} failed to sync", i);
assert_eq!(net.peer(i).client().info().best_number, 25, "Peer #{} failed to sync", i);
}
let net = Arc::new(Mutex::new(net));
@@ -693,12 +692,25 @@ fn sync_justifications_on_change_blocks() {
// the first 3 peers are grandpa voters and therefore have already finalized
// block 21 and stored a justification
for i in 0..3 {
assert!(net.lock().peer(i).client().justifications(&BlockId::Number(21)).unwrap().is_some());
assert!(net
.lock()
.peer(i)
.client()
.justifications(&BlockId::Number(21))
.unwrap()
.is_some());
}
// the last peer should get the justification by syncing from other peers
futures::executor::block_on(futures::future::poll_fn(move |cx| {
if net.lock().peer(3).client().justifications(&BlockId::Number(21)).unwrap().is_none() {
if net
.lock()
.peer(3)
.client()
.justifications(&BlockId::Number(21))
.unwrap()
.is_none()
{
net.lock().poll(cx);
Poll::Pending
} else {
@@ -717,8 +729,12 @@ fn finalizes_multiple_pending_changes_in_order() {
let peers_c = &[Ed25519Keyring::Dave, Ed25519Keyring::Alice, Ed25519Keyring::Bob];
let all_peers = &[
Ed25519Keyring::Alice, Ed25519Keyring::Bob, Ed25519Keyring::Charlie,
Ed25519Keyring::Dave, Ed25519Keyring::Eve, Ed25519Keyring::Ferdie,
Ed25519Keyring::Alice,
Ed25519Keyring::Bob,
Ed25519Keyring::Charlie,
Ed25519Keyring::Dave,
Ed25519Keyring::Eve,
Ed25519Keyring::Ferdie,
];
let genesis_voters = make_ids(peers_a);
@@ -735,10 +751,10 @@ fn finalizes_multiple_pending_changes_in_order() {
// at block 21 we do add a transition which is instant
net.peer(0).generate_blocks(1, BlockOrigin::File, |builder| {
let mut block = builder.build().unwrap().block;
add_scheduled_change(&mut block, ScheduledChange {
next_authorities: make_ids(peers_b),
delay: 0,
});
add_scheduled_change(
&mut block,
ScheduledChange { next_authorities: make_ids(peers_b), delay: 0 },
);
block
});
@@ -748,10 +764,10 @@ fn finalizes_multiple_pending_changes_in_order() {
// at block 26 we add another which is enacted at block 30
net.peer(0).generate_blocks(1, BlockOrigin::File, |builder| {
let mut block = builder.build().unwrap().block;
add_scheduled_change(&mut block, ScheduledChange {
next_authorities: make_ids(peers_c),
delay: 4,
});
add_scheduled_change(
&mut block,
ScheduledChange { next_authorities: make_ids(peers_c), delay: 4 },
);
block
});
@@ -762,8 +778,7 @@ fn finalizes_multiple_pending_changes_in_order() {
// all peers imported both change blocks
for i in 0..6 {
assert_eq!(net.peer(i).client().info().best_number, 30,
"Peer #{} failed to sync", i);
assert_eq!(net.peer(i).client().info().best_number, 30, "Peer #{} failed to sync", i);
}
let net = Arc::new(Mutex::new(net));
@@ -794,16 +809,17 @@ fn force_change_to_new_set() {
let mut block = builder.build().unwrap().block;
// add a forced transition at block 12.
add_forced_change(&mut block, 0, ScheduledChange {
next_authorities: voters.clone(),
delay: 10,
});
add_forced_change(
&mut block,
0,
ScheduledChange { next_authorities: voters.clone(), delay: 10 },
);
// add a normal transition too to ensure that forced changes take priority.
add_scheduled_change(&mut block, ScheduledChange {
next_authorities: make_ids(genesis_authorities),
delay: 5,
});
add_scheduled_change(
&mut block,
ScheduledChange { next_authorities: make_ids(genesis_authorities), delay: 5 },
);
block
});
@@ -812,11 +828,11 @@ fn force_change_to_new_set() {
net.lock().block_until_sync();
for (i, peer) in net.lock().peers().iter().enumerate() {
assert_eq!(peer.client().info().best_number, 26,
"Peer #{} failed to sync", i);
assert_eq!(peer.client().info().best_number, 26, "Peer #{} failed to sync", i);
let full_client = peer.client().as_full().expect("only full clients are used in test");
let set: AuthoritySet<Hash, BlockNumber> = crate::aux_schema::load_authorities(&*full_client).unwrap();
let set: AuthoritySet<Hash, BlockNumber> =
crate::aux_schema::load_authorities(&*full_client).unwrap();
assert_eq!(set.current(), (1, voters.as_slice()));
assert_eq!(set.pending_changes().count(), 0);
@@ -841,12 +857,14 @@ fn allows_reimporting_change_blocks() {
let (mut block_import, ..) = net.make_block_import(client.clone());
let full_client = client.as_full().unwrap();
let builder = full_client.new_block_at(&BlockId::Number(0), Default::default(), false).unwrap();
let builder = full_client
.new_block_at(&BlockId::Number(0), Default::default(), false)
.unwrap();
let mut block = builder.build().unwrap().block;
add_scheduled_change(&mut block, ScheduledChange {
next_authorities: make_ids(peers_b),
delay: 0,
});
add_scheduled_change(
&mut block,
ScheduledChange { next_authorities: make_ids(peers_b), delay: 0 },
);
let block = || {
let block = block.clone();
@@ -886,13 +904,15 @@ fn test_bad_justification() {
let (mut block_import, ..) = net.make_block_import(client.clone());
let full_client = client.as_full().expect("only full clients are used in test");
let builder = full_client.new_block_at(&BlockId::Number(0), Default::default(), false).unwrap();
let builder = full_client
.new_block_at(&BlockId::Number(0), Default::default(), false)
.unwrap();
let mut block = builder.build().unwrap().block;
add_scheduled_change(&mut block, ScheduledChange {
next_authorities: make_ids(peers_b),
delay: 0,
});
add_scheduled_change(
&mut block,
ScheduledChange { next_authorities: make_ids(peers_b), delay: 0 },
);
let block = || {
let block = block.clone();
@@ -923,8 +943,8 @@ fn test_bad_justification() {
#[test]
fn voter_persists_its_votes() {
use std::sync::atomic::{AtomicUsize, Ordering};
use futures::future;
use std::sync::atomic::{AtomicUsize, Ordering};
sp_tracing::try_init_simple();
let mut runtime = Runtime::new().unwrap();
@@ -959,8 +979,7 @@ fn voter_persists_its_votes() {
let set_state = {
let bob_client = net.peer(1).client().clone();
let (_, _, link) = net
.make_block_import(bob_client);
let (_, _, link) = net.make_block_import(bob_client);
let LinkHalf { persistent_data, .. } = link.lock().take().unwrap();
let PersistentData { set_state, .. } = persistent_data;
set_state
@@ -983,10 +1002,7 @@ fn voter_persists_its_votes() {
let (net_service, link) = {
// temporary needed for some reason
let link = net.peers[0].data.lock().take().expect("link initialized at startup; qed");
(
net.peers[0].network_service().clone(),
link,
)
(net.peers[0].network_service().clone(), link)
};
let grandpa_params = GrandpaParams {
@@ -1026,8 +1042,7 @@ fn voter_persists_its_votes() {
// read the persisted state after aborting alice_voter1.
let alice_client = net.peer(0).client().clone();
let (_block_import, _, link) = net
.make_block_import(alice_client);
let (_block_import, _, link) = net.make_block_import(alice_client);
let link = link.lock().take().unwrap();
let grandpa_params = GrandpaParams {
@@ -1064,8 +1079,7 @@ fn voter_persists_its_votes() {
net.peer(0).push_blocks(20, false);
net.block_until_sync();
assert_eq!(net.peer(0).client().info().best_number, 20,
"Peer #{} failed to sync", 0);
assert_eq!(net.peer(0).client().info().best_number, 20, "Peer #{} failed to sync", 0);
let net = Arc::new(Mutex::new(net));
@@ -1113,12 +1127,13 @@ fn voter_persists_its_votes() {
// we push 20 more blocks to alice's chain
net.lock().peer(0).push_blocks(20, false);
let interval = futures::stream::unfold(Delay::new(Duration::from_millis(200)), |delay|
Box::pin(async move {
delay.await;
Some(((), Delay::new(Duration::from_millis(200))))
})
);
let interval =
futures::stream::unfold(Delay::new(Duration::from_millis(200)), |delay| {
Box::pin(async move {
delay.await;
Some(((), Delay::new(Duration::from_millis(200))))
})
});
interval
.take_while(move |_| {
@@ -1135,17 +1150,19 @@ fn voter_persists_its_votes() {
runtime_handle.spawn(alice_voter2(peers, net.clone()));
// and we push our own prevote for block 30
let prevote = finality_grandpa::Prevote {
target_number: 30,
target_hash: block_30_hash,
};
let prevote =
finality_grandpa::Prevote { target_number: 30, target_hash: block_30_hash };
// One should either be calling `Sink::send` or `Sink::start_send` followed
// by `Sink::poll_complete` to make sure items are being flushed. Given that
// we send in a loop including a delay until items are received, this can be
// ignored for the sake of reduced complexity.
Pin::new(&mut *round_tx.lock()).start_send(finality_grandpa::Message::Prevote(prevote)).unwrap();
} else if state.compare_exchange(1, 2, Ordering::SeqCst, Ordering::SeqCst).unwrap() == 1 {
Pin::new(&mut *round_tx.lock())
.start_send(finality_grandpa::Message::Prevote(prevote))
.unwrap();
} else if state.compare_exchange(1, 2, Ordering::SeqCst, Ordering::SeqCst).unwrap() ==
1
{
// the next message we receive should be our own prevote
let prevote = match signed.message {
finality_grandpa::Message::Prevote(prevote) => prevote,
@@ -1155,11 +1172,12 @@ fn voter_persists_its_votes() {
// targeting block 30
assert!(prevote.target_number == 30);
// after alice restarts it should send its previous prevote
// therefore we won't ever receive it again since it will be a
// known message on the gossip layer
} else if state.compare_exchange(2, 3, Ordering::SeqCst, Ordering::SeqCst).unwrap() == 2 {
// after alice restarts it should send its previous prevote
// therefore we won't ever receive it again since it will be a
// known message on the gossip layer
} else if state.compare_exchange(2, 3, Ordering::SeqCst, Ordering::SeqCst).unwrap() ==
2
{
// we then receive a precommit from alice for block 15
// even though we casted a prevote for block 30
let precommit = match signed.message {
@@ -1202,13 +1220,13 @@ fn finalize_3_voters_1_light_observer() {
},
net.peers[3].data.lock().take().expect("link initialized at startup; qed"),
net.peers[3].network_service().clone(),
).unwrap();
)
.unwrap();
net.peer(0).push_blocks(20, false);
net.block_until_sync();
for i in 0..4 {
assert_eq!(net.peer(i).client().info().best_number, 20,
"Peer #{} failed to sync", i);
assert_eq!(net.peer(i).client().info().best_number, 20, "Peer #{} failed to sync", i);
}
let net = Arc::new(Mutex::new(net));
@@ -1231,7 +1249,11 @@ fn voter_catches_up_to_latest_round_when_behind() {
let net = Arc::new(Mutex::new(net));
let mut finality_notifications = Vec::new();
let voter = |keystore, peer_id, link, net: Arc<Mutex<GrandpaTestNet>>| -> Pin<Box<dyn Future<Output = ()> + Send>> {
let voter = |keystore,
peer_id,
link,
net: Arc<Mutex<GrandpaTestNet>>|
-> Pin<Box<dyn Future<Output = ()> + Send>> {
let grandpa_params = GrandpaParams {
config: Config {
gossip_duration: TEST_GOSSIP_DURATION,
@@ -1259,17 +1281,16 @@ fn voter_catches_up_to_latest_round_when_behind() {
for (peer_id, key) in peers.iter().enumerate() {
let (client, link) = {
let net = net.lock();
let link = net.peers[peer_id].data.lock().take().expect("link initialized at startup; qed");
(
net.peers[peer_id].client().clone(),
link,
)
let link =
net.peers[peer_id].data.lock().take().expect("link initialized at startup; qed");
(net.peers[peer_id].client().clone(), link)
};
finality_notifications.push(
client.finality_notification_stream()
client
.finality_notification_stream()
.take_while(|n| future::ready(n.header.number() < &50))
.for_each(move |_| future::ready(()))
.for_each(move |_| future::ready(())),
);
let (keystore, keystore_path) = create_keystore(*key);
@@ -1324,11 +1345,10 @@ fn voter_catches_up_to_latest_round_when_behind() {
};
let drive_to_completion = futures::future::poll_fn(|cx| {
net.lock().poll(cx); Poll::<()>::Pending
net.lock().poll(cx);
Poll::<()>::Pending
});
runtime.block_on(
future::select(test, drive_to_completion)
);
runtime.block_on(future::select(test, drive_to_completion));
}
type TestEnvironment<N, VR> = Environment<
@@ -1350,11 +1370,7 @@ where
N: NetworkT<Block>,
VR: VotingRule<Block, TestClient>,
{
let PersistentData {
ref authority_set,
ref set_state,
..
} = link.persistent_data;
let PersistentData { ref authority_set, ref set_state, .. } = link.persistent_data;
let config = Config {
gossip_duration: TEST_GOSSIP_DURATION,
@@ -1366,13 +1382,8 @@ where
telemetry: None,
};
let network = NetworkBridge::new(
network_service.clone(),
config.clone(),
set_state.clone(),
None,
None,
);
let network =
NetworkBridge::new(network_service.clone(), config.clone(), set_state.clone(), None, None);
Environment {
authority_set: authority_set.clone(),
@@ -1428,25 +1439,28 @@ fn grandpa_environment_respects_voting_rules() {
// the unrestricted environment should just return the best block
assert_eq!(
block_on(unrestricted_env.best_chain_containing(
peer.client().info().finalized_hash
)).unwrap().unwrap().1,
block_on(unrestricted_env.best_chain_containing(peer.client().info().finalized_hash))
.unwrap()
.unwrap()
.1,
21,
);
// both the other environments should return block 16, which is 3/4 of the
// way in the unfinalized chain
assert_eq!(
block_on(three_quarters_env.best_chain_containing(
peer.client().info().finalized_hash
)).unwrap().unwrap().1,
block_on(three_quarters_env.best_chain_containing(peer.client().info().finalized_hash))
.unwrap()
.unwrap()
.1,
16,
);
assert_eq!(
block_on(default_env.best_chain_containing(
peer.client().info().finalized_hash
)).unwrap().unwrap().1,
block_on(default_env.best_chain_containing(peer.client().info().finalized_hash))
.unwrap()
.unwrap()
.1,
16,
);
@@ -1455,18 +1469,20 @@ fn grandpa_environment_respects_voting_rules() {
// the 3/4 environment should propose block 21 for voting
assert_eq!(
block_on(three_quarters_env.best_chain_containing(
peer.client().info().finalized_hash
)).unwrap().unwrap().1,
block_on(three_quarters_env.best_chain_containing(peer.client().info().finalized_hash))
.unwrap()
.unwrap()
.1,
21,
);
// while the default environment will always still make sure we don't vote
// on the best block (2 behind)
assert_eq!(
block_on(default_env.best_chain_containing(
peer.client().info().finalized_hash
)).unwrap().unwrap().1,
block_on(default_env.best_chain_containing(peer.client().info().finalized_hash))
.unwrap()
.unwrap()
.1,
19,
);
@@ -1477,9 +1493,10 @@ fn grandpa_environment_respects_voting_rules() {
// best block, there's a hard rule that we can't cast any votes lower than
// the given base (#21).
assert_eq!(
block_on(default_env.best_chain_containing(
peer.client().info().finalized_hash
)).unwrap().unwrap().1,
block_on(default_env.best_chain_containing(peer.client().info().finalized_hash))
.unwrap()
.unwrap()
.1,
21,
);
}
@@ -1518,9 +1535,7 @@ fn grandpa_environment_never_overwrites_round_voter_state() {
assert_eq!(get_current_round(2), None);
// after completing round 1 we should start tracking round 2
environment
.completed(1, round_state(), base(), &historical_votes())
.unwrap();
environment.completed(1, round_state(), base(), &historical_votes()).unwrap();
assert_eq!(get_current_round(2).unwrap(), HasVoted::No);
@@ -1530,10 +1545,8 @@ fn grandpa_environment_never_overwrites_round_voter_state() {
let info = peer.client().info();
let prevote = finality_grandpa::Prevote {
target_hash: info.best_hash,
target_number: info.best_number,
};
let prevote =
finality_grandpa::Prevote { target_hash: info.best_hash, target_number: info.best_number };
// we prevote for round 2 which should lead to us updating the voter state
environment.prevoted(2, prevote.clone()).unwrap();
@@ -1545,9 +1558,7 @@ fn grandpa_environment_never_overwrites_round_voter_state() {
// if we report round 1 as completed again we should not overwrite the
// voter state for round 2
environment
.completed(1, round_state(), base(), &historical_votes())
.unwrap();
environment.completed(1, round_state(), base(), &historical_votes()).unwrap();
assert_matches!(get_current_round(2).unwrap(), HasVoted::Yes(_, _));
}
@@ -1566,7 +1577,9 @@ fn imports_justification_for_regular_blocks_on_import() {
let (mut block_import, ..) = net.make_block_import(client.clone());
let full_client = client.as_full().expect("only full clients are used in test");
let builder = full_client.new_block_at(&BlockId::Number(0), Default::default(), false).unwrap();
let builder = full_client
.new_block_at(&BlockId::Number(0), Default::default(), false)
.unwrap();
let block = builder.build().unwrap().block;
let block_hash = block.hash();
@@ -1597,11 +1610,7 @@ fn imports_justification_for_regular_blocks_on_import() {
precommits: vec![precommit],
};
GrandpaJustification::from_commit(
&full_client,
round,
commit,
).unwrap()
GrandpaJustification::from_commit(&full_client, round, commit).unwrap()
};
// we import the block with justification attached
@@ -1622,9 +1631,7 @@ fn imports_justification_for_regular_blocks_on_import() {
);
// the justification should be imported and available from the client
assert!(
client.justifications(&BlockId::Hash(block_hash)).unwrap().is_some(),
);
assert!(client.justifications(&BlockId::Hash(block_hash)).unwrap().is_some(),);
}
#[test]
@@ -1644,10 +1651,7 @@ fn grandpa_environment_doesnt_send_equivocation_reports_for_itself() {
};
let signed_prevote = {
let prevote = finality_grandpa::Prevote {
target_hash: H256::random(),
target_number: 1,
};
let prevote = finality_grandpa::Prevote { target_hash: H256::random(), target_number: 1 };
let signed = alice.sign(&[]).into();
(prevote, signed)
@@ -1667,10 +1671,7 @@ fn grandpa_environment_doesnt_send_equivocation_reports_for_itself() {
// reporting the equivocation should fail since the offender is a local
// authority (i.e. we have keys in our keystore for the given id)
let equivocation_proof = sp_finality_grandpa::Equivocation::Prevote(equivocation.clone());
assert!(matches!(
environment.report_equivocation(equivocation_proof),
Err(Error::Safety(_))
));
assert!(matches!(environment.report_equivocation(equivocation_proof), Err(Error::Safety(_))));
// if we set the equivocation offender to another id for which we don't have
// keys it should work