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