sc_authority_discovery/lib.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19#![warn(missing_docs)]
20#![recursion_limit = "1024"]
21
22//! Substrate authority discovery.
23//!
24//! This crate enables Substrate authorities to discover and directly connect to
25//! other authorities. It is split into two components the [`Worker`] and the
26//! [`Service`].
27//!
28//! See [`Worker`] and [`Service`] for more documentation.
29
30pub use crate::{
31 error::Error,
32 service::Service,
33 worker::{AuthorityDiscovery, NetworkProvider, Role, Worker},
34};
35
36use std::{collections::HashSet, sync::Arc, time::Duration};
37
38use futures::{
39 channel::{mpsc, oneshot},
40 Stream,
41};
42
43use sc_network::{event::DhtEvent, Multiaddr};
44use sc_network_types::PeerId;
45use sp_authority_discovery::AuthorityId;
46use sp_blockchain::HeaderBackend;
47use sp_runtime::traits::Block as BlockT;
48
49mod error;
50mod interval;
51mod service;
52mod worker;
53
54#[cfg(test)]
55mod tests;
56
57/// Configuration of [`Worker`].
58pub struct WorkerConfig {
59 /// The maximum interval in which the node will publish its own address on the DHT.
60 ///
61 /// By default this is set to 1 hour.
62 pub max_publish_interval: Duration,
63
64 /// Interval at which the keystore is queried. If the keys have changed, unconditionally
65 /// re-publish its addresses on the DHT.
66 ///
67 /// By default this is set to 1 minute.
68 pub keystore_refresh_interval: Duration,
69
70 /// The maximum interval in which the node will query the DHT for new entries.
71 ///
72 /// By default this is set to 10 minutes.
73 pub max_query_interval: Duration,
74
75 /// If `false`, the node won't publish on the DHT multiaddresses that contain non-global
76 /// IP addresses (such as 10.0.0.1).
77 ///
78 /// Recommended: `false` for live chains, and `true` for local chains or for testing.
79 ///
80 /// Defaults to `true` to avoid the surprise factor.
81 pub publish_non_global_ips: bool,
82
83 /// Public addresses set by the node operator to always publish first in the authority
84 /// discovery DHT record.
85 pub public_addresses: Vec<Multiaddr>,
86
87 /// Reject authority discovery records that are not signed by their network identity (PeerId)
88 ///
89 /// Defaults to `false` to provide compatibility with old versions
90 pub strict_record_validation: bool,
91}
92
93impl Default for WorkerConfig {
94 fn default() -> Self {
95 Self {
96 // Kademlia's default time-to-live for Dht records is 36h, republishing records every
97 // 24h through libp2p-kad. Given that a node could restart at any point in time, one can
98 // not depend on the republishing process, thus publishing own external addresses should
99 // happen on an interval < 36h.
100 max_publish_interval: Duration::from_secs(1 * 60 * 60),
101 keystore_refresh_interval: Duration::from_secs(60),
102 // External addresses of remote authorities can change at any given point in time. The
103 // interval on which to trigger new queries for the current and next authorities is a
104 // trade off between efficiency and performance.
105 //
106 // Querying 700 [`AuthorityId`]s takes ~8m on the Kusama DHT (16th Nov 2020) when
107 // comparing `authority_discovery_authority_addresses_requested_total` and
108 // `authority_discovery_dht_event_received`.
109 max_query_interval: Duration::from_secs(10 * 60),
110 publish_non_global_ips: true,
111 public_addresses: Vec::new(),
112 strict_record_validation: false,
113 }
114 }
115}
116
117/// Create a new authority discovery [`Worker`] and [`Service`].
118///
119/// See the struct documentation of each for more details.
120pub fn new_worker_and_service<Client, Block, DhtEventStream>(
121 client: Arc<Client>,
122 network: Arc<dyn NetworkProvider>,
123 dht_event_rx: DhtEventStream,
124 role: Role,
125 prometheus_registry: Option<prometheus_endpoint::Registry>,
126) -> (Worker<Client, Block, DhtEventStream>, Service)
127where
128 Block: BlockT + Unpin + 'static,
129 Client: AuthorityDiscovery<Block> + Send + Sync + 'static + HeaderBackend<Block>,
130 DhtEventStream: Stream<Item = DhtEvent> + Unpin,
131{
132 new_worker_and_service_with_config(
133 Default::default(),
134 client,
135 network,
136 dht_event_rx,
137 role,
138 prometheus_registry,
139 )
140}
141
142/// Same as [`new_worker_and_service`] but with support for providing the `config`.
143///
144/// When in doubt use [`new_worker_and_service`] as it will use the default configuration.
145pub fn new_worker_and_service_with_config<Client, Block, DhtEventStream>(
146 config: WorkerConfig,
147 client: Arc<Client>,
148 network: Arc<dyn NetworkProvider>,
149 dht_event_rx: DhtEventStream,
150 role: Role,
151 prometheus_registry: Option<prometheus_endpoint::Registry>,
152) -> (Worker<Client, Block, DhtEventStream>, Service)
153where
154 Block: BlockT + Unpin + 'static,
155 Client: AuthorityDiscovery<Block> + 'static,
156 DhtEventStream: Stream<Item = DhtEvent> + Unpin,
157{
158 let (to_worker, from_service) = mpsc::channel(0);
159
160 let worker =
161 Worker::new(from_service, client, network, dht_event_rx, role, prometheus_registry, config);
162 let service = Service::new(to_worker);
163
164 (worker, service)
165}
166
167/// Message send from the [`Service`] to the [`Worker`].
168pub(crate) enum ServicetoWorkerMsg {
169 /// See [`Service::get_addresses_by_authority_id`].
170 GetAddressesByAuthorityId(AuthorityId, oneshot::Sender<Option<HashSet<Multiaddr>>>),
171 /// See [`Service::get_authority_ids_by_peer_id`].
172 GetAuthorityIdsByPeerId(PeerId, oneshot::Sender<Option<HashSet<AuthorityId>>>),
173}