zebra_network/constants.rs
1//! Definitions of Zebra network constants, including:
2//! - network protocol versions,
3//! - network protocol user agents,
4//! - peer address limits,
5//! - peer connection limits, and
6//! - peer connection timeouts.
7
8use std::{collections::HashMap, time::Duration};
9
10use lazy_static::lazy_static;
11use regex::Regex;
12
13// TODO: should these constants be split into protocol also?
14use crate::protocol::external::types::*;
15
16use zebra_chain::{
17 parameters::{
18 Network::{self, *},
19 NetworkKind,
20 NetworkUpgrade::*,
21 },
22 serialization::Duration32,
23};
24
25/// A multiplier used to calculate the inbound connection limit for the peer set,
26///
27/// When it starts up, Zebra opens [`crate::Config::peerset_initial_target_size`]
28/// outbound connections.
29///
30/// Then it opens additional outbound connections as needed for network requests,
31/// and accepts inbound connections initiated by other peers.
32///
33/// The inbound and outbound connection limits are calculated from:
34///
35/// The inbound limit is:
36/// `crate::Config::peerset_initial_target_size * INBOUND_PEER_LIMIT_MULTIPLIER`.
37/// (This is similar to `zcashd`'s default inbound limit.)
38///
39/// The outbound limit is:
40/// `crate::Config::peerset_initial_target_size * OUTBOUND_PEER_LIMIT_MULTIPLIER`.
41/// (This is a bit larger than `zcashd`'s default outbound limit.)
42///
43/// # Security
44///
45/// Each connection requires one inbound slot and one outbound slot, on two different peers.
46/// But some peers only make outbound connections, because they are behind a firewall,
47/// or their lister port address is misconfigured.
48///
49/// Zebra allows extra inbound connection slots,
50/// to prevent accidental connection slot exhaustion.
51/// (`zcashd` also allows a large number of extra inbound slots.)
52///
53/// ## Security Tradeoff
54///
55/// Since the inbound peer limit is higher than the outbound peer limit,
56/// Zebra can be connected to a majority of peers
57/// that it has *not* chosen from its [`crate::AddressBook`].
58///
59/// Inbound peer connections are initiated by the remote peer,
60/// so inbound peer selection is not controlled by the local node.
61/// This means that an attacker can easily become a majority of a node's peers.
62///
63/// However, connection exhaustion is a higher priority.
64pub const INBOUND_PEER_LIMIT_MULTIPLIER: usize = 5;
65
66/// A multiplier used to calculate the outbound connection limit for the peer set,
67///
68/// See [`INBOUND_PEER_LIMIT_MULTIPLIER`] for details.
69pub const OUTBOUND_PEER_LIMIT_MULTIPLIER: usize = 3;
70
71/// The default maximum number of peer connections Zebra will keep for a given IP address
72/// before it drops any additional peer connections with that IP.
73///
74/// This will be used as `Config.max_connections_per_ip` if no valid value is provided.
75///
76/// Note: Zebra will currently avoid initiating outbound connections where it
77/// has recently had a successful handshake with any address
78/// on that IP. Zebra will not initiate more than 1 outbound connection
79/// to an IP based on the default configuration, but it will accept more inbound
80/// connections to an IP.
81pub const DEFAULT_MAX_CONNS_PER_IP: usize = 1;
82
83/// The default peerset target size.
84///
85/// This will be used as `Config.peerset_initial_target_size` if no valid value is provided.
86pub const DEFAULT_PEERSET_INITIAL_TARGET_SIZE: usize = 25;
87
88/// The maximum number of peers we will add to the address book after each `getaddr` request.
89pub const PEER_ADDR_RESPONSE_LIMIT: usize =
90 DEFAULT_PEERSET_INITIAL_TARGET_SIZE * OUTBOUND_PEER_LIMIT_MULTIPLIER / 2;
91
92/// The buffer size for the peer set.
93///
94/// This should be greater than 1 to avoid sender contention, but also reasonably
95/// small, to avoid queueing too many in-flight block downloads. (A large queue
96/// of in-flight block downloads can choke a constrained local network
97/// connection, or a small peer set on testnet.)
98///
99/// We assume that Zebra nodes have at least 10 Mbps bandwidth. Therefore, a
100/// maximum-sized block can take up to 2 seconds to download. So the peer set
101/// buffer adds up to 6 seconds worth of blocks to the queue.
102pub const PEERSET_BUFFER_SIZE: usize = 3;
103
104/// The timeout for sending a message to a remote peer,
105/// and receiving a response from a remote peer.
106pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(20);
107
108/// The timeout for connections and handshakes when connecting to new peers.
109///
110/// Outbound TCP connections must complete within this timeout,
111/// then the handshake messages get an additional `HANDSHAKE_TIMEOUT` to complete.
112/// (Inbound TCP accepts can't have a timeout, because they are handled by the OS.)
113///
114/// This timeout should remain small, because it helps stop slow peers getting
115/// into the peer set. This is particularly important for network-constrained
116/// nodes, and on testnet.
117pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(3);
118
119/// The maximum time difference for two address book changes to be considered concurrent.
120///
121/// This prevents simultaneous or nearby important changes or connection progress
122/// being overridden by less important changes.
123///
124/// This timeout should be less than:
125/// - the [peer reconnection delay](MIN_PEER_RECONNECTION_DELAY), and
126/// - the [peer keepalive/heartbeat interval](HEARTBEAT_INTERVAL).
127///
128/// But more than:
129/// - the amount of time between connection events and address book updates,
130/// even under heavy load (in tests, we have observed delays up to 500ms),
131/// - the delay between an outbound connection failing,
132/// and [candidate selection](crate::peer_set::candidate_set) registering the failure, and
133/// - the delay between the application closing a connection,
134/// and any remaining positive changes from the peer.
135pub const CONCURRENT_ADDRESS_CHANGE_PERIOD: Duration = Duration::from_secs(5);
136
137/// We expect to receive a message from a live peer at least once in this time duration.
138///
139/// This is the sum of:
140/// - the interval between connection heartbeats
141/// - the timeout of a possible pending (already-sent) request
142/// - the timeout for a possible queued request
143/// - the timeout for the heartbeat request itself
144///
145/// This avoids explicit synchronization, but relies on the peer
146/// connector actually setting up channels and these heartbeats in a
147/// specific manner that matches up with this math.
148pub const MIN_PEER_RECONNECTION_DELAY: Duration = Duration::from_secs(59 + 20 + 20 + 20);
149
150/// Zebra rotates its peer inventory registry every time this interval elapses.
151///
152/// Available, missing, and failed inventory entries expire after two rotations. Delayed polling
153/// restarts this interval instead of replaying missed rotations.
154pub const INVENTORY_ROTATION_INTERVAL: Duration = Duration::from_secs(53);
155
156/// How long a single-hash [`Request::BlocksByHash`](crate::Request::BlocksByHash) waits for
157/// eligible busy capacity before returning a local refusal.
158///
159/// Sync and gossip downloaders use [`Request::BlockDownload`](crate::Request::BlockDownload)
160/// instead: capacity waits do not consume peer attempts, and the caller bounds the complete
161/// readiness and response operation. The connection's [`REQUEST_TIMEOUT`] starts at wire dispatch.
162pub const INVENTORY_BUSY_PEER_WAIT_TIMEOUT: Duration = Duration::from_millis(1500);
163
164/// How long a find-blocks or find-headers request waits for a busy serving peer before it can
165/// fall back to any ready peer.
166///
167/// This wait starts when the request enters the peer set and counts towards the syncer's
168/// six-second request timeout, leaving time for the fallback peer to respond.
169pub const FIND_BUSY_SERVING_PEER_WAIT_TIMEOUT: Duration = Duration::from_millis(1500);
170
171/// The default peer address crawler interval.
172///
173/// This should be at least [`HANDSHAKE_TIMEOUT`] lower than all other crawler
174/// intervals.
175///
176/// This makes the following sequence of events more likely:
177/// 1. a peer address crawl,
178/// 2. new peer connections,
179/// 3. peer requests from other crawlers.
180///
181/// Using a prime number makes sure that peer address crawls
182/// don't synchronise with other crawls.
183pub const DEFAULT_CRAWL_NEW_PEER_INTERVAL: Duration = Duration::from_secs(61);
184
185/// The minimum time between re-adds of the initial peers, while the peer crawler has
186/// no outbound connections and no candidates ready to dial.
187///
188/// Each re-add resolves the DNS seeders and reloads the disk cache, and lets failed
189/// initial peers be attempted again after [`MIN_PEER_RECONNECTION_DELAY`].
190///
191/// # Security
192///
193/// This interval bounds the DNS query rate of a node that can't connect to any peers,
194/// regardless of the configured
195/// [`crawl_new_peer_interval`](crate::config::Config.crawl_new_peer_interval).
196pub const MIN_INITIAL_PEER_RECOVERY_INTERVAL: Duration = Duration::from_secs(5 * 60);
197
198/// The maximum time a re-add of the initial peers waits for them to be resolved and loaded.
199///
200/// Without cached peers, DNS resolution retries until it finds a peer, so this stops a
201/// re-add from running until the next one. It allows one retry of every DNS seeder.
202pub const INITIAL_PEER_RECOVERY_TIMEOUT: Duration = Duration::from_secs(15);
203
204/// The peer address disk cache update interval.
205///
206/// This should be longer than [`DEFAULT_CRAWL_NEW_PEER_INTERVAL`],
207/// but shorter than [`MAX_PEER_ACTIVE_FOR_GOSSIP`].
208///
209/// We use a short interval so Zebra instances which are restarted frequently
210/// still have useful caches.
211pub const PEER_DISK_CACHE_UPDATE_INTERVAL: Duration = Duration::from_secs(5 * 60);
212
213/// The maximum number of addresses in the peer disk cache.
214///
215/// This is chosen to be less than the number of active peers,
216/// and approximately the same as the number of seed peers returned by DNS.
217/// It is a tradeoff between fingerprinting attacks, DNS pollution risk, and cache pollution risk.
218pub const MAX_PEER_DISK_CACHE_SIZE: usize = 75;
219
220/// The maximum duration since a peer was last seen to consider it reachable.
221///
222/// This is used to prevent Zebra from gossiping addresses that are likely unreachable. Peers that
223/// have last been seen more than this duration ago will not be gossiped.
224///
225/// This is determined as a tradeoff between network health and network view leakage. From the
226/// [Bitcoin protocol documentation](https://en.bitcoin.it/wiki/Protocol_documentation#getaddr):
227///
228/// "The typical presumption is that a node is likely to be active if it has been sending a message
229/// within the last three hours."
230pub const MAX_PEER_ACTIVE_FOR_GOSSIP: Duration32 = Duration32::from_hours(3);
231
232/// The maximum duration since a peer was last seen to consider reconnecting to it.
233///
234/// Peers that haven't been seen for more than three days and that had its last connection attempt
235/// fail are considered to be offline and Zebra will stop trying to connect to them.
236///
237/// This is to ensure that Zebra can't have a denial-of-service as a consequence of having too many
238/// offline peers that it constantly and uselessly retries to connect to.
239pub const MAX_RECENT_PEER_AGE: Duration32 = Duration32::from_days(3);
240
241/// Regular interval for sending keepalive `Ping` messages to each
242/// connected peer.
243///
244/// Using a prime number makes sure that heartbeats don't synchronise with crawls.
245pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(59);
246
247/// The minimum time between outbound peer connections, implemented by
248/// [`next_reconnect_peer`][crate::peer_set::candidate_set::next_reconnect_peer].
249///
250/// ## Security
251///
252/// Zebra resists distributed denial of service attacks by making sure that new outbound peer
253/// connections are only initiated after this minimum time has elapsed.
254///
255/// It also enforces a minimum per-peer reconnection interval, and filters failed outbound peers.
256pub const MIN_OUTBOUND_PEER_CONNECTION_INTERVAL: Duration = Duration::from_millis(100);
257
258/// The minimum time between _successful_ inbound peer connections, implemented by
259/// `peer_set::initialize::accept_inbound_connections`.
260///
261/// To support multiple peers connecting simultaneously, this is less than the
262/// [`HANDSHAKE_TIMEOUT`].
263///
264/// ## Security
265///
266/// Zebra resists distributed denial of service attacks by limiting the inbound connection rate.
267/// After a _successful_ inbound connection, new inbound peer connections are only accepted,
268/// and our side of the handshake initiated, after this minimum time has elapsed.
269///
270/// The inbound interval is much longer than the outbound interval, because Zebra does not
271/// control the selection or reconnections of inbound peers.
272pub const MIN_INBOUND_PEER_CONNECTION_INTERVAL: Duration = Duration::from_secs(1);
273
274/// The minimum time between _failed_ inbound peer connections, implemented by
275/// `peer_set::initialize::accept_inbound_connections`.
276///
277/// This is a tradeoff between:
278/// - the memory, CPU, and network usage of each new connection attempt, and
279/// - denying service to honest peers due to an attack which makes many inbound connections.
280///
281/// Attacks that reach this limit should be managed using a firewall or intrusion prevention system.
282///
283/// ## Security
284///
285/// Zebra resists distributed denial of service attacks by limiting the inbound connection rate.
286/// After a _failed_ inbound connection, new inbound peer connections are only accepted,
287/// and our side of the handshake initiated, after this minimum time has elapsed.
288pub const MIN_INBOUND_PEER_FAILED_CONNECTION_INTERVAL: Duration = Duration::from_millis(10);
289
290/// The minimum time between successive calls to
291/// [`crawl_once`][crate::peer_set::candidate_set::crawl_once].
292///
293/// Using a prime number makes sure that peer address crawls don't synchronise with other crawls.
294///
295/// ## Security
296///
297/// Zebra resists distributed denial of service attacks by making sure that requests for more
298/// peer addresses are sent at least [`MIN_PEER_GET_ADDR_INTERVAL`] apart.
299pub const MIN_PEER_GET_ADDR_INTERVAL: Duration = Duration::from_secs(31);
300
301/// The combined timeout for all the requests in
302/// [`crawl_once`][crate::peer_set::candidate_set::crawl_once].
303///
304/// `zcashd` doesn't respond to most `getaddr` requests,
305/// so this timeout needs to be short.
306pub const PEER_GET_ADDR_TIMEOUT: Duration = Duration::from_secs(8);
307
308/// The number of GetAddr requests sent when crawling for new peers.
309///
310/// # Security
311///
312/// The fanout should be greater than 2, so that Zebra avoids getting a majority
313/// of its initial address book entries from a single peer.
314///
315/// Zebra regularly crawls for new peers, initiating a new crawl every
316/// [`crawl_new_peer_interval`](crate::config::Config.crawl_new_peer_interval).
317///
318/// TODO: Restore the fanout to 3, once fanouts are limited to the number of ready peers (#2214)
319///
320/// In #3110, we changed the fanout to 1, to make sure we actually use cached address responses.
321/// With a fanout of 3, we were dropping a lot of responses, because the overall crawl timed out.
322pub const GET_ADDR_FANOUT: usize = 1;
323
324/// The maximum number of distinct block hashes retained from a peer's `getdata` request.
325///
326/// The inbound service uses the same limit when serving blocks. Additional block hashes are
327/// ignored before allocating and cloning the internal request.
328///
329/// This is the same as `zcashd`'s request limit:
330/// <https://github.com/zcash/zcash/blob/829dd94f9d253bb705f9e194f13cb8ca8e545e1e/src/main.h#L108>
331///
332/// (Zebra's outbound request limit is one block in transit per peer, because it fans out block
333/// requests to many peers instead of just a few peers.)
334pub const GETDATA_MAX_BLOCK_COUNT: usize = 16;
335
336/// The maximum number of addresses allowed in an `addr` or `addrv2` message.
337///
338/// `addr`:
339/// > The number of IP address entries up to a maximum of 1,000.
340///
341/// <https://developer.bitcoin.org/reference/p2p_networking.html#addr>
342///
343/// `addrv2`:
344/// > One message can contain up to 1,000 addresses.
345/// > Clients MUST reject messages with more addresses.
346///
347/// <https://zips.z.cash/zip-0155#specification>
348pub const MAX_ADDRS_IN_MESSAGE: usize = 1000;
349
350/// The maximum number of block hashes kept from a `FindBlocks` response, matching the
351/// `MAX_FIND_BLOCK_HASHES_RESULTS` limit that Zebra and zcashd apply when serving `getblocks`.
352pub const MAX_FIND_BLOCKS_RESPONSE_HASHES: usize = 500;
353
354/// The fraction of addresses Zebra sends in response to a `Peers` request.
355///
356/// Each response contains approximately:
357/// `address_book.len() / ADDR_RESPONSE_LIMIT_DENOMINATOR`
358/// addresses, selected at random from the address book.
359///
360/// # Security
361///
362/// This limit makes sure that Zebra does not reveal its entire address book
363/// in a single `Peers` response.
364///
365/// This is temporarily set to 2 (up from 4) to speed up peer discovery, so
366/// nodes can recover more quickly from network fragmentation. This reveals
367/// more of the address book to each requester, see #11103 for the tradeoff
368/// discussion and the follow-up conditions for reverting or replacing this
369/// value.
370pub const ADDR_RESPONSE_LIMIT_DENOMINATOR: usize = 2;
371
372/// The maximum number of addresses Zebra will keep in its address book.
373///
374/// This is a tradeoff between:
375/// - revealing the whole address book in a few requests,
376/// - sending the maximum number of peer addresses, and
377/// - making sure the limit code actually gets run.
378///
379/// This value is deliberately pinned rather than derived from
380/// [`ADDR_RESPONSE_LIMIT_DENOMINATOR`], so the temporary denominator change
381/// above does not shrink the address book (see #11103).
382pub const MAX_ADDRS_IN_ADDRESS_BOOK: usize = MAX_ADDRS_IN_MESSAGE * 5;
383
384/// The maximum number of gossiped addresses applied to the address book in one request.
385pub(crate) const GOSSIPED_ADDRS_PER_REQUEST: usize = 100;
386
387/// Truncate timestamps in outbound address messages to this time interval.
388///
389/// ## SECURITY
390///
391/// Timestamp truncation prevents a peer from learning exactly when we received
392/// messages from each of our peers.
393pub const TIMESTAMP_TRUNCATION_SECONDS: u32 = 30 * 60;
394
395/// The Zcash network protocol version implemented by this crate, and advertised
396/// during connection setup.
397///
398/// The current protocol version is checked by our peers. If it is too old,
399/// newer peers will disconnect from us.
400///
401/// The current protocol version typically changes before Mainnet and Testnet
402/// network upgrades.
403///
404/// Advertise NU7 support on Mainnet and Testnet.
405/// See [ZIP 204](https://zips.z.cash/zip-0204#assigning-protocol-versions-to-network-upgrades).
406pub const CURRENT_NETWORK_PROTOCOL_VERSION: Version = Version(170_190);
407
408/// The default RTT estimate for peer responses.
409///
410/// We choose a high value for the default RTT, so that new peers must prove they
411/// are fast, before we prefer them to other peers. This is particularly
412/// important on testnet, which has a small number of peers, which are often
413/// slow.
414///
415/// Make the default RTT slightly higher than the request timeout.
416pub const EWMA_DEFAULT_RTT: Duration = Duration::from_secs(REQUEST_TIMEOUT.as_secs() + 1);
417
418/// The decay time for the EWMA response time metric used for load balancing.
419///
420/// This should be much larger than the `SYNC_RESTART_TIMEOUT`, so we choose
421/// better peers when we restart the sync.
422pub const EWMA_DECAY_TIME_NANOS: f64 = 200.0 * NANOS_PER_SECOND;
423
424/// The number of nanoseconds in one second.
425const NANOS_PER_SECOND: f64 = 1_000_000_000.0;
426
427/// The duration it takes for the drop probability of an overloaded connection to
428/// reach [`MIN_OVERLOAD_DROP_PROBABILITY`].
429///
430/// Peer connections that receive multiple overloads have a higher probability of being dropped.
431///
432/// The probability of a connection being dropped gradually decreases during this interval
433/// until it reaches the default drop probability ([`MIN_OVERLOAD_DROP_PROBABILITY`]).
434///
435/// Increasing this number increases the rate at which connections are dropped.
436pub const OVERLOAD_PROTECTION_INTERVAL: Duration = MIN_INBOUND_PEER_CONNECTION_INTERVAL;
437
438/// The minimum probability of dropping a peer connection when it receives an
439/// [`Overloaded`](crate::PeerError::Overloaded) error.
440pub const MIN_OVERLOAD_DROP_PROBABILITY: f32 = 0.05;
441
442/// The maximum probability of dropping a peer connection when it receives an
443/// [`Overloaded`](crate::PeerError::Overloaded) error.
444pub const MAX_OVERLOAD_DROP_PROBABILITY: f32 = 0.5;
445
446/// The minimum interval between logging peer set status updates.
447pub const MIN_PEER_SET_LOG_INTERVAL: Duration = Duration::from_secs(60);
448
449/// The misbehavior score that bans a peer group.
450pub const MAX_PEER_MISBEHAVIOR_SCORE: u32 = 100;
451
452/// The interval between flushes of batched peer misbehaviour updates into the address book.
453///
454/// Misbehaviour updates are batched so peers can't keep the address book mutex locked by
455/// repeatedly sending invalid blocks or transactions. An update that bans a peer is sent right
456/// away, at most once per peer address and interval.
457#[cfg(not(test))]
458pub const MISBEHAVIOR_FLUSH_INTERVAL: Duration = Duration::from_secs(30);
459
460/// The interval between flushes of batched peer misbehaviour updates into the address book.
461///
462/// Tests use a much shorter interval, so that tests which wait for a misbehaviour update to
463/// turn into a ban don't have to wait for a production flush cycle.
464#[cfg(test)]
465pub const MISBEHAVIOR_FLUSH_INTERVAL: Duration = Duration::from_millis(100);
466
467/// The maximum number of banned IP addresses to be stored in-memory at any time.
468pub const MAX_BANNED_IPS: usize = 20_000;
469
470/// How long a peer group stays banned after reaching
471/// [`MAX_PEER_MISBEHAVIOR_SCORE`].
472///
473/// This matches `zcashd`'s and Bitcoin Core's `DEFAULT_MISBEHAVING_BANTIME`.
474///
475/// # Security
476///
477/// Bans must expire. A ban applies to a whole peer group, and an IPv6 `/64` can
478/// be shared by unrelated nodes at providers that allocate narrower prefixes per
479/// customer, so a permanent ban risks permanently isolating an honest peer.
480/// Expiry also bounds the damage from a misattributed score, at the cost of
481/// letting a genuinely malicious peer retry once the ban lapses — it is banned
482/// again as soon as it misbehaves again.
483pub const BAN_DURATION: Duration = Duration::from_secs(60 * 60 * 24);
484
485lazy_static! {
486 /// The minimum network protocol version accepted by this crate for each network,
487 /// represented as a network upgrade.
488 ///
489 /// The minimum protocol version is used to check the protocol versions of our
490 /// peers during the initial block download. After the initial block download,
491 /// we use the current block height to select the minimum network protocol
492 /// version.
493 ///
494 /// If peer versions are too old, we will disconnect from them.
495 ///
496 /// The minimum network protocol version typically changes after Mainnet and
497 /// Testnet network upgrades.
498 // TODO: Change `Nu6_2` to `Nu7` after NU7 activation.
499 // TODO: Move the value here to a field on `testnet::Parameters` (#8367)
500 pub static ref INITIAL_MIN_NETWORK_PROTOCOL_VERSION: HashMap<NetworkKind, Version> = {
501 let mut hash_map = HashMap::new();
502
503 hash_map.insert(NetworkKind::Mainnet, Version::min_specified_for_upgrade(&Mainnet, Nu6_2));
504 hash_map.insert(NetworkKind::Testnet, Version::min_specified_for_upgrade(&Network::new_default_testnet(), Nu6_2));
505 hash_map.insert(NetworkKind::Regtest, Version::min_specified_for_upgrade(&Network::new_regtest(Default::default()), Nu6_2));
506
507 hash_map
508 };
509
510 /// OS-specific error when the port attempting to be opened is already in use.
511 pub static ref PORT_IN_USE_ERROR: Regex = if cfg!(unix) {
512 #[allow(clippy::trivial_regex)]
513 Regex::new(®ex::escape("already in use"))
514 } else {
515 Regex::new("(access a socket in a way forbidden by its access permissions)|(Only one usage of each socket address)")
516 }.expect("regex is valid");
517}
518
519/// The timeout for DNS lookups.
520///
521/// [6.1.3.3 Efficient Resource Usage] from [RFC 1123: Requirements for Internet Hosts]
522/// suggest no less than 5 seconds for resolving timeout.
523///
524/// [RFC 1123: Requirements for Internet Hosts] <https://tools.ietf.org/rfcmarkup?doc=1123>
525/// [6.1.3.3 Efficient Resource Usage] <https://tools.ietf.org/rfcmarkup?doc=1123#page-77>
526pub const DNS_LOOKUP_TIMEOUT: Duration = Duration::from_secs(5);
527
528#[cfg(test)]
529mod tests {
530 use zebra_chain::parameters::POST_BLOSSOM_POW_TARGET_SPACING;
531
532 use super::*;
533
534 /// This assures that the `Duration` value we are computing for
535 /// [`MIN_PEER_RECONNECTION_DELAY`] actually matches the other const values
536 /// it relies on.
537 #[test]
538 fn ensure_live_peer_duration_value_matches_others() {
539 let _init_guard = zebra_test::init();
540
541 let constructed_live_peer_duration =
542 HEARTBEAT_INTERVAL + REQUEST_TIMEOUT + REQUEST_TIMEOUT + REQUEST_TIMEOUT;
543
544 assert_eq!(MIN_PEER_RECONNECTION_DELAY, constructed_live_peer_duration);
545 }
546
547 /// Make sure that the timeout values are consistent with each other.
548 #[test]
549 fn ensure_timeouts_consistent() {
550 let _init_guard = zebra_test::init();
551
552 assert!(HANDSHAKE_TIMEOUT <= REQUEST_TIMEOUT,
553 "Handshakes are requests, so the handshake timeout can't be longer than the timeout for all requests.");
554 // This check is particularly important on testnet, which has a small
555 // number of peers, which are often slow.
556 assert!(EWMA_DEFAULT_RTT > REQUEST_TIMEOUT,
557 "The default EWMA RTT should be higher than the request timeout, so new peers are required to prove they are fast, before we prefer them to other peers.");
558
559 let request_timeout_nanos = REQUEST_TIMEOUT.as_secs_f64()
560 + f64::from(REQUEST_TIMEOUT.subsec_nanos()) * NANOS_PER_SECOND;
561
562 assert!(EWMA_DECAY_TIME_NANOS > request_timeout_nanos,
563 "The EWMA decay time should be higher than the request timeout, so timed out peers are penalised by the EWMA.");
564
565 assert!(
566 MIN_PEER_RECONNECTION_DELAY.as_secs() as f32
567 / (u32::try_from(MAX_ADDRS_IN_ADDRESS_BOOK).expect("fits in u32")
568 * MIN_OUTBOUND_PEER_CONNECTION_INTERVAL)
569 .as_secs() as f32
570 >= 0.2,
571 "some peers should get a connection attempt in each connection interval",
572 );
573
574 assert!(
575 MIN_PEER_RECONNECTION_DELAY.as_secs() as f32
576 / (u32::try_from(MAX_ADDRS_IN_ADDRESS_BOOK).expect("fits in u32")
577 * MIN_OUTBOUND_PEER_CONNECTION_INTERVAL)
578 .as_secs() as f32
579 <= 2.0,
580 "each peer should only have a few connection attempts in each connection interval",
581 );
582 }
583
584 /// Make sure that peer age limits are consistent with each other.
585 #[test]
586 fn ensure_peer_age_limits_consistent() {
587 let _init_guard = zebra_test::init();
588
589 assert!(
590 MAX_PEER_ACTIVE_FOR_GOSSIP <= MAX_RECENT_PEER_AGE,
591 "we should only gossip peers we are actually willing to try ourselves"
592 );
593 }
594
595 /// Make sure the address limits are consistent with each other.
596 #[test]
597 #[allow(clippy::assertions_on_constants)]
598 fn ensure_address_limits_consistent() {
599 // Estimated network address book size in November 2023, after the address book limit was increased.
600 // Zebra 1.0.0-beta.2 address book metrics in December 2021 showed 4500 peers.
601 const TYPICAL_MAINNET_ADDRESS_BOOK_SIZE: usize = 5_500;
602
603 let _init_guard = zebra_test::init();
604
605 assert!(
606 MAX_ADDRS_IN_ADDRESS_BOOK >= GET_ADDR_FANOUT * MAX_ADDRS_IN_MESSAGE,
607 "the address book should hold at least a fanout's worth of addresses"
608 );
609
610 assert!(
611 MAX_ADDRS_IN_ADDRESS_BOOK / ADDR_RESPONSE_LIMIT_DENOMINATOR > MAX_ADDRS_IN_MESSAGE,
612 "the address book should hold enough addresses for a full response"
613 );
614
615 assert!(
616 MAX_ADDRS_IN_ADDRESS_BOOK <= TYPICAL_MAINNET_ADDRESS_BOOK_SIZE,
617 "the address book limit should actually be used"
618 );
619 }
620
621 /// Make sure inventory registry rotation is consistent with the target block interval.
622 #[test]
623 fn ensure_inventory_rotation_consistent() {
624 let _init_guard = zebra_test::init();
625
626 assert!(
627 INVENTORY_ROTATION_INTERVAL
628 < Duration::from_secs(POST_BLOSSOM_POW_TARGET_SPACING.into()),
629 "we should expire inventory every time 1-2 new blocks get generated"
630 );
631 }
632}