pub struct NetworkWorker<B, H, Client>where
    B: BlockT + 'static,
    H: ExHashT,
    Client: HeaderBackend<B> + 'static,
{ /* private fields */ }
Expand description

Main network worker. Must be polled in order for the network to advance.

You are encouraged to poll this in a separate background thread or task.

Implementations§

Creates the network service.

Returns a NetworkWorker that implements Future and must be regularly polled in order for the network processing to advance. From it, you can extract a NetworkService using worker.service(). The NetworkService can be shared through the codebase.

High-level network status information.

Examples found in repository?
src/service.rs (line 1381)
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
	fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
		let this = &mut *self;

		// At the time of writing of this comment, due to a high volume of messages, the network
		// worker sometimes takes a long time to process the loop below. When that happens, the
		// rest of the polling is frozen. In order to avoid negative side-effects caused by this
		// freeze, a limit to the number of iterations is enforced below. If the limit is reached,
		// the task is interrupted then scheduled again.
		//
		// This allows for a more even distribution in the time taken by each sub-part of the
		// polling.
		let mut num_iterations = 0;
		loop {
			num_iterations += 1;
			if num_iterations >= 100 {
				cx.waker().wake_by_ref();
				break
			}

			// Process the next message coming from the `NetworkService`.
			let msg = match this.from_service.poll_next_unpin(cx) {
				Poll::Ready(Some(msg)) => msg,
				Poll::Ready(None) => return Poll::Ready(()),
				Poll::Pending => break,
			};
			match msg {
				ServiceToWorkerMsg::AnnounceBlock(hash, data) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.announce_block(hash, data),
				ServiceToWorkerMsg::GetValue(key) =>
					this.network_service.behaviour_mut().get_value(key),
				ServiceToWorkerMsg::PutValue(key, value) =>
					this.network_service.behaviour_mut().put_value(key, value),
				ServiceToWorkerMsg::SetReservedOnly(reserved_only) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.set_reserved_only(reserved_only),
				ServiceToWorkerMsg::SetReserved(peers) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.set_reserved_peers(peers),
				ServiceToWorkerMsg::SetPeersetReserved(protocol, peers) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.set_reserved_peerset_peers(protocol, peers),
				ServiceToWorkerMsg::AddReserved(peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.add_reserved_peer(peer_id),
				ServiceToWorkerMsg::RemoveReserved(peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.remove_reserved_peer(peer_id),
				ServiceToWorkerMsg::AddSetReserved(protocol, peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.add_set_reserved_peer(protocol, peer_id),
				ServiceToWorkerMsg::RemoveSetReserved(protocol, peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.remove_set_reserved_peer(protocol, peer_id),
				ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) =>
					this.network_service.behaviour_mut().add_known_address(peer_id, addr),
				ServiceToWorkerMsg::AddToPeersSet(protocol, peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.add_to_peers_set(protocol, peer_id),
				ServiceToWorkerMsg::RemoveFromPeersSet(protocol, peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.remove_from_peers_set(protocol, peer_id),
				ServiceToWorkerMsg::EventStream(sender) => this.event_streams.push(sender),
				ServiceToWorkerMsg::Request {
					target,
					protocol,
					request,
					pending_response,
					connect,
				} => {
					this.network_service.behaviour_mut().send_request(
						&target,
						&protocol,
						request,
						pending_response,
						connect,
					);
				},
				ServiceToWorkerMsg::NetworkStatus { pending_response } => {
					let _ = pending_response.send(Ok(this.status()));
				},
				ServiceToWorkerMsg::NetworkState { pending_response } => {
					let _ = pending_response.send(Ok(this.network_state()));
				},
				ServiceToWorkerMsg::DisconnectPeer(who, protocol_name) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.disconnect_peer(&who, protocol_name),
				ServiceToWorkerMsg::NewBestBlockImported(hash, number) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.new_best_block_imported(hash, number),
			}
		}

		// `num_iterations` serves the same purpose as in the previous loop.
		// See the previous loop for explanations.
		let mut num_iterations = 0;
		loop {
			num_iterations += 1;
			if num_iterations >= 1000 {
				cx.waker().wake_by_ref();
				break
			}

			// Process the next action coming from the network.
			let next_event = this.network_service.select_next_some();
			futures::pin_mut!(next_event);
			let poll_value = next_event.poll_unpin(cx);

			match poll_value {
				Poll::Pending => break,
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::InboundRequest {
					protocol,
					result,
					..
				})) => {
					if let Some(metrics) = this.metrics.as_ref() {
						match result {
							Ok(serve_time) => {
								metrics
									.requests_in_success_total
									.with_label_values(&[&protocol])
									.observe(serve_time.as_secs_f64());
							},
							Err(err) => {
								let reason = match err {
									ResponseFailure::Network(InboundFailure::Timeout) => "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.
										continue,
									ResponseFailure::Network(InboundFailure::ResponseOmission) =>
										"busy-omitted",
									ResponseFailure::Network(InboundFailure::ConnectionClosed) =>
										"connection-closed",
								};

								metrics
									.requests_in_failure_total
									.with_label_values(&[&protocol, reason])
									.inc();
							},
						}
					}
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::RequestFinished {
					protocol,
					duration,
					result,
					..
				})) =>
					if let Some(metrics) = this.metrics.as_ref() {
						match result {
							Ok(_) => {
								metrics
									.requests_out_success_total
									.with_label_values(&[&protocol])
									.observe(duration.as_secs_f64());
							},
							Err(err) => {
								let reason = match err {
									RequestFailure::NotConnected => "not-connected",
									RequestFailure::UnknownProtocol => "unknown-protocol",
									RequestFailure::Refused => "refused",
									RequestFailure::Obsolete => "obsolete",
									RequestFailure::Network(OutboundFailure::DialFailure) =>
										"dial-failure",
									RequestFailure::Network(OutboundFailure::Timeout) => "timeout",
									RequestFailure::Network(OutboundFailure::ConnectionClosed) =>
										"connection-closed",
									RequestFailure::Network(
										OutboundFailure::UnsupportedProtocols,
									) => "unsupported",
								};

								metrics
									.requests_out_failure_total
									.with_label_values(&[&protocol, reason])
									.inc();
							},
						}
					},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::ReputationChanges {
					peer,
					changes,
				})) =>
					for change in changes {
						this.network_service.behaviour().user_protocol().report_peer(peer, change);
					},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::PeerIdentify {
					peer_id,
					info:
						IdentifyInfo {
							protocol_version,
							agent_version,
							mut listen_addrs,
							protocols,
							..
						},
				})) => {
					if listen_addrs.len() > 30 {
						debug!(
							target: "sub-libp2p",
							"Node {:?} has reported more than 30 addresses; it is identified by {:?} and {:?}",
							peer_id, protocol_version, agent_version
						);
						listen_addrs.truncate(30);
					}
					for addr in listen_addrs {
						this.network_service
							.behaviour_mut()
							.add_self_reported_address_to_dht(&peer_id, &protocols, addr);
					}
					this.network_service
						.behaviour_mut()
						.user_protocol_mut()
						.add_default_set_discovered_nodes(iter::once(peer_id));
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::Discovered(peer_id))) => {
					this.network_service
						.behaviour_mut()
						.user_protocol_mut()
						.add_default_set_discovered_nodes(iter::once(peer_id));
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::RandomKademliaStarted)) =>
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.kademlia_random_queries_total.inc();
					},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamOpened {
					remote,
					protocol,
					negotiated_fallback,
					notifications_sink,
					role,
				})) => {
					if let Some(metrics) = this.metrics.as_ref() {
						metrics
							.notifications_streams_opened_total
							.with_label_values(&[&protocol])
							.inc();
					}
					{
						let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
						let _previous_value = peers_notifications_sinks
							.insert((remote, protocol.clone()), notifications_sink);
						debug_assert!(_previous_value.is_none());
					}
					this.event_streams.send(Event::NotificationStreamOpened {
						remote,
						protocol,
						negotiated_fallback,
						role,
					});
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamReplaced {
					remote,
					protocol,
					notifications_sink,
				})) => {
					let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
					if let Some(s) = peers_notifications_sinks.get_mut(&(remote, protocol)) {
						*s = notifications_sink;
					} else {
						error!(
							target: "sub-libp2p",
							"NotificationStreamReplaced for non-existing substream"
						);
						debug_assert!(false);
					}

					// TODO: Notifications might have been lost as a result of the previous
					// connection being dropped, and as a result it would be preferable to notify
					// the users of this fact by simulating the substream being closed then
					// reopened.
					// The code below doesn't compile because `role` is unknown. Propagating the
					// handshake of the secondary connections is quite an invasive change and
					// would conflict with https://github.com/paritytech/substrate/issues/6403.
					// Considering that dropping notifications is generally regarded as
					// acceptable, this bug is at the moment intentionally left there and is
					// intended to be fixed at the same time as
					// https://github.com/paritytech/substrate/issues/6403.
					// this.event_streams.send(Event::NotificationStreamClosed {
					// remote,
					// protocol,
					// });
					// this.event_streams.send(Event::NotificationStreamOpened {
					// remote,
					// protocol,
					// role,
					// });
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamClosed {
					remote,
					protocol,
				})) => {
					if let Some(metrics) = this.metrics.as_ref() {
						metrics
							.notifications_streams_closed_total
							.with_label_values(&[&protocol[..]])
							.inc();
					}
					this.event_streams.send(Event::NotificationStreamClosed {
						remote,
						protocol: protocol.clone(),
					});
					{
						let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
						let _previous_value = peers_notifications_sinks.remove(&(remote, protocol));
						debug_assert!(_previous_value.is_some());
					}
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationsReceived {
					remote,
					messages,
				})) => {
					if let Some(metrics) = this.metrics.as_ref() {
						for (protocol, message) in &messages {
							metrics
								.notifications_sizes
								.with_label_values(&["in", protocol])
								.observe(message.len() as f64);
						}
					}
					this.event_streams.send(Event::NotificationsReceived { remote, messages });
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::SyncConnected(remote))) => {
					this.event_streams.send(Event::SyncConnected { remote });
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::SyncDisconnected(remote))) => {
					this.event_streams.send(Event::SyncDisconnected { remote });
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::Dht(event, duration))) => {
					if let Some(metrics) = this.metrics.as_ref() {
						let query_type = match event {
							DhtEvent::ValueFound(_) => "value-found",
							DhtEvent::ValueNotFound(_) => "value-not-found",
							DhtEvent::ValuePut(_) => "value-put",
							DhtEvent::ValuePutFailed(_) => "value-put-failed",
						};
						metrics
							.kademlia_query_duration
							.with_label_values(&[query_type])
							.observe(duration.as_secs_f64());
					}

					this.event_streams.send(Event::Dht(event));
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::None)) => {
					// Ignored event from lower layers.
				},
				Poll::Ready(SwarmEvent::ConnectionEstablished {
					peer_id,
					endpoint,
					num_established,
					concurrent_dial_errors,
				}) => {
					if let Some(errors) = concurrent_dial_errors {
						debug!(target: "sub-libp2p", "Libp2p => Connected({:?}) with errors: {:?}", peer_id, errors);
					} else {
						debug!(target: "sub-libp2p", "Libp2p => Connected({:?})", peer_id);
					}

					if let Some(metrics) = this.metrics.as_ref() {
						let direction = match endpoint {
							ConnectedPoint::Dialer { .. } => "out",
							ConnectedPoint::Listener { .. } => "in",
						};
						metrics.connections_opened_total.with_label_values(&[direction]).inc();

						if num_established.get() == 1 {
							metrics.distinct_peers_connections_opened_total.inc();
						}
					}
				},
				Poll::Ready(SwarmEvent::ConnectionClosed {
					peer_id,
					cause,
					endpoint,
					num_established,
				}) => {
					debug!(target: "sub-libp2p", "Libp2p => Disconnected({:?}, {:?})", peer_id, cause);
					if let Some(metrics) = this.metrics.as_ref() {
						let direction = match endpoint {
							ConnectedPoint::Dialer { .. } => "out",
							ConnectedPoint::Listener { .. } => "in",
						};
						let reason = match cause {
							Some(ConnectionError::IO(_)) => "transport-error",
							Some(ConnectionError::Handler(EitherError::A(EitherError::A(
								EitherError::B(EitherError::A(PingFailure::Timeout)),
							)))) => "ping-timeout",
							Some(ConnectionError::Handler(EitherError::A(EitherError::A(
								EitherError::A(NotifsHandlerError::SyncNotificationsClogged),
							)))) => "sync-notifications-clogged",
							Some(ConnectionError::Handler(_)) => "protocol-error",
							Some(ConnectionError::KeepAliveTimeout) => "keep-alive-timeout",
							None => "actively-closed",
						};
						metrics
							.connections_closed_total
							.with_label_values(&[direction, reason])
							.inc();

						// `num_established` represents the number of *remaining* connections.
						if num_established == 0 {
							metrics.distinct_peers_connections_closed_total.inc();
						}
					}
				},
				Poll::Ready(SwarmEvent::NewListenAddr { address, .. }) => {
					trace!(target: "sub-libp2p", "Libp2p => NewListenAddr({})", address);
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.listeners_local_addresses.inc();
					}
				},
				Poll::Ready(SwarmEvent::ExpiredListenAddr { address, .. }) => {
					info!(target: "sub-libp2p", "📪 No longer listening on {}", address);
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.listeners_local_addresses.dec();
					}
				},
				Poll::Ready(SwarmEvent::OutgoingConnectionError { peer_id, error }) => {
					if let Some(peer_id) = peer_id {
						trace!(
							target: "sub-libp2p",
							"Libp2p => Failed to reach {:?}: {}",
							peer_id, error,
						);

						if this.boot_node_ids.contains(&peer_id) {
							if let DialError::WrongPeerId { obtained, endpoint } = &error {
								if let ConnectedPoint::Dialer { address, role_override: _ } =
									endpoint
								{
									warn!(
										"💔 The bootnode you want to connect to at `{}` provided a different peer ID `{}` than the one you expect `{}`.",
										address,
										obtained,
										peer_id,
									);
								}
							}
						}
					}

					if let Some(metrics) = this.metrics.as_ref() {
						let reason = match error {
							DialError::ConnectionLimit(_) => Some("limit-reached"),
							DialError::InvalidPeerId(_) => Some("invalid-peer-id"),
							DialError::Transport(_) | DialError::ConnectionIo(_) =>
								Some("transport-error"),
							DialError::Banned |
							DialError::LocalPeerId |
							DialError::NoAddresses |
							DialError::DialPeerConditionFalse(_) |
							DialError::WrongPeerId { .. } |
							DialError::Aborted => None, // ignore them
						};
						if let Some(reason) = reason {
							metrics
								.pending_connections_errors_total
								.with_label_values(&[reason])
								.inc();
						}
					}
				},
				Poll::Ready(SwarmEvent::Dialing(peer_id)) => {
					trace!(target: "sub-libp2p", "Libp2p => Dialing({:?})", peer_id)
				},
				Poll::Ready(SwarmEvent::IncomingConnection { local_addr, send_back_addr }) => {
					trace!(target: "sub-libp2p", "Libp2p => IncomingConnection({},{}))",
						local_addr, send_back_addr);
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.incoming_connections_total.inc();
					}
				},
				Poll::Ready(SwarmEvent::IncomingConnectionError {
					local_addr,
					send_back_addr,
					error,
				}) => {
					debug!(
						target: "sub-libp2p",
						"Libp2p => IncomingConnectionError({},{}): {}",
						local_addr, send_back_addr, error,
					);
					if let Some(metrics) = this.metrics.as_ref() {
						let reason = match error {
							PendingConnectionError::ConnectionLimit(_) => Some("limit-reached"),
							PendingConnectionError::WrongPeerId { .. } => Some("invalid-peer-id"),
							PendingConnectionError::Transport(_) |
							PendingConnectionError::IO(_) => Some("transport-error"),
							PendingConnectionError::Aborted => None, // ignore it
						};

						if let Some(reason) = reason {
							metrics
								.incoming_connections_errors_total
								.with_label_values(&[reason])
								.inc();
						}
					}
				},
				Poll::Ready(SwarmEvent::BannedPeer { peer_id, endpoint }) => {
					debug!(
						target: "sub-libp2p",
						"Libp2p => BannedPeer({}). Connected via {:?}.",
						peer_id, endpoint,
					);
					if let Some(metrics) = this.metrics.as_ref() {
						metrics
							.incoming_connections_errors_total
							.with_label_values(&["banned"])
							.inc();
					}
				},
				Poll::Ready(SwarmEvent::ListenerClosed { reason, addresses, .. }) => {
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.listeners_local_addresses.sub(addresses.len() as u64);
					}
					let addrs =
						addresses.into_iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ");
					match reason {
						Ok(()) => error!(
							target: "sub-libp2p",
							"📪 Libp2p listener ({}) closed gracefully",
							addrs
						),
						Err(e) => error!(
							target: "sub-libp2p",
							"📪 Libp2p listener ({}) closed: {}",
							addrs, e
						),
					}
				},
				Poll::Ready(SwarmEvent::ListenerError { error, .. }) => {
					debug!(target: "sub-libp2p", "Libp2p => ListenerError: {}", error);
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.listeners_errors_total.inc();
					}
				},
			};
		}

		let num_connected_peers =
			this.network_service.behaviour_mut().user_protocol_mut().num_connected_peers();

		// Update the variables shared with the `NetworkService`.
		this.num_connected.store(num_connected_peers, Ordering::Relaxed);
		{
			let external_addresses =
				Swarm::<Behaviour<B, Client>>::external_addresses(&this.network_service)
					.map(|r| &r.addr)
					.cloned()
					.collect();
			*this.external_addresses.lock() = external_addresses;
		}

		let is_major_syncing = this
			.network_service
			.behaviour_mut()
			.user_protocol_mut()
			.sync_state()
			.state
			.is_major_syncing();

		this.is_major_syncing.store(is_major_syncing, Ordering::Relaxed);

		if let Some(metrics) = this.metrics.as_ref() {
			if let Some(buckets) = this.network_service.behaviour_mut().num_entries_per_kbucket() {
				for (lower_ilog2_bucket_bound, num_entries) in buckets {
					metrics
						.kbuckets_num_nodes
						.with_label_values(&[&lower_ilog2_bucket_bound.to_string()])
						.set(num_entries as u64);
				}
			}
			if let Some(num_entries) = this.network_service.behaviour_mut().num_kademlia_records() {
				metrics.kademlia_records_count.set(num_entries as u64);
			}
			if let Some(num_entries) =
				this.network_service.behaviour_mut().kademlia_records_total_size()
			{
				metrics.kademlia_records_sizes_total.set(num_entries as u64);
			}
			metrics
				.peerset_num_discovered
				.set(this.network_service.behaviour_mut().user_protocol().num_discovered_peers()
					as u64);
			metrics.pending_connections.set(
				Swarm::network_info(&this.network_service).connection_counters().num_pending()
					as u64,
			);
		}

		Poll::Pending
	}

Returns the total number of bytes received so far.

Examples found in repository?
src/service.rs (line 470)
462
463
464
465
466
467
468
469
470
471
472
473
474
475
	pub fn status(&self) -> NetworkStatus<B> {
		let status = self.sync_state();
		NetworkStatus {
			sync_state: status.state,
			best_seen_block: self.best_seen_block(),
			num_sync_peers: self.num_sync_peers(),
			num_connected_peers: self.num_connected_peers(),
			num_active_peers: self.num_active_peers(),
			total_bytes_inbound: self.total_bytes_inbound(),
			total_bytes_outbound: self.total_bytes_outbound(),
			state_sync: status.state_sync,
			warp_sync: status.warp_sync,
		}
	}

Returns the total number of bytes sent so far.

Examples found in repository?
src/service.rs (line 471)
462
463
464
465
466
467
468
469
470
471
472
473
474
475
	pub fn status(&self) -> NetworkStatus<B> {
		let status = self.sync_state();
		NetworkStatus {
			sync_state: status.state,
			best_seen_block: self.best_seen_block(),
			num_sync_peers: self.num_sync_peers(),
			num_connected_peers: self.num_connected_peers(),
			num_active_peers: self.num_active_peers(),
			total_bytes_inbound: self.total_bytes_inbound(),
			total_bytes_outbound: self.total_bytes_outbound(),
			state_sync: status.state_sync,
			warp_sync: status.warp_sync,
		}
	}

Returns the number of peers we’re connected to.

Examples found in repository?
src/service.rs (line 468)
462
463
464
465
466
467
468
469
470
471
472
473
474
475
	pub fn status(&self) -> NetworkStatus<B> {
		let status = self.sync_state();
		NetworkStatus {
			sync_state: status.state,
			best_seen_block: self.best_seen_block(),
			num_sync_peers: self.num_sync_peers(),
			num_connected_peers: self.num_connected_peers(),
			num_active_peers: self.num_active_peers(),
			total_bytes_inbound: self.total_bytes_inbound(),
			total_bytes_outbound: self.total_bytes_outbound(),
			state_sync: status.state_sync,
			warp_sync: status.warp_sync,
		}
	}

Returns the number of peers we’re connected to and that are being queried.

Examples found in repository?
src/service.rs (line 469)
462
463
464
465
466
467
468
469
470
471
472
473
474
475
	pub fn status(&self) -> NetworkStatus<B> {
		let status = self.sync_state();
		NetworkStatus {
			sync_state: status.state,
			best_seen_block: self.best_seen_block(),
			num_sync_peers: self.num_sync_peers(),
			num_connected_peers: self.num_connected_peers(),
			num_active_peers: self.num_active_peers(),
			total_bytes_inbound: self.total_bytes_inbound(),
			total_bytes_outbound: self.total_bytes_outbound(),
			state_sync: status.state_sync,
			warp_sync: status.warp_sync,
		}
	}

Current global sync state.

Examples found in repository?
src/service.rs (line 463)
462
463
464
465
466
467
468
469
470
471
472
473
474
475
	pub fn status(&self) -> NetworkStatus<B> {
		let status = self.sync_state();
		NetworkStatus {
			sync_state: status.state,
			best_seen_block: self.best_seen_block(),
			num_sync_peers: self.num_sync_peers(),
			num_connected_peers: self.num_connected_peers(),
			num_active_peers: self.num_active_peers(),
			total_bytes_inbound: self.total_bytes_inbound(),
			total_bytes_outbound: self.total_bytes_outbound(),
			state_sync: status.state_sync,
			warp_sync: status.warp_sync,
		}
	}

Target sync block number.

Examples found in repository?
src/service.rs (line 466)
462
463
464
465
466
467
468
469
470
471
472
473
474
475
	pub fn status(&self) -> NetworkStatus<B> {
		let status = self.sync_state();
		NetworkStatus {
			sync_state: status.state,
			best_seen_block: self.best_seen_block(),
			num_sync_peers: self.num_sync_peers(),
			num_connected_peers: self.num_connected_peers(),
			num_active_peers: self.num_active_peers(),
			total_bytes_inbound: self.total_bytes_inbound(),
			total_bytes_outbound: self.total_bytes_outbound(),
			state_sync: status.state_sync,
			warp_sync: status.warp_sync,
		}
	}

Number of peers participating in syncing.

Examples found in repository?
src/service.rs (line 467)
462
463
464
465
466
467
468
469
470
471
472
473
474
475
	pub fn status(&self) -> NetworkStatus<B> {
		let status = self.sync_state();
		NetworkStatus {
			sync_state: status.state,
			best_seen_block: self.best_seen_block(),
			num_sync_peers: self.num_sync_peers(),
			num_connected_peers: self.num_connected_peers(),
			num_active_peers: self.num_active_peers(),
			total_bytes_inbound: self.total_bytes_inbound(),
			total_bytes_outbound: self.total_bytes_outbound(),
			state_sync: status.state_sync,
			warp_sync: status.warp_sync,
		}
	}

Number of blocks in the import queue.

Returns the number of downloaded blocks.

Number of active sync requests.

Adds an address for a node.

Return a NetworkService that can be shared through the code base and can be used to manipulate the worker.

You must call this when a new block is finalized by the client.

Inform the network service about new best imported block.

Returns the local PeerId.

Returns the list of addresses we are listening on.

Does NOT include a trailing /p2p/ with our PeerId.

Get network state.

Note: Use this only for debugging. This API is unstable. There are warnings literally everywhere about this. Please don’t use this function to retrieve actual information.

Examples found in repository?
src/service.rs (line 1384)
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
	fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
		let this = &mut *self;

		// At the time of writing of this comment, due to a high volume of messages, the network
		// worker sometimes takes a long time to process the loop below. When that happens, the
		// rest of the polling is frozen. In order to avoid negative side-effects caused by this
		// freeze, a limit to the number of iterations is enforced below. If the limit is reached,
		// the task is interrupted then scheduled again.
		//
		// This allows for a more even distribution in the time taken by each sub-part of the
		// polling.
		let mut num_iterations = 0;
		loop {
			num_iterations += 1;
			if num_iterations >= 100 {
				cx.waker().wake_by_ref();
				break
			}

			// Process the next message coming from the `NetworkService`.
			let msg = match this.from_service.poll_next_unpin(cx) {
				Poll::Ready(Some(msg)) => msg,
				Poll::Ready(None) => return Poll::Ready(()),
				Poll::Pending => break,
			};
			match msg {
				ServiceToWorkerMsg::AnnounceBlock(hash, data) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.announce_block(hash, data),
				ServiceToWorkerMsg::GetValue(key) =>
					this.network_service.behaviour_mut().get_value(key),
				ServiceToWorkerMsg::PutValue(key, value) =>
					this.network_service.behaviour_mut().put_value(key, value),
				ServiceToWorkerMsg::SetReservedOnly(reserved_only) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.set_reserved_only(reserved_only),
				ServiceToWorkerMsg::SetReserved(peers) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.set_reserved_peers(peers),
				ServiceToWorkerMsg::SetPeersetReserved(protocol, peers) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.set_reserved_peerset_peers(protocol, peers),
				ServiceToWorkerMsg::AddReserved(peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.add_reserved_peer(peer_id),
				ServiceToWorkerMsg::RemoveReserved(peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.remove_reserved_peer(peer_id),
				ServiceToWorkerMsg::AddSetReserved(protocol, peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.add_set_reserved_peer(protocol, peer_id),
				ServiceToWorkerMsg::RemoveSetReserved(protocol, peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.remove_set_reserved_peer(protocol, peer_id),
				ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) =>
					this.network_service.behaviour_mut().add_known_address(peer_id, addr),
				ServiceToWorkerMsg::AddToPeersSet(protocol, peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.add_to_peers_set(protocol, peer_id),
				ServiceToWorkerMsg::RemoveFromPeersSet(protocol, peer_id) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.remove_from_peers_set(protocol, peer_id),
				ServiceToWorkerMsg::EventStream(sender) => this.event_streams.push(sender),
				ServiceToWorkerMsg::Request {
					target,
					protocol,
					request,
					pending_response,
					connect,
				} => {
					this.network_service.behaviour_mut().send_request(
						&target,
						&protocol,
						request,
						pending_response,
						connect,
					);
				},
				ServiceToWorkerMsg::NetworkStatus { pending_response } => {
					let _ = pending_response.send(Ok(this.status()));
				},
				ServiceToWorkerMsg::NetworkState { pending_response } => {
					let _ = pending_response.send(Ok(this.network_state()));
				},
				ServiceToWorkerMsg::DisconnectPeer(who, protocol_name) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.disconnect_peer(&who, protocol_name),
				ServiceToWorkerMsg::NewBestBlockImported(hash, number) => this
					.network_service
					.behaviour_mut()
					.user_protocol_mut()
					.new_best_block_imported(hash, number),
			}
		}

		// `num_iterations` serves the same purpose as in the previous loop.
		// See the previous loop for explanations.
		let mut num_iterations = 0;
		loop {
			num_iterations += 1;
			if num_iterations >= 1000 {
				cx.waker().wake_by_ref();
				break
			}

			// Process the next action coming from the network.
			let next_event = this.network_service.select_next_some();
			futures::pin_mut!(next_event);
			let poll_value = next_event.poll_unpin(cx);

			match poll_value {
				Poll::Pending => break,
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::InboundRequest {
					protocol,
					result,
					..
				})) => {
					if let Some(metrics) = this.metrics.as_ref() {
						match result {
							Ok(serve_time) => {
								metrics
									.requests_in_success_total
									.with_label_values(&[&protocol])
									.observe(serve_time.as_secs_f64());
							},
							Err(err) => {
								let reason = match err {
									ResponseFailure::Network(InboundFailure::Timeout) => "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.
										continue,
									ResponseFailure::Network(InboundFailure::ResponseOmission) =>
										"busy-omitted",
									ResponseFailure::Network(InboundFailure::ConnectionClosed) =>
										"connection-closed",
								};

								metrics
									.requests_in_failure_total
									.with_label_values(&[&protocol, reason])
									.inc();
							},
						}
					}
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::RequestFinished {
					protocol,
					duration,
					result,
					..
				})) =>
					if let Some(metrics) = this.metrics.as_ref() {
						match result {
							Ok(_) => {
								metrics
									.requests_out_success_total
									.with_label_values(&[&protocol])
									.observe(duration.as_secs_f64());
							},
							Err(err) => {
								let reason = match err {
									RequestFailure::NotConnected => "not-connected",
									RequestFailure::UnknownProtocol => "unknown-protocol",
									RequestFailure::Refused => "refused",
									RequestFailure::Obsolete => "obsolete",
									RequestFailure::Network(OutboundFailure::DialFailure) =>
										"dial-failure",
									RequestFailure::Network(OutboundFailure::Timeout) => "timeout",
									RequestFailure::Network(OutboundFailure::ConnectionClosed) =>
										"connection-closed",
									RequestFailure::Network(
										OutboundFailure::UnsupportedProtocols,
									) => "unsupported",
								};

								metrics
									.requests_out_failure_total
									.with_label_values(&[&protocol, reason])
									.inc();
							},
						}
					},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::ReputationChanges {
					peer,
					changes,
				})) =>
					for change in changes {
						this.network_service.behaviour().user_protocol().report_peer(peer, change);
					},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::PeerIdentify {
					peer_id,
					info:
						IdentifyInfo {
							protocol_version,
							agent_version,
							mut listen_addrs,
							protocols,
							..
						},
				})) => {
					if listen_addrs.len() > 30 {
						debug!(
							target: "sub-libp2p",
							"Node {:?} has reported more than 30 addresses; it is identified by {:?} and {:?}",
							peer_id, protocol_version, agent_version
						);
						listen_addrs.truncate(30);
					}
					for addr in listen_addrs {
						this.network_service
							.behaviour_mut()
							.add_self_reported_address_to_dht(&peer_id, &protocols, addr);
					}
					this.network_service
						.behaviour_mut()
						.user_protocol_mut()
						.add_default_set_discovered_nodes(iter::once(peer_id));
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::Discovered(peer_id))) => {
					this.network_service
						.behaviour_mut()
						.user_protocol_mut()
						.add_default_set_discovered_nodes(iter::once(peer_id));
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::RandomKademliaStarted)) =>
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.kademlia_random_queries_total.inc();
					},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamOpened {
					remote,
					protocol,
					negotiated_fallback,
					notifications_sink,
					role,
				})) => {
					if let Some(metrics) = this.metrics.as_ref() {
						metrics
							.notifications_streams_opened_total
							.with_label_values(&[&protocol])
							.inc();
					}
					{
						let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
						let _previous_value = peers_notifications_sinks
							.insert((remote, protocol.clone()), notifications_sink);
						debug_assert!(_previous_value.is_none());
					}
					this.event_streams.send(Event::NotificationStreamOpened {
						remote,
						protocol,
						negotiated_fallback,
						role,
					});
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamReplaced {
					remote,
					protocol,
					notifications_sink,
				})) => {
					let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
					if let Some(s) = peers_notifications_sinks.get_mut(&(remote, protocol)) {
						*s = notifications_sink;
					} else {
						error!(
							target: "sub-libp2p",
							"NotificationStreamReplaced for non-existing substream"
						);
						debug_assert!(false);
					}

					// TODO: Notifications might have been lost as a result of the previous
					// connection being dropped, and as a result it would be preferable to notify
					// the users of this fact by simulating the substream being closed then
					// reopened.
					// The code below doesn't compile because `role` is unknown. Propagating the
					// handshake of the secondary connections is quite an invasive change and
					// would conflict with https://github.com/paritytech/substrate/issues/6403.
					// Considering that dropping notifications is generally regarded as
					// acceptable, this bug is at the moment intentionally left there and is
					// intended to be fixed at the same time as
					// https://github.com/paritytech/substrate/issues/6403.
					// this.event_streams.send(Event::NotificationStreamClosed {
					// remote,
					// protocol,
					// });
					// this.event_streams.send(Event::NotificationStreamOpened {
					// remote,
					// protocol,
					// role,
					// });
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamClosed {
					remote,
					protocol,
				})) => {
					if let Some(metrics) = this.metrics.as_ref() {
						metrics
							.notifications_streams_closed_total
							.with_label_values(&[&protocol[..]])
							.inc();
					}
					this.event_streams.send(Event::NotificationStreamClosed {
						remote,
						protocol: protocol.clone(),
					});
					{
						let mut peers_notifications_sinks = this.peers_notifications_sinks.lock();
						let _previous_value = peers_notifications_sinks.remove(&(remote, protocol));
						debug_assert!(_previous_value.is_some());
					}
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationsReceived {
					remote,
					messages,
				})) => {
					if let Some(metrics) = this.metrics.as_ref() {
						for (protocol, message) in &messages {
							metrics
								.notifications_sizes
								.with_label_values(&["in", protocol])
								.observe(message.len() as f64);
						}
					}
					this.event_streams.send(Event::NotificationsReceived { remote, messages });
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::SyncConnected(remote))) => {
					this.event_streams.send(Event::SyncConnected { remote });
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::SyncDisconnected(remote))) => {
					this.event_streams.send(Event::SyncDisconnected { remote });
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::Dht(event, duration))) => {
					if let Some(metrics) = this.metrics.as_ref() {
						let query_type = match event {
							DhtEvent::ValueFound(_) => "value-found",
							DhtEvent::ValueNotFound(_) => "value-not-found",
							DhtEvent::ValuePut(_) => "value-put",
							DhtEvent::ValuePutFailed(_) => "value-put-failed",
						};
						metrics
							.kademlia_query_duration
							.with_label_values(&[query_type])
							.observe(duration.as_secs_f64());
					}

					this.event_streams.send(Event::Dht(event));
				},
				Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::None)) => {
					// Ignored event from lower layers.
				},
				Poll::Ready(SwarmEvent::ConnectionEstablished {
					peer_id,
					endpoint,
					num_established,
					concurrent_dial_errors,
				}) => {
					if let Some(errors) = concurrent_dial_errors {
						debug!(target: "sub-libp2p", "Libp2p => Connected({:?}) with errors: {:?}", peer_id, errors);
					} else {
						debug!(target: "sub-libp2p", "Libp2p => Connected({:?})", peer_id);
					}

					if let Some(metrics) = this.metrics.as_ref() {
						let direction = match endpoint {
							ConnectedPoint::Dialer { .. } => "out",
							ConnectedPoint::Listener { .. } => "in",
						};
						metrics.connections_opened_total.with_label_values(&[direction]).inc();

						if num_established.get() == 1 {
							metrics.distinct_peers_connections_opened_total.inc();
						}
					}
				},
				Poll::Ready(SwarmEvent::ConnectionClosed {
					peer_id,
					cause,
					endpoint,
					num_established,
				}) => {
					debug!(target: "sub-libp2p", "Libp2p => Disconnected({:?}, {:?})", peer_id, cause);
					if let Some(metrics) = this.metrics.as_ref() {
						let direction = match endpoint {
							ConnectedPoint::Dialer { .. } => "out",
							ConnectedPoint::Listener { .. } => "in",
						};
						let reason = match cause {
							Some(ConnectionError::IO(_)) => "transport-error",
							Some(ConnectionError::Handler(EitherError::A(EitherError::A(
								EitherError::B(EitherError::A(PingFailure::Timeout)),
							)))) => "ping-timeout",
							Some(ConnectionError::Handler(EitherError::A(EitherError::A(
								EitherError::A(NotifsHandlerError::SyncNotificationsClogged),
							)))) => "sync-notifications-clogged",
							Some(ConnectionError::Handler(_)) => "protocol-error",
							Some(ConnectionError::KeepAliveTimeout) => "keep-alive-timeout",
							None => "actively-closed",
						};
						metrics
							.connections_closed_total
							.with_label_values(&[direction, reason])
							.inc();

						// `num_established` represents the number of *remaining* connections.
						if num_established == 0 {
							metrics.distinct_peers_connections_closed_total.inc();
						}
					}
				},
				Poll::Ready(SwarmEvent::NewListenAddr { address, .. }) => {
					trace!(target: "sub-libp2p", "Libp2p => NewListenAddr({})", address);
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.listeners_local_addresses.inc();
					}
				},
				Poll::Ready(SwarmEvent::ExpiredListenAddr { address, .. }) => {
					info!(target: "sub-libp2p", "📪 No longer listening on {}", address);
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.listeners_local_addresses.dec();
					}
				},
				Poll::Ready(SwarmEvent::OutgoingConnectionError { peer_id, error }) => {
					if let Some(peer_id) = peer_id {
						trace!(
							target: "sub-libp2p",
							"Libp2p => Failed to reach {:?}: {}",
							peer_id, error,
						);

						if this.boot_node_ids.contains(&peer_id) {
							if let DialError::WrongPeerId { obtained, endpoint } = &error {
								if let ConnectedPoint::Dialer { address, role_override: _ } =
									endpoint
								{
									warn!(
										"💔 The bootnode you want to connect to at `{}` provided a different peer ID `{}` than the one you expect `{}`.",
										address,
										obtained,
										peer_id,
									);
								}
							}
						}
					}

					if let Some(metrics) = this.metrics.as_ref() {
						let reason = match error {
							DialError::ConnectionLimit(_) => Some("limit-reached"),
							DialError::InvalidPeerId(_) => Some("invalid-peer-id"),
							DialError::Transport(_) | DialError::ConnectionIo(_) =>
								Some("transport-error"),
							DialError::Banned |
							DialError::LocalPeerId |
							DialError::NoAddresses |
							DialError::DialPeerConditionFalse(_) |
							DialError::WrongPeerId { .. } |
							DialError::Aborted => None, // ignore them
						};
						if let Some(reason) = reason {
							metrics
								.pending_connections_errors_total
								.with_label_values(&[reason])
								.inc();
						}
					}
				},
				Poll::Ready(SwarmEvent::Dialing(peer_id)) => {
					trace!(target: "sub-libp2p", "Libp2p => Dialing({:?})", peer_id)
				},
				Poll::Ready(SwarmEvent::IncomingConnection { local_addr, send_back_addr }) => {
					trace!(target: "sub-libp2p", "Libp2p => IncomingConnection({},{}))",
						local_addr, send_back_addr);
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.incoming_connections_total.inc();
					}
				},
				Poll::Ready(SwarmEvent::IncomingConnectionError {
					local_addr,
					send_back_addr,
					error,
				}) => {
					debug!(
						target: "sub-libp2p",
						"Libp2p => IncomingConnectionError({},{}): {}",
						local_addr, send_back_addr, error,
					);
					if let Some(metrics) = this.metrics.as_ref() {
						let reason = match error {
							PendingConnectionError::ConnectionLimit(_) => Some("limit-reached"),
							PendingConnectionError::WrongPeerId { .. } => Some("invalid-peer-id"),
							PendingConnectionError::Transport(_) |
							PendingConnectionError::IO(_) => Some("transport-error"),
							PendingConnectionError::Aborted => None, // ignore it
						};

						if let Some(reason) = reason {
							metrics
								.incoming_connections_errors_total
								.with_label_values(&[reason])
								.inc();
						}
					}
				},
				Poll::Ready(SwarmEvent::BannedPeer { peer_id, endpoint }) => {
					debug!(
						target: "sub-libp2p",
						"Libp2p => BannedPeer({}). Connected via {:?}.",
						peer_id, endpoint,
					);
					if let Some(metrics) = this.metrics.as_ref() {
						metrics
							.incoming_connections_errors_total
							.with_label_values(&["banned"])
							.inc();
					}
				},
				Poll::Ready(SwarmEvent::ListenerClosed { reason, addresses, .. }) => {
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.listeners_local_addresses.sub(addresses.len() as u64);
					}
					let addrs =
						addresses.into_iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ");
					match reason {
						Ok(()) => error!(
							target: "sub-libp2p",
							"📪 Libp2p listener ({}) closed gracefully",
							addrs
						),
						Err(e) => error!(
							target: "sub-libp2p",
							"📪 Libp2p listener ({}) closed: {}",
							addrs, e
						),
					}
				},
				Poll::Ready(SwarmEvent::ListenerError { error, .. }) => {
					debug!(target: "sub-libp2p", "Libp2p => ListenerError: {}", error);
					if let Some(metrics) = this.metrics.as_ref() {
						metrics.listeners_errors_total.inc();
					}
				},
			};
		}

		let num_connected_peers =
			this.network_service.behaviour_mut().user_protocol_mut().num_connected_peers();

		// Update the variables shared with the `NetworkService`.
		this.num_connected.store(num_connected_peers, Ordering::Relaxed);
		{
			let external_addresses =
				Swarm::<Behaviour<B, Client>>::external_addresses(&this.network_service)
					.map(|r| &r.addr)
					.cloned()
					.collect();
			*this.external_addresses.lock() = external_addresses;
		}

		let is_major_syncing = this
			.network_service
			.behaviour_mut()
			.user_protocol_mut()
			.sync_state()
			.state
			.is_major_syncing();

		this.is_major_syncing.store(is_major_syncing, Ordering::Relaxed);

		if let Some(metrics) = this.metrics.as_ref() {
			if let Some(buckets) = this.network_service.behaviour_mut().num_entries_per_kbucket() {
				for (lower_ilog2_bucket_bound, num_entries) in buckets {
					metrics
						.kbuckets_num_nodes
						.with_label_values(&[&lower_ilog2_bucket_bound.to_string()])
						.set(num_entries as u64);
				}
			}
			if let Some(num_entries) = this.network_service.behaviour_mut().num_kademlia_records() {
				metrics.kademlia_records_count.set(num_entries as u64);
			}
			if let Some(num_entries) =
				this.network_service.behaviour_mut().kademlia_records_total_size()
			{
				metrics.kademlia_records_sizes_total.set(num_entries as u64);
			}
			metrics
				.peerset_num_discovered
				.set(this.network_service.behaviour_mut().user_protocol().num_discovered_peers()
					as u64);
			metrics.pending_connections.set(
				Swarm::network_info(&this.network_service).connection_counters().num_pending()
					as u64,
			);
		}

		Poll::Pending
	}

Get currently connected peers.

Removes a PeerId from the list of reserved peers.

Adds a PeerId and its Multiaddr as reserved.

Returns the list of reserved peers.

Trait Implementations§

The type of value produced on completion.
Attempt to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Convert from a value of T into an equivalent instance of Option<Self>. Read more
Consume self to return Some equivalent value of Option<T>. Read more
Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.

Returns the argument unchanged.

Map this future’s output to a different type, returning a new future of the resulting type. Read more
Map this future’s output to a different type, returning a new future of the resulting type. Read more
Chain on a computation for when a future finished, passing the result of the future to the provided closure f. Read more
Wrap this future in an Either future, making it the left-hand variant of that Either. Read more
Wrap this future in an Either future, making it the right-hand variant of that Either. Read more
Convert this future into a single element stream. Read more
Flatten the execution of this future when the output of this future is itself another future. Read more
Flatten the execution of this future when the successful result of this future is a stream. Read more
Fuse a future such that poll will never again be called once it has completed. This method can be used to turn any Future into a FusedFuture. Read more
Do something with the output of a future before passing it on. Read more
Catches unwinding panics while polling the future. Read more
Create a cloneable handle to this future where all handles will resolve to the same result. Read more
Turn this future into a future that yields () on completion and sends its output to another future on a separate task. Read more
Wrap the future in a Box, pinning it. Read more
Wrap the future in a Box, pinning it. Read more
A convenience for calling Future::poll on Unpin future types.
Evaluates and consumes the future, returning the resulting output if the future is ready after the first call to Future::poll. Read more
A convenience for calling Future::poll() on !Unpin types.
Returns the result of self or other future, preferring self if both are ready. Read more
Returns the result of self or other future, with no preference if both are ready. Read more
Catches panics while polling the future. Read more
Boxes the future and changes its type to dyn Future + Send + 'a. Read more
Boxes the future and changes its type to dyn Future + 'a. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The output that the future will produce on completion.
Which kind of future are we turning this into?
Creates a future from a value. Read more

Get a reference to the inner from the outer.

Get a mutable reference to the inner from the outer.

The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
Should always be Self
Convert from a value of T into an equivalent instance of Self. Read more
Consume self to return an equivalent value of T. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
The counterpart to unchecked_from.
Consume self to return an equivalent value of T.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more