Skip to main content

zebra_network/
config.rs

1//! Configuration for Zebra's network communication.
2
3use std::{
4    collections::HashSet,
5    io::{self, ErrorKind},
6    net::{IpAddr, SocketAddr},
7    sync::Arc,
8    time::Duration,
9};
10
11use indexmap::IndexSet;
12use serde::{de, Deserialize, Deserializer};
13use tokio::fs;
14
15use tracing::Span;
16use zebra_chain::{
17    common::atomic_write,
18    parameters::{
19        constants::magics,
20        subsidy::TESTNET_INITIAL_NSM_VALUE_BALANCE,
21        testnet::{
22            self, ConfiguredActivationHeights, ConfiguredCheckpoints, ConfiguredFundingStreams,
23            ConfiguredLockboxDisbursement, RegtestParameters,
24        },
25        Magic, Network, NetworkKind,
26    },
27    work::difficulty::U256,
28};
29
30use crate::{
31    constants::{
32        DEFAULT_CRAWL_NEW_PEER_INTERVAL, DEFAULT_MAX_CONNS_PER_IP,
33        DEFAULT_PEERSET_INITIAL_TARGET_SIZE, DNS_LOOKUP_TIMEOUT, INBOUND_PEER_LIMIT_MULTIPLIER,
34        MAX_PEER_DISK_CACHE_SIZE, OUTBOUND_PEER_LIMIT_MULTIPLIER,
35    },
36    protocol::external::{canonical_peer_addr, canonical_socket_addr},
37    BoxError, PeerSocketAddr,
38};
39
40mod cache_dir;
41
42#[cfg(test)]
43mod tests;
44
45pub use cache_dir::CacheDir;
46
47/// The number of times Zebra will retry each initial peer's DNS resolution,
48/// before checking if any other initial peers have returned addresses.
49///
50/// After doing this number of retries of a failed single peer, Zebra will
51/// check if it has enough peer addresses from other seed peers. If it has
52/// enough addresses, it won't retry this peer again.
53///
54/// If the number of retries is `0`, other peers are checked after every successful
55/// or failed DNS attempt.
56const MAX_SINGLE_SEED_PEER_DNS_RETRIES: usize = 0;
57
58/// Public DNS seed endpoints, also used to isolate configured networks.
59const DEFAULT_MAINNET_PEERS: [&str; 5] = [
60    "dnsseed.str4d.xyz:8233",
61    "dnsseed.z.cash:8233",
62    "mainnet.seeder.shieldedinfra.net:8233",
63    "mainnet.seeder.zfnd.org:8233",
64    "seeder.zec.rocks:8233",
65];
66const DEFAULT_TESTNET_PEERS: [&str; 3] = [
67    "dnsseed.testnet.z.cash:18233",
68    "seeder.testnet.zec.rocks:18233",
69    "testnet.seeder.zfnd.org:18233",
70];
71
72/// Configuration for networking code.
73#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
74#[serde(deny_unknown_fields, default, into = "DConfig")]
75pub struct Config {
76    /// The address on which this node should listen for connections.
77    ///
78    /// Can be `address:port` or just `address`. If there is no configured
79    /// port, Zebra will use the default port for the configured `network`.
80    ///
81    /// `address` can be an IP address or a DNS name. DNS names are
82    /// only resolved once, when Zebra starts up.
83    ///
84    /// By default, Zebra listens on `[::]` (all IPv6 and IPv4 addresses).
85    /// This enables dual-stack support, accepting both IPv4 and IPv6 connections.
86    ///
87    /// If a specific listener address is configured, Zebra will advertise
88    /// it to other nodes. But by default, Zebra uses an unspecified address
89    /// ("\[::\]:port"), which is not advertised to other nodes.
90    ///
91    /// Zebra does not currently support:
92    /// - [Advertising a different external IP address #1890](https://github.com/ZcashFoundation/zebra/issues/1890), or
93    /// - [Auto-discovering its own external IP address #1893](https://github.com/ZcashFoundation/zebra/issues/1893).
94    ///
95    /// However, other Zebra instances compensate for unspecified or incorrect
96    /// listener addresses by adding the external IP addresses of peers to
97    /// their address books.
98    pub listen_addr: SocketAddr,
99
100    /// The external address of this node if any.
101    ///
102    /// Zebra bind to `listen_addr` but this can be an internal address if the node
103    /// is behind a firewall, load balancer or NAT. This field can be used to
104    /// advertise a different address to peers making it possible to receive inbound
105    /// connections and contribute to the P2P network from behind a firewall, load balancer, or NAT.
106    pub external_addr: Option<SocketAddr>,
107
108    /// The network to connect to.
109    pub network: Network,
110
111    /// Enable compact block relay with peers that also support it.
112    ///
113    /// Disabled by default. Peers that both set this option announce newly committed blocks to
114    /// each other as a header and short transaction IDs, and rebuild the block from their
115    /// mempools instead of downloading its transactions again. Every rebuilt block is still
116    /// verified like any other block, and relay to other peers is unchanged.
117    ///
118    /// Nodes that set it advertise the service bit that the [draft Compact Block Relay ZIP]
119    /// assigns. The option name, the service bit and the messages are the ones Zebra 7.2.0-beta.1
120    /// uses, so the two negotiate compact relay with each other. That release enables the option
121    /// by default, and also relays blocks before it commits them, which this node doesn't do.
122    ///
123    /// The ZIP lets a peer that sets the service bit relay a block before it has validated it,
124    /// once the block passes the ZIP's early relay checks, and its peer misbehaviour rules treat
125    /// the blocks from such a peer differently. So block downloads from connections where both
126    /// peers set the bit return [`Response::EarlyBlocks`](crate::Response::EarlyBlocks) instead
127    /// of [`Response::Blocks`](crate::Response::Blocks).
128    ///
129    /// [draft Compact Block Relay ZIP]: https://github.com/zcash/zips/pull/1429
130    pub compact_block_relay: bool,
131
132    /// A list of initial peers for the peerset when operating on
133    /// mainnet.
134    pub initial_mainnet_peers: IndexSet<String>,
135
136    /// A list of initial peers for the peerset when operating on
137    /// testnet.
138    pub initial_testnet_peers: IndexSet<String>,
139
140    /// An optional root directory for storing cached peer address data.
141    ///
142    /// # Configuration
143    ///
144    /// Set to:
145    /// - `true` to read and write peer addresses to disk using the default cache path,
146    /// - `false` to disable reading and writing peer addresses to disk,
147    /// - `'/custom/cache/directory'` to read and write peer addresses to a custom directory.
148    ///
149    /// By default, all Zebra instances run by the same user will share a single peer cache.
150    /// If you use a custom cache path, you might also want to change `state.cache_dir`.
151    ///
152    /// # Functionality
153    ///
154    /// The peer cache is a list of the addresses of some recently useful peers.
155    ///
156    /// For privacy reasons, the cache does *not* include any other information about peers,
157    /// such as when they were connected to the node.
158    ///
159    /// Deleting or modifying the peer cache can impact your node's:
160    /// - reliability: if DNS or the Zcash DNS seeders are unavailable or broken
161    /// - security: if DNS is compromised with malicious peers
162    ///
163    /// If you delete it, Zebra will replace it with a fresh set of peers from the DNS seeders.
164    ///
165    /// # Defaults
166    ///
167    /// The default directory is platform dependent, based on
168    /// [`dirs::cache_dir()`](https://docs.rs/dirs/3.0.1/dirs/fn.cache_dir.html):
169    ///
170    /// |Platform | Value                                           | Example                              |
171    /// | ------- | ----------------------------------------------- | ------------------------------------ |
172    /// | Linux   | `$XDG_CACHE_HOME/zebra` or `$HOME/.cache/zebra` | `/home/alice/.cache/zebra`           |
173    /// | macOS   | `$HOME/Library/Caches/zebra`                    | `/Users/Alice/Library/Caches/zebra`  |
174    /// | Windows | `{FOLDERID_LocalAppData}\zebra`                 | `C:\Users\Alice\AppData\Local\zebra` |
175    /// | Other   | `std::env::current_dir()/cache/zebra`           | `/cache/zebra`                       |
176    ///
177    /// # Security
178    ///
179    /// If you are running Zebra with elevated permissions ("root"), create the
180    /// directory for this file before running Zebra, and make sure the Zebra user
181    /// account has exclusive access to that directory, and other users can't modify
182    /// its parent directories.
183    ///
184    /// # Implementation Details
185    ///
186    /// Each network has a separate peer list, which is updated regularly from the current
187    /// address book. These lists are stored in `network/mainnet.peers` and
188    /// `network/testnet.peers` files, underneath the `cache_dir` path.
189    ///
190    /// Previous peer lists are automatically loaded at startup, and used to populate the
191    /// initial peer set and address book.
192    pub cache_dir: CacheDir,
193
194    /// The initial target size for the peer set.
195    ///
196    /// Also used to limit the number of inbound and outbound connections made by Zebra,
197    /// and the size of the cached peer list.
198    ///
199    /// If you have a slow network connection, and Zebra is having trouble
200    /// syncing, try reducing the peer set size. You can also reduce the peer
201    /// set size to reduce Zebra's bandwidth usage.
202    pub peerset_initial_target_size: usize,
203
204    /// How frequently we attempt to crawl the network to discover new peer
205    /// addresses.
206    ///
207    /// Zebra asks its connected peers for more peer addresses:
208    /// - regularly, every time `crawl_new_peer_interval` elapses, and
209    /// - if the peer set is busy, and there aren't any peer addresses for the
210    ///   next connection attempt.
211    ///
212    /// When no peer cache file exists on disk yet and this interval is shorter than 20 seconds,
213    /// Zebra makes its first peer cache update attempt after this interval, rather than after
214    /// 20 seconds. Existing cache files and unsuccessful retries still wait 20 seconds.
215    #[serde(with = "humantime_serde")]
216    pub crawl_new_peer_interval: Duration,
217
218    /// The maximum number of peer connections Zebra will keep for a given IP address
219    /// before it drops any additional peer connections with that IP.
220    ///
221    /// IPv6 connections are grouped by `/64` prefix, so the limit applies per
222    /// `/64` subnet rather than per individual address. IPv4 connections are
223    /// limited per address.
224    ///
225    /// The default and minimum value are 1.
226    ///
227    /// # Security
228    ///
229    /// Increasing this config above 1 reduces Zebra's network security.
230    ///
231    /// If this config is greater than 1, Zebra can initiate multiple outbound handshakes to the same
232    /// IP address.
233    ///
234    /// Inbound connection attempts sharing a connection limit key are also rate-limited
235    /// by this config within a short time window.
236    ///
237    /// If Zebra makes multiple inbound or outbound connections to the same IP, they will be dropped
238    /// after the handshake, but before adding them to the peer set. The total numbers of inbound and
239    /// outbound connections are also limited to a multiple of `peerset_initial_target_size`.
240    pub max_connections_per_ip: usize,
241}
242
243impl Config {
244    /// The maximum number of outbound connections that Zebra will open at the same time.
245    /// When this limit is reached, Zebra stops opening outbound connections.
246    ///
247    /// # Security
248    ///
249    /// See the note at [`INBOUND_PEER_LIMIT_MULTIPLIER`].
250    ///
251    /// # Performance
252    ///
253    /// Zebra's peer set should be limited to a reasonable size,
254    /// to avoid queueing too many in-flight block downloads.
255    /// A large queue of in-flight block downloads can choke a
256    /// constrained local network connection.
257    ///
258    /// We assume that Zebra nodes have at least 10 Mbps bandwidth.
259    /// Therefore, a maximum-sized block can take up to 2 seconds to
260    /// download. So the initial outbound peer set adds up to 100 seconds worth
261    /// of blocks to the queue. If Zebra has reached its outbound peer limit,
262    /// that adds an extra 200 seconds of queued blocks.
263    ///
264    /// But the peer set for slow nodes is typically much smaller, due to
265    /// the handshake RTT timeout. And Zebra responds to inbound request
266    /// overloads by dropping peer connections.
267    pub fn peerset_outbound_connection_limit(&self) -> usize {
268        self.peerset_initial_target_size * OUTBOUND_PEER_LIMIT_MULTIPLIER
269    }
270
271    /// The maximum number of inbound connections that Zebra will accept at the same time.
272    /// When this limit is reached, Zebra drops new inbound connections,
273    /// without handshaking on them.
274    ///
275    /// # Security
276    ///
277    /// See the note at [`INBOUND_PEER_LIMIT_MULTIPLIER`].
278    pub fn peerset_inbound_connection_limit(&self) -> usize {
279        self.peerset_initial_target_size * INBOUND_PEER_LIMIT_MULTIPLIER
280    }
281
282    /// The maximum number of inbound and outbound connections that Zebra will have
283    /// at the same time.
284    pub fn peerset_total_connection_limit(&self) -> usize {
285        self.peerset_outbound_connection_limit() + self.peerset_inbound_connection_limit()
286    }
287
288    /// Returns the initial seed peer hostnames for the configured network.
289    pub fn initial_peer_hostnames(&self) -> IndexSet<String> {
290        match &self.network {
291            Network::Mainnet => self.initial_mainnet_peers.clone(),
292            Network::Testnet(params) if params.local_initial_peers_only() => self
293                .initial_testnet_peers
294                .iter()
295                .filter(|peer| !is_default_initial_peer(peer))
296                .cloned()
297                .collect(),
298            Network::Testnet(_params) => self.initial_testnet_peers.clone(),
299        }
300    }
301
302    /// Resolve initial seed peer IP addresses, based on the configured network,
303    /// and load cached peers from disk, if available.
304    ///
305    /// # Panics
306    ///
307    /// If a configured address is an invalid [`SocketAddr`] or DNS name.
308    pub async fn initial_peers(&self) -> HashSet<PeerSocketAddr> {
309        let hostnames = self.initial_peer_hostnames().iter().cloned().collect();
310
311        if self.network.local_initial_peers_only() {
312            // Only return localhost seed peer addresses and skip loading the disk peer cache.
313            return Config::resolve_peers(&hostnames, true)
314                .await
315                .into_iter()
316                .filter(PeerSocketAddr::is_localhost)
317                .collect();
318        }
319
320        // Load the disk cache first, so that failing DNS can't stop Zebra using cached peers.
321        // Ignore disk errors because the cache is optional and the method already logs them.
322        let disk_peers = self.load_peer_cache().await.unwrap_or_default();
323
324        let dns_peers = Config::resolve_peers(&hostnames, disk_peers.is_empty()).await;
325
326        dns_peers.into_iter().chain(disk_peers).collect()
327    }
328
329    /// Concurrently resolves `peers` into zero or more IP addresses, with a
330    /// timeout of a few seconds on each DNS request.
331    ///
332    /// If DNS resolution fails or times out for all peers, and `retry_until_found` is true,
333    /// continues retrying until at least one peer is found.
334    async fn resolve_peers(
335        peers: &HashSet<String>,
336        retry_until_found: bool,
337    ) -> HashSet<PeerSocketAddr> {
338        use futures::stream::StreamExt;
339
340        if peers.is_empty() {
341            warn!(
342                "no initial peers in the network config. \
343                 Hint: you must configure at least one peer IP or DNS seeder to run Zebra, \
344                 give it some previously cached peer IP addresses on disk, \
345                 or make sure Zebra's listener port gets inbound connections."
346            );
347            return HashSet::new();
348        }
349
350        loop {
351            // We retry each peer individually, as well as retrying if there are
352            // no peers in the combined list. DNS failures are correlated, so all
353            // peers can fail DNS, leaving Zebra with a small list of custom IP
354            // address peers. Individual retries avoid this issue.
355            let peer_addresses = peers
356                .iter()
357                .map(|s| Config::resolve_host(s, MAX_SINGLE_SEED_PEER_DNS_RETRIES))
358                .collect::<futures::stream::FuturesUnordered<_>>()
359                .concat()
360                .await;
361
362            if !peer_addresses.is_empty() {
363                return peer_addresses;
364            }
365
366            if !retry_until_found {
367                tracing::info!(
368                    ?peers,
369                    "empty peer list after DNS resolution, using the cached peers",
370                );
371                return peer_addresses;
372            }
373
374            tracing::info!(
375                ?peers,
376                ?peer_addresses,
377                "empty peer list after DNS resolution, retrying after {} seconds",
378                DNS_LOOKUP_TIMEOUT.as_secs(),
379            );
380            tokio::time::sleep(DNS_LOOKUP_TIMEOUT).await;
381        }
382    }
383
384    /// Resolves `host` into zero or more IP addresses, retrying up to
385    /// `max_retries` times.
386    ///
387    /// If DNS continues to fail, returns an empty list of addresses.
388    ///
389    /// # Panics
390    ///
391    /// If a configured address is an invalid [`SocketAddr`] or DNS name.
392    async fn resolve_host(host: &str, max_retries: usize) -> HashSet<PeerSocketAddr> {
393        for retries in 0..=max_retries {
394            if let Ok(addresses) = Config::resolve_host_once(host).await {
395                return addresses;
396            }
397
398            if retries < max_retries {
399                tracing::info!(
400                    ?host,
401                    previous_attempts = ?(retries + 1),
402                    "Waiting {DNS_LOOKUP_TIMEOUT:?} to retry seed peer DNS resolution",
403                );
404                tokio::time::sleep(DNS_LOOKUP_TIMEOUT).await;
405            } else {
406                tracing::info!(
407                    ?host,
408                    attempts = ?(retries + 1),
409                    "Seed peer DNS resolution failed, checking for addresses from other seed peers",
410                );
411            }
412        }
413
414        HashSet::new()
415    }
416
417    /// Resolves `host` into zero or more IP addresses.
418    ///
419    /// If `host` is a DNS name, performs DNS resolution with a timeout of a few seconds.
420    /// If DNS resolution fails or times out, returns an error.
421    ///
422    /// # Panics
423    ///
424    /// If a configured address is an invalid [`SocketAddr`] or DNS name.
425    async fn resolve_host_once(host: &str) -> Result<HashSet<PeerSocketAddr>, BoxError> {
426        let fut = tokio::net::lookup_host(host);
427        let fut = tokio::time::timeout(DNS_LOOKUP_TIMEOUT, fut);
428
429        match fut.await {
430            Ok(Ok(ip_addrs)) => {
431                let ip_addrs: Vec<PeerSocketAddr> = ip_addrs.map(canonical_peer_addr).collect();
432
433                // This log is needed for user debugging, but it's annoying during tests.
434                #[cfg(not(test))]
435                info!(seed = ?host, remote_ip_count = ?ip_addrs.len(), "resolved seed peer IP addresses");
436                #[cfg(test)]
437                debug!(seed = ?host, remote_ip_count = ?ip_addrs.len(), "resolved seed peer IP addresses");
438
439                // Count the initial peers from this seed. If an IP is returned by multiple seeds,
440                // each duplicate adds 1 to the initial peer count. (But we only make one initial
441                // connection attempt to each IP.)
442                metrics::counter!("zcash.net.peers.initial", "seed" => seed_metric_label(host))
443                    .increment(
444                        u64::try_from(ip_addrs.len()).expect("a peer address count fits in u64"),
445                    );
446
447                Ok(ip_addrs.into_iter().collect())
448            }
449            Ok(Err(e)) if e.kind() == ErrorKind::InvalidInput => {
450                // TODO: add testnet/mainnet ports, like we do with the listener address
451                panic!(
452                    "Invalid peer IP address in Zebra config: addresses must have ports:\n\
453                     resolving {host:?} returned {e:?}"
454                );
455            }
456            Ok(Err(e)) => {
457                tracing::info!(?host, ?e, "DNS error resolving peer IP addresses");
458                Err(e.into())
459            }
460            Err(e) => {
461                tracing::info!(?host, ?e, "DNS timeout resolving peer IP addresses");
462                Err(e.into())
463            }
464        }
465    }
466
467    /// Returns the addresses in the peer list cache file, if available.
468    pub async fn load_peer_cache(&self) -> io::Result<HashSet<PeerSocketAddr>> {
469        let Some(peer_cache_file) = self.cache_dir.peer_cache_file_path(&self.network) else {
470            return Ok(HashSet::new());
471        };
472
473        let peer_list = match fs::read_to_string(&peer_cache_file).await {
474            Ok(peer_list) => peer_list,
475            Err(peer_list_error) => {
476                // We expect that the cache will be missing for new Zebra installs
477                if peer_list_error.kind() == ErrorKind::NotFound {
478                    return Ok(HashSet::new());
479                } else {
480                    info!(
481                        ?peer_list_error,
482                        "could not load cached peer list, using default seed peers"
483                    );
484                    return Err(peer_list_error);
485                }
486            }
487        };
488
489        // Skip and log addresses that don't parse, and automatically deduplicate using the HashSet.
490        // (These issues shouldn't happen unless users modify the file.)
491        let peer_list: HashSet<PeerSocketAddr> = peer_list
492            .lines()
493            .filter_map(|peer| {
494                peer.parse()
495                    .map_err(|peer_parse_error| {
496                        info!(
497                            ?peer_parse_error,
498                            "invalid peer address in cached peer list, skipping"
499                        );
500                        peer_parse_error
501                    })
502                    .ok()
503            })
504            .collect();
505
506        // This log is needed for user debugging, but it's annoying during tests.
507        #[cfg(not(test))]
508        info!(
509            cached_ip_count = ?peer_list.len(),
510            ?peer_cache_file,
511            "loaded cached peer IP addresses"
512        );
513        #[cfg(test)]
514        debug!(
515            cached_ip_count = ?peer_list.len(),
516            ?peer_cache_file,
517            "loaded cached peer IP addresses"
518        );
519
520        // Count the initial peers from the cache. If an IP is returned by DNS seeders and the
521        // cache, each duplicate adds 1 to the initial peer count. (But we only make one initial
522        // connection attempt to each IP.)
523        metrics::counter!("zcash.net.peers.initial")
524            .increment(u64::try_from(peer_list.len()).expect("a peer address count fits in u64"));
525
526        Ok(peer_list)
527    }
528
529    /// Atomically writes a new `peer_list` to the peer list cache file, if configured.
530    /// If the list is empty, keeps the previous cache file.
531    ///
532    /// Also creates the peer cache directory, if it doesn't already exist.
533    ///
534    /// Atomic writes avoid corrupting the cache if Zebra panics or crashes, or if multiple Zebra
535    /// instances try to read and write the same cache file.
536    pub async fn update_peer_cache(&self, peer_list: HashSet<PeerSocketAddr>) -> io::Result<()> {
537        let Some(peer_cache_file) = self.cache_dir.peer_cache_file_path(&self.network) else {
538            return Ok(());
539        };
540
541        if peer_list.is_empty() {
542            info!(
543                ?peer_cache_file,
544                "cacheable peer list was empty, keeping previous cache"
545            );
546            return Ok(());
547        }
548
549        // Turn IP addresses into strings
550        let mut peer_list: Vec<String> = peer_list
551            .iter()
552            .take(MAX_PEER_DISK_CACHE_SIZE)
553            .map(|redacted_peer| redacted_peer.remove_socket_addr_privacy().to_string())
554            .collect();
555        // # Privacy
556        //
557        // Sort to destroy any peer order, which could leak peer connection times.
558        // (Currently the HashSet argument does this as well.)
559        peer_list.sort();
560        // Make a newline-separated list
561        let peer_data = peer_list.join("\n");
562
563        // Write the peer cache file atomically so the cache is not corrupted if Zebra shuts down
564        // or crashes.
565        let span = Span::current();
566        let write_result = tokio::task::spawn_blocking(move || {
567            span.in_scope(move || atomic_write(peer_cache_file, peer_data.as_bytes()))
568        })
569        .await
570        .expect("could not write the peer cache file")?;
571
572        match write_result {
573            Ok(peer_cache_file) => {
574                info!(
575                    cached_ip_count = ?peer_list.len(),
576                    ?peer_cache_file,
577                    "updated cached peer IP addresses"
578                );
579
580                metrics::counter!("zcash.net.peers.cache").increment(
581                    u64::try_from(peer_list.len()).expect("a peer address count fits in u64"),
582                );
583
584                Ok(())
585            }
586            Err(error) => Err(error.error),
587        }
588    }
589}
590
591impl Default for Config {
592    fn default() -> Config {
593        let mainnet_peers = DEFAULT_MAINNET_PEERS
594            .into_iter()
595            .map(String::from)
596            .collect();
597        let testnet_peers = DEFAULT_TESTNET_PEERS
598            .into_iter()
599            .map(String::from)
600            .collect();
601
602        Config {
603            listen_addr: "[::]:8233"
604                .parse()
605                .expect("Hardcoded address should be parseable"),
606            external_addr: None,
607            network: Network::Mainnet,
608            compact_block_relay: false,
609            initial_mainnet_peers: mainnet_peers,
610            initial_testnet_peers: testnet_peers,
611            cache_dir: CacheDir::default(),
612            crawl_new_peer_interval: DEFAULT_CRAWL_NEW_PEER_INTERVAL,
613
614            // # Security
615            //
616            // The default peerset target size should be large enough to ensure
617            // nodes have a reliable set of peers.
618            //
619            // But Zebra should only make a small number of initial outbound connections,
620            // so that idle peers don't use too many connection slots.
621            peerset_initial_target_size: DEFAULT_PEERSET_INITIAL_TARGET_SIZE,
622            max_connections_per_ip: DEFAULT_MAX_CONNS_PER_IP,
623        }
624    }
625}
626
627#[derive(Serialize, Deserialize)]
628#[serde(deny_unknown_fields)]
629struct DTestnetParameters {
630    network_name: Option<String>,
631    network_magic: Option<[u8; 4]>,
632    slow_start_interval: Option<u32>,
633    target_difficulty_limit: Option<String>,
634    disable_pow: Option<bool>,
635    genesis_hash: Option<String>,
636    activation_heights: Option<ConfiguredActivationHeights>,
637    /// Override for the first NSM reissuance height; omission uses ZIP 237's crossover.
638    nsm_reissuance_height: Option<zebra_chain::block::Height>,
639    pre_nu6_funding_streams: Option<ConfiguredFundingStreams>,
640    post_nu6_funding_streams: Option<ConfiguredFundingStreams>,
641    /// Omission retains the default streams; an explicitly empty list disables them.
642    /// An empty list cannot be combined with either legacy funding stream field.
643    funding_streams: Option<Vec<ConfiguredFundingStreams>>,
644    /// Must yield a supported first halving height and a schedule within the monetary cap.
645    /// Configured reissuance needs a positive coefficient; funding streams need a nonzero
646    /// address-change interval.
647    pre_blossom_halving_interval: Option<u32>,
648    lockbox_disbursements: Option<Vec<ConfiguredLockboxDisbursement>>,
649    #[serde(default)]
650    checkpoints: ConfiguredCheckpoints,
651    /// If `true`, automatically repeats configured funding stream addresses to fill
652    /// all required periods.
653    extend_funding_stream_addresses_as_required: Option<bool>,
654    /// Height at which the soft fork that temporarily disables Orchard actions activates.
655    ///
656    /// If unset, the default activation height for the network is used; the soft fork
657    /// cannot be disabled via configuration.
658    temporary_orchard_disabling_soft_fork_height: Option<u32>,
659    /// Regtest only: whether to allow coinbase spends to have transparent outputs.
660    should_allow_unshielded_coinbase_spends: Option<bool>,
661
662    /// Regtest and configured Testnets only: the NSM value balance seeded at NU7 activation
663    /// under the halving-preserving issuance ZIP.
664    initial_nsm_value_balance:
665        Option<zebra_chain::amount::Amount<zebra_chain::amount::NonNegative>>,
666}
667
668/// Network configuration used during deserialization.
669#[derive(Serialize, Deserialize)]
670#[serde(untagged)]
671enum DNetwork {
672    DefaultForKind(NetworkKind),
673    ConfiguredRegtest {
674        params: Box<DTestnetParameters>,
675
676        #[serde(default, skip_serializing)]
677        regtest: Option<bool>,
678    },
679    ConfiguredTestnet(Box<DTestnetParameters>),
680}
681
682impl Default for DNetwork {
683    fn default() -> Self {
684        DNetwork::DefaultForKind(NetworkKind::Mainnet)
685    }
686}
687
688#[derive(Serialize, Deserialize)]
689#[serde(deny_unknown_fields, default)]
690struct DConfig {
691    listen_addr: String,
692    external_addr: Option<String>,
693    network: DNetwork,
694    compact_block_relay: bool,
695
696    /// Legacy testnet parameters, kept for backwards compatibility.
697    #[serde(default, skip_serializing_if = "Option::is_none")]
698    testnet_parameters: Option<DTestnetParameters>,
699
700    initial_mainnet_peers: IndexSet<String>,
701    initial_testnet_peers: IndexSet<String>,
702    cache_dir: CacheDir,
703    peerset_initial_target_size: usize,
704    #[serde(alias = "new_peer_interval", with = "humantime_serde")]
705    crawl_new_peer_interval: Duration,
706    max_connections_per_ip: Option<usize>,
707}
708
709impl Default for DConfig {
710    fn default() -> Self {
711        let config = Config::default();
712        Self {
713            listen_addr: "[::]".to_string(),
714            external_addr: None,
715            network: Default::default(),
716            compact_block_relay: config.compact_block_relay,
717            testnet_parameters: None,
718            initial_mainnet_peers: config.initial_mainnet_peers,
719            initial_testnet_peers: config.initial_testnet_peers,
720            cache_dir: config.cache_dir,
721            peerset_initial_target_size: config.peerset_initial_target_size,
722            crawl_new_peer_interval: config.crawl_new_peer_interval,
723            max_connections_per_ip: Some(config.max_connections_per_ip),
724        }
725    }
726}
727
728impl From<Arc<testnet::Parameters>> for DTestnetParameters {
729    fn from(params: Arc<testnet::Parameters>) -> Self {
730        Self {
731            network_name: Some(params.network_name().to_string()),
732            network_magic: Some(params.network_magic().0),
733            slow_start_interval: Some(params.slow_start_interval().0),
734            target_difficulty_limit: Some(params.target_difficulty_limit().to_string()),
735            disable_pow: Some(params.disable_pow()),
736            genesis_hash: Some(params.genesis_hash().to_string()),
737            activation_heights: Some(params.activation_heights().into()),
738            nsm_reissuance_height: params.configured_nsm_reissuance_height(),
739            pre_nu6_funding_streams: None,
740            post_nu6_funding_streams: None,
741            initial_nsm_value_balance: params.configured_initial_nsm_value_balance(),
742            funding_streams: Some(params.funding_streams().iter().map(Into::into).collect()),
743            pre_blossom_halving_interval: Some(
744                params
745                    .pre_blossom_halving_interval()
746                    .try_into()
747                    .expect("should convert"),
748            ),
749            lockbox_disbursements: Some(
750                params
751                    .lockbox_disbursements()
752                    .into_iter()
753                    .map(Into::into)
754                    .collect(),
755            ),
756            checkpoints: if params.checkpoints() == testnet::Parameters::default().checkpoints() {
757                ConfiguredCheckpoints::Default(true)
758            } else {
759                params.checkpoints().into()
760            },
761            extend_funding_stream_addresses_as_required: None,
762            temporary_orchard_disabling_soft_fork_height: params
763                .temporary_orchard_disabling_soft_fork_height()
764                .map(|height| height.0),
765            should_allow_unshielded_coinbase_spends: params
766                .is_regtest()
767                .then(|| params.should_allow_unshielded_coinbase_spends()),
768        }
769    }
770}
771
772impl From<Config> for DConfig {
773    fn from(
774        Config {
775            listen_addr,
776            external_addr,
777            network,
778            compact_block_relay,
779            initial_mainnet_peers,
780            initial_testnet_peers,
781            cache_dir,
782            peerset_initial_target_size,
783            crawl_new_peer_interval,
784            max_connections_per_ip,
785        }: Config,
786    ) -> Self {
787        let dnetwork = match network.kind() {
788            NetworkKind::Testnet => match network
789                .parameters()
790                .filter(|params| !params.is_default_testnet())
791                .map(Into::into)
792            {
793                Some(params) => DNetwork::ConfiguredTestnet(Box::new(params)),
794                None => DNetwork::DefaultForKind(NetworkKind::Testnet),
795            },
796
797            NetworkKind::Regtest => match network.parameters().map(Into::into) {
798                Some(params) => DNetwork::ConfiguredRegtest {
799                    params: Box::new(params),
800                    regtest: Some(true),
801                },
802                None => DNetwork::DefaultForKind(NetworkKind::Regtest),
803            },
804
805            other_kind => DNetwork::DefaultForKind(other_kind),
806        };
807
808        DConfig {
809            listen_addr: listen_addr.to_string(),
810            external_addr: external_addr.map(|addr| addr.to_string()),
811            network: dnetwork,
812            compact_block_relay,
813            testnet_parameters: None,
814            initial_mainnet_peers,
815            initial_testnet_peers,
816            cache_dir,
817            peerset_initial_target_size,
818            crawl_new_peer_interval,
819            max_connections_per_ip: Some(max_connections_per_ip),
820        }
821    }
822}
823
824impl<'de> Deserialize<'de> for Config {
825    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
826    where
827        D: Deserializer<'de>,
828    {
829        let DConfig {
830            listen_addr,
831            external_addr,
832            network: dnetwork,
833            compact_block_relay,
834            testnet_parameters,
835            initial_mainnet_peers,
836            initial_testnet_peers,
837            cache_dir,
838            peerset_initial_target_size,
839            crawl_new_peer_interval,
840            max_connections_per_ip,
841        } = DConfig::deserialize(deserializer)?;
842
843        let network = match (dnetwork, testnet_parameters) {
844            (DNetwork::ConfiguredTestnet(params), _) => {
845                build_configured_testnet::<D>(*params, &initial_testnet_peers)?
846            }
847            (DNetwork::ConfiguredRegtest { params, .. }, _) => testnet::Parameters::new_regtest(
848                build_regtest_params(*params).map_err(de::Error::custom)?,
849            )
850            .map(Network::new_configured_testnet)
851            .map_err(de::Error::custom)?,
852            (DNetwork::DefaultForKind(NetworkKind::Mainnet), _) => Network::Mainnet,
853            (DNetwork::DefaultForKind(NetworkKind::Testnet), Some(params)) => {
854                build_configured_testnet::<D>(params, &initial_testnet_peers)?
855            }
856            (DNetwork::DefaultForKind(NetworkKind::Testnet), None) => {
857                Network::new_default_testnet()
858            }
859            (DNetwork::DefaultForKind(NetworkKind::Regtest), Some(params)) => {
860                testnet::Parameters::new_regtest(
861                    build_regtest_params(params).map_err(de::Error::custom)?,
862                )
863                .map(Network::new_configured_testnet)
864                .map_err(de::Error::custom)?
865            }
866            (DNetwork::DefaultForKind(NetworkKind::Regtest), None) => {
867                Network::new_regtest(Default::default())
868            }
869        };
870
871        let listen_addr = match listen_addr.parse::<SocketAddr>().or_else(|_| format!("{listen_addr}:{}", network.default_port()).parse()) {
872            Ok(socket) => Ok(socket),
873            Err(_) => match listen_addr.parse::<IpAddr>() {
874                Ok(ip) => Ok(SocketAddr::new(ip, network.default_port())),
875                Err(err) => Err(de::Error::custom(format!(
876                    "{err}; Hint: addresses can be a IPv4, IPv6 (with brackets), or a DNS name, the port is optional"
877                ))),
878            },
879        }?;
880
881        let external_socket_addr = if let Some(address) = &external_addr {
882            match address.parse::<SocketAddr>().or_else(|_| format!("{address}:{}", network.default_port()).parse()) {
883                Ok(socket) => Ok(Some(socket)),
884                Err(_) => match address.parse::<IpAddr>() {
885                    Ok(ip) => Ok(Some(SocketAddr::new(ip, network.default_port()))),
886                    Err(err) => Err(de::Error::custom(format!(
887                        "{err}; Hint: addresses can be a IPv4, IPv6 (with brackets), or a DNS name, the port is optional"
888                    ))),
889                },
890            }?
891        } else {
892            None
893        };
894
895        let [max_connections_per_ip, peerset_initial_target_size] = [
896            ("max_connections_per_ip", max_connections_per_ip, DEFAULT_MAX_CONNS_PER_IP),
897            // If we want Zebra to operate with no network,
898            // we should implement a `zebrad` command that doesn't use `zebra-network`.
899            ("peerset_initial_target_size", Some(peerset_initial_target_size), DEFAULT_PEERSET_INITIAL_TARGET_SIZE)
900        ].map(|(field_name, non_zero_config_field, default_config_value)| {
901            if non_zero_config_field == Some(0) {
902                warn!(
903                    ?field_name,
904                    ?non_zero_config_field,
905                    "{field_name} should be greater than 0, using default value of {default_config_value} instead"
906                );
907            }
908
909            non_zero_config_field.filter(|config_value| config_value > &0).unwrap_or(default_config_value)
910        });
911
912        Ok(Config {
913            listen_addr: canonical_socket_addr(listen_addr),
914            external_addr: external_socket_addr,
915            network,
916            compact_block_relay,
917            initial_mainnet_peers,
918            initial_testnet_peers,
919            cache_dir,
920            peerset_initial_target_size,
921            crawl_new_peer_interval,
922            max_connections_per_ip,
923        })
924    }
925}
926
927/// Returns true for a public DNS seed hostname, regardless of case, trailing dot, or port.
928fn is_default_initial_peer(peer: &str) -> bool {
929    fn hostname(peer: &str) -> &str {
930        peer.rsplit_once(':').map_or(peer, |(host, _)| host)
931    }
932    let peer_host = hostname(peer).trim_end_matches('.');
933    DEFAULT_MAINNET_PEERS
934        .iter()
935        .chain(&DEFAULT_TESTNET_PEERS)
936        .any(|default| peer_host.eq_ignore_ascii_case(hostname(default)))
937}
938
939/// Returns `host` if it is exactly one of the default DNS seeders, and `custom` otherwise.
940///
941/// Operators can configure private peer addresses, which must not reach metrics backends.
942fn seed_metric_label(host: &str) -> &'static str {
943    DEFAULT_MAINNET_PEERS
944        .iter()
945        .chain(&DEFAULT_TESTNET_PEERS)
946        .find(|default| **default == host)
947        .copied()
948        .unwrap_or("custom")
949}
950
951fn build_configured_testnet<'de, D>(
952    params: DTestnetParameters,
953    initial_testnet_peers: &IndexSet<String>,
954) -> Result<Network, D::Error>
955where
956    D: Deserializer<'de>,
957{
958    let DTestnetParameters {
959        network_name,
960        network_magic,
961        slow_start_interval,
962        target_difficulty_limit,
963        disable_pow,
964        genesis_hash,
965        activation_heights,
966        nsm_reissuance_height,
967        pre_nu6_funding_streams,
968        post_nu6_funding_streams,
969        funding_streams,
970        pre_blossom_halving_interval,
971        lockbox_disbursements,
972        checkpoints,
973        extend_funding_stream_addresses_as_required,
974        temporary_orchard_disabling_soft_fork_height,
975        should_allow_unshielded_coinbase_spends,
976        initial_nsm_value_balance,
977    } = params;
978
979    // This is a Regtest-only consensus knob, so reject it rather than silently ignoring it.
980    if should_allow_unshielded_coinbase_spends.is_some() {
981        return Err(de::Error::custom(
982            "should_allow_unshielded_coinbase_spends is only supported on Regtest",
983        ));
984    }
985
986    let mut params_builder = testnet::Parameters::build();
987
988    // A redundant public seed must not turn public Testnet into a configured network.
989    if let Some(initial_nsm_value_balance) = initial_nsm_value_balance.filter(|seed| {
990        network_magic.map(Magic).unwrap_or(magics::TESTNET) != magics::TESTNET
991            || u64::from(*seed) != TESTNET_INITIAL_NSM_VALUE_BALANCE
992    }) {
993        params_builder = params_builder.with_initial_nsm_value_balance(initial_nsm_value_balance);
994    }
995
996    if let Some(network_name) = network_name.clone() {
997        params_builder = params_builder
998            .with_network_name(network_name)
999            .map_err(de::Error::custom)?
1000    }
1001
1002    if let Some(network_magic) = network_magic {
1003        params_builder = params_builder
1004            .with_network_magic(Magic(network_magic))
1005            .map_err(de::Error::custom)?;
1006    }
1007
1008    if let Some(genesis_hash) = genesis_hash {
1009        params_builder = params_builder
1010            .with_genesis_hash(genesis_hash)
1011            .map_err(de::Error::custom)?;
1012    }
1013
1014    if let Some(slow_start_interval) = slow_start_interval {
1015        params_builder = params_builder
1016            .with_slow_start_interval(slow_start_interval.try_into().map_err(de::Error::custom)?);
1017    }
1018
1019    if let Some(target_difficulty_limit) = target_difficulty_limit.clone() {
1020        params_builder = params_builder
1021            .with_target_difficulty_limit(
1022                target_difficulty_limit
1023                    .parse::<U256>()
1024                    .map_err(de::Error::custom)?,
1025            )
1026            .map_err(de::Error::custom)?;
1027    }
1028
1029    if let Some(disable_pow) = disable_pow {
1030        params_builder = params_builder.with_disable_pow(disable_pow);
1031    }
1032
1033    // Retain default Testnet activation heights unless there's an empty [testnet_parameters.activation_heights] section.
1034    if let Some(activation_heights) = activation_heights {
1035        params_builder = params_builder
1036            .with_activation_heights(activation_heights)
1037            .map_err(de::Error::custom)?
1038    }
1039
1040    if let Some(height) = nsm_reissuance_height {
1041        params_builder = params_builder.with_nsm_reissuance_height(height);
1042    }
1043
1044    if let Some(halving_interval) = pre_blossom_halving_interval {
1045        params_builder = params_builder
1046            .with_halving_interval(halving_interval.into())
1047            .map_err(de::Error::custom)?
1048    }
1049
1050    // Set configured funding streams after setting any parameters that affect the funding stream address period.
1051    if let Some(funding_streams) = merge_funding_streams(
1052        funding_streams,
1053        pre_nu6_funding_streams,
1054        post_nu6_funding_streams,
1055    )
1056    .map_err(de::Error::custom)?
1057    {
1058        params_builder = params_builder.with_funding_streams(funding_streams);
1059    }
1060
1061    if let Some(lockbox_disbursements) = lockbox_disbursements {
1062        params_builder = params_builder.with_lockbox_disbursements(lockbox_disbursements);
1063    }
1064
1065    params_builder = params_builder
1066        .with_checkpoints(checkpoints)
1067        .map_err(de::Error::custom)?;
1068
1069    if let Some(true) = extend_funding_stream_addresses_as_required {
1070        params_builder = params_builder
1071            .extend_funding_streams()
1072            .map_err(de::Error::custom)?;
1073    }
1074
1075    // Retain the default soft-fork activation height unless one is configured.
1076    if let Some(height) = temporary_orchard_disabling_soft_fork_height {
1077        params_builder = params_builder.with_temporary_orchard_disabling_soft_fork_height(
1078            height.try_into().map_err(de::Error::custom)?,
1079        );
1080    }
1081
1082    // Preserve the canonical public Testnet representation when no parameters changed.
1083    if network_name.is_none() && params_builder == testnet::Parameters::build() {
1084        return Ok(Network::new_default_testnet());
1085    }
1086
1087    if !params_builder.is_compatible_with_default_parameters() {
1088        // Keep the diagnostic for explicitly configured public seeds, even with isolated magic.
1089        if initial_testnet_peers
1090            .iter()
1091            .any(|peer| is_default_initial_peer(peer))
1092        {
1093            return Err(de::Error::custom(
1094                "cannot use default initial peers with incompatible testnet; \
1095                 for public Testnet, remove explicit consensus overrides from \
1096                 [network.testnet_parameters] to use the updated public defaults, including NU7; \
1097                 for a custom network, configure its own initial_testnet_peers and \
1098                 network_magic distinct from public Testnet",
1099            ));
1100        }
1101
1102        // Peer names cannot enforce isolation: aliases, cached peers, and inbound connections
1103        // can all reach public Testnet. Incompatible consensus rules require distinct wire magic.
1104        if network_magic.map(Magic).unwrap_or(magics::TESTNET) == magics::TESTNET {
1105            return Err(de::Error::custom(
1106                "incompatible testnet parameters require network_magic distinct from public Testnet; \
1107                 for public Testnet, remove explicit consensus overrides from \
1108                 [network.testnet_parameters] (including activation_heights and funding_streams) \
1109                 to use the updated public defaults, including NU7; for a custom network, configure its own \
1110                 network_magic and initial_testnet_peers",
1111            ));
1112        }
1113    }
1114
1115    params_builder.to_network().map_err(de::Error::custom)
1116}
1117
1118fn build_regtest_params(params: DTestnetParameters) -> Result<RegtestParameters, &'static str> {
1119    let DTestnetParameters {
1120        activation_heights,
1121        nsm_reissuance_height,
1122        pre_nu6_funding_streams,
1123        post_nu6_funding_streams,
1124        funding_streams,
1125        lockbox_disbursements,
1126        checkpoints,
1127        extend_funding_stream_addresses_as_required,
1128        should_allow_unshielded_coinbase_spends,
1129        initial_nsm_value_balance,
1130        ..
1131    } = params;
1132
1133    Ok(RegtestParameters {
1134        activation_heights: activation_heights.unwrap_or_default(),
1135        nsm_reissuance_height,
1136        funding_streams: merge_funding_streams(
1137            funding_streams,
1138            pre_nu6_funding_streams,
1139            post_nu6_funding_streams,
1140        )?,
1141        lockbox_disbursements,
1142        checkpoints: Some(checkpoints),
1143        extend_funding_stream_addresses_as_required,
1144        should_allow_unshielded_coinbase_spends,
1145        initial_nsm_value_balance,
1146    })
1147}
1148
1149/// Merge legacy streams before the current list, preserving omission and explicit disable.
1150fn merge_funding_streams(
1151    funding_streams: Option<Vec<ConfiguredFundingStreams>>,
1152    pre_nu6_funding_streams: Option<ConfiguredFundingStreams>,
1153    post_nu6_funding_streams: Option<ConfiguredFundingStreams>,
1154) -> Result<Option<Vec<ConfiguredFundingStreams>>, &'static str> {
1155    let has_legacy_streams =
1156        pre_nu6_funding_streams.is_some() || post_nu6_funding_streams.is_some();
1157    if funding_streams.as_ref().is_some_and(Vec::is_empty) && has_legacy_streams {
1158        return Err(
1159            "funding_streams = [] cannot be combined with pre_nu6_funding_streams or post_nu6_funding_streams",
1160        );
1161    }
1162
1163    let specified = funding_streams.is_some() || has_legacy_streams;
1164    let mut funding_streams = funding_streams.unwrap_or_default();
1165    if let Some(mut post_nu6) = post_nu6_funding_streams {
1166        // Legacy names select their own defaults, not their position in the merged list.
1167        if post_nu6.height_range.is_none() || post_nu6.recipients.is_none() {
1168            let default_parameters = testnet::Parameters::default();
1169            let defaults = &default_parameters.funding_streams()[1];
1170            post_nu6
1171                .height_range
1172                .get_or_insert_with(|| defaults.height_range().clone());
1173            if post_nu6.recipients.is_none() {
1174                post_nu6.recipients = ConfiguredFundingStreams::from(defaults).recipients;
1175            }
1176        }
1177        funding_streams.insert(0, post_nu6);
1178    }
1179    if let Some(pre_nu6) = pre_nu6_funding_streams {
1180        funding_streams.insert(0, pre_nu6);
1181    }
1182
1183    Ok(specified.then_some(funding_streams))
1184}