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
+119 -122
View File
@@ -16,13 +16,17 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{Network, Validator};
use crate::state_machine::{ConsensusGossip, TopicNotification, PERIODIC_MAINTENANCE_INTERVAL};
use crate::{
state_machine::{ConsensusGossip, TopicNotification, PERIODIC_MAINTENANCE_INTERVAL},
Network, Validator,
};
use sc_network::{Event, ReputationChange};
use futures::prelude::*;
use futures::channel::mpsc::{channel, Sender, Receiver};
use futures::{
channel::mpsc::{channel, Receiver, Sender},
prelude::*,
};
use libp2p::PeerId;
use log::trace;
use prometheus_endpoint::Registry;
@@ -74,7 +78,10 @@ impl<B: BlockT> GossipEngine<B> {
protocol: impl Into<Cow<'static, str>>,
validator: Arc<dyn Validator<B>>,
metrics_registry: Option<&Registry>,
) -> Self where B: 'static {
) -> Self
where
B: 'static,
{
let protocol = protocol.into();
let network_event_stream = network.event_stream();
@@ -99,11 +106,7 @@ impl<B: BlockT> GossipEngine<B> {
/// the message's topic. No validation is performed on the message, if the
/// message is already expired it should be dropped on the next garbage
/// collection.
pub fn register_gossip_message(
&mut self,
topic: B::Hash,
message: Vec<u8>,
) {
pub fn register_gossip_message(&mut self, topic: B::Hash, message: Vec<u8>) {
self.state_machine.register_message(topic, message);
}
@@ -113,9 +116,7 @@ impl<B: BlockT> GossipEngine<B> {
}
/// Get data of valid, incoming messages for a topic (but might have expired meanwhile).
pub fn messages_for(&mut self, topic: B::Hash)
-> Receiver<TopicNotification>
{
pub fn messages_for(&mut self, topic: B::Hash) -> Receiver<TopicNotification> {
let past_messages = self.state_machine.messages_for(topic).collect::<Vec<_>>();
// The channel length is not critical for correctness. By the implementation of `channel`
// each sender is guaranteed a single buffer slot, making it a non-rendezvous channel and
@@ -124,7 +125,7 @@ impl<B: BlockT> GossipEngine<B> {
// contains a single message.
let (mut tx, rx) = channel(usize::max(past_messages.len(), 10));
for notification in past_messages{
for notification in past_messages {
tx.try_send(notification)
.expect("receiver known to be live, and buffer size known to suffice; qed");
}
@@ -135,22 +136,12 @@ impl<B: BlockT> GossipEngine<B> {
}
/// Send all messages with given topic to a peer.
pub fn send_topic(
&mut self,
who: &PeerId,
topic: B::Hash,
force: bool
) {
pub fn send_topic(&mut self, who: &PeerId, topic: B::Hash, force: bool) {
self.state_machine.send_topic(&mut *self.network, who, topic, force)
}
/// Multicast a message to all peers.
pub fn gossip_message(
&mut self,
topic: B::Hash,
message: Vec<u8>,
force: bool,
) {
pub fn gossip_message(&mut self, topic: B::Hash, message: Vec<u8>, force: bool) {
self.state_machine.multicast(&mut *self.network, topic, message, force)
}
@@ -184,30 +175,33 @@ impl<B: BlockT> Future for GossipEngine<B> {
Poll::Ready(Some(event)) => match event {
Event::SyncConnected { remote } => {
this.network.add_set_reserved(remote, this.protocol.clone());
}
},
Event::SyncDisconnected { remote } => {
this.network.remove_set_reserved(remote, this.protocol.clone());
}
},
Event::NotificationStreamOpened { remote, protocol, role, .. } => {
if protocol != this.protocol {
continue;
continue
}
this.state_machine.new_peer(&mut *this.network, remote, role);
}
},
Event::NotificationStreamClosed { remote, protocol } => {
if protocol != this.protocol {
continue;
continue
}
this.state_machine.peer_disconnected(&mut *this.network, remote);
},
Event::NotificationsReceived { remote, messages } => {
let messages = messages.into_iter().filter_map(|(engine, data)| {
if engine == this.protocol {
Some(data.to_vec())
} else {
None
}
}).collect();
let messages = messages
.into_iter()
.filter_map(|(engine, data)| {
if engine == this.protocol {
Some(data.to_vec())
} else {
None
}
})
.collect();
let to_forward = this.state_machine.on_incoming(
&mut *this.network,
@@ -217,27 +211,25 @@ impl<B: BlockT> Future for GossipEngine<B> {
this.forwarding_state = ForwardingState::Busy(to_forward.into());
},
Event::Dht(_) => {}
}
Event::Dht(_) => {},
},
// The network event stream closed. Do the same for [`GossipValidator`].
Poll::Ready(None) => return Poll::Ready(()),
Poll::Pending => break,
}
}
},
ForwardingState::Busy(to_forward) => {
let (topic, notification) = match to_forward.pop_front() {
Some(n) => n,
None => {
this.forwarding_state = ForwardingState::Idle;
continue;
}
continue
},
};
let sinks = match this.message_sinks.get_mut(&topic) {
Some(sinks) => sinks,
None => {
continue;
},
None => continue,
};
// Make sure all sinks for the given topic are ready.
@@ -249,8 +241,8 @@ impl<B: BlockT> Future for GossipEngine<B> {
Poll::Pending => {
// Push back onto queue for later.
to_forward.push_front((topic, notification));
break 'outer;
}
break 'outer
},
}
}
@@ -259,7 +251,7 @@ impl<B: BlockT> Future for GossipEngine<B> {
if sinks.is_empty() {
this.message_sinks.remove(&topic);
continue;
continue
}
trace!(
@@ -271,18 +263,16 @@ impl<B: BlockT> Future for GossipEngine<B> {
for sink in sinks {
match sink.start_send(notification.clone()) {
Ok(()) => {},
Err(e) if e.is_full() => unreachable!(
"Previously ensured that all sinks are ready; qed.",
),
Err(e) if e.is_full() =>
unreachable!("Previously ensured that all sinks are ready; qed.",),
// Receiver got dropped. Will be removed in next iteration (See (1)).
Err(_) => {},
}
}
}
},
}
}
while let Poll::Ready(()) = this.periodic_maintenance_interval.poll_unpin(cx) {
this.periodic_maintenance_interval.reset(PERIODIC_MAINTENANCE_INTERVAL);
this.state_machine.tick(&mut *this.network);
@@ -299,17 +289,23 @@ impl<B: BlockT> Future for GossipEngine<B> {
#[cfg(test)]
mod tests {
use async_std::task::spawn;
use super::*;
use crate::{ValidationResult, ValidatorContext};
use futures::{channel::mpsc::{unbounded, UnboundedSender}, executor::{block_on, block_on_stream}, future::poll_fn};
use async_std::task::spawn;
use futures::{
channel::mpsc::{unbounded, UnboundedSender},
executor::{block_on, block_on_stream},
future::poll_fn,
};
use quickcheck::{Arbitrary, Gen, QuickCheck};
use sc_network::ObservedRole;
use sp_runtime::{testing::H256, traits::{Block as BlockT}};
use std::borrow::Cow;
use std::convert::TryInto;
use std::sync::{Arc, Mutex};
use sp_runtime::{testing::H256, traits::Block as BlockT};
use std::{
borrow::Cow,
convert::TryInto,
sync::{Arc, Mutex},
};
use substrate_test_runtime_client::runtime::Block;
use super::*;
#[derive(Clone, Default)]
struct TestNetwork {
@@ -329,18 +325,15 @@ mod tests {
Box::pin(rx)
}
fn report_peer(&self, _: PeerId, _: ReputationChange) {
}
fn report_peer(&self, _: PeerId, _: ReputationChange) {}
fn disconnect_peer(&self, _: PeerId, _: Cow<'static, str>) {
unimplemented!();
}
fn add_set_reserved(&self, _: PeerId, _: Cow<'static, str>) {
}
fn add_set_reserved(&self, _: PeerId, _: Cow<'static, str>) {}
fn remove_set_reserved(&self, _: PeerId, _: Cow<'static, str>) {
}
fn remove_set_reserved(&self, _: PeerId, _: Cow<'static, str>) {}
fn write_notification(&self, _: PeerId, _: Cow<'static, str>, _: Vec<u8>) {
unimplemented!();
@@ -405,32 +398,32 @@ mod tests {
None,
);
let mut event_sender = network.inner.lock()
.unwrap()
.event_senders
.pop()
.unwrap();
let mut event_sender = network.inner.lock().unwrap().event_senders.pop().unwrap();
// Register the remote peer.
event_sender.start_send(
Event::NotificationStreamOpened {
event_sender
.start_send(Event::NotificationStreamOpened {
remote: remote_peer.clone(),
protocol: protocol.clone(),
negotiated_fallback: None,
role: ObservedRole::Authority,
}
).expect("Event stream is unbounded; qed.");
})
.expect("Event stream is unbounded; qed.");
let messages = vec![vec![1], vec![2]];
let events = messages.iter().cloned().map(|m| {
Event::NotificationsReceived {
let events = messages
.iter()
.cloned()
.map(|m| Event::NotificationsReceived {
remote: remote_peer.clone(),
messages: vec![(protocol.clone(), m.into())]
}
}).collect::<Vec<_>>();
messages: vec![(protocol.clone(), m.into())],
})
.collect::<Vec<_>>();
// Send first event before subscribing.
event_sender.start_send(events[0].clone()).expect("Event stream is unbounded; qed.");
event_sender
.start_send(events[0].clone())
.expect("Event stream is unbounded; qed.");
let mut subscribers = vec![];
for _ in 0..2 {
@@ -438,13 +431,14 @@ mod tests {
}
// Send second event after subscribing.
event_sender.start_send(events[1].clone()).expect("Event stream is unbounded; qed.");
event_sender
.start_send(events[1].clone())
.expect("Event stream is unbounded; qed.");
spawn(gossip_engine);
let mut subscribers = subscribers.into_iter()
.map(|s| block_on_stream(s))
.collect::<Vec<_>>();
let mut subscribers =
subscribers.into_iter().map(|s| block_on_stream(s)).collect::<Vec<_>>();
// Expect each subscriber to receive both events.
for message in messages {
@@ -463,7 +457,7 @@ mod tests {
#[test]
fn forwarding_to_different_size_and_topic_channels() {
#[derive(Clone, Debug)]
struct ChannelLengthAndTopic{
struct ChannelLengthAndTopic {
length: usize,
topic: H256,
}
@@ -486,7 +480,7 @@ mod tests {
topic: H256,
}
impl Arbitrary for Message{
impl Arbitrary for Message {
fn arbitrary(g: &mut Gen) -> Self {
let possible_topics = (0..10).collect::<Vec<u64>>();
Self {
@@ -517,13 +511,16 @@ mod tests {
let remote_peer = PeerId::random();
let network = TestNetwork::default();
let num_channels_per_topic = channels.iter()
.fold(HashMap::new(), |mut acc, ChannelLengthAndTopic { topic, .. }| {
let num_channels_per_topic = channels.iter().fold(
HashMap::new(),
|mut acc, ChannelLengthAndTopic { topic, .. }| {
acc.entry(topic).and_modify(|e| *e += 1).or_insert(1);
acc
});
},
);
let expected_msgs_per_topic_all_chan = notifications.iter()
let expected_msgs_per_topic_all_chan = notifications
.iter()
.fold(HashMap::new(), |mut acc, messages| {
for message in messages {
acc.entry(message.topic).and_modify(|e| *e += 1).or_insert(1);
@@ -545,12 +542,12 @@ mod tests {
);
// Create channels.
let (txs, mut rxs) = channels.iter()
.map(|ChannelLengthAndTopic { length, topic }| {
(topic.clone(), channel(*length))
})
let (txs, mut rxs) = channels
.iter()
.map(|ChannelLengthAndTopic { length, topic }| (topic.clone(), channel(*length)))
.fold((vec![], vec![]), |mut acc, (topic, (tx, rx))| {
acc.0.push((topic, tx)); acc.1.push((topic, rx));
acc.0.push((topic, tx));
acc.1.push((topic, rx));
acc
});
@@ -560,30 +557,27 @@ mod tests {
Some(entry) => entry.push(tx),
None => {
gossip_engine.message_sinks.insert(topic, vec![tx]);
}
},
}
}
let mut event_sender = network.inner.lock()
.unwrap()
.event_senders
.pop()
.unwrap();
let mut event_sender = network.inner.lock().unwrap().event_senders.pop().unwrap();
// Register the remote peer.
event_sender.start_send(
Event::NotificationStreamOpened {
event_sender
.start_send(Event::NotificationStreamOpened {
remote: remote_peer.clone(),
protocol: protocol.clone(),
negotiated_fallback: None,
role: ObservedRole::Authority,
}
).expect("Event stream is unbounded; qed.");
})
.expect("Event stream is unbounded; qed.");
// Send messages into the network event stream.
for (i_notification, messages) in notifications.iter().enumerate() {
let messages = messages.into_iter().enumerate()
let messages = messages
.into_iter()
.enumerate()
.map(|(i_message, Message { topic })| {
// Embed the topic in the first 256 bytes of the message to be extracted by
// the [`TestValidator`] later on.
@@ -595,12 +589,15 @@ mod tests {
message.push(i_message.try_into().unwrap());
(protocol.clone(), message.into())
}).collect();
})
.collect();
event_sender.start_send(Event::NotificationsReceived {
remote: remote_peer.clone(),
messages,
}).expect("Event stream is unbounded; qed.");
event_sender
.start_send(Event::NotificationsReceived {
remote: remote_peer.clone(),
messages,
})
.expect("Event stream is unbounded; qed.");
}
let mut received_msgs_per_topic_all_chan = HashMap::<H256, _>::new();
@@ -621,19 +618,19 @@ mod tests {
match rx.poll_next_unpin(cx) {
Poll::Ready(Some(_)) => {
progress = true;
received_msgs_per_topic_all_chan.entry(*topic)
received_msgs_per_topic_all_chan
.entry(*topic)
.and_modify(|e| *e += 1)
.or_insert(1);
},
Poll::Ready(None) => unreachable!(
"Sender side of channel is never dropped",
),
Poll::Ready(None) =>
unreachable!("Sender side of channel is never dropped",),
Poll::Pending => {},
}
}
if !progress {
break;
break
}
}
Poll::Ready(())
@@ -655,10 +652,10 @@ mod tests {
}
// Past regressions.
prop(vec![], vec![vec![Message{ topic: H256::default()}]]);
prop(vec![], vec![vec![Message { topic: H256::default() }]]);
prop(
vec![ChannelLengthAndTopic {length: 71, topic: H256::default()}],
vec![vec![Message{ topic: H256::default()}]],
vec![ChannelLengthAndTopic { length: 71, topic: H256::default() }],
vec![vec![Message { topic: H256::default() }]],
);
QuickCheck::new().quickcheck(prop as fn(_, _))