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, path::PathBuf, 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_core::traits::SpawnNamed;
48use sp_runtime::traits::Block as BlockT;
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 /// The directory of where the persisted AddrCache file is located,
93 /// optional since NetworkConfiguration's `net_config_path` field
94 /// is optional. If None, we won't persist the AddrCache at all.
95 pub persisted_cache_directory: Option<PathBuf>,
96}
97
98impl Default for WorkerConfig {
99 fn default() -> Self {
100 Self {
101 // Kademlia's default time-to-live for Dht records is 36h, republishing records every
102 // 24h through libp2p-kad. Given that a node could restart at any point in time, one can
103 // not depend on the republishing process, thus publishing own external addresses should
104 // happen on an interval < 36h.
105 max_publish_interval: Duration::from_secs(1 * 60 * 60),
106 keystore_refresh_interval: Duration::from_secs(60),
107 // External addresses of remote authorities can change at any given point in time. The
108 // interval on which to trigger new queries for the current and next authorities is a
109 // trade off between efficiency and performance.
110 //
111 // Querying 700 [`AuthorityId`]s takes ~8m on the Kusama DHT (16th Nov 2020) when
112 // comparing `authority_discovery_authority_addresses_requested_total` and
113 // `authority_discovery_dht_event_received`.
114 max_query_interval: Duration::from_secs(10 * 60),
115 publish_non_global_ips: true,
116 public_addresses: Vec::new(),
117 strict_record_validation: false,
118 persisted_cache_directory: None,
119 }
120 }
121}
122
123/// Create a new authority discovery [`Worker`] and [`Service`].
124///
125/// See the struct documentation of each for more details.
126pub fn new_worker_and_service<Client, Block, DhtEventStream>(
127 client: Arc<Client>,
128 network: Arc<dyn NetworkProvider>,
129 dht_event_rx: DhtEventStream,
130 role: Role,
131 prometheus_registry: Option<prometheus_endpoint::Registry>,
132 spawner: impl SpawnNamed + 'static,
133) -> (Worker<Client, Block, DhtEventStream>, Service)
134where
135 Block: BlockT + Unpin + 'static,
136 Client: AuthorityDiscovery<Block> + Send + Sync + 'static + HeaderBackend<Block>,
137 DhtEventStream: Stream<Item = DhtEvent> + Unpin,
138{
139 new_worker_and_service_with_config(
140 Default::default(),
141 client,
142 network,
143 dht_event_rx,
144 role,
145 prometheus_registry,
146 spawner,
147 )
148}
149
150/// Same as [`new_worker_and_service`] but with support for providing the `config`.
151///
152/// When in doubt use [`new_worker_and_service`] as it will use the default configuration.
153pub fn new_worker_and_service_with_config<Client, Block, DhtEventStream>(
154 config: WorkerConfig,
155 client: Arc<Client>,
156 network: Arc<dyn NetworkProvider>,
157 dht_event_rx: DhtEventStream,
158 role: Role,
159 prometheus_registry: Option<prometheus_endpoint::Registry>,
160 spawner: impl SpawnNamed + 'static,
161) -> (Worker<Client, Block, DhtEventStream>, Service)
162where
163 Block: BlockT + Unpin + 'static,
164 Client: AuthorityDiscovery<Block> + 'static,
165 DhtEventStream: Stream<Item = DhtEvent> + Unpin,
166{
167 let (to_worker, from_service) = mpsc::channel(0);
168
169 let worker = Worker::new(
170 from_service,
171 client,
172 network,
173 dht_event_rx,
174 role,
175 prometheus_registry,
176 config,
177 spawner,
178 );
179 let service = Service::new(to_worker);
180
181 (worker, service)
182}
183
184/// Message send from the [`Service`] to the [`Worker`].
185pub(crate) enum ServicetoWorkerMsg {
186 /// See [`Service::get_addresses_by_authority_id`].
187 GetAddressesByAuthorityId(AuthorityId, oneshot::Sender<Option<HashSet<Multiaddr>>>),
188 /// See [`Service::get_authority_ids_by_peer_id`].
189 GetAuthorityIdsByPeerId(PeerId, oneshot::Sender<Option<HashSet<AuthorityId>>>),
190}