style: Migrate to stable-only rustfmt configuration

- Remove nightly-only features from .rustfmt.toml and vendor/ss58-registry/rustfmt.toml
- Removed features: imports_granularity, wrap_comments, comment_width,
  reorder_impl_items, spaces_around_ranges, binop_separator,
  match_arm_blocks, trailing_semicolon, trailing_comma
- Format all 898 affected files with stable rustfmt
- Ensures long-term reliability without nightly toolchain dependency
This commit is contained in:
2025-12-22 17:12:58 +03:00
parent 65b7f5e640
commit 4c8f281051
898 changed files with 8671 additions and 6432 deletions
@@ -149,14 +149,18 @@ where
let request = schema::v1::light::Request::decode(&payload[..])?;
let response = match &request.request {
Some(schema::v1::light::request::Request::RemoteCallRequest(r)) =>
self.on_remote_call_request(&peer, r)?,
Some(schema::v1::light::request::Request::RemoteReadRequest(r)) =>
self.on_remote_read_request(&peer, r)?,
Some(schema::v1::light::request::Request::RemoteReadChildRequest(r)) =>
self.on_remote_read_child_request(&peer, r)?,
None =>
return Err(HandleRequestError::BadRequest("Remote request without request data.")),
Some(schema::v1::light::request::Request::RemoteCallRequest(r)) => {
self.on_remote_call_request(&peer, r)?
},
Some(schema::v1::light::request::Request::RemoteReadRequest(r)) => {
self.on_remote_read_request(&peer, r)?
},
Some(schema::v1::light::request::Request::RemoteReadChildRequest(r)) => {
self.on_remote_read_child_request(&peer, r)?
},
None => {
return Err(HandleRequestError::BadRequest("Remote request without request data."))
},
};
let mut data = Vec::new();
+45 -30
View File
@@ -360,10 +360,12 @@ impl From<CustomMessageOutcome> for BehaviourOut {
set_id,
notifications_sink,
} => BehaviourOut::NotificationStreamReplaced { remote, set_id, notifications_sink },
CustomMessageOutcome::NotificationStreamClosed { remote, set_id } =>
BehaviourOut::NotificationStreamClosed { remote, set_id },
CustomMessageOutcome::NotificationsReceived { remote, set_id, notification } =>
BehaviourOut::NotificationsReceived { remote, set_id, notification },
CustomMessageOutcome::NotificationStreamClosed { remote, set_id } => {
BehaviourOut::NotificationStreamClosed { remote, set_id }
},
CustomMessageOutcome::NotificationsReceived { remote, set_id, notification } => {
BehaviourOut::NotificationsReceived { remote, set_id, notification }
},
}
}
}
@@ -371,12 +373,15 @@ impl From<CustomMessageOutcome> for BehaviourOut {
impl From<request_responses::Event> for BehaviourOut {
fn from(event: request_responses::Event) -> Self {
match event {
request_responses::Event::InboundRequest { protocol, result, .. } =>
BehaviourOut::InboundRequest { protocol, result },
request_responses::Event::RequestFinished { protocol, duration, result, .. } =>
BehaviourOut::RequestFinished { protocol, duration, result },
request_responses::Event::ReputationChanges { peer, changes } =>
BehaviourOut::ReputationChanges { peer, changes },
request_responses::Event::InboundRequest { protocol, result, .. } => {
BehaviourOut::InboundRequest { protocol, result }
},
request_responses::Event::RequestFinished { protocol, duration, result, .. } => {
BehaviourOut::RequestFinished { protocol, duration, result }
},
request_responses::Event::ReputationChanges { peer, changes } => {
BehaviourOut::ReputationChanges { peer, changes }
},
}
}
}
@@ -409,25 +414,33 @@ impl From<DiscoveryOut> for BehaviourOut {
),
Some(duration),
),
DiscoveryOut::ClosestPeersNotFound(target, duration) =>
BehaviourOut::Dht(DhtEvent::ClosestPeersNotFound(target.into()), Some(duration)),
DiscoveryOut::ValueFound(results, duration) =>
BehaviourOut::Dht(DhtEvent::ValueFound(results.into()), Some(duration)),
DiscoveryOut::ValueNotFound(key, duration) =>
BehaviourOut::Dht(DhtEvent::ValueNotFound(key.into()), Some(duration)),
DiscoveryOut::ValuePut(key, duration) =>
BehaviourOut::Dht(DhtEvent::ValuePut(key.into()), Some(duration)),
DiscoveryOut::PutRecordRequest(record_key, record_value, publisher, expires) =>
DiscoveryOut::ClosestPeersNotFound(target, duration) => {
BehaviourOut::Dht(DhtEvent::ClosestPeersNotFound(target.into()), Some(duration))
},
DiscoveryOut::ValueFound(results, duration) => {
BehaviourOut::Dht(DhtEvent::ValueFound(results.into()), Some(duration))
},
DiscoveryOut::ValueNotFound(key, duration) => {
BehaviourOut::Dht(DhtEvent::ValueNotFound(key.into()), Some(duration))
},
DiscoveryOut::ValuePut(key, duration) => {
BehaviourOut::Dht(DhtEvent::ValuePut(key.into()), Some(duration))
},
DiscoveryOut::PutRecordRequest(record_key, record_value, publisher, expires) => {
BehaviourOut::Dht(
DhtEvent::PutRecordRequest(record_key.into(), record_value, publisher, expires),
None,
),
DiscoveryOut::ValuePutFailed(key, duration) =>
BehaviourOut::Dht(DhtEvent::ValuePutFailed(key.into()), Some(duration)),
DiscoveryOut::StartedProviding(key, duration) =>
BehaviourOut::Dht(DhtEvent::StartedProviding(key.into()), Some(duration)),
DiscoveryOut::StartProvidingFailed(key, duration) =>
BehaviourOut::Dht(DhtEvent::StartProvidingFailed(key.into()), Some(duration)),
)
},
DiscoveryOut::ValuePutFailed(key, duration) => {
BehaviourOut::Dht(DhtEvent::ValuePutFailed(key.into()), Some(duration))
},
DiscoveryOut::StartedProviding(key, duration) => {
BehaviourOut::Dht(DhtEvent::StartedProviding(key.into()), Some(duration))
},
DiscoveryOut::StartProvidingFailed(key, duration) => {
BehaviourOut::Dht(DhtEvent::StartProvidingFailed(key.into()), Some(duration))
},
DiscoveryOut::ProvidersFound(key, providers, duration) => BehaviourOut::Dht(
DhtEvent::ProvidersFound(
key.into(),
@@ -435,10 +448,12 @@ impl From<DiscoveryOut> for BehaviourOut {
),
Some(duration),
),
DiscoveryOut::NoMoreProviders(key, duration) =>
BehaviourOut::Dht(DhtEvent::NoMoreProviders(key.into()), Some(duration)),
DiscoveryOut::ProvidersNotFound(key, duration) =>
BehaviourOut::Dht(DhtEvent::ProvidersNotFound(key.into()), Some(duration)),
DiscoveryOut::NoMoreProviders(key, duration) => {
BehaviourOut::Dht(DhtEvent::NoMoreProviders(key.into()), Some(duration))
},
DiscoveryOut::ProvidersNotFound(key, duration) => {
BehaviourOut::Dht(DhtEvent::ProvidersNotFound(key.into()), Some(duration))
},
DiscoveryOut::RandomKademliaStarted => BehaviourOut::RandomKademliaStarted,
}
}
+3 -3
View File
@@ -197,9 +197,9 @@ impl<B: BlockT> BitswapRequestHandler<B> {
},
};
if cid.version() != cid::Version::V1 ||
cid.hash().code() != u64::from(cid::multihash::Code::Blake2b256) ||
cid.hash().size() != 32
if cid.version() != cid::Version::V1
|| cid.hash().code() != u64::from(cid::multihash::Code::Blake2b256)
|| cid.hash().size() != 32
{
debug!(target: LOG_TARGET, "Ignoring unsupported CID {}: {}", peer, cid);
continue;
+8 -6
View File
@@ -584,8 +584,9 @@ impl DiscoveryBehaviour {
let ip = match addr.iter().next() {
Some(Protocol::Ip4(ip)) => IpNetwork::from(ip),
Some(Protocol::Ip6(ip)) => IpNetwork::from(ip),
Some(Protocol::Dns(_)) | Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) =>
return true,
Some(Protocol::Dns(_)) | Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) => {
return true
},
_ => return false,
};
ip.is_global()
@@ -939,7 +940,7 @@ impl NetworkBehaviour for DiscoveryBehaviour {
// We are not interested in this event at the moment.
},
KademliaEvent::InboundRequest { request } => match request {
libp2p::kad::InboundRequest::PutRecord { record: Some(record), .. } =>
libp2p::kad::InboundRequest::PutRecord { record: Some(record), .. } => {
return Poll::Ready(ToSwarm::GenerateEvent(
DiscoveryOut::PutRecordRequest(
record.key,
@@ -947,7 +948,8 @@ impl NetworkBehaviour for DiscoveryBehaviour {
record.publisher.map(Into::into),
record.expires,
),
)),
))
},
_ => {},
},
KademliaEvent::OutboundQueryProgressed {
@@ -1417,8 +1419,8 @@ mod tests {
match e {
SwarmEvent::Behaviour(behavior) => {
match behavior {
DiscoveryOut::UnroutablePeer(other) |
DiscoveryOut::Discovered(other) => {
DiscoveryOut::UnroutablePeer(other)
| DiscoveryOut::Discovered(other) => {
// Call `add_self_reported_address` to simulate identify
// happening.
let addr = swarms
@@ -507,8 +507,9 @@ impl Discovery {
let ip = match address.iter().next() {
Some(Protocol::Ip4(ip)) => IpNetwork::from(ip),
Some(Protocol::Ip6(ip)) => IpNetwork::from(ip),
Some(Protocol::Dns(_)) | Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) =>
return true,
Some(Protocol::Dns(_)) | Some(Protocol::Dns4(_)) | Some(Protocol::Dns6(_)) => {
return true
},
_ => return false,
};
@@ -554,8 +555,8 @@ impl Discovery {
}
},
None => {
let oldest = (self.address_confirmations.len() >=
self.address_confirmations.limiter().max_length() as usize)
let oldest = (self.address_confirmations.len()
>= self.address_confirmations.limiter().max_length() as usize)
.then(|| {
self.address_confirmations.pop_oldest().map(|(address, peers)| {
if peers.len() >= MIN_ADDRESS_CONFIRMATIONS {
@@ -668,8 +669,9 @@ impl Stream for Discovery {
record,
}));
},
Poll::Ready(Some(KademliaEvent::PutRecordSuccess { query_id, key: _ })) =>
return Poll::Ready(Some(DiscoveryEvent::PutRecordSuccess { query_id })),
Poll::Ready(Some(KademliaEvent::PutRecordSuccess { query_id, key: _ })) => {
return Poll::Ready(Some(DiscoveryEvent::PutRecordSuccess { query_id }))
},
Poll::Ready(Some(KademliaEvent::QueryFailed { query_id })) => {
match this.random_walk_query_id == Some(query_id) {
true => {
@@ -781,16 +783,18 @@ impl Stream for Discovery {
match Pin::new(&mut this.ping_event_stream).poll_next(cx) {
Poll::Pending => {},
Poll::Ready(None) => return Poll::Ready(None),
Poll::Ready(Some(PingEvent::Ping { peer, ping })) =>
return Poll::Ready(Some(DiscoveryEvent::Ping { peer, rtt: ping })),
Poll::Ready(Some(PingEvent::Ping { peer, ping })) => {
return Poll::Ready(Some(DiscoveryEvent::Ping { peer, rtt: ping }))
},
}
if let Some(ref mut mdns_event_stream) = &mut this.mdns_event_stream {
match Pin::new(mdns_event_stream).poll_next(cx) {
Poll::Pending => {},
Poll::Ready(None) => return Poll::Ready(None),
Poll::Ready(Some(MdnsEvent::Discovered(addresses))) =>
return Poll::Ready(Some(DiscoveryEvent::Discovered { addresses })),
Poll::Ready(Some(MdnsEvent::Discovered(addresses))) => {
return Poll::Ready(Some(DiscoveryEvent::Discovered { addresses }))
},
}
}
+14 -11
View File
@@ -206,19 +206,20 @@ impl Litep2pNetworkBackend {
.into_iter()
.filter_map(|address| match address.iter().next() {
Some(
Protocol::Dns(_) |
Protocol::Dns4(_) |
Protocol::Dns6(_) |
Protocol::Ip6(_) |
Protocol::Ip4(_),
Protocol::Dns(_)
| Protocol::Dns4(_)
| Protocol::Dns6(_)
| Protocol::Ip6(_)
| Protocol::Ip4(_),
) => match address.iter().find(|protocol| std::matches!(protocol, Protocol::P2p(_)))
{
Some(Protocol::P2p(multihash)) => PeerId::from_multihash(multihash.into())
.map_or(None, |peer| Some((peer, Some(address)))),
_ => None,
},
Some(Protocol::P2p(multihash)) =>
PeerId::from_multihash(multihash.into()).map_or(None, |peer| Some((peer, None))),
Some(Protocol::P2p(multihash)) => {
PeerId::from_multihash(multihash.into()).map_or(None, |peer| Some((peer, None)))
},
_ => None,
})
.fold(HashMap::new(), |mut acc, (peer, maybe_address)| {
@@ -300,8 +301,9 @@ impl Litep2pNetworkBackend {
match iter.next() {
Some(Protocol::Tcp(_)) => match iter.next() {
Some(Protocol::Ws(_) | Protocol::Wss(_)) =>
Some((None, Some(address.clone()))),
Some(Protocol::Ws(_) | Protocol::Wss(_)) => {
Some((None, Some(address.clone())))
},
Some(Protocol::P2p(_)) | None => Some((Some(address.clone()), None)),
protocol => {
log::error!(
@@ -484,8 +486,9 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkBackend<B, H> for Litep2pNetworkBac
use pezsc_network_types::multiaddr::Protocol;
let address = match address.iter().last() {
Some(Protocol::Ws(_) | Protocol::Wss(_) | Protocol::Tcp(_)) =>
address.with(Protocol::P2p(peer.into())),
Some(Protocol::Ws(_) | Protocol::Wss(_) | Protocol::Tcp(_)) => {
address.with(Protocol::P2p(peer.into()))
},
Some(Protocol::P2p(_)) => address,
_ => return acc,
};
@@ -76,8 +76,9 @@ impl<Block: BlockT> BitswapServer<Block> {
log::trace!(target: LOG_TARGET, "found cid {cid:?}, hash {hash:?}");
match want_type {
WantType::Block =>
ResponseType::Block { cid, block: transaction },
WantType::Block => {
ResponseType::Block { cid, block: transaction }
},
_ => ResponseType::Presence {
cid,
presence: BlockPresenceType::Have,
@@ -123,8 +123,9 @@ pub enum Direction {
impl Direction {
fn set_reserved(&mut self, new_reserved: Reserved) {
match self {
Direction::Inbound(ref mut reserved) | Direction::Outbound(ref mut reserved) =>
*reserved = new_reserved,
Direction::Inbound(ref mut reserved) | Direction::Outbound(ref mut reserved) => {
*reserved = new_reserved
},
}
}
}
@@ -541,8 +542,8 @@ impl Peerset {
match &state {
// close was initiated either by remote ([`PeerState::Connected`]) or local node
// ([`PeerState::Closing`]) and it was a non-reserved peer
PeerState::Connected { direction: Direction::Inbound(Reserved::No) } |
PeerState::Closing { direction: Direction::Inbound(Reserved::No) } => {
PeerState::Connected { direction: Direction::Inbound(Reserved::No) }
| PeerState::Closing { direction: Direction::Inbound(Reserved::No) } => {
log::trace!(
target: LOG_TARGET,
"{}: inbound substream closed to non-reserved peer {peer:?}: {state:?}",
@@ -558,8 +559,8 @@ impl Peerset {
},
// close was initiated either by remote ([`PeerState::Connected`]) or local node
// ([`PeerState::Closing`]) and it was a non-reserved peer
PeerState::Connected { direction: Direction::Outbound(Reserved::No) } |
PeerState::Closing { direction: Direction::Outbound(Reserved::No) } => {
PeerState::Connected { direction: Direction::Outbound(Reserved::No) }
| PeerState::Closing { direction: Direction::Outbound(Reserved::No) } => {
log::trace!(
target: LOG_TARGET,
"{}: outbound substream closed to non-reserved peer {peer:?} {state:?}",
@@ -791,8 +792,8 @@ impl Peerset {
_ => {},
},
// reserved peers do not require change in the slot counts
Some(PeerState::Opening { direction: Direction::Inbound(Reserved::Yes) }) |
Some(PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }) => {
Some(PeerState::Opening { direction: Direction::Inbound(Reserved::Yes) })
| Some(PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }) => {
log::debug!(
target: LOG_TARGET,
"{}: substream open failure for reserved peer {peer:?}",
@@ -884,10 +885,10 @@ impl Peerset {
match self.peers.get_mut(peer) {
Some(PeerState::Disconnected | PeerState::Backoff) => {},
Some(
PeerState::Opening { ref mut direction } |
PeerState::Connected { ref mut direction } |
PeerState::Canceled { ref mut direction } |
PeerState::Closing { ref mut direction },
PeerState::Opening { ref mut direction }
| PeerState::Connected { ref mut direction }
| PeerState::Canceled { ref mut direction }
| PeerState::Closing { ref mut direction },
) => {
*direction = match direction {
Direction::Inbound(Reserved::No) => {
@@ -1440,8 +1441,8 @@ impl Stream for Peerset {
.peers
.iter()
.filter_map(|(peer, state)| {
(!self.reserved_peers.contains(peer) &&
std::matches!(state, PeerState::Connected { .. }))
(!self.reserved_peers.contains(peer)
&& std::matches!(state, PeerState::Connected { .. }))
.then_some(*peer)
})
.collect::<Vec<_>>();
@@ -162,7 +162,7 @@ async fn test_once() {
// substream to `Peerset` and move peer state to `open`.
//
// if the substream was canceled while it was opening, move peer to `closing`
2 =>
2 => {
if let Some(peer) = opening.keys().choose(&mut rng).copied() {
let direction = opening.remove(&peer).unwrap();
match peerset.report_substream_opened(peer, direction) {
@@ -173,37 +173,43 @@ async fn test_once() {
assert!(closing.insert(peer));
},
}
},
}
},
// substream failed to open
3 =>
3 => {
if let Some(peer) = opening.keys().choose(&mut rng).copied() {
let _ = opening.remove(&peer).unwrap();
peerset.report_substream_open_failure(peer, NotificationError::Rejected);
},
}
},
// substream was closed by remote peer
4 =>
4 => {
if let Some(peer) = open.keys().choose(&mut rng).copied() {
let _ = open.remove(&peer).unwrap();
peerset.report_substream_closed(peer);
assert!(closed.insert(peer));
},
}
},
// substream was closed by local node
5 =>
5 => {
if let Some(peer) = closing.iter().choose(&mut rng).copied() {
assert!(closing.remove(&peer));
assert!(closed.insert(peer));
peerset.report_substream_closed(peer);
},
}
},
// random connected peer was disconnected by the protocol
6 =>
6 => {
if let Some(peer) = open.keys().choose(&mut rng).copied() {
to_peerset.unbounded_send(PeersetCommand::DisconnectPeer { peer }).unwrap();
},
}
},
// ban random peer
7 =>
7 => {
if let Some(peer) = known_peers.iter().choose(&mut rng).copied() {
peer_store_handle.report_peer(peer, ReputationChange::new_fatal(""));
},
}
},
// inbound substream is received for a peer that was considered
// outbound
8 => {
@@ -364,7 +370,7 @@ async fn test_once() {
}
},
// inbound substream received for a peer in `closed`
15 =>
15 => {
if let Some(peer) = closed.iter().choose(&mut rng).copied() {
match peerset.report_inbound_substream(peer) {
ValidationResult::Accept => {
@@ -373,7 +379,8 @@ async fn test_once() {
},
ValidationResult::Reject => {},
}
},
}
},
_ => unreachable!(),
}
}
@@ -382,36 +382,45 @@ impl RequestResponseProtocol {
};
let status = match error {
RequestResponseError::NotConnected =>
Some((RequestFailure::NotConnected, "not-connected")),
RequestResponseError::NotConnected => {
Some((RequestFailure::NotConnected, "not-connected"))
},
RequestResponseError::Rejected(reason) => {
let reason = match reason {
RejectReason::ConnectionClosed => "connection-closed",
RejectReason::SubstreamClosed => "substream-closed",
RejectReason::SubstreamOpenError(substream_error) => match substream_error {
SubstreamError::NegotiationError(NegotiationError::Timeout) =>
"substream-timeout",
SubstreamError::NegotiationError(NegotiationError::Timeout) => {
"substream-timeout"
},
_ => "substream-open-error",
},
RejectReason::DialFailed(None) => "dial-failed",
RejectReason::DialFailed(Some(ImmediateDialError::AlreadyConnected)) =>
"dial-already-connected",
RejectReason::DialFailed(Some(ImmediateDialError::PeerIdMissing)) =>
"dial-peerid-missing",
RejectReason::DialFailed(Some(ImmediateDialError::TriedToDialSelf)) =>
"dial-tried-to-dial-self",
RejectReason::DialFailed(Some(ImmediateDialError::NoAddressAvailable)) =>
"dial-no-address-available",
RejectReason::DialFailed(Some(ImmediateDialError::TaskClosed)) =>
"dial-task-closed",
RejectReason::DialFailed(Some(ImmediateDialError::ChannelClogged)) =>
"dial-channel-clogged",
RejectReason::DialFailed(Some(ImmediateDialError::AlreadyConnected)) => {
"dial-already-connected"
},
RejectReason::DialFailed(Some(ImmediateDialError::PeerIdMissing)) => {
"dial-peerid-missing"
},
RejectReason::DialFailed(Some(ImmediateDialError::TriedToDialSelf)) => {
"dial-tried-to-dial-self"
},
RejectReason::DialFailed(Some(ImmediateDialError::NoAddressAvailable)) => {
"dial-no-address-available"
},
RejectReason::DialFailed(Some(ImmediateDialError::TaskClosed)) => {
"dial-task-closed"
},
RejectReason::DialFailed(Some(ImmediateDialError::ChannelClogged)) => {
"dial-channel-clogged"
},
};
Some((RequestFailure::Refused, reason))
},
RequestResponseError::Timeout =>
Some((RequestFailure::Network(OutboundFailure::Timeout), "timeout")),
RequestResponseError::Timeout => {
Some((RequestFailure::Network(OutboundFailure::Timeout), "timeout"))
},
RequestResponseError::Canceled => {
log::debug!(
target: LOG_TARGET,
@@ -514,8 +523,9 @@ impl RequestResponseProtocol {
match sent_feedback {
None => self.handle.send_response(request_id, response),
Some(feedback) =>
self.handle.send_response_with_feedback(request_id, response, feedback),
Some(feedback) => {
self.handle.send_response_with_feedback(request_id, response, feedback)
},
}
self.metrics.register_inbound_request_success(started.elapsed());
@@ -106,10 +106,12 @@ pub enum Endpoint {
impl From<ConnectedPoint> for PeerEndpoint {
fn from(endpoint: ConnectedPoint) -> Self {
match endpoint {
ConnectedPoint::Dialer { address, role_override, port_use: _ } =>
Self::Dialing(address, role_override.into()),
ConnectedPoint::Listener { local_addr, send_back_addr } =>
Self::Listening { local_addr, send_back_addr },
ConnectedPoint::Dialer { address, role_override, port_use: _ } => {
Self::Dialing(address, role_override.into())
},
ConnectedPoint::Listener { local_addr, send_back_addr } => {
Self::Listening { local_addr, send_back_addr }
},
}
}
}
+8 -6
View File
@@ -288,8 +288,8 @@ impl PeerInfoBehaviour {
}
},
None => {
let oldest = (self.address_confirmations.len() >=
self.address_confirmations.limiter().max_length() as usize)
let oldest = (self.address_confirmations.len()
>= self.address_confirmations.limiter().max_length() as usize)
.then(|| {
self.address_confirmations.pop_oldest().map(|(address, peers)| {
if peers.len() >= MIN_ADDRESS_CONFIRMATIONS {
@@ -599,10 +599,12 @@ impl NetworkBehaviour for PeerInfoBehaviour {
event: THandlerOutEvent<Self>,
) {
match event {
Either::Left(event) =>
self.ping.on_connection_handler_event(peer_id, connection_id, event),
Either::Right(event) =>
self.identify.on_connection_handler_event(peer_id, connection_id, event),
Either::Left(event) => {
self.ping.on_connection_handler_event(peer_id, connection_id, event)
},
Either::Right(event) => {
self.identify.on_connection_handler_event(peer_id, connection_id, event)
},
}
}
+6 -4
View File
@@ -309,7 +309,7 @@ impl<B: BlockT> NetworkBehaviour for Protocol<B> {
notifications_sink,
negotiated_fallback,
..
} =>
} => {
if set_id == HARDCODED_PEERSETS_SYNC {
let _ = self.sync_handle.report_substream_opened(
peer_id,
@@ -334,8 +334,9 @@ impl<B: BlockT> NetworkBehaviour for Protocol<B> {
None
},
}
},
NotificationsOut::CustomProtocolReplaced { peer_id, notifications_sink, set_id } =>
}
},
NotificationsOut::CustomProtocolReplaced { peer_id, notifications_sink, set_id } => {
if set_id == HARDCODED_PEERSETS_SYNC {
let _ = self
.sync_handle
@@ -349,7 +350,8 @@ impl<B: BlockT> NetworkBehaviour for Protocol<B> {
notifications_sink,
},
)
},
}
},
NotificationsOut::CustomProtocolClosed { peer_id, set_id } => {
if set_id == HARDCODED_PEERSETS_SYNC {
let _ = self.sync_handle.report_substream_closed(peer_id);
@@ -109,12 +109,13 @@ pub mod generic {
let compact = CompactStatus::decode(value)?;
let chain_status = match <Vec<u8>>::decode(value) {
Ok(v) => v,
Err(e) =>
Err(e) => {
if compact.version <= LAST_CHAIN_STATUS_VERSION {
return Err(e);
} else {
Vec::new()
},
}
},
};
let CompactStatus {
@@ -1263,8 +1263,8 @@ impl NetworkBehaviour for Notifications {
for set_id in (0..self.notif_protocols.len()).map(SetId::from) {
match self.peers.entry((peer_id, set_id)).or_insert(PeerState::Poisoned) {
// Requested | PendingRequest => Enabled
st @ &mut PeerState::Requested |
st @ &mut PeerState::PendingRequest { .. } => {
st @ &mut PeerState::Requested
| st @ &mut PeerState::PendingRequest { .. } => {
trace!(target: LOG_TARGET,
"Libp2p => Connected({}, {:?}, {:?}): Connection was requested by PSM.",
peer_id, set_id, endpoint
@@ -1304,10 +1304,10 @@ impl NetworkBehaviour for Notifications {
// In all other states, add this new connection to the list of closed
// inactive connections.
PeerState::Incoming { connections, .. } |
PeerState::Disabled { connections, .. } |
PeerState::DisabledPendingEnable { connections, .. } |
PeerState::Enabled { connections, .. } => {
PeerState::Incoming { connections, .. }
| PeerState::Disabled { connections, .. }
| PeerState::DisabledPendingEnable { connections, .. }
| PeerState::Enabled { connections, .. } => {
trace!(target: LOG_TARGET,
"Libp2p => Connected({}, {:?}, {:?}, {:?}): Secondary connection. Leaving closed.",
peer_id, set_id, endpoint, connection_id);
@@ -1593,9 +1593,9 @@ impl NetworkBehaviour for Notifications {
}
},
PeerState::Requested |
PeerState::PendingRequest { .. } |
PeerState::Backoff { .. } => {
PeerState::Requested
| PeerState::PendingRequest { .. }
| PeerState::Backoff { .. } => {
// This is a serious bug either in this state machine or in libp2p.
error!(target: LOG_TARGET,
"`inject_connection_closed` called for unknown peer {}",
@@ -1629,8 +1629,8 @@ impl NetworkBehaviour for Notifications {
// "Basic" situation: we failed to reach a peer that the peerset
// requested.
st @ PeerState::Requested |
st @ PeerState::PendingRequest { .. } => {
st @ PeerState::Requested
| st @ PeerState::PendingRequest { .. } => {
trace!(target: LOG_TARGET, "PSM <= Dropped({}, {:?})", peer_id, set_id);
self.protocol_controller_handles[usize::from(set_id)]
.dropped(peer_id);
@@ -1639,7 +1639,9 @@ impl NetworkBehaviour for Notifications {
let ban_duration = match st {
PeerState::PendingRequest { timer_deadline, .. }
if timer_deadline > now =>
cmp::max(timer_deadline - now, Duration::from_secs(5)),
{
cmp::max(timer_deadline - now, Duration::from_secs(5))
},
_ => Duration::from_secs(5),
};
@@ -1662,10 +1664,10 @@ impl NetworkBehaviour for Notifications {
// We can still get dial failures even if we are already connected
// to the peer, as an extra diagnostic for an earlier attempt.
st @ PeerState::Disabled { .. } |
st @ PeerState::Enabled { .. } |
st @ PeerState::DisabledPendingEnable { .. } |
st @ PeerState::Incoming { .. } => {
st @ PeerState::Disabled { .. }
| st @ PeerState::Enabled { .. }
| st @ PeerState::DisabledPendingEnable { .. }
| st @ PeerState::Incoming { .. } => {
*entry.into_mut() = st;
},
@@ -1793,8 +1795,8 @@ impl NetworkBehaviour for Notifications {
// more to do.
debug_assert!(matches!(
connec_state,
ConnectionState::OpenDesiredByRemote |
ConnectionState::Closing | ConnectionState::Opening
ConnectionState::OpenDesiredByRemote
| ConnectionState::Closing | ConnectionState::Opening
));
}
} else {
@@ -2005,8 +2007,8 @@ impl NetworkBehaviour for Notifications {
// All connections in `Disabled` and `DisabledPendingEnable` have been sent a
// `Close` message already, and as such ignore any `CloseDesired` message.
state @ PeerState::Disabled { .. } |
state @ PeerState::DisabledPendingEnable { .. } => {
state @ PeerState::Disabled { .. }
| state @ PeerState::DisabledPendingEnable { .. } => {
*entry.into_mut() = state;
},
state => {
@@ -2026,10 +2028,10 @@ impl NetworkBehaviour for Notifications {
match self.peers.get_mut(&(peer_id, set_id)) {
// Move the connection from `Closing` to `Closed`.
Some(PeerState::Incoming { connections, .. }) |
Some(PeerState::DisabledPendingEnable { connections, .. }) |
Some(PeerState::Disabled { connections, .. }) |
Some(PeerState::Enabled { connections, .. }) => {
Some(PeerState::Incoming { connections, .. })
| Some(PeerState::DisabledPendingEnable { connections, .. })
| Some(PeerState::Disabled { connections, .. })
| Some(PeerState::Enabled { connections, .. }) => {
if let Some((_, connec_state)) = connections.iter_mut().find(|(c, s)| {
*c == connection_id && matches!(s, ConnectionState::Closing)
}) {
@@ -2094,8 +2096,8 @@ impl NetworkBehaviour for Notifications {
*connec_state = ConnectionState::Open(notifications_sink);
} else if let Some((_, connec_state)) =
connections.iter_mut().find(|(c, s)| {
*c == connection_id &&
matches!(s, ConnectionState::OpeningThenClosing)
*c == connection_id
&& matches!(s, ConnectionState::OpeningThenClosing)
}) {
*connec_state = ConnectionState::Closing;
} else {
@@ -2105,9 +2107,9 @@ impl NetworkBehaviour for Notifications {
}
},
Some(PeerState::Incoming { connections, .. }) |
Some(PeerState::DisabledPendingEnable { connections, .. }) |
Some(PeerState::Disabled { connections, .. }) => {
Some(PeerState::Incoming { connections, .. })
| Some(PeerState::DisabledPendingEnable { connections, .. })
| Some(PeerState::Disabled { connections, .. }) => {
if let Some((_, connec_state)) = connections.iter_mut().find(|(c, s)| {
*c == connection_id && matches!(s, ConnectionState::OpeningThenClosing)
}) {
@@ -2156,8 +2158,8 @@ impl NetworkBehaviour for Notifications {
*connec_state = ConnectionState::Closed;
} else if let Some((_, connec_state)) =
connections.iter_mut().find(|(c, s)| {
*c == connection_id &&
matches!(s, ConnectionState::OpeningThenClosing)
*c == connection_id
&& matches!(s, ConnectionState::OpeningThenClosing)
}) {
*connec_state = ConnectionState::Closing;
} else {
@@ -2181,17 +2183,17 @@ impl NetworkBehaviour for Notifications {
*entry.into_mut() = PeerState::Enabled { connections };
}
},
mut state @ PeerState::Incoming { .. } |
mut state @ PeerState::DisabledPendingEnable { .. } |
mut state @ PeerState::Disabled { .. } => {
mut state @ PeerState::Incoming { .. }
| mut state @ PeerState::DisabledPendingEnable { .. }
| mut state @ PeerState::Disabled { .. } => {
match &mut state {
PeerState::Incoming { connections, .. } |
PeerState::Disabled { connections, .. } |
PeerState::DisabledPendingEnable { connections, .. } => {
PeerState::Incoming { connections, .. }
| PeerState::Disabled { connections, .. }
| PeerState::DisabledPendingEnable { connections, .. } => {
if let Some((_, connec_state)) =
connections.iter_mut().find(|(c, s)| {
*c == connection_id &&
matches!(s, ConnectionState::OpeningThenClosing)
*c == connection_id
&& matches!(s, ConnectionState::OpeningThenClosing)
}) {
*connec_state = ConnectionState::Closing;
} else {
@@ -2301,8 +2303,8 @@ impl NetworkBehaviour for Notifications {
NotificationCommand::SetHandshake(handshake) => {
self.set_notif_protocol_handshake(set_id.into(), handshake);
},
NotificationCommand::OpenSubstream(_peer) |
NotificationCommand::CloseSubstream(_peer) => {
NotificationCommand::OpenSubstream(_peer)
| NotificationCommand::CloseSubstream(_peer) => {
todo!("substream control not implemented");
},
},
@@ -2416,8 +2418,9 @@ mod tests {
(ConnectionState::Closing, ConnectionState::Closing) => true,
(ConnectionState::Opening, ConnectionState::Opening) => true,
(ConnectionState::OpeningThenClosing, ConnectionState::OpeningThenClosing) => true,
(ConnectionState::OpenDesiredByRemote, ConnectionState::OpenDesiredByRemote) =>
true,
(ConnectionState::OpenDesiredByRemote, ConnectionState::OpenDesiredByRemote) => {
true
},
(ConnectionState::Open(_), ConnectionState::Open(_)) => true,
_ => false,
}
@@ -560,8 +560,8 @@ impl ConnectionHandler for NotifsHandler {
// to do.
return;
},
State::Opening { ref mut in_substream, .. } |
State::Open { ref mut in_substream, .. } => {
State::Opening { ref mut in_substream, .. }
| State::Open { ref mut in_substream, .. } => {
if in_substream.is_some() {
// Same remark as above.
return;
@@ -579,8 +579,8 @@ impl ConnectionHandler for NotifsHandler {
let (new_open, protocol_index) = (outbound.protocol, outbound.info);
match self.protocols[protocol_index].state {
State::Closed { ref mut pending_opening } |
State::OpenDesiredByRemote { ref mut pending_opening, .. } => {
State::Closed { ref mut pending_opening }
| State::OpenDesiredByRemote { ref mut pending_opening, .. } => {
debug_assert!(*pending_opening);
*pending_opening = false;
},
@@ -626,8 +626,8 @@ impl ConnectionHandler for NotifsHandler {
[dial_upgrade_error.info]
.state
{
State::Closed { ref mut pending_opening } |
State::OpenDesiredByRemote { ref mut pending_opening, .. } => {
State::Closed { ref mut pending_opening }
| State::OpenDesiredByRemote { ref mut pending_opening, .. } => {
debug_assert!(*pending_opening);
*pending_opening = false;
},
@@ -786,10 +786,11 @@ impl ConnectionHandler for NotifsHandler {
// available in `notifications_sink_rx`. This avoids waking up the task when
// a substream is ready to send if there isn't actually something to send.
match Pin::new(&mut *notifications_sink_rx).as_mut().poll_peek(cx) {
Poll::Ready(Some(&NotificationsSinkMessage::ForceClose)) =>
Poll::Ready(Some(&NotificationsSinkMessage::ForceClose)) => {
return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(
NotifsHandlerOut::Close { protocol_index },
)),
))
},
Poll::Ready(Some(&NotificationsSinkMessage::Notification { .. })) => {},
Poll::Ready(None) | Poll::Pending => break,
}
@@ -803,11 +804,12 @@ impl ConnectionHandler for NotifsHandler {
// Now that the substream is ready for a message, grab what to send.
let message = match notifications_sink_rx.poll_next_unpin(cx) {
Poll::Ready(Some(NotificationsSinkMessage::Notification { message })) =>
message,
Poll::Ready(Some(NotificationsSinkMessage::ForceClose)) |
Poll::Ready(None) |
Poll::Pending => {
Poll::Ready(Some(NotificationsSinkMessage::Notification { message })) => {
message
},
Poll::Ready(Some(NotificationsSinkMessage::ForceClose))
| Poll::Ready(None)
| Poll::Pending => {
// Should never be reached, as per `poll_peek` above.
debug_assert!(false);
break;
@@ -839,10 +841,12 @@ impl ConnectionHandler for NotifsHandler {
*out_substream = None;
let reason = match error {
NotificationsOutError::Io(_) | NotificationsOutError::Closed =>
CloseReason::RemoteRequest,
NotificationsOutError::UnexpectedData =>
CloseReason::ProtocolMisbehavior,
NotificationsOutError::Io(_) | NotificationsOutError::Closed => {
CloseReason::RemoteRequest
},
NotificationsOutError::UnexpectedData => {
CloseReason::ProtocolMisbehavior
},
};
let event = NotifsHandlerOut::CloseDesired { protocol_index, reason };
@@ -851,10 +855,10 @@ impl ConnectionHandler for NotifsHandler {
};
},
State::Closed { .. } |
State::Opening { .. } |
State::Open { out_substream: None, .. } |
State::OpenDesiredByRemote { .. } => {},
State::Closed { .. }
| State::Opening { .. }
| State::Open { out_substream: None, .. }
| State::OpenDesiredByRemote { .. } => {},
}
}
@@ -863,11 +867,11 @@ impl ConnectionHandler for NotifsHandler {
// Inbound substreams being closed is always tolerated, except for the
// `OpenDesiredByRemote` state which might need to be switched back to `Closed`.
match &mut self.protocols[protocol_index].state {
State::Closed { .. } |
State::Open { in_substream: None, .. } |
State::Opening { in_substream: None, .. } => {},
State::Closed { .. }
| State::Open { in_substream: None, .. }
| State::Opening { in_substream: None, .. } => {},
State::Open { in_substream: in_substream @ Some(_), .. } =>
State::Open { in_substream: in_substream @ Some(_), .. } => {
match futures::prelude::stream::Stream::poll_next(
Pin::new(in_substream.as_mut().unwrap()),
cx,
@@ -878,9 +882,10 @@ impl ConnectionHandler for NotifsHandler {
return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(event));
},
Poll::Ready(None) | Poll::Ready(Some(Err(_))) => *in_substream = None,
},
}
},
State::OpenDesiredByRemote { in_substream, pending_opening } =>
State::OpenDesiredByRemote { in_substream, pending_opening } => {
match NotificationsInSubstream::poll_process(Pin::new(in_substream), cx) {
Poll::Pending => {},
Poll::Ready(Ok(())) => {},
@@ -894,9 +899,10 @@ impl ConnectionHandler for NotifsHandler {
},
));
},
},
}
},
State::Opening { in_substream: in_substream @ Some(_), .. } =>
State::Opening { in_substream: in_substream @ Some(_), .. } => {
match NotificationsInSubstream::poll_process(
Pin::new(in_substream.as_mut().unwrap()),
cx,
@@ -904,7 +910,8 @@ impl ConnectionHandler for NotifsHandler {
Poll::Pending => {},
Poll::Ready(Ok(())) => {},
Poll::Ready(Err(_)) => *in_substream = None,
},
}
},
}
}
@@ -1003,8 +1010,9 @@ pub mod tests {
};
futures::future::poll_fn(|cx| match substream.notifications.poll_next_unpin(cx) {
Poll::Ready(Some(NotificationsSinkMessage::Notification { message })) =>
Poll::Ready(Some(message)),
Poll::Ready(Some(NotificationsSinkMessage::Notification { message })) => {
Poll::Ready(Some(message))
},
Poll::Pending => Poll::Ready(None),
Poll::Ready(Some(NotificationsSinkMessage::ForceClose)) | Poll::Ready(None) => {
panic!("sink closed")
@@ -1108,8 +1116,9 @@ pub mod tests {
) -> Poll<Result<usize, Error>> {
match self.rx.poll_recv(cx) {
Poll::Ready(Some(data)) => self.rx_buffer.extend_from_slice(&data),
Poll::Ready(None) =>
return Poll::Ready(Err(std::io::ErrorKind::UnexpectedEof.into())),
Poll::Ready(None) => {
return Poll::Ready(Err(std::io::ErrorKind::UnexpectedEof.into()))
},
_ => {},
}
@@ -295,12 +295,13 @@ impl NotificationService for NotificationHandle {
async fn next_event(&mut self) -> Option<NotificationEvent> {
loop {
match self.rx.next().await? {
InnerNotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx } =>
InnerNotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx } => {
return Some(NotificationEvent::ValidateInboundSubstream {
peer: peer.into(),
handshake,
result_tx,
}),
})
},
InnerNotificationEvent::NotificationStreamOpened {
peer,
handshake,
@@ -326,11 +327,12 @@ impl NotificationService for NotificationHandle {
self.peers.remove(&peer);
return Some(NotificationEvent::NotificationStreamClosed { peer: peer.into() });
},
InnerNotificationEvent::NotificationReceived { peer, notification } =>
InnerNotificationEvent::NotificationReceived { peer, notification } => {
return Some(NotificationEvent::NotificationReceived {
peer: peer.into(),
notification,
}),
})
},
InnerNotificationEvent::NotificationSinkReplaced { peer, sink } => {
match self.peers.get_mut(&peer) {
None => log::error!(
@@ -515,8 +517,9 @@ impl ProtocolHandle {
tokio::spawn(async move {
while let Some(event) = results.next().await {
match event {
Err(_) | Ok(ValidationResult::Reject) =>
return tx.send(ValidationResult::Reject),
Err(_) | Ok(ValidationResult::Reject) => {
return tx.send(ValidationResult::Reject)
},
Ok(ValidationResult::Accept) => {},
}
}
@@ -209,12 +209,12 @@ async fn libp2p_to_litep2p_substream() {
let mut libp2p_1111_seen = false;
let mut libp2p_2222_seen = false;
while !libp2p_ready ||
!litep2p_ready ||
!litep2p_3333_seen ||
!litep2p_4444_seen ||
!libp2p_1111_seen ||
!libp2p_2222_seen
while !libp2p_ready
|| !litep2p_ready
|| !litep2p_3333_seen
|| !litep2p_4444_seen
|| !libp2p_1111_seen
|| !libp2p_2222_seen
{
tokio::select! {
event = libp2p.select_next_some() => match event {
@@ -318,9 +318,9 @@ async fn reconnect_after_disconnect() {
NotificationsOut::CustomProtocolClosed { .. },
)) => match service1_state {
ServiceState::FirstConnec => service1_state = ServiceState::Disconnected,
ServiceState::ConnectedAgain |
ServiceState::NotConnected |
ServiceState::Disconnected => panic!(),
ServiceState::ConnectedAgain
| ServiceState::NotConnected
| ServiceState::Disconnected => panic!(),
},
future::Either::Right(SwarmEvent::Behaviour(
NotificationsOut::CustomProtocolOpen { .. },
@@ -340,9 +340,9 @@ async fn reconnect_after_disconnect() {
NotificationsOut::CustomProtocolClosed { .. },
)) => match service2_state {
ServiceState::FirstConnec => service2_state = ServiceState::Disconnected,
ServiceState::ConnectedAgain |
ServiceState::NotConnected |
ServiceState::Disconnected => panic!(),
ServiceState::ConnectedAgain
| ServiceState::NotConnected
| ServiceState::Disconnected => panic!(),
},
_ => {},
}
@@ -355,12 +355,12 @@ async fn reconnect_after_disconnect() {
// In this case the disconnected node does not transit via `ServiceState::NotConnected`
// and stays in `ServiceState::FirstConnec`.
// TODO: update this once the fix is finally merged.
if service1_state == ServiceState::ConnectedAgain &&
service2_state == ServiceState::ConnectedAgain ||
service1_state == ServiceState::ConnectedAgain &&
service2_state == ServiceState::FirstConnec ||
service1_state == ServiceState::FirstConnec &&
service2_state == ServiceState::ConnectedAgain
if service1_state == ServiceState::ConnectedAgain
&& service2_state == ServiceState::ConnectedAgain
|| service1_state == ServiceState::ConnectedAgain
&& service2_state == ServiceState::FirstConnec
|| service1_state == ServiceState::FirstConnec
&& service2_state == ServiceState::ConnectedAgain
{
break;
}
@@ -384,8 +384,8 @@ async fn reconnect_after_disconnect() {
};
match event {
SwarmEvent::Behaviour(NotificationsOut::CustomProtocolOpen { .. }) |
SwarmEvent::Behaviour(NotificationsOut::CustomProtocolClosed { .. }) => panic!(),
SwarmEvent::Behaviour(NotificationsOut::CustomProtocolOpen { .. })
| SwarmEvent::Behaviour(NotificationsOut::CustomProtocolClosed { .. }) => panic!(),
_ => {},
}
}
@@ -263,10 +263,10 @@ where
}
},
st @ NotificationsInSubstreamHandshake::NotSent |
st @ NotificationsInSubstreamHandshake::Sent |
st @ NotificationsInSubstreamHandshake::ClosingInResponseToRemote |
st @ NotificationsInSubstreamHandshake::BothSidesClosed => {
st @ NotificationsInSubstreamHandshake::NotSent
| st @ NotificationsInSubstreamHandshake::Sent
| st @ NotificationsInSubstreamHandshake::ClosingInResponseToRemote
| st @ NotificationsInSubstreamHandshake::BothSidesClosed => {
*this.handshake = st;
return Poll::Ready(Ok(()));
},
@@ -308,8 +308,9 @@ where
},
NotificationsInSubstreamHandshake::Flush => {
match Sink::poll_flush(this.socket.as_mut(), cx)? {
Poll::Ready(()) =>
*this.handshake = NotificationsInSubstreamHandshake::Sent,
Poll::Ready(()) => {
*this.handshake = NotificationsInSubstreamHandshake::Sent
},
Poll::Pending => {
*this.handshake = NotificationsInSubstreamHandshake::Flush;
return Poll::Pending;
@@ -319,9 +320,10 @@ where
NotificationsInSubstreamHandshake::Sent => {
match Stream::poll_next(this.socket.as_mut(), cx) {
Poll::Ready(None) =>
Poll::Ready(None) => {
*this.handshake =
NotificationsInSubstreamHandshake::ClosingInResponseToRemote,
NotificationsInSubstreamHandshake::ClosingInResponseToRemote
},
Poll::Ready(Some(msg)) => {
*this.handshake = NotificationsInSubstreamHandshake::Sent;
return Poll::Ready(Some(msg));
@@ -333,16 +335,18 @@ where
}
},
NotificationsInSubstreamHandshake::ClosingInResponseToRemote =>
NotificationsInSubstreamHandshake::ClosingInResponseToRemote => {
match Sink::poll_close(this.socket.as_mut(), cx)? {
Poll::Ready(()) =>
*this.handshake = NotificationsInSubstreamHandshake::BothSidesClosed,
Poll::Ready(()) => {
*this.handshake = NotificationsInSubstreamHandshake::BothSidesClosed
},
Poll::Pending => {
*this.handshake =
NotificationsInSubstreamHandshake::ClosingInResponseToRemote;
return Poll::Pending;
},
},
}
},
NotificationsInSubstreamHandshake::BothSidesClosed => return Poll::Ready(None),
}
@@ -372,8 +372,9 @@ impl ProtocolController {
/// Process connection event.
fn process_event(&mut self, event: Event) {
match event {
Event::IncomingConnection(peer_id, index) =>
self.on_incoming_connection(peer_id, index),
Event::IncomingConnection(peer_id, index) => {
self.on_incoming_connection(peer_id, index)
},
Event::Dropped(peer_id) => self.on_peer_dropped(peer_id),
}
}
@@ -386,8 +387,9 @@ impl ProtocolController {
Action::SetReservedPeers(peer_ids) => self.on_set_reserved_peers(peer_ids),
Action::SetReservedOnly(reserved_only) => self.on_set_reserved_only(reserved_only),
Action::DisconnectPeer(peer_id) => self.on_disconnect_peer(peer_id),
Action::GetReservedPeers(pending_response) =>
self.on_get_reserved_peers(pending_response),
Action::GetReservedPeers(pending_response) => {
self.on_get_reserved_peers(pending_response)
},
}
}
@@ -516,8 +518,8 @@ impl ProtocolController {
if let PeerState::Connected(direction) = state {
// Disconnect if we're at (or over) the regular node limit
let disconnect = self.reserved_only ||
match direction {
let disconnect = self.reserved_only
|| match direction {
Direction::Inbound => self.num_in >= self.max_in,
Direction::Outbound => self.num_out >= self.max_out,
};
@@ -671,13 +673,14 @@ impl ProtocolController {
*direction = Direction::Inbound;
self.accept_connection(peer_id, incoming_index);
},
PeerState::NotConnected =>
PeerState::NotConnected => {
if self.peer_store.is_banned(&peer_id.into()) {
self.reject_connection(peer_id, incoming_index);
} else {
*state = PeerState::Connected(Direction::Inbound);
self.accept_connection(peer_id, incoming_index);
},
}
},
}
return;
}
@@ -827,8 +830,8 @@ impl ProtocolController {
.outgoing_candidates(available_slots, ignored)
.into_iter()
.filter_map(|peer_id| {
(!self.reserved_nodes.contains_key(&peer_id.into()) &&
!self.nodes.contains_key(&peer_id.into()))
(!self.reserved_nodes.contains_key(&peer_id.into())
&& !self.nodes.contains_key(&peer_id.into()))
.then_some(peer_id)
.or_else(|| {
error!(
@@ -96,10 +96,12 @@ impl From<request_response::OutboundFailure> for OutboundFailure {
match out {
request_response::OutboundFailure::DialFailure => OutboundFailure::DialFailure,
request_response::OutboundFailure::Timeout => OutboundFailure::Timeout,
request_response::OutboundFailure::ConnectionClosed =>
OutboundFailure::ConnectionClosed,
request_response::OutboundFailure::UnsupportedProtocols =>
OutboundFailure::UnsupportedProtocols,
request_response::OutboundFailure::ConnectionClosed => {
OutboundFailure::ConnectionClosed
},
request_response::OutboundFailure::UnsupportedProtocols => {
OutboundFailure::UnsupportedProtocols
},
request_response::OutboundFailure::Io(error) => OutboundFailure::Io(Arc::new(error)),
}
}
@@ -133,8 +135,9 @@ impl From<request_response::InboundFailure> for InboundFailure {
request_response::InboundFailure::ResponseOmission => InboundFailure::ResponseOmission,
request_response::InboundFailure::Timeout => InboundFailure::Timeout,
request_response::InboundFailure::ConnectionClosed => InboundFailure::ConnectionClosed,
request_response::InboundFailure::UnsupportedProtocols =>
InboundFailure::UnsupportedProtocols,
request_response::InboundFailure::UnsupportedProtocols => {
InboundFailure::UnsupportedProtocols
},
request_response::InboundFailure::Io(error) => InboundFailure::Io(Arc::new(error)),
}
}
@@ -434,7 +437,9 @@ impl RequestResponsesBehaviour {
inbound_queue: protocol.inbound_queue,
request_timeout: protocol.request_timeout,
}),
Entry::Occupied(e) => return Err(RegisterError::DuplicateProtocol(e.key().clone())),
Entry::Occupied(e) => {
return Err(RegisterError::DuplicateProtocol(e.key().clone()))
},
};
}
@@ -1086,7 +1091,9 @@ impl Codec for GenericCodec {
Ok(l) => l,
Err(unsigned_varint::io::ReadError::Io(err))
if matches!(err.kind(), io::ErrorKind::UnexpectedEof) =>
return Ok(Err(())),
{
return Ok(Err(()))
},
Err(err) => return Err(io::Error::new(io::ErrorKind::InvalidInput, err)),
};
+60 -40
View File
@@ -529,8 +529,9 @@ where
match result {
Ok(b) => b,
Err(crate::request_responses::RegisterError::DuplicateProtocol(proto)) =>
return Err(Error::DuplicateRequestResponseProtocol { protocol: proto }),
Err(crate::request_responses::RegisterError::DuplicateProtocol(proto)) => {
return Err(Error::DuplicateRequestResponseProtocol { protocol: proto })
},
}
};
@@ -1442,12 +1443,15 @@ where
/// Process the next message coming from the `NetworkService`.
fn handle_worker_message(&mut self, msg: ServiceToWorkerMsg) {
match msg {
ServiceToWorkerMsg::FindClosestPeers(target) =>
self.network_service.behaviour_mut().find_closest_peers(target),
ServiceToWorkerMsg::GetValue(key) =>
self.network_service.behaviour_mut().get_value(key.into()),
ServiceToWorkerMsg::PutValue(key, value) =>
self.network_service.behaviour_mut().put_value(key.into(), value),
ServiceToWorkerMsg::FindClosestPeers(target) => {
self.network_service.behaviour_mut().find_closest_peers(target)
},
ServiceToWorkerMsg::GetValue(key) => {
self.network_service.behaviour_mut().get_value(key.into())
},
ServiceToWorkerMsg::PutValue(key, value) => {
self.network_service.behaviour_mut().put_value(key.into(), value)
},
ServiceToWorkerMsg::PutRecordTo { record, peers, update_local_storage } => self
.network_service
.behaviour_mut()
@@ -1456,14 +1460,18 @@ where
.network_service
.behaviour_mut()
.store_record(key.into(), value, publisher, expires),
ServiceToWorkerMsg::StartProviding(key) =>
self.network_service.behaviour_mut().start_providing(key.into()),
ServiceToWorkerMsg::StopProviding(key) =>
self.network_service.behaviour_mut().stop_providing(&key.into()),
ServiceToWorkerMsg::GetProviders(key) =>
self.network_service.behaviour_mut().get_providers(key.into()),
ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) =>
self.network_service.behaviour_mut().add_known_address(peer_id, addr),
ServiceToWorkerMsg::StartProviding(key) => {
self.network_service.behaviour_mut().start_providing(key.into())
},
ServiceToWorkerMsg::StopProviding(key) => {
self.network_service.behaviour_mut().stop_providing(&key.into())
},
ServiceToWorkerMsg::GetProviders(key) => {
self.network_service.behaviour_mut().get_providers(key.into())
},
ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) => {
self.network_service.behaviour_mut().add_known_address(peer_id, addr)
},
ServiceToWorkerMsg::EventStream(sender) => self.event_streams.push(sender),
ServiceToWorkerMsg::Request {
target,
@@ -1510,18 +1518,23 @@ where
},
Err(err) => {
let reason = match err {
ResponseFailure::Network(InboundFailure::Timeout) =>
Some("timeout"),
ResponseFailure::Network(InboundFailure::Timeout) => {
Some("timeout")
},
ResponseFailure::Network(InboundFailure::UnsupportedProtocols) =>
// `UnsupportedProtocols` is reported for every single
// inbound request whenever a request with an unsupported
// protocol is received. This is not reported in order to
// avoid confusions.
None,
ResponseFailure::Network(InboundFailure::ResponseOmission) =>
Some("busy-omitted"),
ResponseFailure::Network(InboundFailure::ConnectionClosed) =>
Some("connection-closed"),
{
None
},
ResponseFailure::Network(InboundFailure::ResponseOmission) => {
Some("busy-omitted")
},
ResponseFailure::Network(InboundFailure::ConnectionClosed) => {
Some("connection-closed")
},
ResponseFailure::Network(InboundFailure::Io(_)) => Some("io"),
};
@@ -1540,7 +1553,7 @@ where
duration,
result,
..
}) =>
}) => {
if let Some(metrics) = self.metrics.as_ref() {
match result {
Ok(_) => {
@@ -1555,13 +1568,16 @@ where
RequestFailure::UnknownProtocol => "unknown-protocol",
RequestFailure::Refused => "refused",
RequestFailure::Obsolete => "obsolete",
RequestFailure::Network(OutboundFailure::DialFailure) =>
"dial-failure",
RequestFailure::Network(OutboundFailure::DialFailure) => {
"dial-failure"
},
RequestFailure::Network(OutboundFailure::Timeout) => "timeout",
RequestFailure::Network(OutboundFailure::ConnectionClosed) =>
"connection-closed",
RequestFailure::Network(OutboundFailure::UnsupportedProtocols) =>
"unsupported",
RequestFailure::Network(OutboundFailure::ConnectionClosed) => {
"connection-closed"
},
RequestFailure::Network(OutboundFailure::UnsupportedProtocols) => {
"unsupported"
},
RequestFailure::Network(OutboundFailure::Io(_)) => "io",
};
@@ -1571,7 +1587,8 @@ where
.inc();
},
}
},
}
},
SwarmEvent::Behaviour(BehaviourOut::ReputationChanges { peer, changes }) => {
for change in changes {
self.peer_store_handle.report_peer(peer.into(), change);
@@ -1801,18 +1818,19 @@ where
if let Some(metrics) = self.metrics.as_ref() {
let reason = match error {
DialError::Denied { cause } =>
DialError::Denied { cause } => {
if cause.downcast::<Exceeded>().is_ok() {
Some("limit-reached")
} else {
None
},
}
},
DialError::LocalPeerId { .. } => Some("local-peer-id"),
DialError::WrongPeerId { .. } => Some("invalid-peer-id"),
DialError::Transport(_) => Some("transport-error"),
DialError::NoAddresses |
DialError::DialPeerConditionFalse(_) |
DialError::Aborted => None, // ignore them
DialError::NoAddresses
| DialError::DialPeerConditionFalse(_)
| DialError::Aborted => None, // ignore them
};
if let Some(reason) = reason {
metrics.pending_connections_errors_total.with_label_values(&[reason]).inc();
@@ -1840,14 +1858,16 @@ where
);
if let Some(metrics) = self.metrics.as_ref() {
let reason = match error {
ListenError::Denied { cause } =>
ListenError::Denied { cause } => {
if cause.downcast::<Exceeded>().is_ok() {
Some("limit-reached")
} else {
None
},
ListenError::WrongPeerId { .. } | ListenError::LocalPeerId { .. } =>
Some("invalid-peer-id"),
}
},
ListenError::WrongPeerId { .. } | ListenError::LocalPeerId { .. } => {
Some("invalid-peer-id")
},
ListenError::Transport(_) => Some("transport-error"),
ListenError::Aborted => None, // ignore it
};
@@ -205,8 +205,8 @@ impl OutChannels {
);
}
sender.warning_fired = SenderWarningState::FiredFull;
} else if sender.warning_fired == SenderWarningState::FiredFull &&
current_pending < sender.queue_size_warning.wrapping_div(2)
} else if sender.warning_fired == SenderWarningState::FiredFull
&& current_pending < sender.queue_size_warning.wrapping_div(2)
{
sender.warning_fired = SenderWarningState::FiredFree;
debug!(
@@ -304,7 +304,7 @@ impl Metrics {
self.events_total.with_label_values(&[protocol_label, "sent", name]).inc();
});
},
Event::NotificationsReceived { messages, .. } =>
Event::NotificationsReceived { messages, .. } => {
for (protocol, message) in messages {
format_label("notif-", protocol, |protocol_label| {
self.events_total.with_label_values(&[protocol_label, "sent", name]).inc();
@@ -312,7 +312,8 @@ impl Metrics {
self.notifications_sizes
.with_label_values(&[protocol, "sent", name])
.inc_by(u64::try_from(message.len()).unwrap_or(u64::MAX));
},
}
},
}
}
@@ -331,7 +332,7 @@ impl Metrics {
self.events_total.with_label_values(&[protocol_label, "received", name]).inc();
});
},
Event::NotificationsReceived { messages, .. } =>
Event::NotificationsReceived { messages, .. } => {
for (protocol, message) in messages {
format_label("notif-", protocol, |protocol_label| {
self.events_total
@@ -341,7 +342,8 @@ impl Metrics {
self.notifications_sizes
.with_label_values(&[protocol, "received", name])
.inc_by(u64::try_from(message.len()).unwrap_or(u64::MAX));
},
}
},
}
}
}
@@ -503,10 +503,12 @@ where
fn on_handle_statement_import(&mut self, who: PeerId, import: &SubmitResult) {
match import {
SubmitResult::New(NetworkPriority::High) =>
self.network.report_peer(who, rep::EXCELLENT_STATEMENT),
SubmitResult::New(NetworkPriority::Low) =>
self.network.report_peer(who, rep::GOOD_STATEMENT),
SubmitResult::New(NetworkPriority::High) => {
self.network.report_peer(who, rep::EXCELLENT_STATEMENT)
},
SubmitResult::New(NetworkPriority::Low) => {
self.network.report_peer(who, rep::GOOD_STATEMENT)
},
SubmitResult::Known => self.network.report_peer(who, rep::ANY_STATEMENT_REFUND),
SubmitResult::KnownExpired => {},
SubmitResult::Ignored => {},
@@ -75,9 +75,9 @@ pub(crate) enum BlockAnnounceValidationResult<H> {
impl<H> BlockAnnounceValidationResult<H> {
fn peer_id(&self) -> &PeerId {
match self {
BlockAnnounceValidationResult::Failure { peer_id, .. } |
BlockAnnounceValidationResult::Process { peer_id, .. } |
BlockAnnounceValidationResult::Skip { peer_id } => peer_id,
BlockAnnounceValidationResult::Failure { peer_id, .. }
| BlockAnnounceValidationResult::Process { peer_id, .. }
| BlockAnnounceValidationResult::Skip { peer_id } => peer_id,
}
}
}
@@ -262,12 +262,13 @@ impl<B: BlockT> BlockAnnounceValidator<B> {
);
},
Entry::Occupied(mut entry) => match entry.get().checked_sub(1) {
Some(value) =>
Some(value) => {
if value == 0 {
entry.remove();
} else {
*entry.get_mut() = value;
},
}
},
None => {
entry.remove();
@@ -400,8 +400,9 @@ where
let body = if get_body {
match self.client.block_body(hash)? {
Some(mut extrinsics) =>
extrinsics.iter_mut().map(|extrinsic| extrinsic.encode()).collect(),
Some(mut extrinsics) => {
extrinsics.iter_mut().map(|extrinsic| extrinsic.encode()).collect()
},
None => {
log::trace!(target: LOG_TARGET, "Missing data for block request.");
break;
@@ -441,9 +442,9 @@ where
indexed_body,
};
let new_total_size = total_size +
block_data.body.iter().map(|ex| ex.len()).sum::<usize>() +
block_data.indexed_body.iter().map(|ex| ex.len()).sum::<usize>();
let new_total_size = total_size
+ block_data.body.iter().map(|ex| ex.len()).sum::<usize>()
+ block_data.indexed_body.iter().map(|ex| ex.len()).sum::<usize>();
// Send at least one block, but make sure to not exceed the limit.
if !blocks.is_empty() && new_total_size > MAX_BODY_BYTES {
+14 -8
View File
@@ -136,23 +136,29 @@ impl<B: BlockT> BlockCollection<B> {
// the range start.
(Some((start, &BlockRangeState::Downloading { ref len, downloading })), _)
if downloading < max_parallel && *start >= first_different =>
(*start..*start + *len, downloading),
{
(*start..*start + *len, downloading)
},
// If there is a gap between ranges requested, download this gap unless the peer
// has common number above the gap start
(Some((start, r)), Some((next_start, _)))
if *start + r.len() < *next_start &&
*start + r.len() >= first_different =>
(*start + r.len()..cmp::min(*next_start, *start + r.len() + count), 0),
if *start + r.len() < *next_start
&& *start + r.len() >= first_different =>
{
(*start + r.len()..cmp::min(*next_start, *start + r.len() + count), 0)
},
// Download `count` blocks after the last range requested unless the peer
// has common number above this new range
(Some((start, r)), None) if *start + r.len() >= first_different =>
(*start + r.len()..*start + r.len() + count, 0),
(Some((start, r)), None) if *start + r.len() >= first_different => {
(*start + r.len()..*start + r.len() + count, 0)
},
// If there are no ranges currently requested, download `count` blocks after
// `common` number
(None, None) => (first_different..first_different + count, 0),
// If the first range starts above `common + 1`, download the gap at the start
(None, Some((start, _))) if *start > first_different =>
(first_different..cmp::min(first_different + count, *start), 0),
(None, Some((start, _))) if *start > first_different => {
(first_different..cmp::min(first_different + count, *start), 0)
},
// Move on to the next range pair
_ => {
prev = next;
+29 -26
View File
@@ -290,8 +290,8 @@ where
where
N: NetworkBackend<B, <B as BlockT>::Hash>,
{
let cache_capacity = (net_config.network_config.default_peers_set.in_peers +
net_config.network_config.default_peers_set.out_peers)
let cache_capacity = (net_config.network_config.default_peers_set.in_peers
+ net_config.network_config.default_peers_set.out_peers)
.max(1);
let important_peers = {
let mut imp_p = HashSet::new();
@@ -328,8 +328,8 @@ where
let default_peers_set_num_full =
net_config.network_config.default_peers_set_num_full as usize;
let default_peers_set_num_light = {
let total = net_config.network_config.default_peers_set.out_peers +
net_config.network_config.default_peers_set.in_peers;
let total = net_config.network_config.default_peers_set.out_peers
+ net_config.network_config.default_peers_set.in_peers;
total.saturating_sub(net_config.network_config.default_peers_set_num_full) as usize
};
@@ -663,10 +663,12 @@ where
}
self.event_streams.push(tx);
},
ToServiceCommand::RequestJustification(hash, number) =>
self.strategy.request_justification(&hash, number),
ToServiceCommand::ClearJustificationRequests =>
self.strategy.clear_justification_requests(),
ToServiceCommand::RequestJustification(hash, number) => {
self.strategy.request_justification(&hash, number)
},
ToServiceCommand::ClearJustificationRequests => {
self.strategy.clear_justification_requests()
},
ToServiceCommand::BlocksProcessed(imported, count, results) => {
self.strategy.on_blocks_processed(imported, count, results);
},
@@ -734,8 +736,9 @@ where
self.peers.iter().map(|(peer_id, peer)| (*peer_id, peer.info)).collect();
let _ = tx.send(peers_info);
},
ToServiceCommand::OnBlockFinalized(hash, header) =>
self.strategy.on_block_finalized(&hash, *header.number()),
ToServiceCommand::OnBlockFinalized(hash, header) => {
self.strategy.on_block_finalized(&hash, *header.number())
},
}
}
@@ -815,9 +818,9 @@ where
log::debug!(target: LOG_TARGET, "{peer_id} disconnected");
}
if !self.default_peers_set_no_slot_connected_peers.remove(&peer_id) &&
info.inbound &&
info.info.roles.is_full()
if !self.default_peers_set_no_slot_connected_peers.remove(&peer_id)
&& info.inbound
&& info.info.roles.is_full()
{
match self.num_in_peers.checked_sub(1) {
Some(value) => {
@@ -918,21 +921,21 @@ where
let no_slot_peer = self.default_peers_set_no_slot_peers.contains(&peer_id);
let this_peer_reserved_slot: usize = if no_slot_peer { 1 } else { 0 };
if handshake.roles.is_full() &&
self.strategy.num_peers() >=
self.default_peers_set_num_full +
self.default_peers_set_no_slot_connected_peers.len() +
this_peer_reserved_slot
if handshake.roles.is_full()
&& self.strategy.num_peers()
>= self.default_peers_set_num_full
+ self.default_peers_set_no_slot_connected_peers.len()
+ this_peer_reserved_slot
{
log::debug!(target: LOG_TARGET, "Too many full nodes, rejecting {peer_id}");
return Err(false);
}
// make sure to accept no more than `--in-peers` many full nodes
if !no_slot_peer &&
handshake.roles.is_full() &&
direction.is_inbound() &&
self.num_in_peers == self.max_in_peers
if !no_slot_peer
&& handshake.roles.is_full()
&& direction.is_inbound()
&& self.num_in_peers == self.max_in_peers
{
log::debug!(target: LOG_TARGET, "All inbound slots have been consumed, rejecting {peer_id}");
return Err(false);
@@ -942,8 +945,8 @@ where
//
// `ChainSync` only accepts full peers whereas `SyncingEngine` accepts both full and light
// peers. Verify that there is a slot in `SyncingEngine` for the inbound light peer
if handshake.roles.is_light() &&
(self.peers.len() - self.strategy.num_peers()) >= self.default_peers_set_num_light
if handshake.roles.is_light()
&& (self.peers.len() - self.strategy.num_peers()) >= self.default_peers_set_num_light
{
log::debug!(target: LOG_TARGET, "Too many light nodes, rejecting {peer_id}");
return Err(false);
@@ -1034,8 +1037,8 @@ where
self.network_service
.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
},
RequestFailure::Network(OutboundFailure::ConnectionClosed) |
RequestFailure::NotConnected => {
RequestFailure::Network(OutboundFailure::ConnectionClosed)
| RequestFailure::NotConnected => {
self.network_service
.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
},
@@ -119,12 +119,15 @@ impl NetworkServiceProvider {
while let Some(inner) = rx.next().await {
match inner {
ToServiceCommand::DisconnectPeer(peer, protocol_name) =>
service.disconnect_peer(peer, protocol_name),
ToServiceCommand::ReportPeer(peer, reputation_change) =>
service.report_peer(peer, reputation_change),
ToServiceCommand::StartRequest(peer, protocol, request, tx, connect) =>
service.start_request(peer, protocol, request, None, tx, connect),
ToServiceCommand::DisconnectPeer(peer, protocol_name) => {
service.disconnect_peer(peer, protocol_name)
},
ToServiceCommand::ReportPeer(peer, reputation_change) => {
service.report_peer(peer, reputation_change)
},
ToServiceCommand::StartRequest(peer, protocol, request, tx, connect) => {
service.start_request(peer, protocol, request, None, tx, connect)
},
}
}
}
@@ -441,8 +441,8 @@ where
if is_best {
if known && self.best_queued_number >= number {
self.update_peer_common_number(&peer_id, number);
} else if announce.header.parent_hash() == &self.best_queued_hash ||
known_parent && self.best_queued_number >= number
} else if announce.header.parent_hash() == &self.best_queued_hash
|| known_parent && self.best_queued_number >= number
{
self.update_peer_common_number(&peer_id, number.saturating_sub(One::one()));
}
@@ -727,7 +727,7 @@ where
self.complete_gap_if_target(number);
},
Err(BlockImportError::IncompleteHeader(peer_id)) =>
Err(BlockImportError::IncompleteHeader(peer_id)) => {
if let Some(peer) = peer_id {
warn!(
target: LOG_TARGET,
@@ -736,7 +736,8 @@ where
self.actions
.push(SyncingAction::DropPeer(BadPeer(peer, rep::INCOMPLETE_HEADER)));
self.restart();
},
}
},
Err(BlockImportError::VerificationFailed(peer_id, e)) => {
let extra_message = peer_id
.map_or_else(|| "".into(), |peer| format!(" received from ({peer})"));
@@ -753,14 +754,15 @@ where
self.restart();
},
Err(BlockImportError::BadBlock(peer_id)) =>
Err(BlockImportError::BadBlock(peer_id)) => {
if let Some(peer) = peer_id {
warn!(
target: LOG_TARGET,
"💔 Block {hash:?} received from peer {peer} has been blacklisted",
);
self.actions.push(SyncingAction::DropPeer(BadPeer(peer, rep::BAD_BLOCK)));
},
}
},
Err(BlockImportError::MissingState) => {
// This may happen if the chain we were requesting upon has been discarded
// in the meantime because other chain has been finalized.
@@ -1096,9 +1098,9 @@ where
Ok(req)
},
Ok(BlockStatus::Queued) |
Ok(BlockStatus::InChainWithState) |
Ok(BlockStatus::InChainPruned) => {
Ok(BlockStatus::Queued)
| Ok(BlockStatus::InChainWithState)
| Ok(BlockStatus::InChainPruned) => {
debug!(
target: LOG_TARGET,
"New peer {peer_id} with known best hash {best_hash} ({best_number}).",
@@ -1278,8 +1280,8 @@ where
},
};
if matching_hash.is_some() {
if *start < self.best_queued_number &&
self.best_queued_number <= peer.best_number
if *start < self.best_queued_number
&& self.best_queued_number <= peer.best_number
{
// We've made progress on this chain since the search was started.
// Opportunistically set common number to updated number
@@ -1335,8 +1337,8 @@ where
matching_hash,
peer.common_number,
);
if peer.common_number < peer.best_number &&
peer.best_number < self.best_queued_number
if peer.common_number < peer.best_number
&& peer.best_number < self.best_queued_number
{
trace!(
target: LOG_TARGET,
@@ -1364,9 +1366,9 @@ where
return Ok(());
}
},
PeerSyncState::Available |
PeerSyncState::DownloadingJustification(..) |
PeerSyncState::DownloadingState => Vec::new(),
PeerSyncState::Available
| PeerSyncState::DownloadingJustification(..)
| PeerSyncState::DownloadingState => Vec::new(),
}
} else {
// When request.is_none() this is a block announcement. Just accept blocks.
@@ -1525,14 +1527,17 @@ where
fn required_block_attributes(&self) -> BlockAttributes {
match self.mode {
ChainSyncMode::Full =>
BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION | BlockAttributes::BODY,
ChainSyncMode::LightState { storage_chain_mode: false, .. } =>
BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION | BlockAttributes::BODY,
ChainSyncMode::LightState { storage_chain_mode: true, .. } =>
BlockAttributes::HEADER |
BlockAttributes::JUSTIFICATION |
BlockAttributes::INDEXED_BODY,
ChainSyncMode::Full => {
BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION | BlockAttributes::BODY
},
ChainSyncMode::LightState { storage_chain_mode: false, .. } => {
BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION | BlockAttributes::BODY
},
ChainSyncMode::LightState { storage_chain_mode: true, .. } => {
BlockAttributes::HEADER
| BlockAttributes::JUSTIFICATION
| BlockAttributes::INDEXED_BODY
},
}
}
@@ -1653,11 +1658,11 @@ where
PeerSyncState::Available => {
self.add_peer(peer_id, peer_sync.best_hash, peer_sync.best_number);
},
PeerSyncState::AncestorSearch { .. } |
PeerSyncState::DownloadingNew(_) |
PeerSyncState::DownloadingStale(_) |
PeerSyncState::DownloadingGap(_) |
PeerSyncState::DownloadingState => {
PeerSyncState::AncestorSearch { .. }
| PeerSyncState::DownloadingNew(_)
| PeerSyncState::DownloadingStale(_)
| PeerSyncState::DownloadingGap(_)
| PeerSyncState::DownloadingState => {
// Cancel a request first, as `add_peer` may generate a new request.
self.actions
.push(SyncingAction::CancelRequest { peer_id, key: Self::STRATEGY_KEY });
@@ -1699,8 +1704,8 @@ where
self.best_queued_hash = info.best_hash;
self.best_queued_number = info.best_number;
if self.mode == ChainSyncMode::Full &&
self.client.block_status(info.best_hash)? != BlockStatus::InChainWithState
if self.mode == ChainSyncMode::Full
&& self.client.block_status(info.best_hash)? != BlockStatus::InChainWithState
{
self.import_existing = true;
// Latest state is missing, start with the last finalized state or genesis instead.
@@ -1835,9 +1840,9 @@ where
.peers
.iter_mut()
.filter_map(move |(&id, peer)| {
if !peer.state.is_available() ||
!allowed_requests.contains(&id) ||
!disconnected_peers.is_peer_available(&id)
if !peer.state.is_available()
|| !allowed_requests.contains(&id)
|| !disconnected_peers.is_peer_available(&id)
{
return None;
}
@@ -1847,11 +1852,11 @@ where
// common number is smaller than the last finalized block number, we should do an
// ancestor search to find a better common block. If the queue is full we wait till
// all blocks are imported though.
if best_queued.saturating_sub(peer.common_number) >
MAX_BLOCKS_TO_LOOK_BACKWARDS.into() &&
best_queued < peer.best_number &&
peer.common_number < last_finalized &&
queue_blocks.len() <= MAJOR_SYNC_BLOCKS as usize
if best_queued.saturating_sub(peer.common_number)
> MAX_BLOCKS_TO_LOOK_BACKWARDS.into()
&& best_queued < peer.best_number
&& peer.common_number < last_finalized
&& queue_blocks.len() <= MAJOR_SYNC_BLOCKS as usize
{
trace!(
target: LOG_TARGET,
@@ -1947,8 +1952,8 @@ where
if self.allowed_requests.is_empty() {
return None;
}
if self.state_sync.is_some() &&
self.peers.iter().any(|(_, peer)| peer.state == PeerSyncState::DownloadingState)
if self.state_sync.is_some()
&& self.peers.iter().any(|(_, peer)| peer.state == PeerSyncState::DownloadingState)
{
// Only one pending state request is allowed.
return None;
@@ -1959,9 +1964,9 @@ where
}
for (id, peer) in self.peers.iter_mut() {
if peer.state.is_available() &&
peer.common_number >= sync.target_number() &&
self.disconnected_peers.is_peer_available(&id)
if peer.state.is_available()
&& peer.common_number >= sync.target_number()
&& self.disconnected_peers.is_peer_available(&id)
{
peer.state = PeerSyncState::DownloadingState;
let request = sync.next_request();
@@ -2286,8 +2291,8 @@ fn fork_sync_request<B: BlockT>(
}
// Download the fork only if it is behind or not too far ahead our tip of the chain
// Otherwise it should be downloaded in full sync mode.
if r.number <= best_num ||
(r.number - best_num).saturated_into::<u32>() < max_blocks_per_request as u32
if r.number <= best_num
|| (r.number - best_num).saturated_into::<u32>() < max_blocks_per_request as u32
{
let parent_status = r.parent_hash.as_ref().map_or(BlockStatus::Unknown, check_block);
let count = if parent_status == BlockStatus::Unknown {
@@ -2378,8 +2383,8 @@ pub fn validate_blocks<Block: BlockT>(
return Err(BadPeer(*peer_id, rep::NOT_REQUESTED));
}
if request.fields.contains(BlockAttributes::HEADER) &&
blocks.iter().any(|b| b.header.is_none())
if request.fields.contains(BlockAttributes::HEADER)
&& blocks.iter().any(|b| b.header.is_none())
{
trace!(
target: LOG_TARGET,
@@ -211,9 +211,9 @@ fn restart_doesnt_affect_peers_downloading_finality_data() {
// the justification request should be scheduled to the
// new peer which is at the given block
assert!(sync.justification_requests().iter().any(|(p, r)| {
*p == peer_id3 &&
r.fields == BlockAttributes::JUSTIFICATION &&
r.from == FromBlock::Hash(b1_hash)
*p == peer_id3
&& r.fields == BlockAttributes::JUSTIFICATION
&& r.from == FromBlock::Hash(b1_hash)
}));
assert_eq!(
@@ -47,8 +47,9 @@ use std::{any::Any, collections::HashMap, sync::Arc};
fn chain_sync_mode(sync_mode: SyncMode) -> ChainSyncMode {
match sync_mode {
SyncMode::Full => ChainSyncMode::Full,
SyncMode::LightState { skip_proofs, storage_chain_mode } =>
ChainSyncMode::LightState { skip_proofs, storage_chain_mode },
SyncMode::LightState { skip_proofs, storage_chain_mode } => {
ChainSyncMode::LightState { skip_proofs, storage_chain_mode }
},
SyncMode::Warp => ChainSyncMode::Full,
}
}
@@ -188,7 +189,7 @@ where
response: Box<dyn Any + Send>,
) {
match key {
StateStrategy::<B>::STRATEGY_KEY =>
StateStrategy::<B>::STRATEGY_KEY => {
if let Some(state) = &mut self.state {
let Ok(response) = response.downcast::<Vec<u8>>() else {
warn!(target: LOG_TARGET, "Failed to downcast state response");
@@ -206,8 +207,9 @@ where
or corresponding strategy is not active.",
);
debug_assert!(false);
},
WarpSync::<B, Client>::STRATEGY_KEY =>
}
},
WarpSync::<B, Client>::STRATEGY_KEY => {
if let Some(warp) = &mut self.warp {
warp.on_generic_response(peer_id, protocol_name, response);
} else {
@@ -217,8 +219,9 @@ where
or warp strategy is not active",
);
debug_assert!(false);
},
ChainSync::<B, Client>::STRATEGY_KEY =>
}
},
ChainSync::<B, Client>::STRATEGY_KEY => {
if let Some(chain_sync) = &mut self.chain_sync {
chain_sync.on_generic_response(peer_id, key, protocol_name, response);
} else {
@@ -228,7 +231,8 @@ where
or corresponding strategy is not active.",
);
debug_assert!(false);
},
}
},
key => {
warn!(
target: LOG_TARGET,
@@ -268,9 +272,9 @@ where
}
fn is_major_syncing(&self) -> bool {
self.warp.is_some() ||
self.state.is_some() ||
match self.chain_sync {
self.warp.is_some()
|| self.state.is_some()
|| match self.chain_sync {
Some(ref s) => s.status().state.is_major_syncing(),
None => unreachable!("At least one syncing strategy is active; qed"),
}
@@ -322,9 +322,9 @@ impl<B: BlockT> StateStrategy<B> {
// Find a random peer that is synced as much as peer majority and is above
// `min_best_number`.
for (peer_id, peer) in self.peers.iter_mut() {
if peer.state.is_available() &&
peer.best_number >= threshold &&
self.disconnected_peers.is_peer_available(peer_id)
if peer.state.is_available()
&& peer.best_number >= threshold
&& self.disconnected_peers.is_peer_available(peer_id)
{
peer.state = new_state;
return Some(*peer_id);
@@ -261,8 +261,9 @@ where
}
let phase = match warp_sync_config {
WarpSyncConfig::WithProvider(warp_sync_provider) =>
Phase::WaitingForPeers { warp_sync_provider },
WarpSyncConfig::WithProvider(warp_sync_provider) => {
Phase::WaitingForPeers { warp_sync_provider }
},
WarpSyncConfig::WithTarget(target_header) => Phase::TargetBlock(target_header),
};
@@ -558,9 +559,9 @@ where
// Find a random peer that is synced as much as peer majority and is above
// `min_best_number`.
for (peer_id, peer) in self.peers.iter_mut() {
if peer.state.is_available() &&
peer.best_number >= threshold &&
self.disconnected_peers.is_peer_available(peer_id)
if peer.state.is_available()
&& peer.best_number >= threshold
&& self.disconnected_peers.is_peer_available(peer_id)
{
peer.state = new_state;
return Some(*peer_id);
@@ -632,9 +633,9 @@ where
peer_id,
BlockRequest::<B> {
id: 0,
fields: BlockAttributes::HEADER |
BlockAttributes::BODY |
BlockAttributes::JUSTIFICATION,
fields: BlockAttributes::HEADER
| BlockAttributes::BODY
| BlockAttributes::JUSTIFICATION,
from: FromBlock::Hash(target_hash),
direction: Direction::Ascending,
max: Some(1),
+17 -12
View File
@@ -259,7 +259,7 @@ async fn test_once() {
let state = known_nodes.get_mut(&peer_id).unwrap();
match *state {
State::Incoming(incoming_index) =>
State::Incoming(incoming_index) => {
if n.0 < incoming_index.0 {
log::info!(
"Ignoring obsolete Accept for {:?} while awaiting {:?} for peer {}",
@@ -271,7 +271,8 @@ async fn test_once() {
"Received {:?} while awaiting {:?} for peer {}",
n, incoming_index, peer_id,
);
},
}
},
_ => {},
}
@@ -290,7 +291,7 @@ async fn test_once() {
let state = known_nodes.get_mut(&peer_id).unwrap();
match *state {
State::Incoming(incoming_index) =>
State::Incoming(incoming_index) => {
if n.0 < incoming_index.0 {
log::info!(
"Ignoring obsolete Reject for {:?} while awaiting {:?} for peer {}",
@@ -302,7 +303,8 @@ async fn test_once() {
"Received {:?} while awaiting {:?} for peer {}",
n, incoming_index, peer_id,
);
},
}
},
_ => {},
}
@@ -326,15 +328,16 @@ async fn test_once() {
},
// If we generate 2, adjust a random reputation.
2 =>
2 => {
if let Some(id) = known_nodes.keys().choose(&mut rng) {
let val = Uniform::new_inclusive(i32::MIN, i32::MAX).sample(&mut rng);
let peer: pezsc_network_types::PeerId = id.into();
peer_store_handle.report_peer(peer, ReputationChange::new(val, ""));
},
}
},
// If we generate 3, disconnect from a random node.
3 =>
3 => {
if let Some(id) = connected_nodes.iter().choose(&mut rng).cloned() {
log::info!("Disconnected from {}", id);
connected_nodes.remove(&id);
@@ -347,15 +350,16 @@ async fn test_once() {
current_peer = Some(id);
current_event = Some(Event::Disconnected);
},
}
},
// If we generate 4, connect to a random node.
4 => {
if let Some(id) = known_nodes
.keys()
.filter(|n| {
incoming_nodes.values().all(|m| m != *n) &&
!connected_nodes.contains(*n)
incoming_nodes.values().all(|m| m != *n)
&& !connected_nodes.contains(*n)
})
.choose(&mut rng)
.cloned()
@@ -395,12 +399,13 @@ async fn test_once() {
reserved_nodes.insert(*id);
}
},
8 =>
8 => {
if let Some(id) = reserved_nodes.iter().choose(&mut rng).cloned() {
log::info!("Remove reserved: {}", id);
reserved_nodes.remove(&id);
protocol_handle.remove_reserved_peer(id);
},
}
},
_ => unreachable!(),
}
+4 -4
View File
@@ -768,8 +768,8 @@ pub trait TestNetFactory: Default + Sized + Send {
*genesis_extra_storage = storage;
}
if !config.force_genesis &&
matches!(config.sync_mode, SyncMode::LightState { .. } | SyncMode::Warp)
if !config.force_genesis
&& matches!(config.sync_mode, SyncMode::LightState { .. } | SyncMode::Warp)
{
test_client_builder = test_client_builder.set_no_genesis();
}
@@ -1040,8 +1040,8 @@ pub trait TestNetFactory: Default + Sized + Send {
let peers = self.peers_mut();
for peer in peers {
if peer.sync_service.is_major_syncing() ||
peer.sync_service.status().await.unwrap().queued_blocks != 0
if peer.sync_service.is_major_syncing()
|| peer.sync_service.status().await.unwrap().queued_blocks != 0
{
return false;
}
@@ -392,10 +392,12 @@ async fn notifications_state_consistent() {
// forever while nothing at all happens on the network.
let continue_test = futures_timer::Delay::new(Duration::from_millis(20));
match future::select(future::select(next1, next2), continue_test).await {
future::Either::Left((future::Either::Left((Some(ev), _)), _)) =>
future::Either::Left(ev),
future::Either::Left((future::Either::Right((Some(ev), _)), _)) =>
future::Either::Right(ev),
future::Either::Left((future::Either::Left((Some(ev), _)), _)) => {
future::Either::Left(ev)
},
future::Either::Left((future::Either::Right((Some(ev), _)), _)) => {
future::Either::Right(ev)
},
future::Either::Right(_) => continue,
_ => break,
}
+16 -16
View File
@@ -44,9 +44,9 @@ async fn sync_peers_works() {
pezsp_tracing::try_init_simple();
let mut net = TestNet::new(3);
while net.peer(0).num_peers().await != 2 &&
net.peer(1).num_peers().await != 2 &&
net.peer(2).num_peers().await != 2
while net.peer(0).num_peers().await != 2
&& net.peer(1).num_peers().await != 2
&& net.peer(2).num_peers().await != 2
{
futures::future::poll_fn::<(), _>(|cx| {
net.poll(cx);
@@ -280,13 +280,13 @@ async fn sync_justifications() {
net.poll(cx);
for height in (10..21).step_by(5) {
if net.peer(0).client().justifications(hashes[height - 1]).unwrap() !=
Some(Justifications::from((*b"FRNK", Vec::new())))
if net.peer(0).client().justifications(hashes[height - 1]).unwrap()
!= Some(Justifications::from((*b"FRNK", Vec::new())))
{
return Poll::Pending;
}
if net.peer(1).client().justifications(hashes[height - 1]).unwrap() !=
Some(Justifications::from((*b"FRNK", Vec::new())))
if net.peer(1).client().justifications(hashes[height - 1]).unwrap()
!= Some(Justifications::from((*b"FRNK", Vec::new())))
{
return Poll::Pending;
}
@@ -320,10 +320,10 @@ async fn sync_justifications_across_forks() {
futures::future::poll_fn::<(), _>(|cx| {
net.poll(cx);
if net.peer(0).client().justifications(f1_best).unwrap() ==
Some(Justifications::from((*b"FRNK", Vec::new()))) &&
net.peer(1).client().justifications(f1_best).unwrap() ==
Some(Justifications::from((*b"FRNK", Vec::new())))
if net.peer(0).client().justifications(f1_best).unwrap()
== Some(Justifications::from((*b"FRNK", Vec::new())))
&& net.peer(1).client().justifications(f1_best).unwrap()
== Some(Justifications::from((*b"FRNK", Vec::new())))
{
Poll::Ready(())
} else {
@@ -896,9 +896,9 @@ async fn block_announce_data_is_propagated() {
});
// Wait until peer 1 is connected to both nodes.
while net.peer(1).num_peers().await != 2 ||
net.peer(0).num_peers().await != 1 ||
net.peer(2).num_peers().await != 1
while net.peer(1).num_peers().await != 2
|| net.peer(0).num_peers().await != 1
|| net.peer(2).num_peers().await != 1
{
futures::future::poll_fn::<(), _>(|cx| {
net.poll(cx);
@@ -1000,8 +1000,8 @@ async fn multiple_requests_are_accepted_as_long_as_they_are_not_fulfilled() {
futures::future::poll_fn::<(), _>(|cx| {
net.poll(cx);
if net.peer(1).client().justifications(hashof10).unwrap() !=
Some(Justifications::from((*b"FRNK", Vec::new())))
if net.peer(1).client().justifications(hashof10).unwrap()
!= Some(Justifications::from((*b"FRNK", Vec::new())))
{
return Poll::Pending;
}
@@ -443,8 +443,9 @@ where
fn on_handle_transaction_import(&mut self, who: PeerId, import: TransactionImport) {
match import {
TransactionImport::KnownGood =>
self.network.report_peer(who, rep::ANY_TRANSACTION_REFUND),
TransactionImport::KnownGood => {
self.network.report_peer(who, rep::ANY_TRANSACTION_REFUND)
},
TransactionImport::NewGood => self.network.report_peer(who, rep::GOOD_TRANSACTION),
TransactionImport::Bad => self.network.report_peer(who, rep::BAD_TRANSACTION),
TransactionImport::None => {},
@@ -116,8 +116,9 @@ impl<'a> From<LiteP2pProtocol<'a>> for Protocol<'a> {
LiteP2pProtocol::P2pWebSocketStar => Protocol::P2pWebSocketStar,
LiteP2pProtocol::Memory(port) => Protocol::Memory(port),
LiteP2pProtocol::Onion(str, port) => Protocol::Onion(str, port),
LiteP2pProtocol::Onion3(addr) =>
Protocol::Onion3(Cow::Owned(*addr.hash()), addr.port()),
LiteP2pProtocol::Onion3(addr) => {
Protocol::Onion3(Cow::Owned(*addr.hash()), addr.port())
},
LiteP2pProtocol::P2p(multihash) => Protocol::P2p(multihash.into()),
LiteP2pProtocol::P2pCircuit => Protocol::P2pCircuit,
LiteP2pProtocol::Quic => Protocol::Quic,
@@ -77,8 +77,9 @@ impl PeerId {
pub fn from_multihash(multihash: Multihash) -> Result<PeerId, Multihash> {
match Code::try_from(multihash.code()) {
Ok(Code::Sha2_256) => Ok(PeerId { multihash }),
Ok(Code::Identity) if multihash.digest().len() <= MAX_INLINE_KEY_LENGTH =>
Ok(PeerId { multihash }),
Ok(Code::Identity) if multihash.digest().len() <= MAX_INLINE_KEY_LENGTH => {
Ok(PeerId { multihash })
},
_ => Err(multihash),
}
}