Clean up sc-network (#9761)

* Clean up sc-network

- Avoid using clone() for the Copy type `PeerId`.
- Use `find_map` for `filter_map` and `next`.
- Use `Self`.

* More on Copy types

* Cargo +nightly fmt --all

* More ..

* fmt

* Revert vec![default_notif_handshake_message]
This commit is contained in:
Liu-Cheng Xu
2021-09-14 02:11:29 +08:00
committed by GitHub
parent 0472a43855
commit 2562f8c65e
37 changed files with 475 additions and 526 deletions
@@ -117,6 +117,6 @@ pub enum ObservedRole {
impl ObservedRole {
/// Returns `true` for `ObservedRole::Light`.
pub fn is_light(&self) -> bool {
matches!(self, ObservedRole::Light)
matches!(self, Self::Light)
}
}
@@ -85,7 +85,7 @@ impl BlockAttributes {
/// Decodes attributes, encoded with the `encode_to_be_u32()` call.
pub fn from_be_u32(encoded: u32) -> Result<Self, Error> {
BlockAttributes::from_bits(encoded.to_be_bytes()[0])
Self::from_bits(encoded.to_be_bytes()[0])
.ok_or_else(|| Error::from("Invalid BlockAttributes"))
}
}
@@ -187,12 +187,12 @@ pub mod generic {
impl Roles {
/// Does this role represents a client that holds full chain data locally?
pub fn is_full(&self) -> bool {
self.intersects(Roles::FULL | Roles::AUTHORITY)
self.intersects(Self::FULL | Self::AUTHORITY)
}
/// Does this role represents a client that does not participates in the consensus?
pub fn is_authority(&self) -> bool {
*self == Roles::AUTHORITY
*self == Self::AUTHORITY
}
/// Does this role represents a client that does not hold full chain data locally?
@@ -204,9 +204,9 @@ pub mod generic {
impl<'a> From<&'a crate::config::Role> for Roles {
fn from(roles: &'a crate::config::Role) -> Self {
match roles {
crate::config::Role::Full => Roles::FULL,
crate::config::Role::Light => Roles::LIGHT,
crate::config::Role::Authority { .. } => Roles::AUTHORITY,
crate::config::Role::Full => Self::FULL,
crate::config::Role::Light => Self::LIGHT,
crate::config::Role::Authority { .. } => Self::AUTHORITY,
}
}
}
@@ -368,7 +368,7 @@ pub mod generic {
genesis_hash,
} = compact;
Ok(Status {
Ok(Self {
version,
min_supported_version,
roles,
@@ -438,7 +438,7 @@ pub mod generic {
let header = H::decode(input)?;
let state = BlockState::decode(input).ok();
let data = Vec::decode(input).ok();
Ok(BlockAnnounce { header, state, data })
Ok(Self { header, state, data })
}
}
@@ -32,6 +32,7 @@ use libp2p::{
use log::{error, trace, warn};
use parking_lot::RwLock;
use rand::distributions::{Distribution as _, Uniform};
use sc_peerset::DropReason;
use smallvec::SmallVec;
use std::{
borrow::Cow,
@@ -242,35 +243,22 @@ impl PeerState {
/// that is open for custom protocol traffic.
fn get_open(&self) -> Option<&NotificationsSink> {
match self {
PeerState::Enabled { connections, .. } => connections
.iter()
.filter_map(|(_, s)| match s {
ConnectionState::Open(s) => Some(s),
_ => None,
})
.next(),
PeerState::Poisoned => None,
PeerState::Backoff { .. } => None,
PeerState::PendingRequest { .. } => None,
PeerState::Requested => None,
PeerState::Disabled { .. } => None,
PeerState::DisabledPendingEnable { .. } => None,
PeerState::Incoming { .. } => None,
Self::Enabled { connections, .. } => connections.iter().find_map(|(_, s)| match s {
ConnectionState::Open(s) => Some(s),
_ => None,
}),
_ => None,
}
}
/// True if that node has been requested by the PSM.
fn is_requested(&self) -> bool {
match self {
PeerState::Poisoned => false,
PeerState::Backoff { .. } => false,
PeerState::PendingRequest { .. } => true,
PeerState::Requested => true,
PeerState::Disabled { .. } => false,
PeerState::DisabledPendingEnable { .. } => true,
PeerState::Enabled { .. } => true,
PeerState::Incoming { .. } => false,
}
matches!(
self,
Self::PendingRequest { .. } |
Self::Requested | Self::DisabledPendingEnable { .. } |
Self::Enabled { .. }
)
}
}
@@ -391,7 +379,7 @@ impl Notifications {
assert!(!notif_protocols.is_empty());
Notifications {
Self {
notif_protocols,
peerset,
peers: FnvHashMap::default(),
@@ -446,8 +434,7 @@ impl Notifications {
set_id: sc_peerset::SetId,
ban: Option<Duration>,
) {
let mut entry = if let Entry::Occupied(entry) = self.peers.entry((peer_id.clone(), set_id))
{
let mut entry = if let Entry::Occupied(entry) = self.peers.entry((*peer_id, set_id)) {
entry
} else {
return
@@ -463,7 +450,7 @@ impl Notifications {
// DisabledPendingEnable => Disabled.
PeerState::DisabledPendingEnable { connections, timer_deadline, timer: _ } => {
trace!(target: "sub-libp2p", "PSM <= Dropped({}, {:?})", peer_id, set_id);
self.peerset.dropped(set_id, peer_id.clone(), sc_peerset::DropReason::Unknown);
self.peerset.dropped(set_id, *peer_id, DropReason::Unknown);
let backoff_until = Some(if let Some(ban) = ban {
cmp::max(timer_deadline, Instant::now() + ban)
} else {
@@ -477,12 +464,12 @@ impl Notifications {
// If relevant, the external API is instantly notified.
PeerState::Enabled { mut connections } => {
trace!(target: "sub-libp2p", "PSM <= Dropped({}, {:?})", peer_id, set_id);
self.peerset.dropped(set_id, peer_id.clone(), sc_peerset::DropReason::Unknown);
self.peerset.dropped(set_id, *peer_id, DropReason::Unknown);
if connections.iter().any(|(_, s)| matches!(s, ConnectionState::Open(_))) {
trace!(target: "sub-libp2p", "External API <= Closed({}, {:?})", peer_id, set_id);
let event =
NotificationsOut::CustomProtocolClosed { peer_id: peer_id.clone(), set_id };
NotificationsOut::CustomProtocolClosed { peer_id: *peer_id, set_id };
self.events.push_back(NetworkBehaviourAction::GenerateEvent(event));
}
@@ -491,7 +478,7 @@ impl Notifications {
{
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Close({:?})", peer_id, *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: peer_id.clone(),
peer_id: *peer_id,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Close { protocol_index: set_id.into() },
});
@@ -503,7 +490,7 @@ impl Notifications {
{
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Close({:?})", peer_id, *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: peer_id.clone(),
peer_id: *peer_id,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Close { protocol_index: set_id.into() },
});
@@ -531,8 +518,10 @@ impl Notifications {
{
inc
} else {
error!(target: "sub-libp2p", "State mismatch in libp2p: no entry in \
incoming for incoming peer");
error!(
target: "sub-libp2p",
"State mismatch in libp2p: no entry in incoming for incoming peer"
);
return
};
@@ -544,7 +533,7 @@ impl Notifications {
{
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Close({:?})", peer_id, *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: peer_id.clone(),
peer_id: *peer_id,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Close { protocol_index: set_id.into() },
});
@@ -605,12 +594,13 @@ impl Notifications {
set_id: sc_peerset::SetId,
message: impl Into<Vec<u8>>,
) {
let notifs_sink = match self.peers.get(&(target.clone(), set_id)).and_then(|p| p.get_open())
{
let notifs_sink = match self.peers.get(&(*target, set_id)).and_then(|p| p.get_open()) {
None => {
trace!(target: "sub-libp2p",
trace!(
target: "sub-libp2p",
"Tried to sent notification to {:?} without an open channel.",
target);
target,
);
return
},
Some(sink) => sink,
@@ -638,12 +628,16 @@ impl Notifications {
/// Function that is called when the peerset wants us to connect to a peer.
fn peerset_report_connect(&mut self, peer_id: PeerId, set_id: sc_peerset::SetId) {
// If `PeerId` is unknown to us, insert an entry, start dialing, and return early.
let mut occ_entry = match self.peers.entry((peer_id.clone(), set_id)) {
let mut occ_entry = match self.peers.entry((peer_id, set_id)) {
Entry::Occupied(entry) => entry,
Entry::Vacant(entry) => {
// If there's no entry in `self.peers`, start dialing.
trace!(target: "sub-libp2p", "PSM => Connect({}, {:?}): Starting to connect",
entry.key().0, set_id);
trace!(
target: "sub-libp2p",
"PSM => Connect({}, {:?}): Starting to connect",
entry.key().0,
set_id,
);
trace!(target: "sub-libp2p", "Libp2p <= Dial {}", entry.key().0);
// The `DialPeerCondition` ensures that dial attempts are de-duplicated
self.events.push_back(NetworkBehaviourAction::DialPeer {
@@ -661,16 +655,25 @@ impl Notifications {
// Backoff (not expired) => PendingRequest
PeerState::Backoff { ref timer, ref timer_deadline } if *timer_deadline > now => {
let peer_id = occ_entry.key().0.clone();
trace!(target: "sub-libp2p", "PSM => Connect({}, {:?}): Will start to connect at \
until {:?}", peer_id, set_id, timer_deadline);
trace!(
target: "sub-libp2p",
"PSM => Connect({}, {:?}): Will start to connect at until {:?}",
peer_id,
set_id,
timer_deadline,
);
*occ_entry.into_mut() =
PeerState::PendingRequest { timer: *timer, timer_deadline: *timer_deadline };
},
// Backoff (expired) => Requested
PeerState::Backoff { .. } => {
trace!(target: "sub-libp2p", "PSM => Connect({}, {:?}): Starting to connect",
occ_entry.key().0, set_id);
trace!(
target: "sub-libp2p",
"PSM => Connect({}, {:?}): Starting to connect",
occ_entry.key().0,
set_id,
);
trace!(target: "sub-libp2p", "Libp2p <= Dial {:?}", occ_entry.key());
// The `DialPeerCondition` ensures that dial attempts are de-duplicated
self.events.push_back(NetworkBehaviourAction::DialPeer {
@@ -685,8 +688,13 @@ impl Notifications {
if *backoff > now =>
{
let peer_id = occ_entry.key().0.clone();
trace!(target: "sub-libp2p", "PSM => Connect({}, {:?}): But peer is backed-off until {:?}",
peer_id, set_id, backoff);
trace!(
target: "sub-libp2p",
"PSM => Connect({}, {:?}): But peer is backed-off until {:?}",
peer_id,
set_id,
backoff,
);
let delay_id = self.next_delay_id;
self.next_delay_id.0 += 1;
@@ -720,7 +728,7 @@ impl Notifications {
occ_entry.key().0, set_id);
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Open({:?})", peer_id, *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: peer_id.clone(),
peer_id,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Open { protocol_index: set_id.into() },
});
@@ -778,8 +786,10 @@ impl Notifications {
{
inc.alive = false;
} else {
error!(target: "sub-libp2p", "State mismatch in libp2p: no entry in \
incoming for incoming peer")
error!(
target: "sub-libp2p",
"State mismatch in libp2p: no entry in incoming for incoming peer",
)
}
debug_assert!(connections
@@ -953,23 +963,19 @@ impl Notifications {
if !incoming.alive {
trace!(target: "sub-libp2p", "PSM => Accept({:?}, {}, {:?}): Obsolete incoming",
index, incoming.peer_id, incoming.set_id);
match self.peers.get_mut(&(incoming.peer_id.clone(), incoming.set_id)) {
match self.peers.get_mut(&(incoming.peer_id, incoming.set_id)) {
Some(PeerState::DisabledPendingEnable { .. }) | Some(PeerState::Enabled { .. }) => {
},
_ => {
trace!(target: "sub-libp2p", "PSM <= Dropped({}, {:?})",
incoming.peer_id, incoming.set_id);
self.peerset.dropped(
incoming.set_id,
incoming.peer_id,
sc_peerset::DropReason::Unknown,
);
self.peerset.dropped(incoming.set_id, incoming.peer_id, DropReason::Unknown);
},
}
return
}
let state = match self.peers.get_mut(&(incoming.peer_id.clone(), incoming.set_id)) {
let state = match self.peers.get_mut(&(incoming.peer_id, incoming.set_id)) {
Some(s) => s,
None => {
debug_assert!(false);
@@ -993,7 +999,7 @@ impl Notifications {
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Open({:?})",
incoming.peer_id, *connec_id, incoming.set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: incoming.peer_id.clone(),
peer_id: incoming.peer_id,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Open { protocol_index: incoming.set_id.into() },
});
@@ -1029,7 +1035,7 @@ impl Notifications {
return
}
let state = match self.peers.get_mut(&(incoming.peer_id.clone(), incoming.set_id)) {
let state = match self.peers.get_mut(&(incoming.peer_id, incoming.set_id)) {
Some(s) => s,
None => {
debug_assert!(false);
@@ -1053,7 +1059,7 @@ impl Notifications {
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Close({:?})",
incoming.peer_id, connec_id, incoming.set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: incoming.peer_id.clone(),
peer_id: incoming.peer_id,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Close { protocol_index: incoming.set_id.into() },
});
@@ -1090,7 +1096,7 @@ impl NetworkBehaviour for Notifications {
endpoint: &ConnectedPoint,
) {
for set_id in (0..self.notif_protocols.len()).map(sc_peerset::SetId::from) {
match self.peers.entry((peer_id.clone(), set_id)).or_insert(PeerState::Poisoned) {
match self.peers.entry((*peer_id, set_id)).or_insert(PeerState::Poisoned) {
// Requested | PendingRequest => Enabled
st @ &mut PeerState::Requested | st @ &mut PeerState::PendingRequest { .. } => {
trace!(target: "sub-libp2p",
@@ -1099,7 +1105,7 @@ impl NetworkBehaviour for Notifications {
);
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Open({:?})", peer_id, *conn, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: peer_id.clone(),
peer_id: *peer_id,
handler: NotifyHandler::One(*conn),
event: NotifsHandlerIn::Open { protocol_index: set_id.into() },
});
@@ -1148,9 +1154,7 @@ impl NetworkBehaviour for Notifications {
_endpoint: &ConnectedPoint,
) {
for set_id in (0..self.notif_protocols.len()).map(sc_peerset::SetId::from) {
let mut entry = if let Entry::Occupied(entry) =
self.peers.entry((peer_id.clone(), set_id))
{
let mut entry = if let Entry::Occupied(entry) = self.peers.entry((*peer_id, set_id)) {
entry
} else {
error!(target: "sub-libp2p", "inject_connection_closed: State mismatch in the custom protos handler");
@@ -1179,7 +1183,7 @@ impl NetworkBehaviour for Notifications {
let delay_id = self.next_delay_id;
self.next_delay_id.0 += 1;
let delay = futures_timer::Delay::new(until - now);
let peer_id = peer_id.clone();
let peer_id = *peer_id;
self.delays.push(
async move {
delay.await;
@@ -1219,11 +1223,7 @@ impl NetworkBehaviour for Notifications {
if connections.is_empty() {
trace!(target: "sub-libp2p", "PSM <= Dropped({}, {:?})", peer_id, set_id);
self.peerset.dropped(
set_id,
peer_id.clone(),
sc_peerset::DropReason::Unknown,
);
self.peerset.dropped(set_id, *peer_id, DropReason::Unknown);
*entry.get_mut() = PeerState::Backoff { timer, timer_deadline };
} else {
*entry.get_mut() =
@@ -1246,9 +1246,9 @@ impl NetworkBehaviour for Notifications {
if let Some(pos) = connections.iter().position(|(c, _)| *c == *conn) {
connections.remove(pos);
} else {
debug_assert!(false);
error!(target: "sub-libp2p",
"inject_connection_closed: State mismatch in the custom protos handler");
debug_assert!(false);
}
let no_desired_left = !connections
@@ -1280,7 +1280,7 @@ impl NetworkBehaviour for Notifications {
let delay_id = self.next_delay_id;
self.next_delay_id.0 += 1;
let delay = futures_timer::Delay::new(until - now);
let peer_id = peer_id.clone();
let peer_id = *peer_id;
self.delays.push(
async move {
delay.await;
@@ -1322,15 +1322,11 @@ impl NetworkBehaviour for Notifications {
if let Some(pos) = connections.iter().position(|(c, _)| *c == *conn) {
let (_, state) = connections.remove(pos);
if let ConnectionState::Open(_) = state {
if let Some((replacement_pos, replacement_sink)) = connections
.iter()
.enumerate()
.filter_map(|(num, (_, s))| match s {
if let Some((replacement_pos, replacement_sink)) =
connections.iter().enumerate().find_map(|(num, (_, s))| match s {
ConnectionState::Open(s) => Some((num, s.clone())),
_ => None,
})
.next()
{
}) {
if pos <= replacement_pos {
trace!(
target: "sub-libp2p",
@@ -1338,7 +1334,7 @@ impl NetworkBehaviour for Notifications {
peer_id, set_id
);
let event = NotificationsOut::CustomProtocolReplaced {
peer_id: peer_id.clone(),
peer_id: *peer_id,
set_id,
notifications_sink: replacement_sink,
};
@@ -1351,7 +1347,7 @@ impl NetworkBehaviour for Notifications {
peer_id, set_id
);
let event = NotificationsOut::CustomProtocolClosed {
peer_id: peer_id.clone(),
peer_id: *peer_id,
set_id,
};
self.events.push_back(NetworkBehaviourAction::GenerateEvent(event));
@@ -1365,17 +1361,13 @@ impl NetworkBehaviour for Notifications {
if connections.is_empty() {
trace!(target: "sub-libp2p", "PSM <= Dropped({}, {:?})", peer_id, set_id);
self.peerset.dropped(
set_id,
peer_id.clone(),
sc_peerset::DropReason::Unknown,
);
self.peerset.dropped(set_id, *peer_id, DropReason::Unknown);
let ban_dur = Uniform::new(5, 10).sample(&mut rand::thread_rng());
let delay_id = self.next_delay_id;
self.next_delay_id.0 += 1;
let delay = futures_timer::Delay::new(Duration::from_secs(ban_dur));
let peer_id = peer_id.clone();
let peer_id = *peer_id;
self.delays.push(
async move {
delay.await;
@@ -1392,11 +1384,7 @@ impl NetworkBehaviour for Notifications {
matches!(s, ConnectionState::Opening | ConnectionState::Open(_))
}) {
trace!(target: "sub-libp2p", "PSM <= Dropped({}, {:?})", peer_id, set_id);
self.peerset.dropped(
set_id,
peer_id.clone(),
sc_peerset::DropReason::Unknown,
);
self.peerset.dropped(set_id, *peer_id, DropReason::Unknown);
*entry.get_mut() = PeerState::Disabled { connections, backoff_until: None };
} else {
@@ -1446,11 +1434,7 @@ impl NetworkBehaviour for Notifications {
// "Basic" situation: we failed to reach a peer that the peerset requested.
st @ PeerState::Requested | st @ PeerState::PendingRequest { .. } => {
trace!(target: "sub-libp2p", "PSM <= Dropped({}, {:?})", peer_id, set_id);
self.peerset.dropped(
set_id,
peer_id.clone(),
sc_peerset::DropReason::Unknown,
);
self.peerset.dropped(set_id, *peer_id, DropReason::Unknown);
let now = Instant::now();
let ban_duration = match st {
@@ -1463,7 +1447,7 @@ impl NetworkBehaviour for Notifications {
let delay_id = self.next_delay_id;
self.next_delay_id.0 += 1;
let delay = futures_timer::Delay::new(ban_duration);
let peer_id = peer_id.clone();
let peer_id = *peer_id;
self.delays.push(
async move {
delay.await;
@@ -1505,14 +1489,16 @@ impl NetworkBehaviour for Notifications {
"Handler({:?}, {:?}]) => OpenDesiredByRemote({:?})",
source, connection, set_id);
let mut entry =
if let Entry::Occupied(entry) = self.peers.entry((source.clone(), set_id)) {
entry
} else {
error!(target: "sub-libp2p", "OpenDesiredByRemote: State mismatch in the custom protos handler");
debug_assert!(false);
return
};
let mut entry = if let Entry::Occupied(entry) = self.peers.entry((source, set_id)) {
entry
} else {
error!(
target: "sub-libp2p",
"OpenDesiredByRemote: State mismatch in the custom protos handler"
);
debug_assert!(false);
return
};
match mem::replace(entry.get_mut(), PeerState::Poisoned) {
// Incoming => Incoming
@@ -1601,9 +1587,9 @@ impl NetworkBehaviour for Notifications {
trace!(target: "sub-libp2p", "PSM <= Incoming({}, {:?}).",
source, incoming_id);
self.peerset.incoming(set_id, source.clone(), incoming_id);
self.peerset.incoming(set_id, source, incoming_id);
self.incoming.push(IncomingPeer {
peer_id: source.clone(),
peer_id: source,
set_id,
alive: true,
incoming_id,
@@ -1641,7 +1627,7 @@ impl NetworkBehaviour for Notifications {
trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Open({:?})",
source, connection, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: source.clone(),
peer_id: source,
handler: NotifyHandler::One(connection),
event: NotifsHandlerIn::Open { protocol_index: set_id.into() },
});
@@ -1689,14 +1675,13 @@ impl NetworkBehaviour for Notifications {
"Handler({}, {:?}) => CloseDesired({:?})",
source, connection, set_id);
let mut entry =
if let Entry::Occupied(entry) = self.peers.entry((source.clone(), set_id)) {
entry
} else {
error!(target: "sub-libp2p", "CloseDesired: State mismatch in the custom protos handler");
debug_assert!(false);
return
};
let mut entry = if let Entry::Occupied(entry) = self.peers.entry((source, set_id)) {
entry
} else {
error!(target: "sub-libp2p", "CloseDesired: State mismatch in the custom protos handler");
debug_assert!(false);
return
};
match mem::replace(entry.get_mut(), PeerState::Poisoned) {
// Enabled => Enabled | Disabled
@@ -1727,20 +1712,16 @@ impl NetworkBehaviour for Notifications {
trace!(target: "sub-libp2p", "Handler({}, {:?}) <= Close({:?})", source, connection, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: source.clone(),
peer_id: source,
handler: NotifyHandler::One(connection),
event: NotifsHandlerIn::Close { protocol_index: set_id.into() },
});
if let Some((replacement_pos, replacement_sink)) = connections
.iter()
.enumerate()
.filter_map(|(num, (_, s))| match s {
if let Some((replacement_pos, replacement_sink)) =
connections.iter().enumerate().find_map(|(num, (_, s))| match s {
ConnectionState::Open(s) => Some((num, s.clone())),
_ => None,
})
.next()
{
}) {
if pos <= replacement_pos {
trace!(target: "sub-libp2p", "External API <= Sink replaced({:?})", source);
let event = NotificationsOut::CustomProtocolReplaced {
@@ -1759,11 +1740,7 @@ impl NetworkBehaviour for Notifications {
.any(|(_, s)| matches!(s, ConnectionState::Opening))
{
trace!(target: "sub-libp2p", "PSM <= Dropped({}, {:?})", source, set_id);
self.peerset.dropped(
set_id,
source.clone(),
sc_peerset::DropReason::Refused,
);
self.peerset.dropped(set_id, source, DropReason::Refused);
*entry.into_mut() =
PeerState::Disabled { connections, backoff_until: None };
} else {
@@ -1838,7 +1815,7 @@ impl NetworkBehaviour for Notifications {
"Handler({}, {:?}) => OpenResultOk({:?})",
source, connection, set_id);
match self.peers.get_mut(&(source.clone(), set_id)) {
match self.peers.get_mut(&(source, set_id)) {
Some(PeerState::Enabled { connections, .. }) => {
debug_assert!(connections.iter().any(|(_, s)| matches!(
s,
@@ -1868,9 +1845,9 @@ impl NetworkBehaviour for Notifications {
}) {
*connec_state = ConnectionState::Closing;
} else {
debug_assert!(false);
error!(target: "sub-libp2p",
"OpenResultOk State mismatch in the custom protos handler");
debug_assert!(false);
}
},
@@ -1904,15 +1881,13 @@ impl NetworkBehaviour for Notifications {
"Handler({:?}, {:?}) => OpenResultErr({:?})",
source, connection, set_id);
let mut entry =
if let Entry::Occupied(entry) = self.peers.entry((source.clone(), set_id)) {
entry
} else {
error!(target: "sub-libp2p", "OpenResultErr: State mismatch in the custom protos handler");
debug_assert!(false);
debug_assert!(false);
return
};
let mut entry = if let Entry::Occupied(entry) = self.peers.entry((source, set_id)) {
entry
} else {
error!(target: "sub-libp2p", "OpenResultErr: State mismatch in the custom protos handler");
debug_assert!(false);
return
};
match mem::replace(entry.get_mut(), PeerState::Poisoned) {
PeerState::Enabled { mut connections } => {
@@ -1940,11 +1915,7 @@ impl NetworkBehaviour for Notifications {
matches!(s, ConnectionState::Opening | ConnectionState::Open(_))
}) {
trace!(target: "sub-libp2p", "PSM <= Dropped({:?})", source);
self.peerset.dropped(
set_id,
source.clone(),
sc_peerset::DropReason::Refused,
);
self.peerset.dropped(set_id, source, DropReason::Refused);
let ban_dur = Uniform::new(5, 10).sample(&mut rand::thread_rng());
*entry.into_mut() = PeerState::Disabled {
@@ -2002,8 +1973,12 @@ impl NetworkBehaviour for Notifications {
set_id,
message.len()
);
trace!(target: "sub-libp2p", "External API <= Message({}, {:?})",
source, set_id);
trace!(
target: "sub-libp2p",
"External API <= Message({}, {:?})",
source,
set_id,
);
let event = NotificationsOut::Notification { peer_id: source, set_id, message };
self.events.push_back(NetworkBehaviourAction::GenerateEvent(event));
@@ -2057,7 +2032,7 @@ impl NetworkBehaviour for Notifications {
while let Poll::Ready(Some((delay_id, peer_id, set_id))) =
Pin::new(&mut self.delays).poll_next(cx)
{
let peer_state = match self.peers.get_mut(&(peer_id.clone(), set_id)) {
let peer_state = match self.peers.get_mut(&(peer_id, set_id)) {
Some(s) => s,
// We intentionally never remove elements from `delays`, and it may
// thus contain peers which are now gone. This is a normal situation.
@@ -2090,7 +2065,7 @@ impl NetworkBehaviour for Notifications {
trace!(target: "sub-libp2p", "Handler({}, {:?}) <= Open({:?}) (ban expired)",
peer_id, *connec_id, set_id);
self.events.push_back(NetworkBehaviourAction::NotifyHandler {
peer_id: peer_id.clone(),
peer_id,
handler: NotifyHandler::One(*connec_id),
event: NotifsHandlerIn::Open { protocol_index: set_id.into() },
});
@@ -256,7 +256,7 @@ impl IntoProtocolsHandler for NotifsHandlerProto {
Protocol { config, in_upgrade, state: State::Closed { pending_opening: false } }
})
.collect(),
peer_id: peer_id.clone(),
peer_id: *peer_id,
endpoint: connected_point.clone(),
when_connection_open: Instant::now(),
events_queue: VecDeque::with_capacity(16),
@@ -463,7 +463,7 @@ impl NotifsHandlerProto {
/// is always the same whether we open a substream ourselves or respond to handshake from
/// the remote.
pub fn new(list: impl Into<Vec<ProtocolConfig>>) -> Self {
NotifsHandlerProto { protocols: list.into() }
Self { protocols: list.into() }
}
}
@@ -552,7 +552,7 @@ impl ProtocolsHandler for NotifsHandler {
let (sync_tx, sync_rx) = mpsc::channel(SYNC_NOTIFICATIONS_BUFFER_SIZE);
let notifications_sink = NotificationsSink {
inner: Arc::new(NotificationsSinkInner {
peer_id: self.peer_id.clone(),
peer_id: self.peer_id,
async_channel: FuturesMutex::new(async_tx),
sync_channel: Mutex::new(sync_tx),
}),
@@ -34,13 +34,13 @@ pub struct UpgradeCollec<T>(pub Vec<T>);
impl<T> From<Vec<T>> for UpgradeCollec<T> {
fn from(list: Vec<T>) -> Self {
UpgradeCollec(list)
Self(list)
}
}
impl<T> FromIterator<T> for UpgradeCollec<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
UpgradeCollec(iter.into_iter().collect())
Self(iter.into_iter().collect())
}
}
@@ -38,7 +38,7 @@ use asynchronous_codec::Framed;
use bytes::BytesMut;
use futures::prelude::*;
use libp2p::core::{upgrade, InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use log::error;
use log::{error, warn};
use std::{
borrow::Cow,
convert::{Infallible, TryFrom as _},
@@ -121,7 +121,7 @@ impl NotificationsIn {
let mut protocol_names = fallback_names;
protocol_names.insert(0, main_protocol_name.into());
NotificationsIn { protocol_names, max_notification_size }
Self { protocol_names, max_notification_size }
}
}
@@ -347,7 +347,7 @@ impl NotificationsOut {
let mut protocol_names = fallback_names;
protocol_names.insert(0, main_protocol_name.into());
NotificationsOut { protocol_names, initial_message, max_notification_size }
Self { protocol_names, initial_message, max_notification_size }
}
}
@@ -478,12 +478,11 @@ pub enum NotificationsHandshakeError {
impl From<unsigned_varint::io::ReadError> for NotificationsHandshakeError {
fn from(err: unsigned_varint::io::ReadError) -> Self {
match err {
unsigned_varint::io::ReadError::Io(err) => NotificationsHandshakeError::Io(err),
unsigned_varint::io::ReadError::Decode(err) =>
NotificationsHandshakeError::VarintDecode(err),
unsigned_varint::io::ReadError::Io(err) => Self::Io(err),
unsigned_varint::io::ReadError::Decode(err) => Self::VarintDecode(err),
_ => {
log::warn!("Unrecognized varint decoding error");
NotificationsHandshakeError::Io(From::from(io::ErrorKind::InvalidData))
warn!("Unrecognized varint decoding error");
Self::Io(From::from(io::ErrorKind::InvalidData))
},
}
}
+66 -67
View File
@@ -148,40 +148,37 @@ enum PendingRequests {
impl PendingRequests {
fn add(&mut self, id: &PeerId) {
match self {
PendingRequests::Some(set) => {
set.insert(id.clone());
},
PendingRequests::All => {},
if let Self::Some(ref mut set) = self {
set.insert(*id);
}
}
fn take(&mut self) -> PendingRequests {
fn take(&mut self) -> Self {
std::mem::take(self)
}
fn set_all(&mut self) {
*self = PendingRequests::All;
*self = Self::All;
}
fn contains(&self, id: &PeerId) -> bool {
match self {
PendingRequests::Some(set) => set.contains(id),
PendingRequests::All => true,
Self::Some(set) => set.contains(id),
Self::All => true,
}
}
fn is_empty(&self) -> bool {
match self {
PendingRequests::Some(set) => set.is_empty(),
PendingRequests::All => false,
Self::Some(set) => set.is_empty(),
Self::All => false,
}
}
}
impl Default for PendingRequests {
fn default() -> Self {
PendingRequests::Some(HashSet::default())
Self::Some(HashSet::default())
}
}
@@ -343,10 +340,10 @@ pub enum WarpSyncPhase {
impl fmt::Display for WarpSyncPhase {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
WarpSyncPhase::AwaitingPeers => write!(f, "Waiting for peers"),
WarpSyncPhase::DownloadingWarpProofs => write!(f, "Downloading finality proofs"),
WarpSyncPhase::DownloadingState => write!(f, "Downloading state"),
WarpSyncPhase::ImportingState => write!(f, "Importing state"),
Self::AwaitingPeers => write!(f, "Waiting for peers"),
Self::DownloadingWarpProofs => write!(f, "Downloading finality proofs"),
Self::DownloadingState => write!(f, "Downloading state"),
Self::ImportingState => write!(f, "Importing state"),
}
}
}
@@ -538,7 +535,7 @@ impl<B: BlockT> ChainSync<B> {
max_parallel_downloads: u32,
warp_sync_provider: Option<Arc<dyn WarpSyncProvider<B>>>,
) -> Result<Self, ClientError> {
let mut sync = ChainSync {
let mut sync = Self {
client,
peers: HashMap::new(),
blocks: BlockCollection::new(),
@@ -732,7 +729,7 @@ impl<B: BlockT> ChainSync<B> {
self.pending_requests.add(&who);
self.peers.insert(
who.clone(),
who,
PeerSync {
peer_id: who,
common_number: Zero::zero(),
@@ -754,9 +751,9 @@ impl<B: BlockT> ChainSync<B> {
best_number,
);
self.peers.insert(
who.clone(),
who,
PeerSync {
peer_id: who.clone(),
peer_id: who,
common_number: std::cmp::min(self.best_queued_number, best_number),
best_hash,
best_number,
@@ -835,7 +832,7 @@ impl<B: BlockT> ChainSync<B> {
}
self.fork_targets
.entry(hash.clone())
.entry(*hash)
.or_insert_with(|| ForkTarget { number, peers: Default::default(), parent_hash: None })
.peers
.extend(peers);
@@ -972,7 +969,7 @@ impl<B: BlockT> ChainSync<B> {
trace!(target: "sync", "New StateRequest for {}", id);
peer.state = PeerSyncState::DownloadingState;
let request = sync.next_request();
return Some((id.clone(), request))
return Some((*id, request))
}
}
}
@@ -987,7 +984,7 @@ impl<B: BlockT> ChainSync<B> {
if peer.state.is_available() && peer.best_number >= target {
trace!(target: "sync", "New StateRequest for {}", id);
peer.state = PeerSyncState::DownloadingState;
return Some((id.clone(), request))
return Some((*id, request))
}
}
}
@@ -1019,7 +1016,7 @@ impl<B: BlockT> ChainSync<B> {
if peer.state.is_available() && peer.best_number >= median {
trace!(target: "sync", "New WarpProofRequest for {}", id);
peer.state = PeerSyncState::DownloadingWarpProof;
return Some((id.clone(), request))
return Some((*id, request))
}
}
}
@@ -1068,7 +1065,7 @@ impl<B: BlockT> ChainSync<B> {
peer.state = PeerSyncState::Available;
if blocks.is_empty() {
debug!(target: "sync", "Empty block response from {}", who);
return Err(BadPeer(who.clone(), rep::NO_BLOCK))
return Err(BadPeer(*who, rep::NO_BLOCK))
}
validate_blocks::<B>(&blocks, who, Some(request))?;
blocks
@@ -1083,7 +1080,7 @@ impl<B: BlockT> ChainSync<B> {
body: b.body,
indexed_body: None,
justifications,
origin: Some(who.clone()),
origin: Some(*who),
allow_missing_state: true,
import_existing: self.import_existing,
skip_execution: self.skip_execution(),
@@ -1110,7 +1107,7 @@ impl<B: BlockT> ChainSync<B> {
"Invalid response when searching for ancestor from {}",
who,
);
return Err(BadPeer(who.clone(), rep::UNKNOWN_ANCESTOR))
return Err(BadPeer(*who, rep::UNKNOWN_ANCESTOR))
},
(_, Err(e)) => {
info!(
@@ -1118,7 +1115,7 @@ impl<B: BlockT> ChainSync<B> {
"❌ Error answering legitimate blockchain query: {:?}",
e,
);
return Err(BadPeer(who.clone(), rep::BLOCKCHAIN_READ_ERROR))
return Err(BadPeer(*who, rep::BLOCKCHAIN_READ_ERROR))
},
};
if matching_hash.is_some() {
@@ -1135,7 +1132,7 @@ impl<B: BlockT> ChainSync<B> {
}
if matching_hash.is_none() && current.is_zero() {
trace!(target:"sync", "Ancestry search: genesis mismatch for peer {}", who);
return Err(BadPeer(who.clone(), rep::GENESIS_MISMATCH))
return Err(BadPeer(*who, rep::GENESIS_MISMATCH))
}
if let Some((next_state, next_num)) =
handle_ancestor_search_state(state, *current, matching_hash.is_some())
@@ -1145,10 +1142,7 @@ impl<B: BlockT> ChainSync<B> {
start: *start,
state: next_state,
};
return Ok(OnBlockData::Request(
who.clone(),
ancestry_request::<B>(next_num),
))
return Ok(OnBlockData::Request(*who, ancestry_request::<B>(next_num)))
} else {
// Ancestry search is complete. Check if peer is on a stale fork unknown
// to us and add it to sync targets if necessary.
@@ -1172,14 +1166,14 @@ impl<B: BlockT> ChainSync<B> {
who,
);
self.fork_targets
.entry(peer.best_hash.clone())
.entry(peer.best_hash)
.or_insert_with(|| ForkTarget {
number: peer.best_number,
parent_hash: None,
peers: Default::default(),
})
.peers
.insert(who.clone());
.insert(*who);
}
peer.state = PeerSyncState::Available;
Vec::new()
@@ -1204,7 +1198,7 @@ impl<B: BlockT> ChainSync<B> {
body: b.body,
indexed_body: None,
justifications,
origin: Some(who.clone()),
origin: Some(*who),
allow_missing_state: true,
import_existing: false,
skip_execution: true,
@@ -1215,7 +1209,7 @@ impl<B: BlockT> ChainSync<B> {
}
} else {
// We don't know of this peer, so we also did not request anything from it.
return Err(BadPeer(who.clone(), rep::NOT_REQUESTED))
return Err(BadPeer(*who, rep::NOT_REQUESTED))
};
Ok(self.validate_and_queue_blocks(new_blocks))
@@ -1249,7 +1243,7 @@ impl<B: BlockT> ChainSync<B> {
sync.import_state(response)
} else {
debug!(target: "sync", "Ignored obsolete state response from {}", who);
return Err(BadPeer(who.clone(), rep::NOT_REQUESTED))
return Err(BadPeer(*who, rep::NOT_REQUESTED))
};
match import_result {
@@ -1274,7 +1268,7 @@ impl<B: BlockT> ChainSync<B> {
Ok(OnStateData::Request(who.clone(), request)),
state::ImportResult::BadResponse => {
debug!(target: "sync", "Bad state data received from {}", who);
Err(BadPeer(who.clone(), rep::BAD_BLOCK))
Err(BadPeer(*who, rep::BAD_BLOCK))
},
}
}
@@ -1297,17 +1291,17 @@ impl<B: BlockT> ChainSync<B> {
sync.import_warp_proof(response)
} else {
debug!(target: "sync", "Ignored obsolete warp sync response from {}", who);
return Err(BadPeer(who.clone(), rep::NOT_REQUESTED))
return Err(BadPeer(*who, rep::NOT_REQUESTED))
};
match import_result {
warp::WarpProofImportResult::StateRequest(request) =>
Ok(OnWarpSyncData::StateRequest(who.clone(), request)),
Ok(OnWarpSyncData::StateRequest(*who, request)),
warp::WarpProofImportResult::WarpProofRequest(request) =>
Ok(OnWarpSyncData::WarpProofRequest(who.clone(), request)),
Ok(OnWarpSyncData::WarpProofRequest(*who, request)),
warp::WarpProofImportResult::BadResponse => {
debug!(target: "sync", "Bad proof data received from {}", who);
Err(BadPeer(who.clone(), rep::BAD_BLOCK))
Err(BadPeer(*who, rep::BAD_BLOCK))
},
}
}
@@ -1319,7 +1313,11 @@ impl<B: BlockT> ChainSync<B> {
let orig_len = new_blocks.len();
new_blocks.retain(|b| !self.queue_blocks.contains(&b.hash));
if new_blocks.len() != orig_len {
debug!(target: "sync", "Ignoring {} blocks that are already queued", orig_len - new_blocks.len());
debug!(
target: "sync",
"Ignoring {} blocks that are already queued",
orig_len - new_blocks.len(),
);
}
let origin = if self.status().state != SyncState::Downloading {
@@ -1372,7 +1370,10 @@ impl<B: BlockT> ChainSync<B> {
if hash != block.hash {
warn!(
target: "sync",
"💔 Invalid block justification provided by {}: requested: {:?} got: {:?}", who, hash, block.hash
"💔 Invalid block justification provided by {}: requested: {:?} got: {:?}",
who,
hash,
block.hash,
);
return Err(BadPeer(who, rep::BAD_JUSTIFICATION))
}
@@ -1381,7 +1382,8 @@ impl<B: BlockT> ChainSync<B> {
} 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).
trace!(target: "sync",
trace!(
target: "sync",
"Peer {:?} provided empty response for justification request {:?}",
who,
hash,
@@ -1441,7 +1443,7 @@ impl<B: BlockT> ChainSync<B> {
target: "sync",
"Block imported clears all pending justification requests {}: {:?}",
number,
hash
hash,
);
self.clear_justification_requests();
}
@@ -1459,7 +1461,7 @@ impl<B: BlockT> ChainSync<B> {
if aux.bad_justification {
if let Some(ref peer) = who {
warn!("💔 Sent block with bad justification to import");
output.push(Err(BadPeer(peer.clone(), rep::BAD_JUSTIFICATION)));
output.push(Err(BadPeer(*peer, rep::BAD_JUSTIFICATION)));
}
}
@@ -1934,14 +1936,14 @@ impl<B: BlockT> ChainSync<B> {
announce.summary(),
);
self.fork_targets
.entry(hash.clone())
.entry(hash)
.or_insert_with(|| ForkTarget {
number,
parent_hash: Some(*announce.header.parent_hash()),
peers: Default::default(),
})
.peers
.insert(who.clone());
.insert(who);
}
PollBlockAnnounceValidation::Nothing { is_best, who, announce }
@@ -2008,14 +2010,14 @@ impl<B: BlockT> ChainSync<B> {
fn reset_sync_start_point(&mut self) -> Result<(), ClientError> {
let info = self.client.info();
if matches!(self.mode, SyncMode::LightState { .. }) && info.finalized_state.is_some() {
log::warn!(
warn!(
target: "sync",
"Can't use fast sync mode with a partially synced database. Reverting to full sync mode."
);
self.mode = SyncMode::Full;
}
if matches!(self.mode, SyncMode::Warp) && info.finalized_state.is_some() {
log::warn!(
warn!(
target: "sync",
"Can't use warp sync mode with a partially synced database. Reverting to full sync mode."
);
@@ -2031,17 +2033,17 @@ impl<B: BlockT> ChainSync<B> {
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 {
log::debug!(target: "sync", "Starting from finalized state #{}", number);
debug!(target: "sync", "Starting from finalized state #{}", number);
self.best_queued_hash = hash;
self.best_queued_number = number;
} else {
log::debug!(target: "sync", "Restarting from genesis");
debug!(target: "sync", "Restarting from genesis");
self.best_queued_hash = Default::default();
self.best_queued_number = Zero::zero();
}
}
}
log::trace!(target: "sync", "Restarted sync at #{} ({:?})", self.best_queued_number, self.best_queued_hash);
trace!(target: "sync", "Restarted sync at #{} ({:?})", self.best_queued_number, self.best_queued_hash);
Ok(())
}
@@ -2219,7 +2221,7 @@ fn peer_block_request<B: BlockT>(
);
}
let range = blocks.needed_blocks(
id.clone(),
*id,
MAX_BLOCKS_TO_REQUEST,
peer.best_number,
peer.common_number,
@@ -2335,7 +2337,7 @@ fn validate_blocks<Block: BlockT>(
blocks.len(),
);
return Err(BadPeer(who.clone(), rep::NOT_REQUESTED))
return Err(BadPeer(*who, rep::NOT_REQUESTED))
}
let block_header = if request.direction == message::Direction::Descending {
@@ -2358,7 +2360,7 @@ fn validate_blocks<Block: BlockT>(
block_header,
);
return Err(BadPeer(who.clone(), rep::NOT_REQUESTED))
return Err(BadPeer(*who, rep::NOT_REQUESTED))
}
if request.fields.contains(message::BlockAttributes::HEADER) &&
@@ -2370,7 +2372,7 @@ fn validate_blocks<Block: BlockT>(
who,
);
return Err(BadPeer(who.clone(), rep::BAD_RESPONSE))
return Err(BadPeer(*who, rep::BAD_RESPONSE))
}
if request.fields.contains(message::BlockAttributes::BODY) &&
@@ -2382,7 +2384,7 @@ fn validate_blocks<Block: BlockT>(
who,
);
return Err(BadPeer(who.clone(), rep::BAD_RESPONSE))
return Err(BadPeer(*who, rep::BAD_RESPONSE))
}
}
@@ -2397,7 +2399,7 @@ fn validate_blocks<Block: BlockT>(
b.hash,
hash,
);
return Err(BadPeer(who.clone(), rep::BAD_BLOCK))
return Err(BadPeer(*who, rep::BAD_BLOCK))
}
}
if let (Some(header), Some(body)) = (&b.header, &b.body) {
@@ -2413,7 +2415,7 @@ fn validate_blocks<Block: BlockT>(
expected,
got,
);
return Err(BadPeer(who.clone(), rep::BAD_BLOCK))
return Err(BadPeer(*who, rep::BAD_BLOCK))
}
}
}
@@ -2457,7 +2459,7 @@ mod test {
};
// add a new peer with the same best block
sync.new_peer(peer_id.clone(), a1_hash, a1_number).unwrap();
sync.new_peer(peer_id, a1_hash, a1_number).unwrap();
// and request a justification for the block
sync.request_justification(&a1_hash, a1_number);
@@ -2478,10 +2480,7 @@ mod test {
// if the peer replies with an empty response (i.e. it doesn't know the block),
// the active request should be cleared.
assert_eq!(
sync.on_block_justification(
peer_id.clone(),
BlockResponse::<Block> { id: 0, blocks: vec![] }
),
sync.on_block_justification(peer_id, BlockResponse::<Block> { id: 0, blocks: vec![] }),
Ok(OnBlockJustification::Nothing),
);
@@ -44,8 +44,8 @@ enum BlockRangeState<B: BlockT> {
impl<B: BlockT> BlockRangeState<B> {
pub fn len(&self) -> NumberFor<B> {
match *self {
BlockRangeState::Downloading { len, .. } => len,
BlockRangeState::Complete(ref blocks) => (blocks.len() as u32).into(),
Self::Downloading { len, .. } => len,
Self::Complete(ref blocks) => (blocks.len() as u32).into(),
}
}
}
@@ -61,7 +61,7 @@ pub struct BlockCollection<B: BlockT> {
impl<B: BlockT> BlockCollection<B> {
/// Create a new instance.
pub fn new() -> Self {
BlockCollection { blocks: BTreeMap::new(), peer_requests: HashMap::new() }
Self { blocks: BTreeMap::new(), peer_requests: HashMap::new() }
}
/// Clear everything.
@@ -90,10 +90,7 @@ impl<B: BlockT> BlockCollection<B> {
self.blocks.insert(
start,
BlockRangeState::Complete(
blocks
.into_iter()
.map(|b| BlockData { origin: Some(who.clone()), block: b })
.collect(),
blocks.into_iter().map(|b| BlockData { origin: Some(who), block: b }).collect(),
),
);
}
@@ -67,7 +67,7 @@ pub(crate) struct Metrics {
impl<B: BlockT> ExtraRequests<B> {
pub(crate) fn new(request_type_name: &'static str) -> Self {
ExtraRequests {
Self {
tree: ForkTree::new(),
best_seen_finalized_number: Zero::zero(),
pending_requests: VecDeque::new(),
@@ -132,27 +132,25 @@ impl<B: BlockT> ExtraRequests<B> {
// messages to chain sync.
if let Some(request) = self.active_requests.remove(&who) {
if let Some(r) = resp {
trace!(target: "sync", "Queuing import of {} from {:?} for {:?}",
self.request_type_name,
who,
request,
trace!(target: "sync",
"Queuing import of {} from {:?} for {:?}",
self.request_type_name, who, request,
);
self.importing_requests.insert(request);
return Some((who, request.0, request.1, r))
} else {
trace!(target: "sync", "Empty {} response from {:?} for {:?}",
self.request_type_name,
who,
request,
trace!(target: "sync",
"Empty {} response from {:?} for {:?}",
self.request_type_name, who, request,
);
}
self.failed_requests.entry(request).or_default().push((who, Instant::now()));
self.pending_requests.push_front(request);
} else {
trace!(target: "sync", "No active {} request to {:?}",
self.request_type_name,
who,
trace!(target: "sync",
"No active {} request to {:?}",
self.request_type_name, who,
);
}
None
@@ -227,10 +225,9 @@ impl<B: BlockT> ExtraRequests<B> {
};
if self.tree.finalize_root(&finalized_hash).is_none() {
warn!(target: "sync", "‼️ Imported {:?} {:?} which isn't a root in the tree: {:?}",
finalized_hash,
finalized_number,
self.tree.roots().collect::<Vec<_>>()
warn!(target: "sync",
"‼️ Imported {:?} {:?} which isn't a root in the tree: {:?}",
finalized_hash, finalized_number, self.tree.roots().collect::<Vec<_>>()
);
return true
}
@@ -280,7 +277,7 @@ pub(crate) struct Matcher<'a, B: BlockT> {
impl<'a, B: BlockT> Matcher<'a, B> {
fn new(extras: &'a mut ExtraRequests<B>) -> Self {
Matcher { remaining: extras.pending_requests.len(), extras }
Self { remaining: extras.pending_requests.len(), extras }
}
/// Finds a peer to which a pending request can be sent.
@@ -335,13 +332,12 @@ impl<'a, B: BlockT> Matcher<'a, B> {
}
self.extras.active_requests.insert(peer.clone(), request);
trace!(target: "sync", "Sending {} request to {:?} for {:?}",
self.extras.request_type_name,
peer,
request,
trace!(target: "sync",
"Sending {} request to {:?} for {:?}",
self.extras.request_type_name, peer, request,
);
return Some((peer.clone(), request))
return Some((*peer, request))
}
self.extras.pending_requests.push_back(request);
@@ -594,7 +590,7 @@ mod tests {
let mut peers = HashMap::with_capacity(g.size());
for _ in 0..g.size() {
let ps = ArbitraryPeerSync::arbitrary(g).0;
peers.insert(ps.peer_id.clone(), ps);
peers.insert(ps.peer_id, ps);
}
ArbitraryPeers(peers)
}
@@ -22,6 +22,7 @@ use crate::{
schema::v1::{StateEntry, StateRequest, StateResponse},
};
use codec::{Decode, Encode};
use log::debug;
use sc_client_api::StorageProof;
use sp_runtime::traits::{Block as BlockT, Header, NumberFor};
use std::sync::Arc;
@@ -55,7 +56,7 @@ pub enum ImportResult<B: BlockT> {
impl<B: BlockT> StateSync<B> {
/// Create a new instance.
pub fn new(client: Arc<dyn Client<B>>, target: B::Header, skip_proof: bool) -> Self {
StateSync {
Self {
client,
target_block: target.hash(),
target_root: target.state_root().clone(),
@@ -71,46 +72,32 @@ impl<B: BlockT> StateSync<B> {
/// Validate and import a state reponse.
pub fn import(&mut self, response: StateResponse) -> ImportResult<B> {
if response.entries.is_empty() && response.proof.is_empty() && !response.complete {
log::debug!(
target: "sync",
"Bad state response",
);
debug!(target: "sync", "Bad state response");
return ImportResult::BadResponse
}
if !self.skip_proof && response.proof.is_empty() {
log::debug!(
target: "sync",
"Missing proof",
);
debug!(target: "sync", "Missing proof");
return ImportResult::BadResponse
}
let complete = if !self.skip_proof {
log::debug!(
target: "sync",
"Importing state from {} trie nodes",
response.proof.len(),
);
debug!(target: "sync", "Importing state from {} trie nodes", response.proof.len());
let proof_size = response.proof.len() as u64;
let proof = match StorageProof::decode(&mut response.proof.as_ref()) {
Ok(proof) => proof,
Err(e) => {
log::debug!(target: "sync", "Error decoding proof: {:?}", e);
debug!(target: "sync", "Error decoding proof: {:?}", e);
return ImportResult::BadResponse
},
};
let (values, complete) =
match self.client.verify_range_proof(self.target_root, proof, &self.last_key) {
Err(e) => {
log::debug!(
target: "sync",
"StateResponse failed proof verification: {:?}",
e,
);
debug!(target: "sync", "StateResponse failed proof verification: {:?}", e);
return ImportResult::BadResponse
},
Ok(values) => values,
};
log::debug!(target: "sync", "Imported with {} keys", values.len());
debug!(target: "sync", "Imported with {} keys", values.len());
if let Some(last) = values.last().map(|(k, _)| k) {
self.last_key = last.clone();
@@ -123,7 +110,7 @@ impl<B: BlockT> StateSync<B> {
self.imported_bytes += proof_size;
complete
} else {
log::debug!(
debug!(
target: "sync",
"Importing state from {:?} to {:?}",
response.entries.last().map(|e| sp_core::hexdisplay::HexDisplay::from(&e.key)),
@@ -142,12 +129,9 @@ impl<B: BlockT> StateSync<B> {
if complete {
self.complete = true;
ImportResult::Import(
self.target_block.clone(),
self.target_block,
self.target_header.clone(),
ImportedState {
block: self.target_block.clone(),
state: std::mem::take(&mut self.state),
},
ImportedState { block: self.target_block, state: std::mem::take(&mut self.state) },
)
} else {
ImportResult::Continue(self.next_request())
@@ -170,12 +154,12 @@ impl<B: BlockT> StateSync<B> {
/// Returns target block number.
pub fn target_block_num(&self) -> NumberFor<B> {
self.target_header.number().clone()
*self.target_header.number()
}
/// Returns target block hash.
pub fn target(&self) -> B::Hash {
self.target_block.clone()
self.target_block
}
/// Returns state sync estimated progress.
@@ -66,7 +66,7 @@ impl<B: BlockT> WarpSync<B> {
authorities: warp_sync_provider.current_authorities(),
last_hash,
};
WarpSync { client, warp_sync_provider, phase, total_proof_bytes: 0 }
Self { client, warp_sync_provider, phase, total_proof_bytes: 0 }
}
/// Validate and import a state reponse.
@@ -132,8 +132,7 @@ impl<B: BlockT> WarpSync<B> {
pub fn next_warp_poof_request(&self) -> Option<WarpProofRequest<B>> {
match &self.phase {
Phase::State(_) => None,
Phase::WarpProof { last_hash, .. } =>
Some(WarpProofRequest { begin: last_hash.clone() }),
Phase::WarpProof { last_hash, .. } => Some(WarpProofRequest { begin: *last_hash }),
}
}