Apply some clippy lints (#11154)

* Apply some clippy hints

* Revert clippy ci changes

* Update client/cli/src/commands/generate.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/cli/src/commands/inspect_key.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/db/src/bench.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/db/src/bench.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/service/src/client/block_rules.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/service/src/client/block_rules.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/network/src/transactions.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/network/src/protocol.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Revert due to missing `or_default` function.

* Fix compilation and simplify code

* Undo change that corrupts benchmark.

* fix clippy

* Update client/service/test/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/state-db/src/noncanonical.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/state-db/src/noncanonical.rs

remove leftovers!

* Update client/tracing/src/logging/directives.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update utils/fork-tree/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* added needed ref

* Update frame/referenda/src/benchmarking.rs

* Simplify byte-vec creation

* let's just not overlap the ranges

* Correction

* cargo fmt

* Update utils/frame/benchmarking-cli/src/shared/stats.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update utils/frame/benchmarking-cli/src/pallet/command.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update utils/frame/benchmarking-cli/src/pallet/command.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
Co-authored-by: Giles Cope <gilescope@gmail.com>
This commit is contained in:
Falco Hirschenberger
2022-04-30 23:28:27 +02:00
committed by GitHub
parent a990473cf9
commit b581604aa7
368 changed files with 1927 additions and 2236 deletions
+1 -2
View File
@@ -434,7 +434,6 @@ where
"Trying to send warp sync request when no protocol is configured {:?}",
request,
);
return
},
},
CustomMessageOutcome::NotificationStreamOpened {
@@ -449,7 +448,7 @@ where
protocol,
negotiated_fallback,
role: reported_roles_to_observed_role(roles),
notifications_sink: notifications_sink.clone(),
notifications_sink,
});
},
CustomMessageOutcome::NotificationStreamReplaced {
+3 -3
View File
@@ -65,7 +65,7 @@ const MAX_RESPONSE_QUEUE: usize = 20;
// Max number of blocks per wantlist
const MAX_WANTED_BLOCKS: usize = 16;
const PROTOCOL_NAME: &'static [u8] = b"/ipfs/bitswap/1.2.0";
const PROTOCOL_NAME: &[u8] = b"/ipfs/bitswap/1.2.0";
type FutureResult<T, E> = Pin<Box<dyn Future<Output = Result<T, E>> + Send>>;
@@ -167,10 +167,10 @@ impl Prefix {
let version = varint_encode::u64(self.version.into(), &mut buf);
res.extend_from_slice(version);
let mut buf = varint_encode::u64_buffer();
let codec = varint_encode::u64(self.codec.into(), &mut buf);
let codec = varint_encode::u64(self.codec, &mut buf);
res.extend_from_slice(codec);
let mut buf = varint_encode::u64_buffer();
let mh_type = varint_encode::u64(self.mh_type.into(), &mut buf);
let mh_type = varint_encode::u64(self.mh_type, &mut buf);
res.extend_from_slice(mh_type);
let mut buf = varint_encode::u64_buffer();
let mh_len = varint_encode::u64(self.mh_len as u64, &mut buf);
@@ -197,7 +197,7 @@ where
peer: *peer,
max_blocks,
direction,
from: from_block_id.clone(),
from: from_block_id,
attributes,
support_multiple_justifications,
};
+8 -8
View File
@@ -287,7 +287,7 @@ impl DiscoveryBehaviour {
for b in k.kbuckets() {
for e in b.iter() {
if !peers.contains(e.node.key.preimage()) {
peers.insert(e.node.key.preimage().clone());
peers.insert(*e.node.key.preimage());
}
}
}
@@ -307,7 +307,7 @@ impl DiscoveryBehaviour {
k.add_address(&peer_id, addr.clone());
}
self.pending_events.push_back(DiscoveryOut::Discovered(peer_id.clone()));
self.pending_events.push_back(DiscoveryOut::Discovered(peer_id));
addrs_list.push(addr);
}
}
@@ -718,7 +718,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
// Poll the stream that fires when we need to start a random Kademlia query.
if let Some(next_kad_random_query) = self.next_kad_random_query.as_mut() {
while let Poll::Ready(_) = next_kad_random_query.poll_unpin(cx) {
while next_kad_random_query.poll_unpin(cx).is_ready() {
let actually_started = if self.num_connections < self.discovery_only_if_under_num {
let random_peer_id = PeerId::random();
debug!(
@@ -815,7 +815,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
DiscoveryOut::ValueFound(
results,
stats.duration().unwrap_or_else(Default::default),
stats.duration().unwrap_or_default(),
)
},
Err(e @ libp2p::kad::GetRecordError::NotFound { .. }) => {
@@ -826,7 +826,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
);
DiscoveryOut::ValueNotFound(
e.into_key(),
stats.duration().unwrap_or_else(Default::default),
stats.duration().unwrap_or_default(),
)
},
Err(e) => {
@@ -837,7 +837,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
);
DiscoveryOut::ValueNotFound(
e.into_key(),
stats.duration().unwrap_or_else(Default::default),
stats.duration().unwrap_or_default(),
)
},
};
@@ -851,7 +851,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
let ev = match res {
Ok(ok) => DiscoveryOut::ValuePut(
ok.key,
stats.duration().unwrap_or_else(Default::default),
stats.duration().unwrap_or_default(),
),
Err(e) => {
debug!(
@@ -861,7 +861,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
);
DiscoveryOut::ValuePutFailed(
e.into_key(),
stats.duration().unwrap_or_else(Default::default),
stats.duration().unwrap_or_default(),
)
},
};
@@ -27,11 +27,7 @@ use std::time::Duration;
/// Generate the light client protocol name from chain specific protocol identifier.
fn generate_protocol_name(protocol_id: &ProtocolId) -> String {
let mut s = String::new();
s.push_str("/");
s.push_str(protocol_id.as_ref());
s.push_str("/light/2");
s
format!("/{}/light/2", protocol_id.as_ref())
}
/// Generates a [`ProtocolConfig`] for the light client request protocol, refusing incoming
+9 -14
View File
@@ -391,13 +391,8 @@ where
sc_peerset::Peerset::from_config(sc_peerset::PeersetConfig { sets })
};
let block_announces_protocol: Cow<'static, str> = Cow::from({
let mut proto = String::new();
proto.push_str("/");
proto.push_str(protocol_id.as_ref());
proto.push_str("/block-announces/1");
proto
});
let block_announces_protocol: Cow<'static, str> =
format!("/{}/block-announces/1", protocol_id.as_ref()).into();
let behaviour = {
let best_number = info.best_number;
@@ -952,7 +947,7 @@ where
},
};
peer.known_blocks.insert(hash.clone());
peer.known_blocks.insert(hash);
let is_best = match announce.state.unwrap_or(message::BlockState::Best) {
message::BlockState::Best => true,
@@ -1062,7 +1057,7 @@ where
/// Uses `protocol` to queue a new justification request and tries to dispatch all pending
/// requests.
pub fn request_justification(&mut self, hash: &B::Hash, number: NumberFor<B>) {
self.sync.request_justification(&hash, number)
self.sync.request_justification(hash, number)
}
/// Clear all pending justification requests.
@@ -1479,7 +1474,7 @@ where
},
};
finished_block_requests.push((id.clone(), req, protobuf_response));
finished_block_requests.push((*id, req, protobuf_response));
},
PeerRequest::State => {
let protobuf_response =
@@ -1576,7 +1571,7 @@ where
}
for (id, request) in self.sync.block_requests() {
let event = prepare_block_request(&mut self.peers, id.clone(), request);
let event = prepare_block_request(&mut self.peers, *id, request);
self.pending_messages.push_back(event);
}
if let Some((id, request)) = self.sync.state_request() {
@@ -1727,9 +1722,9 @@ where
}
},
NotificationsOut::CustomProtocolReplaced { peer_id, notifications_sink, set_id } =>
if set_id == HARDCODED_PEERSETS_SYNC {
CustomMessageOutcome::None
} else if self.bad_handshake_substreams.contains(&(peer_id, set_id)) {
if set_id == HARDCODED_PEERSETS_SYNC ||
self.bad_handshake_substreams.contains(&(peer_id, set_id))
{
CustomMessageOutcome::None
} else {
CustomMessageOutcome::NotificationStreamReplaced {
@@ -154,7 +154,7 @@ impl<H: HeaderT> generic::BlockAnnounce<H> {
AnnouncementSummary {
block_hash: self.header.hash(),
number: *self.header.number(),
parent_hash: self.header.parent_hash().clone(),
parent_hash: *self.header.parent_hash(),
state: self.state,
}
}
@@ -402,7 +402,7 @@ impl Notifications {
}
/// Returns the list of all the peers we have an open channel to.
pub fn open_peers<'a>(&'a self) -> impl Iterator<Item = &'a PeerId> + 'a {
pub fn open_peers(&self) -> impl Iterator<Item = &PeerId> {
self.peers.iter().filter(|(_, state)| state.is_open()).map(|((id, _), _)| id)
}
@@ -551,10 +551,7 @@ impl Notifications {
}
/// Returns the list of reserved peers.
pub fn reserved_peers<'a>(
&'a self,
set_id: sc_peerset::SetId,
) -> impl Iterator<Item = &'a PeerId> + 'a {
pub fn reserved_peers(&self, set_id: sc_peerset::SetId) -> impl Iterator<Item = &PeerId> {
self.peerset.reserved_peers(set_id)
}
@@ -621,7 +618,7 @@ impl Notifications {
);
trace!(target: "sub-libp2p", "Libp2p <= Dial {}", entry.key().0);
self.events.push_back(NetworkBehaviourAction::Dial {
opts: entry.key().0.clone().into(),
opts: entry.key().0.into(),
handler,
});
entry.insert(PeerState::Requested);
@@ -634,7 +631,7 @@ impl Notifications {
match mem::replace(occ_entry.get_mut(), PeerState::Poisoned) {
// Backoff (not expired) => PendingRequest
PeerState::Backoff { ref timer, ref timer_deadline } if *timer_deadline > now => {
let peer_id = occ_entry.key().0.clone();
let peer_id = occ_entry.key().0;
trace!(
target: "sub-libp2p",
"PSM => Connect({}, {:?}): Will start to connect at until {:?}",
@@ -656,7 +653,7 @@ impl Notifications {
);
trace!(target: "sub-libp2p", "Libp2p <= Dial {:?}", occ_entry.key());
self.events.push_back(NetworkBehaviourAction::Dial {
opts: occ_entry.key().0.clone().into(),
opts: occ_entry.key().0.into(),
handler,
});
*occ_entry.into_mut() = PeerState::Requested;
@@ -666,7 +663,7 @@ impl Notifications {
PeerState::Disabled { connections, backoff_until: Some(ref backoff) }
if *backoff > now =>
{
let peer_id = occ_entry.key().0.clone();
let peer_id = occ_entry.key().0;
trace!(
target: "sub-libp2p",
"PSM => Connect({}, {:?}): But peer is backed-off until {:?}",
@@ -781,7 +778,7 @@ impl Notifications {
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Open({:?})",
occ_entry.key(), *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: occ_entry.key().0.clone(),
peer_id: occ_entry.key().0,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Open { protocol_index: set_id.into() },
});
@@ -861,10 +858,8 @@ impl Notifications {
if connections.iter().any(|(_, s)| matches!(s, ConnectionState::Open(_))) {
trace!(target: "sub-libp2p", "External API <= Closed({}, {:?})", entry.key().0, set_id);
let event = NotificationsOut::CustomProtocolClosed {
peer_id: entry.key().0.clone(),
set_id,
};
let event =
NotificationsOut::CustomProtocolClosed { peer_id: entry.key().0, set_id };
self.events.push_back(NetworkBehaviourAction::GenerateEvent(event));
}
@@ -874,7 +869,7 @@ impl Notifications {
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Close({:?})",
entry.key(), *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: entry.key().0.clone(),
peer_id: entry.key().0,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Close { protocol_index: set_id.into() },
});
@@ -887,7 +882,7 @@ impl Notifications {
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Close({:?})",
entry.key(), *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: entry.key().0.clone(),
peer_id: entry.key().0,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Close { protocol_index: set_id.into() },
});
@@ -1406,7 +1401,7 @@ impl NetworkBehaviour for Notifications {
trace!(target: "sub-libp2p", "Libp2p => Dial failure for {:?}", peer_id);
for set_id in (0..self.notif_protocols.len()).map(sc_peerset::SetId::from) {
if let Entry::Occupied(mut entry) = self.peers.entry((peer_id.clone(), set_id)) {
if let Entry::Occupied(mut entry) = self.peers.entry((peer_id, set_id)) {
match mem::replace(entry.get_mut(), PeerState::Poisoned) {
// The peer is not in our list.
st @ PeerState::Backoff { .. } => {
@@ -1646,7 +1641,6 @@ impl NetworkBehaviour for Notifications {
"OpenDesiredByRemote: Unexpected state in the custom protos handler: {:?}",
state);
debug_assert!(false);
return
},
};
},
@@ -1742,13 +1736,11 @@ impl NetworkBehaviour for Notifications {
state @ PeerState::Disabled { .. } |
state @ PeerState::DisabledPendingEnable { .. } => {
*entry.into_mut() = state;
return
},
state => {
error!(target: "sub-libp2p",
"Unexpected state in the custom protos handler: {:?}",
state);
return
},
}
},
@@ -1853,7 +1845,6 @@ impl NetworkBehaviour for Notifications {
"OpenResultOk: Unexpected state in the custom protos handler: {:?}",
state);
debug_assert!(false);
return
},
}
},
@@ -2052,9 +2043,7 @@ impl NetworkBehaviour for Notifications {
event: NotifsHandlerIn::Open { protocol_index: set_id.into() },
});
*connec_state = ConnectionState::Opening;
*peer_state = PeerState::Enabled {
connections: mem::replace(connections, Default::default()),
};
*peer_state = PeerState::Enabled { connections: mem::take(connections) };
} else {
*timer_deadline = Instant::now() + Duration::from_secs(5);
let delay = futures_timer::Delay::new(Duration::from_secs(5));
@@ -400,7 +400,7 @@ impl NotificationsSink {
/// error to send a notification using an unknown protocol.
///
/// This method will be removed in a future version.
pub fn send_sync_notification<'a>(&'a self, message: impl Into<Vec<u8>>) {
pub fn send_sync_notification(&self, message: impl Into<Vec<u8>>) {
let mut lock = self.inner.sync_channel.lock();
if let Some(tx) = lock.as_mut() {
@@ -425,7 +425,7 @@ impl NotificationsSink {
///
/// The protocol name is expected to be checked ahead of calling this method. It is a logic
/// error to send a notification using an unknown protocol.
pub async fn reserve_notification<'a>(&'a self) -> Result<Ready<'a>, ()> {
pub async fn reserve_notification(&self) -> Result<Ready<'_>, ()> {
let mut lock = self.inner.async_channel.lock().await;
let poll_ready = future::poll_fn(|cx| lock.poll_ready(cx)).await;
+61 -62
View File
@@ -672,7 +672,7 @@ where
self.best_queued_number
);
self.peers.insert(
who.clone(),
who,
PeerSync {
peer_id: who,
common_number: self.best_queued_number,
@@ -796,7 +796,7 @@ where
.iter()
// Only request blocks from peers who are ahead or on a par.
.filter(|(_, peer)| peer.best_number >= number)
.map(|(id, _)| id.clone())
.map(|(id, _)| *id)
.collect();
debug!(
@@ -809,7 +809,7 @@ where
debug!(target: "sync", "Explicit sync request for block {:?} with {:?}", hash, peers);
}
if self.is_known(&hash) {
if self.is_known(hash) {
debug!(target: "sync", "Refusing to sync known hash {:?}", hash);
return
}
@@ -843,7 +843,7 @@ where
let peers = &mut self.peers;
let mut matcher = self.extra_justifications.matcher();
std::iter::from_fn(move || {
if let Some((peer, request)) = matcher.next(&peers) {
if let Some((peer, request)) = matcher.next(peers) {
peers
.get_mut(&peer)
.expect(
@@ -1087,7 +1087,7 @@ where
if let Some(start_block) =
validate_blocks::<B>(&blocks, who, Some(request))?
{
self.blocks.insert(start_block, blocks, who.clone());
self.blocks.insert(start_block, blocks, *who);
}
self.drain_blocks()
},
@@ -1098,7 +1098,7 @@ where
if let Some(start_block) =
validate_blocks::<B>(&blocks, who, Some(request))?
{
gap_sync.blocks.insert(start_block, blocks, who.clone());
gap_sync.blocks.insert(start_block, blocks, *who);
}
gap = true;
let blocks: Vec<_> = gap_sync
@@ -1106,11 +1106,12 @@ where
.drain(gap_sync.best_queued_number + One::one())
.into_iter()
.map(|block_data| {
let justifications = block_data.block.justifications.or(
legacy_justification_mapping(
block_data.block.justification,
),
);
let justifications =
block_data.block.justifications.or_else(|| {
legacy_justification_mapping(
block_data.block.justification,
)
});
IncomingBlock {
hash: block_data.block.hash,
header: block_data.block.header,
@@ -1129,7 +1130,7 @@ where
blocks
} else {
debug!(target: "sync", "Unexpected gap block response from {}", who);
return Err(BadPeer(who.clone(), rep::NO_BLOCK))
return Err(BadPeer(*who, rep::NO_BLOCK))
}
},
PeerSyncState::DownloadingStale(_) => {
@@ -1144,7 +1145,7 @@ where
.map(|b| {
let justifications = b
.justifications
.or(legacy_justification_mapping(b.justification));
.or_else(|| legacy_justification_mapping(b.justification));
IncomingBlock {
hash: b.hash,
header: b.header,
@@ -1261,8 +1262,9 @@ where
blocks
.into_iter()
.map(|b| {
let justifications =
b.justifications.or(legacy_justification_mapping(b.justification));
let justifications = b
.justifications
.or_else(|| legacy_justification_mapping(b.justification));
IncomingBlock {
hash: b.hash,
header: b.header,
@@ -1294,7 +1296,7 @@ where
who: &PeerId,
response: StateResponse,
) -> Result<OnStateData<B>, BadPeer> {
if let Some(peer) = self.peers.get_mut(&who) {
if let Some(peer) = self.peers.get_mut(who) {
if let PeerSyncState::DownloadingState = peer.state {
peer.state = PeerSyncState::Available;
self.allowed_requests.set_all();
@@ -1357,7 +1359,7 @@ where
who: &PeerId,
response: warp::EncodedProof,
) -> Result<(), BadPeer> {
if let Some(peer) = self.peers.get_mut(&who) {
if let Some(peer) = self.peers.get_mut(who) {
if let PeerSyncState::DownloadingWarpProof = peer.state {
peer.state = PeerSyncState::Available;
self.allowed_requests.set_all();
@@ -1458,7 +1460,9 @@ where
return Err(BadPeer(who, rep::BAD_JUSTIFICATION))
}
block.justifications.or(legacy_justification_mapping(block.justification))
block
.justifications
.or_else(|| legacy_justification_mapping(block.justification))
} else {
// we might have asked the peer for a justification on a block that we assumed it
// had but didn't (regardless of whether it had a justification for it or not).
@@ -1488,19 +1492,19 @@ where
/// queue, with or without errors.
///
/// `peer_info` is passed in case of a restart.
pub fn on_blocks_processed<'a>(
&'a mut self,
pub fn on_blocks_processed(
&mut self,
imported: usize,
count: usize,
results: Vec<(Result<BlockImportStatus<NumberFor<B>>, BlockImportError>, B::Hash)>,
) -> impl Iterator<Item = Result<(PeerId, BlockRequest<B>), BadPeer>> + 'a {
) -> impl Iterator<Item = Result<(PeerId, BlockRequest<B>), BadPeer>> {
trace!(target: "sync", "Imported {} of {}", imported, count);
let mut output = Vec::new();
let mut has_error = false;
for (_, hash) in &results {
self.queue_blocks.remove(&hash);
self.queue_blocks.remove(hash);
}
for (result, hash) in results {
if has_error {
@@ -1659,7 +1663,7 @@ where
heads.sort();
let median = heads[heads.len() / 2];
if number + STATE_SYNC_FINALITY_THRESHOLD.saturated_into() >= median {
if let Ok(Some(header)) = self.client.header(BlockId::hash(hash.clone())) {
if let Ok(Some(header)) = self.client.header(BlockId::hash(*hash)) {
log::debug!(
target: "sync",
"Starting state sync for #{} ({})",
@@ -1688,7 +1692,7 @@ where
/// Updates our internal state for best queued block and then goes
/// through all peers to update our view of their state as well.
fn on_block_queued(&mut self, hash: &B::Hash, number: NumberFor<B>) {
if self.fork_targets.remove(&hash).is_some() {
if self.fork_targets.remove(hash).is_some() {
trace!(target: "sync", "Completed fork sync {:?}", hash);
}
if let Some(gap_sync) = &mut self.gap_sync {
@@ -1741,7 +1745,7 @@ where
return HasSlotForBlockAnnounceValidation::TotalMaximumSlotsReached
}
match self.block_announce_validation_per_peer_stats.entry(peer.clone()) {
match self.block_announce_validation_per_peer_stats.entry(*peer) {
Entry::Vacant(entry) => {
entry.insert(1);
HasSlotForBlockAnnounceValidation::Yes
@@ -1830,8 +1834,7 @@ where
// Let external validator check the block announcement.
let assoc_data = announce.data.as_ref().map_or(&[][..], |v| v.as_slice());
let future = self.block_announce_validator.validate(&header, assoc_data);
let hash = hash.clone();
let future = self.block_announce_validator.validate(header, assoc_data);
self.block_announce_validation.push(
async move {
@@ -1900,7 +1903,7 @@ where
PreValidateBlockAnnounce::Skip => return,
};
match self.block_announce_validation_per_peer_stats.entry(peer.clone()) {
match self.block_announce_validation_per_peer_stats.entry(*peer) {
Entry::Vacant(_) => {
error!(
target: "sync",
@@ -1994,7 +1997,7 @@ where
if known || self.is_already_downloading(&hash) {
trace!(target: "sync", "Known block announce from {}: {}", who, hash);
if let Some(target) = self.fork_targets.get_mut(&hash) {
target.peers.insert(who.clone());
target.peers.insert(who);
}
return PollBlockAnnounceValidation::Nothing { is_best, who, announce }
}
@@ -2070,9 +2073,7 @@ where
/// Restart the sync process. This will reset all pending block requests and return an iterator
/// of new block requests to make to peers. Peers that were downloading finality data (i.e.
/// their state was `DownloadingJustification`) are unaffected and will stay in the same state.
fn restart<'a>(
&'a mut self,
) -> impl Iterator<Item = Result<(PeerId, BlockRequest<B>), BadPeer>> + 'a {
fn restart(&mut self) -> impl Iterator<Item = Result<(PeerId, BlockRequest<B>), BadPeer>> + '_ {
self.blocks.clear();
if let Err(e) = self.reset_sync_start_point() {
warn!(target: "sync", "💔 Unable to restart sync: {}", e);
@@ -2084,18 +2085,15 @@ where
old_peers.into_iter().filter_map(move |(id, mut p)| {
// peers that were downloading justifications
// should be kept in that state.
match p.state {
PeerSyncState::DownloadingJustification(_) => {
// We make sure our commmon number is at least something we have.
p.common_number = self.best_queued_number;
self.peers.insert(id, p);
return None
},
_ => {},
if let PeerSyncState::DownloadingJustification(_) = p.state {
// We make sure our commmon number is at least something we have.
p.common_number = self.best_queued_number;
self.peers.insert(id, p);
return None
}
// handle peers that were in other states.
match self.new_peer(id.clone(), p.best_hash, p.best_number) {
match self.new_peer(id, p.best_hash, p.best_number) {
Ok(None) => None,
Ok(Some(x)) => Some(Ok((id, x))),
Err(e) => Some(Err(e)),
@@ -2124,23 +2122,24 @@ where
self.import_existing = false;
self.best_queued_hash = info.best_hash;
self.best_queued_number = info.best_number;
if self.mode == SyncMode::Full {
if self.client.block_status(&BlockId::hash(info.best_hash))? !=
if self.mode == SyncMode::Full &&
self.client.block_status(&BlockId::hash(info.best_hash))? !=
BlockStatus::InChainWithState
{
self.import_existing = true;
// Latest state is missing, start with the last finalized state or genesis instead.
if let Some((hash, number)) = info.finalized_state {
debug!(target: "sync", "Starting from finalized state #{}", number);
self.best_queued_hash = hash;
self.best_queued_number = number;
} else {
debug!(target: "sync", "Restarting from genesis");
self.best_queued_hash = Default::default();
self.best_queued_number = Zero::zero();
}
{
self.import_existing = true;
// Latest state is missing, start with the last finalized state or genesis instead.
if let Some((hash, number)) = info.finalized_state {
debug!(target: "sync", "Starting from finalized state #{}", number);
self.best_queued_hash = hash;
self.best_queued_number = number;
} else {
debug!(target: "sync", "Restarting from genesis");
self.best_queued_hash = Default::default();
self.best_queued_number = Zero::zero();
}
}
if let Some((start, end)) = info.block_gap {
debug!(target: "sync", "Starting gap sync #{} - #{}", start, end);
self.gap_sync = Some(GapSync {
@@ -2192,7 +2191,7 @@ where
let justifications = block_data
.block
.justifications
.or(legacy_justification_mapping(block_data.block.justification));
.or_else(|| legacy_justification_mapping(block_data.block.justification));
IncomingBlock {
hash: block_data.block.hash,
header: block_data.block.header,
@@ -2349,7 +2348,7 @@ fn peer_block_request<B: BlockT>(
let request = message::generic::BlockRequest {
id: 0,
fields: attrs.clone(),
fields: attrs,
from,
to: None,
direction: message::Direction::Descending,
@@ -2369,7 +2368,7 @@ fn peer_gap_block_request<B: BlockT>(
common_number: NumberFor<B>,
) -> Option<(Range<NumberFor<B>>, BlockRequest<B>)> {
let range = blocks.needed_blocks(
id.clone(),
*id,
MAX_BLOCKS_TO_REQUEST,
std::cmp::min(peer.best_number, target),
common_number,
@@ -2383,7 +2382,7 @@ fn peer_gap_block_request<B: BlockT>(
let request = message::generic::BlockRequest {
id: 0,
fields: attrs.clone(),
fields: attrs,
from,
to: None,
direction: message::Direction::Descending,
@@ -2430,11 +2429,11 @@ fn fork_sync_request<B: BlockT>(
};
trace!(target: "sync", "Downloading requested fork {:?} from {}, {} blocks", hash, id, count);
return Some((
hash.clone(),
*hash,
message::generic::BlockRequest {
id: 0,
fields: attributes.clone(),
from: message::FromBlock::Hash(hash.clone()),
fields: attributes,
from: message::FromBlock::Hash(*hash),
to: None,
direction: message::Direction::Descending,
max: Some(count),
@@ -327,7 +327,7 @@ impl<'a, B: BlockT> Matcher<'a, B> {
{
continue
}
self.extras.active_requests.insert(peer.clone(), request);
self.extras.active_requests.insert(*peer, request);
trace!(target: "sync",
"Sending {} request to {:?} for {:?}",
@@ -71,7 +71,7 @@ where
Self {
client,
target_block: target.hash(),
target_root: target.state_root().clone(),
target_root: *target.state_root(),
target_header: target,
last_key: SmallVec::default(),
state: HashMap::default(),
@@ -149,18 +149,16 @@ where
if entry.0.len() > 0 && entry.1.len() > 1 {
// Already imported child_trie with same root.
// Warning this will not work with parallel download.
} else {
if entry.0.is_empty() {
for (key, _value) in key_values.iter() {
self.imported_bytes += key.len() as u64;
}
} else if entry.0.is_empty() {
for (key, _value) in key_values.iter() {
self.imported_bytes += key.len() as u64;
}
entry.0 = key_values;
} else {
for (key, value) in key_values {
self.imported_bytes += key.len() as u64;
entry.0.push((key, value))
}
entry.0 = key_values;
} else {
for (key, value) in key_values {
self.imported_bytes += key.len() as u64;
entry.0.push((key, value))
}
}
}
@@ -172,7 +170,7 @@ where
// the parent cursor stays valid.
// Empty parent trie content only happens when all the response content
// is part of a single child trie.
if self.last_key.len() == 2 && response.entries[0].entries.len() == 0 {
if self.last_key.len() == 2 && response.entries[0].entries.is_empty() {
// Do not remove the parent trie position.
self.last_key.pop();
} else {
@@ -220,7 +218,7 @@ where
self.target_block,
self.target_header.clone(),
ImportedState {
block: self.target_block.clone(),
block: self.target_block,
state: std::mem::take(&mut self.state).into(),
},
)
@@ -94,7 +94,7 @@ where
match &mut self.phase {
Phase::WarpProof { .. } => {
log::debug!(target: "sync", "Unexpected state response");
return ImportResult::BadResponse
ImportResult::BadResponse
},
Phase::State(sync) => sync.import(response),
}
@@ -111,13 +111,13 @@ where
match self.warp_sync_provider.verify(&response, *set_id, authorities.clone()) {
Err(e) => {
log::debug!(target: "sync", "Bad warp proof response: {}", e);
return WarpProofImportResult::BadResponse
WarpProofImportResult::BadResponse
},
Ok(VerificationResult::Partial(new_set_id, new_authorities, new_last_hash)) => {
log::debug!(target: "sync", "Verified partial proof, set_id={:?}", new_set_id);
*set_id = new_set_id;
*authorities = new_authorities;
*last_hash = new_last_hash.clone();
*last_hash = new_last_hash;
self.total_proof_bytes += response.0.len() as u64;
WarpProofImportResult::Success
},
@@ -355,25 +355,21 @@ impl RequestResponsesBehaviour {
(Instant::now(), pending_response),
);
debug_assert!(prev_req_id.is_none(), "Expect request id to be unique.");
} else {
if pending_response.send(Err(RequestFailure::NotConnected)).is_err() {
log::debug!(
target: "sub-libp2p",
"Not connected to peer {:?}. At the same time local \
node is no longer interested in the result.",
target,
);
};
}
} else {
if pending_response.send(Err(RequestFailure::UnknownProtocol)).is_err() {
} else if pending_response.send(Err(RequestFailure::NotConnected)).is_err() {
log::debug!(
target: "sub-libp2p",
"Unknown protocol {:?}. At the same time local \
"Not connected to peer {:?}. At the same time local \
node is no longer interested in the result.",
protocol_name,
target,
);
};
}
} else if pending_response.send(Err(RequestFailure::UnknownProtocol)).is_err() {
log::debug!(
target: "sub-libp2p",
"Unknown protocol {:?}. At the same time local \
node is no longer interested in the result.",
protocol_name,
);
}
}
@@ -599,7 +595,7 @@ impl NetworkBehaviour for RequestResponsesBehaviour {
// will be reported by the corresponding `RequestResponse` through
// an `InboundFailure::Omission` event.
let _ = resp_builder.try_send(IncomingRequest {
peer: peer.clone(),
peer,
payload: request,
pending_response: tx,
});
@@ -648,7 +644,7 @@ impl NetworkBehaviour for RequestResponsesBehaviour {
if let Ok(payload) = result {
if let Some((protocol, _)) = self.protocols.get_mut(&*protocol_name) {
if let Err(_) = protocol.send_response(inner_channel, Ok(payload)) {
if protocol.send_response(inner_channel, Ok(payload)).is_err() {
// Note: Failure is handled further below when receiving
// `InboundFailure` event from `RequestResponse` behaviour.
log::debug!(
@@ -658,11 +654,9 @@ impl NetworkBehaviour for RequestResponsesBehaviour {
Dropping response",
request_id, protocol_name,
);
} else {
if let Some(sent_feedback) = sent_feedback {
self.send_feedback
.insert((protocol_name, request_id).into(), sent_feedback);
}
} else if let Some(sent_feedback) = sent_feedback {
self.send_feedback
.insert((protocol_name, request_id).into(), sent_feedback);
}
}
}
@@ -718,13 +712,10 @@ impl NetworkBehaviour for RequestResponsesBehaviour {
message:
RequestResponseMessage::Request { request_id, request, channel, .. },
} => {
self.pending_responses_arrival_time.insert(
(protocol.clone(), request_id.clone()).into(),
Instant::now(),
);
self.pending_responses_arrival_time
.insert((protocol.clone(), request_id).into(), Instant::now());
let get_peer_reputation =
self.peerset.clone().peer_reputation(peer.clone());
let get_peer_reputation = self.peerset.clone().peer_reputation(peer);
let get_peer_reputation = Box::pin(get_peer_reputation);
// Save the Future-like state with params to poll `get_peer_reputation`
+20 -28
View File
@@ -195,7 +195,7 @@ where
// Private and public keys configuration.
let local_identity = params.network_config.node_key.clone().into_keypair()?;
let local_public = local_identity.public();
let local_peer_id = local_public.clone().to_peer_id();
let local_peer_id = local_public.to_peer_id();
info!(
target: "sub-libp2p",
"🏷 Local node identity is: {}",
@@ -248,7 +248,7 @@ where
Err(Error::DuplicateBootnode {
address: addr.clone(),
first_id: *peer_id,
second_id: other.0.clone(),
second_id: other.0,
})
} else {
Ok(())
@@ -644,7 +644,7 @@ where
.collect()
};
let peer_id = Swarm::<Behaviour<B, Client>>::local_peer_id(&swarm).to_base58();
let peer_id = Swarm::<Behaviour<B, Client>>::local_peer_id(swarm).to_base58();
let listened_addresses = swarm.listeners().cloned().collect();
let external_addresses = swarm.external_addresses().map(|r| &r.addr).cloned().collect();
@@ -664,7 +664,7 @@ where
.behaviour_mut()
.user_protocol_mut()
.peers_info()
.map(|(id, info)| (id.clone(), info.clone()))
.map(|(id, info)| (*id, info.clone()))
.collect()
}
@@ -753,7 +753,7 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
// `peers_notifications_sinks` mutex as soon as possible.
let sink = {
let peers_notifications_sinks = self.peers_notifications_sinks.lock();
if let Some(sink) = peers_notifications_sinks.get(&(target.clone(), protocol.clone())) {
if let Some(sink) = peers_notifications_sinks.get(&(target, protocol.clone())) {
sink.clone()
} else {
// Notification silently discarded, as documented.
@@ -1093,7 +1093,7 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
let _ = self
.to_worker
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id.clone(), addr));
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr));
let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::AddReserved(peer_id));
Ok(())
}
@@ -1173,7 +1173,7 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
if !addr.is_empty() {
let _ = self
.to_worker
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id.clone(), addr));
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr));
}
let _ = self
.to_worker
@@ -1227,7 +1227,7 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
if !addr.is_empty() {
let _ = self
.to_worker
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id.clone(), addr));
.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr));
}
let _ = self
.to_worker
@@ -1351,9 +1351,7 @@ pub struct NotificationSender {
impl NotificationSender {
/// Returns a future that resolves when the `NotificationSender` is ready to send a
/// notification.
pub async fn ready<'a>(
&'a self,
) -> Result<NotificationSenderReady<'a>, NotificationSenderError> {
pub async fn ready(&self) -> Result<NotificationSenderReady<'_>, NotificationSenderError> {
Ok(NotificationSenderReady {
ready: match self.sink.reserve_notification().await {
Ok(r) => r,
@@ -1771,7 +1769,7 @@ where
if let Some(metrics) = this.metrics.as_ref() {
metrics
.kademlia_random_queries_total
.with_label_values(&[&protocol.as_ref()])
.with_label_values(&[protocol.as_ref()])
.inc();
},
Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamOpened {
@@ -1790,7 +1788,7 @@ where
{
let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
let _previous_value = peers_notifications_sinks
.insert((remote.clone(), protocol.clone()), notifications_sink);
.insert((remote, protocol.clone()), notifications_sink);
debug_assert!(_previous_value.is_none());
}
this.event_streams.send(Event::NotificationStreamOpened {
@@ -1848,13 +1846,12 @@ where
.inc();
}
this.event_streams.send(Event::NotificationStreamClosed {
remote: remote.clone(),
remote,
protocol: protocol.clone(),
});
{
let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
let _previous_value =
peers_notifications_sinks.remove(&(remote.clone(), protocol));
let _previous_value = peers_notifications_sinks.remove(&(remote, protocol));
debug_assert!(_previous_value.is_some());
}
},
@@ -2117,10 +2114,7 @@ where
for (lower_ilog2_bucket_bound, num_entries) in buckets {
metrics
.kbuckets_num_nodes
.with_label_values(&[
&proto.as_ref(),
&lower_ilog2_bucket_bound.to_string(),
])
.with_label_values(&[proto.as_ref(), &lower_ilog2_bucket_bound.to_string()])
.set(num_entries as u64);
}
}
@@ -2128,7 +2122,7 @@ where
{
metrics
.kademlia_records_count
.with_label_values(&[&proto.as_ref()])
.with_label_values(&[proto.as_ref()])
.set(num_entries as u64);
}
for (proto, num_entries) in
@@ -2136,7 +2130,7 @@ where
{
metrics
.kademlia_records_sizes_total
.with_label_values(&[&proto.as_ref()])
.with_label_values(&[proto.as_ref()])
.set(num_entries as u64);
}
metrics
@@ -2211,12 +2205,10 @@ where
number: NumberFor<B>,
success: bool,
) {
self.protocol.behaviour_mut().user_protocol_mut().justification_import_result(
who,
hash.clone(),
number,
success,
);
self.protocol
.behaviour_mut()
.user_protocol_mut()
.justification_import_result(who, *hash, number, success);
}
fn request_justification(&mut self, hash: &B::Hash, number: NumberFor<B>) {
self.protocol
@@ -280,8 +280,8 @@ impl MetricSource for BandwidthCounters {
type N = u64;
fn collect(&self, mut set: impl FnMut(&[&str], Self::N)) {
set(&[&"in"], self.0.total_inbound());
set(&[&"out"], self.0.total_outbound());
set(&["in"], self.0.total_inbound());
set(&["out"], self.0.total_outbound());
}
}
@@ -197,9 +197,9 @@ fn format_label(prefix: &str, protocol: &str, callback: impl FnOnce(&str)) {
label_buffer.clear();
label_buffer.reserve(prefix.len() + protocol.len() + 2);
label_buffer.push_str(prefix);
label_buffer.push_str("\"");
label_buffer.push('"');
label_buffer.push_str(protocol);
label_buffer.push_str("\"");
label_buffer.push('"');
callback(&label_buffer);
});
}
@@ -249,14 +249,14 @@ impl Metrics {
.inc_by(num);
},
Event::NotificationStreamOpened { protocol, .. } => {
format_label("notif-open-", &protocol, |protocol_label| {
format_label("notif-open-", protocol, |protocol_label| {
self.events_total
.with_label_values(&[protocol_label, "sent", name])
.inc_by(num);
});
},
Event::NotificationStreamClosed { protocol, .. } => {
format_label("notif-closed-", &protocol, |protocol_label| {
format_label("notif-closed-", protocol, |protocol_label| {
self.events_total
.with_label_values(&[protocol_label, "sent", name])
.inc_by(num);
@@ -264,7 +264,7 @@ impl Metrics {
},
Event::NotificationsReceived { messages, .. } =>
for (protocol, message) in messages {
format_label("notif-", &protocol, |protocol_label| {
format_label("notif-", protocol, |protocol_label| {
self.events_total
.with_label_values(&[protocol_label, "sent", name])
.inc_by(num);
@@ -290,24 +290,24 @@ impl Metrics {
.inc();
},
Event::NotificationStreamOpened { protocol, .. } => {
format_label("notif-open-", &protocol, |protocol_label| {
format_label("notif-open-", protocol, |protocol_label| {
self.events_total.with_label_values(&[protocol_label, "received", name]).inc();
});
},
Event::NotificationStreamClosed { protocol, .. } => {
format_label("notif-closed-", &protocol, |protocol_label| {
format_label("notif-closed-", protocol, |protocol_label| {
self.events_total.with_label_values(&[protocol_label, "received", name]).inc();
});
},
Event::NotificationsReceived { messages, .. } =>
for (protocol, message) in messages {
format_label("notif-", &protocol, |protocol_label| {
format_label("notif-", protocol, |protocol_label| {
self.events_total
.with_label_values(&[protocol_label, "received", name])
.inc();
});
self.notifications_sizes
.with_label_values(&[&protocol, "received", name])
.with_label_values(&[protocol, "received", name])
.inc_by(u64::try_from(message.len()).unwrap_or(u64::MAX));
},
}
@@ -63,11 +63,7 @@ pub fn generate_protocol_config(protocol_id: &ProtocolId) -> ProtocolConfig {
/// Generate the state protocol name from chain specific protocol identifier.
fn generate_protocol_name(protocol_id: &ProtocolId) -> String {
let mut s = String::new();
s.push_str("/");
s.push_str(protocol_id.as_ref());
s.push_str("/state/2");
s
format!("/{}/state/2", protocol_id.as_ref())
}
/// The key of [`BlockRequestHandler::seen_requests`].
@@ -152,8 +148,7 @@ where
let request = StateRequest::decode(&payload[..])?;
let block: B::Hash = Decode::decode(&mut request.block.as_ref())?;
let key =
SeenRequestsKey { peer: *peer, block: block.clone(), start: request.start.clone() };
let key = SeenRequestsKey { peer: *peer, block, start: request.start.clone() };
let mut reputation_changes = Vec::new();
+1 -9
View File
@@ -133,15 +133,7 @@ pub struct TransactionsHandlerPrototype {
impl TransactionsHandlerPrototype {
/// Create a new instance.
pub fn new(protocol_id: ProtocolId) -> Self {
Self {
protocol_name: Cow::from({
let mut proto = String::new();
proto.push_str("/");
proto.push_str(protocol_id.as_ref());
proto.push_str("/transactions/1");
proto
}),
}
Self { protocol_name: format!("/{}/transactions/1", protocol_id.as_ref()).into() }
}
/// Returns the configuration of the set to put in the network configuration.
+3 -3
View File
@@ -82,11 +82,11 @@ pub fn build_transport(
rare panic here is basically zero");
// Legacy noise configurations for backward compatibility.
let mut noise_legacy = noise::LegacyConfig::default();
noise_legacy.recv_legacy_handshake = true;
let noise_legacy =
noise::LegacyConfig { recv_legacy_handshake: true, ..Default::default() };
let mut xx_config = noise::NoiseConfig::xx(noise_keypair);
xx_config.set_legacy_config(noise_legacy.clone());
xx_config.set_legacy_config(noise_legacy);
xx_config.into_authenticated()
};
@@ -82,11 +82,7 @@ pub fn generate_request_response_config(protocol_id: ProtocolId) -> RequestRespo
/// Generate the grandpa warp sync protocol name from chain specific protocol identifier.
fn generate_protocol_name(protocol_id: ProtocolId) -> String {
let mut s = String::new();
s.push_str("/");
s.push_str(protocol_id.as_ref());
s.push_str("/sync/warp");
s
format!("/{}/sync/warp", protocol_id.as_ref())
}
/// Handler for incoming grandpa warp sync requests from a remote peer.