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    #[serde(with = "humantime_serde")]
212    pub crawl_new_peer_interval: Duration,
213
214    /// The maximum number of peer connections Zebra will keep for a given IP address
215    /// before it drops any additional peer connections with that IP.
216    ///
217    /// IPv6 connections are grouped by `/64` prefix, so the limit applies per
218    /// `/64` subnet rather than per individual address. IPv4 connections are
219    /// limited per address.
220    ///
221    /// The default and minimum value are 1.
222    ///
223    /// # Security
224    ///
225    /// Increasing this config above 1 reduces Zebra's network security.
226    ///
227    /// If this config is greater than 1, Zebra can initiate multiple outbound handshakes to the same
228    /// IP address.
229    ///
230    /// Inbound connection attempts sharing a connection limit key are also rate-limited
231    /// by this config within a short time window.
232    ///
233    /// If Zebra makes multiple inbound or outbound connections to the same IP, they will be dropped
234    /// after the handshake, but before adding them to the peer set. The total numbers of inbound and
235    /// outbound connections are also limited to a multiple of `peerset_initial_target_size`.
236    pub max_connections_per_ip: usize,
237}
238
239impl Config {
240    /// The maximum number of outbound connections that Zebra will open at the same time.
241    /// When this limit is reached, Zebra stops opening outbound connections.
242    ///
243    /// # Security
244    ///
245    /// See the note at [`INBOUND_PEER_LIMIT_MULTIPLIER`].
246    ///
247    /// # Performance
248    ///
249    /// Zebra's peer set should be limited to a reasonable size,
250    /// to avoid queueing too many in-flight block downloads.
251    /// A large queue of in-flight block downloads can choke a
252    /// constrained local network connection.
253    ///
254    /// We assume that Zebra nodes have at least 10 Mbps bandwidth.
255    /// Therefore, a maximum-sized block can take up to 2 seconds to
256    /// download. So the initial outbound peer set adds up to 100 seconds worth
257    /// of blocks to the queue. If Zebra has reached its outbound peer limit,
258    /// that adds an extra 200 seconds of queued blocks.
259    ///
260    /// But the peer set for slow nodes is typically much smaller, due to
261    /// the handshake RTT timeout. And Zebra responds to inbound request
262    /// overloads by dropping peer connections.
263    pub fn peerset_outbound_connection_limit(&self) -> usize {
264        self.peerset_initial_target_size * OUTBOUND_PEER_LIMIT_MULTIPLIER
265    }
266
267    /// The maximum number of inbound connections that Zebra will accept at the same time.
268    /// When this limit is reached, Zebra drops new inbound connections,
269    /// without handshaking on them.
270    ///
271    /// # Security
272    ///
273    /// See the note at [`INBOUND_PEER_LIMIT_MULTIPLIER`].
274    pub fn peerset_inbound_connection_limit(&self) -> usize {
275        self.peerset_initial_target_size * INBOUND_PEER_LIMIT_MULTIPLIER
276    }
277
278    /// The maximum number of inbound and outbound connections that Zebra will have
279    /// at the same time.
280    pub fn peerset_total_connection_limit(&self) -> usize {
281        self.peerset_outbound_connection_limit() + self.peerset_inbound_connection_limit()
282    }
283
284    /// Returns the initial seed peer hostnames for the configured network.
285    pub fn initial_peer_hostnames(&self) -> IndexSet<String> {
286        match &self.network {
287            Network::Mainnet => self.initial_mainnet_peers.clone(),
288            Network::Testnet(params) if params.is_regtest() => self
289                .initial_testnet_peers
290                .iter()
291                .filter(|peer| !is_default_initial_peer(peer))
292                .cloned()
293                .collect(),
294            Network::Testnet(_params) => self.initial_testnet_peers.clone(),
295        }
296    }
297
298    /// Resolve initial seed peer IP addresses, based on the configured network,
299    /// and load cached peers from disk, if available.
300    ///
301    /// # Panics
302    ///
303    /// If a configured address is an invalid [`SocketAddr`] or DNS name.
304    pub async fn initial_peers(&self) -> HashSet<PeerSocketAddr> {
305        let hostnames = self.initial_peer_hostnames().iter().cloned().collect();
306
307        if self.network.is_regtest() {
308            // Only return local peer addresses and skip loading the peer cache on Regtest.
309            return Config::resolve_peers(&hostnames, true)
310                .await
311                .into_iter()
312                .filter(PeerSocketAddr::is_localhost)
313                .collect();
314        }
315
316        // Load the disk cache first, so that failing DNS can't stop Zebra using cached peers.
317        // Ignore disk errors because the cache is optional and the method already logs them.
318        let disk_peers = self.load_peer_cache().await.unwrap_or_default();
319
320        let dns_peers = Config::resolve_peers(&hostnames, disk_peers.is_empty()).await;
321
322        dns_peers.into_iter().chain(disk_peers).collect()
323    }
324
325    /// Concurrently resolves `peers` into zero or more IP addresses, with a
326    /// timeout of a few seconds on each DNS request.
327    ///
328    /// If DNS resolution fails or times out for all peers, and `retry_until_found` is true,
329    /// continues retrying until at least one peer is found.
330    async fn resolve_peers(
331        peers: &HashSet<String>,
332        retry_until_found: bool,
333    ) -> HashSet<PeerSocketAddr> {
334        use futures::stream::StreamExt;
335
336        if peers.is_empty() {
337            warn!(
338                "no initial peers in the network config. \
339                 Hint: you must configure at least one peer IP or DNS seeder to run Zebra, \
340                 give it some previously cached peer IP addresses on disk, \
341                 or make sure Zebra's listener port gets inbound connections."
342            );
343            return HashSet::new();
344        }
345
346        loop {
347            // We retry each peer individually, as well as retrying if there are
348            // no peers in the combined list. DNS failures are correlated, so all
349            // peers can fail DNS, leaving Zebra with a small list of custom IP
350            // address peers. Individual retries avoid this issue.
351            let peer_addresses = peers
352                .iter()
353                .map(|s| Config::resolve_host(s, MAX_SINGLE_SEED_PEER_DNS_RETRIES))
354                .collect::<futures::stream::FuturesUnordered<_>>()
355                .concat()
356                .await;
357
358            if !peer_addresses.is_empty() {
359                return peer_addresses;
360            }
361
362            if !retry_until_found {
363                tracing::info!(
364                    ?peers,
365                    "empty peer list after DNS resolution, using the cached peers",
366                );
367                return peer_addresses;
368            }
369
370            tracing::info!(
371                ?peers,
372                ?peer_addresses,
373                "empty peer list after DNS resolution, retrying after {} seconds",
374                DNS_LOOKUP_TIMEOUT.as_secs(),
375            );
376            tokio::time::sleep(DNS_LOOKUP_TIMEOUT).await;
377        }
378    }
379
380    /// Resolves `host` into zero or more IP addresses, retrying up to
381    /// `max_retries` times.
382    ///
383    /// If DNS continues to fail, returns an empty list of addresses.
384    ///
385    /// # Panics
386    ///
387    /// If a configured address is an invalid [`SocketAddr`] or DNS name.
388    async fn resolve_host(host: &str, max_retries: usize) -> HashSet<PeerSocketAddr> {
389        for retries in 0..=max_retries {
390            if let Ok(addresses) = Config::resolve_host_once(host).await {
391                return addresses;
392            }
393
394            if retries < max_retries {
395                tracing::info!(
396                    ?host,
397                    previous_attempts = ?(retries + 1),
398                    "Waiting {DNS_LOOKUP_TIMEOUT:?} to retry seed peer DNS resolution",
399                );
400                tokio::time::sleep(DNS_LOOKUP_TIMEOUT).await;
401            } else {
402                tracing::info!(
403                    ?host,
404                    attempts = ?(retries + 1),
405                    "Seed peer DNS resolution failed, checking for addresses from other seed peers",
406                );
407            }
408        }
409
410        HashSet::new()
411    }
412
413    /// Resolves `host` into zero or more IP addresses.
414    ///
415    /// If `host` is a DNS name, performs DNS resolution with a timeout of a few seconds.
416    /// If DNS resolution fails or times out, returns an error.
417    ///
418    /// # Panics
419    ///
420    /// If a configured address is an invalid [`SocketAddr`] or DNS name.
421    async fn resolve_host_once(host: &str) -> Result<HashSet<PeerSocketAddr>, BoxError> {
422        let fut = tokio::net::lookup_host(host);
423        let fut = tokio::time::timeout(DNS_LOOKUP_TIMEOUT, fut);
424
425        match fut.await {
426            Ok(Ok(ip_addrs)) => {
427                let ip_addrs: Vec<PeerSocketAddr> = ip_addrs.map(canonical_peer_addr).collect();
428
429                // This log is needed for user debugging, but it's annoying during tests.
430                #[cfg(not(test))]
431                info!(seed = ?host, remote_ip_count = ?ip_addrs.len(), "resolved seed peer IP addresses");
432                #[cfg(test)]
433                debug!(seed = ?host, remote_ip_count = ?ip_addrs.len(), "resolved seed peer IP addresses");
434
435                // Count the initial peers from this seed. If an IP is returned by multiple seeds,
436                // each duplicate adds 1 to the initial peer count. (But we only make one initial
437                // connection attempt to each IP.)
438                metrics::counter!("zcash.net.peers.initial", "seed" => seed_metric_label(host))
439                    .increment(
440                        u64::try_from(ip_addrs.len()).expect("a peer address count fits in u64"),
441                    );
442
443                Ok(ip_addrs.into_iter().collect())
444            }
445            Ok(Err(e)) if e.kind() == ErrorKind::InvalidInput => {
446                // TODO: add testnet/mainnet ports, like we do with the listener address
447                panic!(
448                    "Invalid peer IP address in Zebra config: addresses must have ports:\n\
449                     resolving {host:?} returned {e:?}"
450                );
451            }
452            Ok(Err(e)) => {
453                tracing::info!(?host, ?e, "DNS error resolving peer IP addresses");
454                Err(e.into())
455            }
456            Err(e) => {
457                tracing::info!(?host, ?e, "DNS timeout resolving peer IP addresses");
458                Err(e.into())
459            }
460        }
461    }
462
463    /// Returns the addresses in the peer list cache file, if available.
464    pub async fn load_peer_cache(&self) -> io::Result<HashSet<PeerSocketAddr>> {
465        let Some(peer_cache_file) = self.cache_dir.peer_cache_file_path(&self.network) else {
466            return Ok(HashSet::new());
467        };
468
469        let peer_list = match fs::read_to_string(&peer_cache_file).await {
470            Ok(peer_list) => peer_list,
471            Err(peer_list_error) => {
472                // We expect that the cache will be missing for new Zebra installs
473                if peer_list_error.kind() == ErrorKind::NotFound {
474                    return Ok(HashSet::new());
475                } else {
476                    info!(
477                        ?peer_list_error,
478                        "could not load cached peer list, using default seed peers"
479                    );
480                    return Err(peer_list_error);
481                }
482            }
483        };
484
485        // Skip and log addresses that don't parse, and automatically deduplicate using the HashSet.
486        // (These issues shouldn't happen unless users modify the file.)
487        let peer_list: HashSet<PeerSocketAddr> = peer_list
488            .lines()
489            .filter_map(|peer| {
490                peer.parse()
491                    .map_err(|peer_parse_error| {
492                        info!(
493                            ?peer_parse_error,
494                            "invalid peer address in cached peer list, skipping"
495                        );
496                        peer_parse_error
497                    })
498                    .ok()
499            })
500            .collect();
501
502        // This log is needed for user debugging, but it's annoying during tests.
503        #[cfg(not(test))]
504        info!(
505            cached_ip_count = ?peer_list.len(),
506            ?peer_cache_file,
507            "loaded cached peer IP addresses"
508        );
509        #[cfg(test)]
510        debug!(
511            cached_ip_count = ?peer_list.len(),
512            ?peer_cache_file,
513            "loaded cached peer IP addresses"
514        );
515
516        // Count the initial peers from the cache. If an IP is returned by DNS seeders and the
517        // cache, each duplicate adds 1 to the initial peer count. (But we only make one initial
518        // connection attempt to each IP.)
519        metrics::counter!("zcash.net.peers.initial")
520            .increment(u64::try_from(peer_list.len()).expect("a peer address count fits in u64"));
521
522        Ok(peer_list)
523    }
524
525    /// Atomically writes a new `peer_list` to the peer list cache file, if configured.
526    /// If the list is empty, keeps the previous cache file.
527    ///
528    /// Also creates the peer cache directory, if it doesn't already exist.
529    ///
530    /// Atomic writes avoid corrupting the cache if Zebra panics or crashes, or if multiple Zebra
531    /// instances try to read and write the same cache file.
532    pub async fn update_peer_cache(&self, peer_list: HashSet<PeerSocketAddr>) -> io::Result<()> {
533        let Some(peer_cache_file) = self.cache_dir.peer_cache_file_path(&self.network) else {
534            return Ok(());
535        };
536
537        if peer_list.is_empty() {
538            info!(
539                ?peer_cache_file,
540                "cacheable peer list was empty, keeping previous cache"
541            );
542            return Ok(());
543        }
544
545        // Turn IP addresses into strings
546        let mut peer_list: Vec<String> = peer_list
547            .iter()
548            .take(MAX_PEER_DISK_CACHE_SIZE)
549            .map(|redacted_peer| redacted_peer.remove_socket_addr_privacy().to_string())
550            .collect();
551        // # Privacy
552        //
553        // Sort to destroy any peer order, which could leak peer connection times.
554        // (Currently the HashSet argument does this as well.)
555        peer_list.sort();
556        // Make a newline-separated list
557        let peer_data = peer_list.join("\n");
558
559        // Write the peer cache file atomically so the cache is not corrupted if Zebra shuts down
560        // or crashes.
561        let span = Span::current();
562        let write_result = tokio::task::spawn_blocking(move || {
563            span.in_scope(move || atomic_write(peer_cache_file, peer_data.as_bytes()))
564        })
565        .await
566        .expect("could not write the peer cache file")?;
567
568        match write_result {
569            Ok(peer_cache_file) => {
570                info!(
571                    cached_ip_count = ?peer_list.len(),
572                    ?peer_cache_file,
573                    "updated cached peer IP addresses"
574                );
575
576                metrics::counter!("zcash.net.peers.cache").increment(
577                    u64::try_from(peer_list.len()).expect("a peer address count fits in u64"),
578                );
579
580                Ok(())
581            }
582            Err(error) => Err(error.error),
583        }
584    }
585}
586
587impl Default for Config {
588    fn default() -> Config {
589        let mainnet_peers = DEFAULT_MAINNET_PEERS
590            .into_iter()
591            .map(String::from)
592            .collect();
593        let testnet_peers = DEFAULT_TESTNET_PEERS
594            .into_iter()
595            .map(String::from)
596            .collect();
597
598        Config {
599            listen_addr: "[::]:8233"
600                .parse()
601                .expect("Hardcoded address should be parseable"),
602            external_addr: None,
603            network: Network::Mainnet,
604            compact_block_relay: false,
605            initial_mainnet_peers: mainnet_peers,
606            initial_testnet_peers: testnet_peers,
607            cache_dir: CacheDir::default(),
608            crawl_new_peer_interval: DEFAULT_CRAWL_NEW_PEER_INTERVAL,
609
610            // # Security
611            //
612            // The default peerset target size should be large enough to ensure
613            // nodes have a reliable set of peers.
614            //
615            // But Zebra should only make a small number of initial outbound connections,
616            // so that idle peers don't use too many connection slots.
617            peerset_initial_target_size: DEFAULT_PEERSET_INITIAL_TARGET_SIZE,
618            max_connections_per_ip: DEFAULT_MAX_CONNS_PER_IP,
619        }
620    }
621}
622
623#[derive(Serialize, Deserialize)]
624#[serde(deny_unknown_fields)]
625struct DTestnetParameters {
626    network_name: Option<String>,
627    network_magic: Option<[u8; 4]>,
628    slow_start_interval: Option<u32>,
629    target_difficulty_limit: Option<String>,
630    disable_pow: Option<bool>,
631    genesis_hash: Option<String>,
632    activation_heights: Option<ConfiguredActivationHeights>,
633    /// Override for the first NSM reissuance height; omission uses ZIP 237's crossover.
634    nsm_reissuance_height: Option<zebra_chain::block::Height>,
635    pre_nu6_funding_streams: Option<ConfiguredFundingStreams>,
636    post_nu6_funding_streams: Option<ConfiguredFundingStreams>,
637    /// Omission retains the default streams; an explicitly empty list disables them.
638    /// An empty list cannot be combined with either legacy funding stream field.
639    funding_streams: Option<Vec<ConfiguredFundingStreams>>,
640    /// Must yield a supported first halving height and a schedule within the monetary cap.
641    /// Configured reissuance needs a positive coefficient; funding streams need a nonzero
642    /// address-change interval.
643    pre_blossom_halving_interval: Option<u32>,
644    lockbox_disbursements: Option<Vec<ConfiguredLockboxDisbursement>>,
645    #[serde(default)]
646    checkpoints: ConfiguredCheckpoints,
647    /// If `true`, automatically repeats configured funding stream addresses to fill
648    /// all required periods.
649    extend_funding_stream_addresses_as_required: Option<bool>,
650    /// Height at which the soft fork that temporarily disables Orchard actions activates.
651    ///
652    /// If unset, the default activation height for the network is used; the soft fork
653    /// cannot be disabled via configuration.
654    temporary_orchard_disabling_soft_fork_height: Option<u32>,
655    /// Regtest only: whether to allow coinbase spends to have transparent outputs.
656    should_allow_unshielded_coinbase_spends: Option<bool>,
657
658    /// Regtest and configured Testnets only: the NSM value balance seeded at NU7 activation
659    /// under the halving-preserving issuance ZIP.
660    initial_nsm_value_balance:
661        Option<zebra_chain::amount::Amount<zebra_chain::amount::NonNegative>>,
662}
663
664/// Network configuration used during deserialization.
665#[derive(Serialize, Deserialize)]
666#[serde(untagged)]
667enum DNetwork {
668    DefaultForKind(NetworkKind),
669    ConfiguredRegtest {
670        params: Box<DTestnetParameters>,
671
672        #[serde(default, skip_serializing)]
673        regtest: Option<bool>,
674    },
675    ConfiguredTestnet(Box<DTestnetParameters>),
676}
677
678impl Default for DNetwork {
679    fn default() -> Self {
680        DNetwork::DefaultForKind(NetworkKind::Mainnet)
681    }
682}
683
684#[derive(Serialize, Deserialize)]
685#[serde(deny_unknown_fields, default)]
686struct DConfig {
687    listen_addr: String,
688    external_addr: Option<String>,
689    network: DNetwork,
690    compact_block_relay: bool,
691
692    /// Legacy testnet parameters, kept for backwards compatibility.
693    #[serde(default, skip_serializing_if = "Option::is_none")]
694    testnet_parameters: Option<DTestnetParameters>,
695
696    initial_mainnet_peers: IndexSet<String>,
697    initial_testnet_peers: IndexSet<String>,
698    cache_dir: CacheDir,
699    peerset_initial_target_size: usize,
700    #[serde(alias = "new_peer_interval", with = "humantime_serde")]
701    crawl_new_peer_interval: Duration,
702    max_connections_per_ip: Option<usize>,
703}
704
705impl Default for DConfig {
706    fn default() -> Self {
707        let config = Config::default();
708        Self {
709            listen_addr: "[::]".to_string(),
710            external_addr: None,
711            network: Default::default(),
712            compact_block_relay: config.compact_block_relay,
713            testnet_parameters: None,
714            initial_mainnet_peers: config.initial_mainnet_peers,
715            initial_testnet_peers: config.initial_testnet_peers,
716            cache_dir: config.cache_dir,
717            peerset_initial_target_size: config.peerset_initial_target_size,
718            crawl_new_peer_interval: config.crawl_new_peer_interval,
719            max_connections_per_ip: Some(config.max_connections_per_ip),
720        }
721    }
722}
723
724impl From<Arc<testnet::Parameters>> for DTestnetParameters {
725    fn from(params: Arc<testnet::Parameters>) -> Self {
726        Self {
727            network_name: Some(params.network_name().to_string()),
728            network_magic: Some(params.network_magic().0),
729            slow_start_interval: Some(params.slow_start_interval().0),
730            target_difficulty_limit: Some(params.target_difficulty_limit().to_string()),
731            disable_pow: Some(params.disable_pow()),
732            genesis_hash: Some(params.genesis_hash().to_string()),
733            activation_heights: Some(params.activation_heights().into()),
734            nsm_reissuance_height: params.configured_nsm_reissuance_height(),
735            pre_nu6_funding_streams: None,
736            post_nu6_funding_streams: None,
737            initial_nsm_value_balance: params.configured_initial_nsm_value_balance(),
738            funding_streams: Some(params.funding_streams().iter().map(Into::into).collect()),
739            pre_blossom_halving_interval: Some(
740                params
741                    .pre_blossom_halving_interval()
742                    .try_into()
743                    .expect("should convert"),
744            ),
745            lockbox_disbursements: Some(
746                params
747                    .lockbox_disbursements()
748                    .into_iter()
749                    .map(Into::into)
750                    .collect(),
751            ),
752            checkpoints: if params.checkpoints() == testnet::Parameters::default().checkpoints() {
753                ConfiguredCheckpoints::Default(true)
754            } else {
755                params.checkpoints().into()
756            },
757            extend_funding_stream_addresses_as_required: None,
758            temporary_orchard_disabling_soft_fork_height: params
759                .temporary_orchard_disabling_soft_fork_height()
760                .map(|height| height.0),
761            should_allow_unshielded_coinbase_spends: params
762                .is_regtest()
763                .then(|| params.should_allow_unshielded_coinbase_spends()),
764        }
765    }
766}
767
768impl From<Config> for DConfig {
769    fn from(
770        Config {
771            listen_addr,
772            external_addr,
773            network,
774            compact_block_relay,
775            initial_mainnet_peers,
776            initial_testnet_peers,
777            cache_dir,
778            peerset_initial_target_size,
779            crawl_new_peer_interval,
780            max_connections_per_ip,
781        }: Config,
782    ) -> Self {
783        let dnetwork = match network.kind() {
784            NetworkKind::Testnet => match network
785                .parameters()
786                .filter(|params| !params.is_default_testnet())
787                .map(Into::into)
788            {
789                Some(params) => DNetwork::ConfiguredTestnet(Box::new(params)),
790                None => DNetwork::DefaultForKind(NetworkKind::Testnet),
791            },
792
793            NetworkKind::Regtest => match network.parameters().map(Into::into) {
794                Some(params) => DNetwork::ConfiguredRegtest {
795                    params: Box::new(params),
796                    regtest: Some(true),
797                },
798                None => DNetwork::DefaultForKind(NetworkKind::Regtest),
799            },
800
801            other_kind => DNetwork::DefaultForKind(other_kind),
802        };
803
804        DConfig {
805            listen_addr: listen_addr.to_string(),
806            external_addr: external_addr.map(|addr| addr.to_string()),
807            network: dnetwork,
808            compact_block_relay,
809            testnet_parameters: None,
810            initial_mainnet_peers,
811            initial_testnet_peers,
812            cache_dir,
813            peerset_initial_target_size,
814            crawl_new_peer_interval,
815            max_connections_per_ip: Some(max_connections_per_ip),
816        }
817    }
818}
819
820impl<'de> Deserialize<'de> for Config {
821    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
822    where
823        D: Deserializer<'de>,
824    {
825        let DConfig {
826            listen_addr,
827            external_addr,
828            network: dnetwork,
829            compact_block_relay,
830            testnet_parameters,
831            initial_mainnet_peers,
832            initial_testnet_peers,
833            cache_dir,
834            peerset_initial_target_size,
835            crawl_new_peer_interval,
836            max_connections_per_ip,
837        } = DConfig::deserialize(deserializer)?;
838
839        let network = match (dnetwork, testnet_parameters) {
840            (DNetwork::ConfiguredTestnet(params), _) => {
841                build_configured_testnet::<D>(*params, &initial_testnet_peers)?
842            }
843            (DNetwork::ConfiguredRegtest { params, .. }, _) => testnet::Parameters::new_regtest(
844                build_regtest_params(*params).map_err(de::Error::custom)?,
845            )
846            .map(Network::new_configured_testnet)
847            .map_err(de::Error::custom)?,
848            (DNetwork::DefaultForKind(NetworkKind::Mainnet), _) => Network::Mainnet,
849            (DNetwork::DefaultForKind(NetworkKind::Testnet), Some(params)) => {
850                build_configured_testnet::<D>(params, &initial_testnet_peers)?
851            }
852            (DNetwork::DefaultForKind(NetworkKind::Testnet), None) => {
853                Network::new_default_testnet()
854            }
855            (DNetwork::DefaultForKind(NetworkKind::Regtest), Some(params)) => {
856                testnet::Parameters::new_regtest(
857                    build_regtest_params(params).map_err(de::Error::custom)?,
858                )
859                .map(Network::new_configured_testnet)
860                .map_err(de::Error::custom)?
861            }
862            (DNetwork::DefaultForKind(NetworkKind::Regtest), None) => {
863                Network::new_regtest(Default::default())
864            }
865        };
866
867        let listen_addr = match listen_addr.parse::<SocketAddr>().or_else(|_| format!("{listen_addr}:{}", network.default_port()).parse()) {
868            Ok(socket) => Ok(socket),
869            Err(_) => match listen_addr.parse::<IpAddr>() {
870                Ok(ip) => Ok(SocketAddr::new(ip, network.default_port())),
871                Err(err) => Err(de::Error::custom(format!(
872                    "{err}; Hint: addresses can be a IPv4, IPv6 (with brackets), or a DNS name, the port is optional"
873                ))),
874            },
875        }?;
876
877        let external_socket_addr = if let Some(address) = &external_addr {
878            match address.parse::<SocketAddr>().or_else(|_| format!("{address}:{}", network.default_port()).parse()) {
879                Ok(socket) => Ok(Some(socket)),
880                Err(_) => match address.parse::<IpAddr>() {
881                    Ok(ip) => Ok(Some(SocketAddr::new(ip, network.default_port()))),
882                    Err(err) => Err(de::Error::custom(format!(
883                        "{err}; Hint: addresses can be a IPv4, IPv6 (with brackets), or a DNS name, the port is optional"
884                    ))),
885                },
886            }?
887        } else {
888            None
889        };
890
891        let [max_connections_per_ip, peerset_initial_target_size] = [
892            ("max_connections_per_ip", max_connections_per_ip, DEFAULT_MAX_CONNS_PER_IP),
893            // If we want Zebra to operate with no network,
894            // we should implement a `zebrad` command that doesn't use `zebra-network`.
895            ("peerset_initial_target_size", Some(peerset_initial_target_size), DEFAULT_PEERSET_INITIAL_TARGET_SIZE)
896        ].map(|(field_name, non_zero_config_field, default_config_value)| {
897            if non_zero_config_field == Some(0) {
898                warn!(
899                    ?field_name,
900                    ?non_zero_config_field,
901                    "{field_name} should be greater than 0, using default value of {default_config_value} instead"
902                );
903            }
904
905            non_zero_config_field.filter(|config_value| config_value > &0).unwrap_or(default_config_value)
906        });
907
908        Ok(Config {
909            listen_addr: canonical_socket_addr(listen_addr),
910            external_addr: external_socket_addr,
911            network,
912            compact_block_relay,
913            initial_mainnet_peers,
914            initial_testnet_peers,
915            cache_dir,
916            peerset_initial_target_size,
917            crawl_new_peer_interval,
918            max_connections_per_ip,
919        })
920    }
921}
922
923/// Returns true for a public DNS seed hostname, regardless of case, trailing dot, or port.
924fn is_default_initial_peer(peer: &str) -> bool {
925    fn hostname(peer: &str) -> &str {
926        peer.rsplit_once(':').map_or(peer, |(host, _)| host)
927    }
928    let peer_host = hostname(peer).trim_end_matches('.');
929    DEFAULT_MAINNET_PEERS
930        .iter()
931        .chain(&DEFAULT_TESTNET_PEERS)
932        .any(|default| peer_host.eq_ignore_ascii_case(hostname(default)))
933}
934
935/// Returns `host` if it is exactly one of the default DNS seeders, and `custom` otherwise.
936///
937/// Operators can configure private peer addresses, which must not reach metrics backends.
938fn seed_metric_label(host: &str) -> &'static str {
939    DEFAULT_MAINNET_PEERS
940        .iter()
941        .chain(&DEFAULT_TESTNET_PEERS)
942        .find(|default| **default == host)
943        .copied()
944        .unwrap_or("custom")
945}
946
947fn build_configured_testnet<'de, D>(
948    params: DTestnetParameters,
949    initial_testnet_peers: &IndexSet<String>,
950) -> Result<Network, D::Error>
951where
952    D: Deserializer<'de>,
953{
954    let DTestnetParameters {
955        network_name,
956        network_magic,
957        slow_start_interval,
958        target_difficulty_limit,
959        disable_pow,
960        genesis_hash,
961        activation_heights,
962        nsm_reissuance_height,
963        pre_nu6_funding_streams,
964        post_nu6_funding_streams,
965        funding_streams,
966        pre_blossom_halving_interval,
967        lockbox_disbursements,
968        checkpoints,
969        extend_funding_stream_addresses_as_required,
970        temporary_orchard_disabling_soft_fork_height,
971        should_allow_unshielded_coinbase_spends,
972        initial_nsm_value_balance,
973    } = params;
974
975    // This is a Regtest-only consensus knob, so reject it rather than silently ignoring it.
976    if should_allow_unshielded_coinbase_spends.is_some() {
977        return Err(de::Error::custom(
978            "should_allow_unshielded_coinbase_spends is only supported on Regtest",
979        ));
980    }
981
982    let mut params_builder = testnet::Parameters::build();
983
984    // A redundant public seed must not turn public Testnet into a configured network.
985    if let Some(initial_nsm_value_balance) = initial_nsm_value_balance.filter(|seed| {
986        network_magic.map(Magic).unwrap_or(magics::TESTNET) != magics::TESTNET
987            || u64::from(*seed) != TESTNET_INITIAL_NSM_VALUE_BALANCE
988    }) {
989        params_builder = params_builder.with_initial_nsm_value_balance(initial_nsm_value_balance);
990    }
991
992    if let Some(network_name) = network_name.clone() {
993        params_builder = params_builder
994            .with_network_name(network_name)
995            .map_err(de::Error::custom)?
996    }
997
998    if let Some(network_magic) = network_magic {
999        params_builder = params_builder
1000            .with_network_magic(Magic(network_magic))
1001            .map_err(de::Error::custom)?;
1002    }
1003
1004    if let Some(genesis_hash) = genesis_hash {
1005        params_builder = params_builder
1006            .with_genesis_hash(genesis_hash)
1007            .map_err(de::Error::custom)?;
1008    }
1009
1010    if let Some(slow_start_interval) = slow_start_interval {
1011        params_builder = params_builder
1012            .with_slow_start_interval(slow_start_interval.try_into().map_err(de::Error::custom)?);
1013    }
1014
1015    if let Some(target_difficulty_limit) = target_difficulty_limit.clone() {
1016        params_builder = params_builder
1017            .with_target_difficulty_limit(
1018                target_difficulty_limit
1019                    .parse::<U256>()
1020                    .map_err(de::Error::custom)?,
1021            )
1022            .map_err(de::Error::custom)?;
1023    }
1024
1025    if let Some(disable_pow) = disable_pow {
1026        params_builder = params_builder.with_disable_pow(disable_pow);
1027    }
1028
1029    // Retain default Testnet activation heights unless there's an empty [testnet_parameters.activation_heights] section.
1030    if let Some(activation_heights) = activation_heights {
1031        params_builder = params_builder
1032            .with_activation_heights(activation_heights)
1033            .map_err(de::Error::custom)?
1034    }
1035
1036    if let Some(height) = nsm_reissuance_height {
1037        params_builder = params_builder.with_nsm_reissuance_height(height);
1038    }
1039
1040    if let Some(halving_interval) = pre_blossom_halving_interval {
1041        params_builder = params_builder
1042            .with_halving_interval(halving_interval.into())
1043            .map_err(de::Error::custom)?
1044    }
1045
1046    // Set configured funding streams after setting any parameters that affect the funding stream address period.
1047    if let Some(funding_streams) = merge_funding_streams(
1048        funding_streams,
1049        pre_nu6_funding_streams,
1050        post_nu6_funding_streams,
1051    )
1052    .map_err(de::Error::custom)?
1053    {
1054        params_builder = params_builder.with_funding_streams(funding_streams);
1055    }
1056
1057    if let Some(lockbox_disbursements) = lockbox_disbursements {
1058        params_builder = params_builder.with_lockbox_disbursements(lockbox_disbursements);
1059    }
1060
1061    params_builder = params_builder
1062        .with_checkpoints(checkpoints)
1063        .map_err(de::Error::custom)?;
1064
1065    if let Some(true) = extend_funding_stream_addresses_as_required {
1066        params_builder = params_builder
1067            .extend_funding_streams()
1068            .map_err(de::Error::custom)?;
1069    }
1070
1071    // Retain the default soft-fork activation height unless one is configured.
1072    if let Some(height) = temporary_orchard_disabling_soft_fork_height {
1073        params_builder = params_builder.with_temporary_orchard_disabling_soft_fork_height(
1074            height.try_into().map_err(de::Error::custom)?,
1075        );
1076    }
1077
1078    // Preserve the canonical public Testnet representation when no parameters changed.
1079    if network_name.is_none() && params_builder == testnet::Parameters::build() {
1080        return Ok(Network::new_default_testnet());
1081    }
1082
1083    if !params_builder.is_compatible_with_default_parameters() {
1084        // Keep the diagnostic for explicitly configured public seeds, even with isolated magic.
1085        if initial_testnet_peers
1086            .iter()
1087            .any(|peer| is_default_initial_peer(peer))
1088        {
1089            return Err(de::Error::custom(
1090                "cannot use default initial peers with incompatible testnet; \
1091                 for public Testnet, remove explicit consensus overrides from \
1092                 [network.testnet_parameters] to use the updated public defaults, including NU7; \
1093                 for a custom network, configure its own initial_testnet_peers and \
1094                 network_magic distinct from public Testnet",
1095            ));
1096        }
1097
1098        // Peer names cannot enforce isolation: aliases, cached peers, and inbound connections
1099        // can all reach public Testnet. Incompatible consensus rules require distinct wire magic.
1100        if network_magic.map(Magic).unwrap_or(magics::TESTNET) == magics::TESTNET {
1101            return Err(de::Error::custom(
1102                "incompatible testnet parameters require network_magic distinct from public Testnet; \
1103                 for public Testnet, remove explicit consensus overrides from \
1104                 [network.testnet_parameters] (including activation_heights and funding_streams) \
1105                 to use the updated public defaults, including NU7; for a custom network, configure its own \
1106                 network_magic and initial_testnet_peers",
1107            ));
1108        }
1109    }
1110
1111    params_builder.to_network().map_err(de::Error::custom)
1112}
1113
1114fn build_regtest_params(params: DTestnetParameters) -> Result<RegtestParameters, &'static str> {
1115    let DTestnetParameters {
1116        activation_heights,
1117        nsm_reissuance_height,
1118        pre_nu6_funding_streams,
1119        post_nu6_funding_streams,
1120        funding_streams,
1121        lockbox_disbursements,
1122        checkpoints,
1123        extend_funding_stream_addresses_as_required,
1124        should_allow_unshielded_coinbase_spends,
1125        initial_nsm_value_balance,
1126        ..
1127    } = params;
1128
1129    Ok(RegtestParameters {
1130        activation_heights: activation_heights.unwrap_or_default(),
1131        nsm_reissuance_height,
1132        funding_streams: merge_funding_streams(
1133            funding_streams,
1134            pre_nu6_funding_streams,
1135            post_nu6_funding_streams,
1136        )?,
1137        lockbox_disbursements,
1138        checkpoints: Some(checkpoints),
1139        extend_funding_stream_addresses_as_required,
1140        should_allow_unshielded_coinbase_spends,
1141        initial_nsm_value_balance,
1142    })
1143}
1144
1145/// Merge legacy streams before the current list, preserving omission and explicit disable.
1146fn merge_funding_streams(
1147    funding_streams: Option<Vec<ConfiguredFundingStreams>>,
1148    pre_nu6_funding_streams: Option<ConfiguredFundingStreams>,
1149    post_nu6_funding_streams: Option<ConfiguredFundingStreams>,
1150) -> Result<Option<Vec<ConfiguredFundingStreams>>, &'static str> {
1151    let has_legacy_streams =
1152        pre_nu6_funding_streams.is_some() || post_nu6_funding_streams.is_some();
1153    if funding_streams.as_ref().is_some_and(Vec::is_empty) && has_legacy_streams {
1154        return Err(
1155            "funding_streams = [] cannot be combined with pre_nu6_funding_streams or post_nu6_funding_streams",
1156        );
1157    }
1158
1159    let specified = funding_streams.is_some() || has_legacy_streams;
1160    let mut funding_streams = funding_streams.unwrap_or_default();
1161    if let Some(mut post_nu6) = post_nu6_funding_streams {
1162        // Legacy names select their own defaults, not their position in the merged list.
1163        if post_nu6.height_range.is_none() || post_nu6.recipients.is_none() {
1164            let default_parameters = testnet::Parameters::default();
1165            let defaults = &default_parameters.funding_streams()[1];
1166            post_nu6
1167                .height_range
1168                .get_or_insert_with(|| defaults.height_range().clone());
1169            if post_nu6.recipients.is_none() {
1170                post_nu6.recipients = ConfiguredFundingStreams::from(defaults).recipients;
1171            }
1172        }
1173        funding_streams.insert(0, post_nu6);
1174    }
1175    if let Some(pre_nu6) = pre_nu6_funding_streams {
1176        funding_streams.insert(0, pre_nu6);
1177    }
1178
1179    Ok(specified.then_some(funding_streams))
1180}