Skip to main content

zebrad/commands/
start.rs

1//! `start` subcommand - entry point for starting a zebra node
2//!
3//! ## Application Structure
4//!
5//! A zebra node consists of the following major services and tasks:
6//!
7//! Peers:
8//!  * Peer Connection Pool Service
9//!    * primary external interface for outbound requests from this node to remote peers
10//!    * accepts requests from services and tasks in this node, and sends them to remote peers
11//!  * Peer Discovery Service
12//!    * maintains a list of peer addresses, and connection priority metadata
13//!    * discovers new peer addresses from existing peer connections
14//!    * initiates new outbound peer connections in response to demand from tasks within this node
15//!  * Peer Cache Service
16//!    * Reads previous peer cache on startup, and adds it to the configured DNS seed peers
17//!    * Periodically updates the peer cache on disk from the latest address book state
18//!
19//! Blocks & Mempool Transactions:
20//!  * Consensus Service
21//!    * handles all validation logic for the node
22//!    * verifies blocks using zebra-chain, then stores verified blocks in zebra-state
23//!    * verifies mempool and block transactions using zebra-chain and zebra-script,
24//!      and returns verified mempool transactions for mempool storage
25//!  * Inbound Service
26//!    * primary external interface for inbound peer requests to this node
27//!    * handles requests from peers for network data, chain data, and mempool transactions
28//!    * spawns download and verify tasks for each gossiped block
29//!    * sends gossiped transactions to the mempool service
30//!
31//! Blocks:
32//!  * Sync Task
33//!    * runs in the background and continuously queries the network for
34//!      new blocks to be verified and added to the local state
35//!    * spawns download and verify tasks for each crawled block
36//!  * State Service
37//!    * contextually verifies blocks
38//!    * handles in-memory storage of multiple non-finalized chains
39//!    * handles permanent storage of the best finalized chain
40//!  * Old State Version Cleanup Task
41//!    * deletes outdated state versions
42//!  * Block Gossip Task
43//!    * runs in the background and continuously queries the state for
44//!      newly committed blocks to be gossiped to peers
45//!  * Block Notify Task
46//!    * if the user has configured a `notify.block_notify_command`, runs that command
47//!      whenever the best chain tip changes (Zebra's equivalent of zcashd's `-blocknotify`)
48//!  * Progress Task
49//!    * logs progress towards the chain tip
50//!
51//! Block Mining:
52//!  * Internal Miner Task
53//!    * if the user has configured Zebra to mine blocks, spawns tasks to generate new blocks,
54//!      and submits them for verification. This automatically shares these new blocks with peers.
55//!
56//! Mempool Transactions:
57//!  * Mempool Service
58//!    * activates when the syncer is near the chain tip
59//!    * spawns download and verify tasks for each crawled or gossiped transaction
60//!    * handles in-memory storage of unmined transactions
61//!  * Queue Checker Task
62//!    * runs in the background, polling the mempool to store newly verified transactions
63//!  * Transaction Gossip Task
64//!    * runs in the background and gossips newly added mempool transactions
65//!      to peers
66//!
67//! Remote Procedure Calls:
68//!  * JSON-RPC Service
69//!    * answers RPC client requests using the State Service and Mempool Service
70//!    * submits client transactions to the node's mempool
71//!
72//! Zebra also has diagnostic support:
73//! * [metrics](https://github.com/ZcashFoundation/zebra/blob/main/book/src/user/metrics.md)
74//! * [tracing](https://github.com/ZcashFoundation/zebra/blob/main/book/src/user/tracing.md)
75//! * [progress-bar](https://docs.rs/howudoin/0.1.1/howudoin)
76//!
77//! Some of the diagnostic features are optional, and need to be enabled at compile-time.
78
79use std::{
80    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
81    path::Path,
82    sync::Arc,
83};
84
85use abscissa_core::{config, Command, FrameworkError};
86use color_eyre::eyre::{eyre, Report};
87use futures::FutureExt;
88use tokio::{
89    pin, select,
90    sync::{oneshot, watch},
91};
92use tower::{builder::ServiceBuilder, util::BoxService, ServiceExt};
93use tracing::Instrument;
94
95use zebra_chain::block::genesis::regtest_genesis_block;
96use zebra_consensus::router::BackgroundTaskHandles;
97use zebra_rpc::{
98    config::rpc::StaticCredentialsError, methods::RpcImpl, server::RpcServer, SubmitBlockChannel,
99};
100
101use crate::{
102    application::{build_version, user_agent, LAST_WARN_ERROR_LOG_SENDER},
103    components::{
104        health,
105        inbound::{self, InboundSetupData, MAX_INBOUND_RESPONSE_TIME},
106        mempool::{self, Mempool},
107        metrics::node_context,
108        notify::{self, BlockNotifyError},
109        sync::{
110            self, record_tip_block_delay, show_block_chain_progress,
111            VERIFICATION_PIPELINE_SCALING_MULTIPLIER,
112        },
113        tokio::{RuntimeRun, TokioComponent},
114        zcashd_compat, ChainSync, Inbound,
115    },
116    config::ZebradConfig,
117    prelude::*,
118};
119
120#[cfg(feature = "internal-miner")]
121use crate::components;
122
123/// Start the application (default command)
124#[derive(Command, Debug, Default, clap::Parser)]
125pub struct StartCmd {
126    /// Filter strings which override the config file and defaults
127    #[clap(help = "tracing filters which override the zebrad.toml config")]
128    filters: Vec<String>,
129
130    /// Enable zcashd-compat mode.
131    #[clap(long)]
132    zcashd_compat: bool,
133
134    /// Continue startup even when zcashd-compat preflight detects minimum hardware shortfalls.
135    #[clap(long = "unsafe-low-specs")]
136    unsafe_low_specs: bool,
137}
138
139/// Warns if Linux TCP slow-start-after-idle is enabled, which significantly
140/// reduces single-peer throughput for block propagation.
141///
142/// See `book/src/user/troubleshooting.md`.
143#[cfg(target_os = "linux")]
144fn check_tcp_slow_start_after_idle() {
145    const PATH: &str = "/proc/sys/net/ipv4/tcp_slow_start_after_idle";
146
147    let raw = match std::fs::read_to_string(PATH) {
148        Ok(raw) => raw,
149        Err(error) => {
150            debug!(
151                ?error,
152                path = PATH,
153                "could not read TCP sysctl, skipping check"
154            );
155            return;
156        }
157    };
158
159    if raw.trim() == "0" {
160        return;
161    }
162
163    warn!(
164        setting = "net.ipv4.tcp_slow_start_after_idle",
165        "TCP slow-start-after-idle is enabled, which resets TCP's congestion window \
166         between block requests and significantly reduces single-peer throughput for \
167         block propagation. \
168         Hint: set `net.ipv4.tcp_slow_start_after_idle=0` via sysctl. \
169         See https://zebra.zfnd.org/user/troubleshooting.html#linux-tcp-tuning-for-block-propagation"
170    );
171}
172
173#[cfg(not(target_os = "linux"))]
174fn check_tcp_slow_start_after_idle() {}
175
176/// Report credential configuration errors while preserving panic diagnostics for other RPC failures.
177fn rpc_startup_error(error: tower::BoxError) -> Report {
178    match error.downcast::<StaticCredentialsError>() {
179        Ok(credentials_error) => Report::new(*credentials_error),
180        Err(error) => panic!("server should start: {error:?}"),
181    }
182}
183
184impl StartCmd {
185    /// Extra time Zebra waits for the zcashd-compat supervisor task beyond the
186    /// child's `shutdown_grace_period`. The supervisor's `terminate_child` waits
187    /// the full grace period before its SIGKILL last resort, so the outer wait
188    /// must be strictly longer or aborting the task races the graceful path.
189    const ZCASHD_COMPAT_SHUTDOWN_TIMEOUT_MARGIN: std::time::Duration =
190        std::time::Duration::from_secs(30);
191
192    /// Returns the Zebra P2P address supervised zcashd should `-connect` to.
193    ///
194    /// Uses `zcashd_compat.p2p_connect_addr` when set, otherwise Zebra's bound
195    /// P2P listener, substituting loopback for unspecified addresses so
196    /// zcashd gets a dialable target on the same host.
197    fn zcashd_compat_p2p_connect_addr(
198        config: &ZebradConfig,
199        local_listener: SocketAddr,
200    ) -> SocketAddr {
201        if let Some(addr) = config.zcashd_compat.p2p_connect_addr {
202            return addr;
203        }
204
205        if local_listener.ip().is_unspecified() {
206            // Substitute the loopback address of the same IP family: an
207            // IPv6-only listener is not reachable via 127.0.0.1.
208            match local_listener.ip() {
209                IpAddr::V4(_) => SocketAddr::from(([127, 0, 0, 1], local_listener.port())),
210                IpAddr::V6(_) => {
211                    SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), local_listener.port())
212                }
213            }
214        } else {
215            local_listener
216        }
217    }
218
219    /// Returns the default inbound peer IPs that always receive block gossip in
220    /// zcashd-compat mode.
221    fn zcashd_compat_default_block_gossip_peer_ips() -> Vec<IpAddr> {
222        vec![
223            IpAddr::V4(Ipv4Addr::LOCALHOST),
224            IpAddr::V6(Ipv6Addr::LOCALHOST),
225        ]
226    }
227
228    /// Returns the supervisor shutdown timeout when zcashd-compat `zcashd` supervision is active.
229    ///
230    /// This is the configured `shutdown_grace_period` plus a fixed margin, so the
231    /// supervisor task always gets to finish its own SIGTERM → grace → SIGKILL
232    /// sequence before Zebra gives up on the task.
233    fn zcashd_compat_supervisor_shutdown_timeout(
234        config: &ZebradConfig,
235    ) -> Option<std::time::Duration> {
236        (config.zcashd_compat.enabled && config.zcashd_compat.manage_zcashd).then_some(
237            config
238                .zcashd_compat
239                .shutdown_grace_period
240                .saturating_add(Self::ZCASHD_COMPAT_SHUTDOWN_TIMEOUT_MARGIN),
241        )
242    }
243
244    /// Returns `false` so Zebra keeps running if zcashd-compat supervision exits unexpectedly.
245    fn zcashd_compat_supervisor_should_exit(
246        zcashd_compat_result: Result<Result<(), Report>, tokio::task::JoinError>,
247    ) -> bool {
248        zcashd_compat::set_supervision_unexpectedly_disabled_metrics();
249
250        match zcashd_compat_result {
251            Ok(Ok(())) => {
252                warn!(
253                    "zcashd-compat supervisor task exited unexpectedly in supervision mode; \
254                     continuing without zcashd supervision"
255                );
256            }
257            Ok(Err(err)) => {
258                warn!(
259                    ?err,
260                    "zcashd-compat supervisor task failed in supervision mode; \
261                     continuing without zcashd supervision"
262                );
263            }
264            Err(join_err) => {
265                warn!(
266                    ?join_err,
267                    "zcashd-compat supervisor task panicked in supervision mode; \
268                     continuing without zcashd supervision"
269                );
270            }
271        }
272
273        false
274    }
275
276    async fn start(&self) -> Result<(), Report> {
277        check_tcp_slow_start_after_idle();
278
279        let config = APPLICATION.config();
280        let is_regtest = config.network.network.is_regtest();
281
282        let config = if is_regtest {
283            Arc::new(ZebradConfig {
284                mempool: mempool::Config {
285                    debug_enable_at_height: Some(0),
286                    ..config.mempool
287                },
288                ..Arc::unwrap_or_clone(config)
289            })
290        } else {
291            config
292        };
293
294        let zcashd_compat_block_gossip_peer_ips = if config.zcashd_compat.enabled {
295            if config.zcashd_compat.block_gossip_peer_ips.is_empty() {
296                // The sidecar privileges (pinned gossip, reserved slot, stall
297                // exemption) match on the sidecar's *source* IP. In
298                // cross-container/cross-host topologies that source is not
299                // loopback, so the default list would silently strip the
300                // sidecar of everything this mode provides.
301                if config
302                    .zcashd_compat
303                    .p2p_connect_addr
304                    .is_some_and(|addr| !addr.ip().is_loopback())
305                {
306                    warn!(
307                        p2p_connect_addr = ?config.zcashd_compat.p2p_connect_addr,
308                        "zcashd_compat.p2p_connect_addr is not loopback, but \
309                         zcashd_compat.block_gossip_peer_ips defaults to loopback only; \
310                         if the sidecar connects from a non-loopback IP, set \
311                         block_gossip_peer_ips to that IP or it will not receive \
312                         pinned block gossip"
313                    );
314                }
315
316                Self::zcashd_compat_default_block_gossip_peer_ips()
317            } else {
318                config.zcashd_compat.block_gossip_peer_ips.clone()
319            }
320        } else {
321            Vec::new()
322        };
323
324        if config.zcashd_compat.enabled {
325            // Preflight does blocking filesystem and /proc reads, and can hash
326            // the cached zcashd binary, so keep it off the async runtime.
327            let preflight_config = config.clone();
328            let unsafe_low_specs = self.unsafe_low_specs;
329            tokio::task::spawn_blocking(move || {
330                zcashd_compat::run_preflight(&preflight_config, unsafe_low_specs)
331            })
332            .await
333            .map_err(|err| eyre!("failed to join zcashd-compat preflight task: {err}"))??;
334        }
335
336        let resolved_zcashd_path = if config.zcashd_compat.enabled
337            && config.zcashd_compat.manage_zcashd
338        {
339            let zcashd_compat_config = config.zcashd_compat.clone();
340            let state_cache_dir = config.state.cache_dir.clone();
341            Some(
342                tokio::task::spawn_blocking(move || {
343                    zcashd_compat::resolve_zcashd_binary_path(
344                        &zcashd_compat_config,
345                        &state_cache_dir,
346                    )
347                })
348                .await
349                .map_err(|err| eyre!("failed to join managed zcashd binary resolver: {err}"))??,
350            )
351        } else {
352            None
353        };
354
355        info!("initializing node state");
356        let (_, max_checkpoint_height) = zebra_consensus::router::init_checkpoint_list(
357            config.consensus.clone(),
358            &config.network.network,
359        );
360
361        info!("opening database, this may take a few minutes");
362
363        let (state_service, read_only_state_service, latest_chain_tip, chain_tip_change) =
364            zebra_state::init(
365                config.state.clone(),
366                &config.network.network,
367                max_checkpoint_height,
368                config.sync.checkpoint_verify_concurrency_limit
369                    * (VERIFICATION_PIPELINE_SCALING_MULTIPLIER + 1),
370            )
371            .await;
372
373        info!("logging database metrics on startup");
374        read_only_state_service.log_db_metrics();
375
376        let state = ServiceBuilder::new()
377            .buffer(Self::state_buffer_bound())
378            .service(state_service);
379
380        info!("initializing network");
381        // The service that our node uses to respond to requests by peers. The
382        // load_shed middleware ensures that we reduce the size of the peer set
383        // in response to excess load.
384        //
385        // # Security
386        //
387        // This layer stack is security-sensitive, modifying it can cause hangs,
388        // or enable denial of service attacks.
389        //
390        // See `zebra_network::Connection::drive_peer_request()` for details.
391        let (setup_tx, setup_rx) = oneshot::channel();
392        let inbound = ServiceBuilder::new()
393            .load_shed()
394            .buffer(inbound::downloads::MAX_INBOUND_CONCURRENCY)
395            .timeout(MAX_INBOUND_RESPONSE_TIME)
396            .service(
397                Inbound::new(config.sync.full_verify_concurrency_limit, setup_rx)
398                    .with_compact_relay(
399                        config.network.network.clone(),
400                        read_only_state_service.clone(),
401                    ),
402            );
403
404        let (peer_set, address_book, misbehavior_sender, block_advertiser) =
405            zebra_network::init_with_block_gossip_peer_ips(
406                config.network.clone(),
407                inbound,
408                latest_chain_tip.clone(),
409                user_agent(),
410                zcashd_compat_block_gossip_peer_ips,
411            )
412            .await;
413
414        // Start health server if configured (after sync_status is available)
415
416        info!("initializing verifiers");
417        let (tx_verifier_setup_tx, tx_verifier_setup_rx) = oneshot::channel();
418        let (block_verifier_router, tx_verifier, consensus_task_handles, max_checkpoint_height) =
419            zebra_consensus::router::init(
420                config.consensus.clone(),
421                &config.network.network,
422                state.clone(),
423                tx_verifier_setup_rx,
424            )
425            .await;
426
427        info!("initializing syncer");
428        let (mut syncer, sync_status) = ChainSync::new(
429            &config,
430            max_checkpoint_height,
431            peer_set.clone(),
432            block_verifier_router.clone(),
433            state.clone(),
434            read_only_state_service.clone(),
435            latest_chain_tip.clone(),
436            misbehavior_sender.clone(),
437        );
438
439        info!("initializing mempool");
440        let (mempool, mempool_transaction_subscriber, mempool_transaction_verified) = Mempool::new(
441            &config.network.network,
442            &config.mempool,
443            peer_set.background_service(),
444            state.clone(),
445            tx_verifier,
446            sync_status.clone(),
447            latest_chain_tip.clone(),
448            chain_tip_change.clone(),
449            misbehavior_sender.clone(),
450        );
451
452        // Subscribe as soon as possible to not miss any events
453        let mempool_change_receiver = mempool_transaction_subscriber.subscribe();
454
455        let mempool = BoxService::new(mempool);
456        let mempool = ServiceBuilder::new()
457            .buffer(mempool::downloads::MAX_INBOUND_CONCURRENCY)
458            .service(mempool);
459
460        if tx_verifier_setup_tx.send(mempool.clone()).is_err() {
461            warn!("error setting up the transaction verifier with a handle to the mempool service");
462        };
463
464        info!("fully initializing inbound peer request handler");
465        // Fully start the inbound service as soon as possible
466        let setup_data = InboundSetupData {
467            address_book: address_book.clone(),
468            block_download_peer_set: peer_set.background_service(),
469            block_verifier: block_verifier_router.clone(),
470            mempool: mempool.clone(),
471            state: state.clone(),
472            latest_chain_tip: latest_chain_tip.clone(),
473            misbehavior_sender,
474        };
475        setup_tx
476            .send(setup_data)
477            .map_err(|_| eyre!("could not send setup data to inbound service"))?;
478        // And give it time to clear its queue
479        tokio::task::yield_now().await;
480
481        // Create a channel to send mined blocks to the gossip task
482        let submit_block_channel = SubmitBlockChannel::new();
483
484        // Launch RPC server
485        let (rpc_impl, mut rpc_tx_queue_handle) = RpcImpl::new(
486            config.network.network.clone(),
487            config.mining.clone(),
488            config.rpc.debug_force_finished_sync,
489            build_version(),
490            user_agent(),
491            mempool.clone(),
492            state.clone(),
493            read_only_state_service.clone(),
494            block_verifier_router.clone(),
495            sync_status.clone(),
496            latest_chain_tip.clone(),
497            address_book.clone(),
498            LAST_WARN_ERROR_LOG_SENDER.subscribe(),
499            Some(submit_block_channel.sender()),
500        );
501        let rpc_impl = rpc_impl.with_end_of_support_height(
502            sync::end_of_support::end_of_support_height(&config.network.network),
503        );
504
505        // Keep a block template ready for the `getblocktemplate` RPC, if this node is configured
506        // for mining, and something can actually ask for a template. Without the RPC server and
507        // without the internal miner, nothing can call `getblocktemplate`, so precomputing
508        // templates would build coinbase transactions that no one reads.
509        #[cfg(feature = "internal-miner")]
510        let is_internal_miner_enabled = config.mining.is_internal_miner_enabled();
511        #[cfg(not(feature = "internal-miner"))]
512        let is_internal_miner_enabled = false;
513
514        let block_template_task_handle =
515            if config.rpc.listen_addr.is_some() || is_internal_miner_enabled {
516                rpc_impl
517                    .spawn_block_template_updater(&mempool_transaction_subscriber)
518                    .inspect(|_| info!("spawned block template updater task"))
519            } else {
520                None
521            };
522
523        // Supervise the updater like every other ongoing task: if it exits or panics, the RPC
524        // keeps serving the last template it published, and pays the new-tip timeout on every call
525        // after the next tip change, so a silent exit has to be visible.
526        let block_template_task_handle: tokio::task::JoinHandle<()> = block_template_task_handle
527            .unwrap_or_else(|| tokio::spawn(std::future::pending().in_current_span()));
528
529        let rpc_task_handle = if config.rpc.listen_addr.is_some() {
530            RpcServer::start(rpc_impl.clone(), config.rpc.clone())
531                .await
532                .map_err(rpc_startup_error)?
533        } else {
534            tokio::spawn(std::future::pending().in_current_span())
535        };
536
537        let zcashd_compat_shutdown_timeout =
538            Self::zcashd_compat_supervisor_shutdown_timeout(&config);
539        let (zcashd_compat_shutdown_tx, zcashd_compat_shutdown_rx) = watch::channel(false);
540        let mut zcashd_compat_task_handle = if let Some(resolved_zcashd_path) = resolved_zcashd_path
541        {
542            let local_listener = address_book
543                .lock()
544                .expect("unexpected panic in address book mutex guard")
545                .local_listener_socket_addr();
546            let supervisor_config = zcashd_compat::SupervisorConfig::new(
547                &config.zcashd_compat,
548                resolved_zcashd_path,
549                &config.state.cache_dir,
550                config.network.network.kind(),
551                Self::zcashd_compat_p2p_connect_addr(&config, local_listener),
552            );
553
554            info!(
555                connect = %supervisor_config.zebra_p2p_addr,
556                "zcashd-compat mode enabled"
557            );
558
559            tokio::spawn(
560                zcashd_compat::run_supervisor(supervisor_config, zcashd_compat_shutdown_rx)
561                    .in_current_span(),
562            )
563        } else {
564            if config.zcashd_compat.enabled {
565                zcashd_compat::set_supervision_config_disabled_metrics();
566                info!("zcashd-compat mode enabled: zcashd supervision disabled");
567            }
568
569            tokio::spawn(std::future::pending().in_current_span())
570        };
571
572        // TODO: Add a shutdown signal and start the server with `serve_with_incoming_shutdown()` if
573        //       any related unit tests sometimes crash with memory errors
574        let indexer_rpc_task_handle = {
575            if let Some(indexer_listen_addr) = config.rpc.indexer_listen_addr {
576                info!("spawning indexer RPC server");
577                let (indexer_rpc_task_handle, _listen_addr) = zebra_rpc::indexer::server::init(
578                    indexer_listen_addr,
579                    read_only_state_service.clone(),
580                    latest_chain_tip.clone(),
581                    mempool_transaction_subscriber.clone(),
582                )
583                .await
584                .map_err(|err| eyre!(err))?;
585
586                indexer_rpc_task_handle
587            } else {
588                warn!("configure an indexer_listen_addr to start the indexer RPC server");
589                tokio::spawn(std::future::pending().in_current_span())
590            }
591        };
592
593        let lightwalletd_rpc_task_handle = {
594            if let Some(lightwalletd_listen_addr) = config.rpc.lightwalletd_listen_addr {
595                info!("spawning lightwalletd gRPC server");
596                let (lightwalletd_rpc_task_handle, _listen_addr) =
597                    zebra_rpc::lightwalletd::server::init(
598                        lightwalletd_listen_addr,
599                        rpc_impl.clone(),
600                        read_only_state_service.clone(),
601                        mempool.clone(),
602                        latest_chain_tip.clone(),
603                        mempool_transaction_subscriber.clone(),
604                        config.network.network.clone(),
605                    )
606                    .await
607                    .map_err(|err| eyre!(err))?;
608
609                lightwalletd_rpc_task_handle
610            } else {
611                tokio::spawn(std::future::pending().in_current_span())
612            }
613        };
614
615        // Start concurrent tasks which don't add load to other tasks
616        info!("spawning block gossip task");
617        let block_gossip_task_handle = tokio::spawn(
618            sync::gossip_best_tip_block_hashes(
619                sync_status.clone(),
620                chain_tip_change.clone(),
621                block_advertiser,
622                Some(submit_block_channel.receiver()),
623            )
624            .in_current_span(),
625        );
626
627        info!("spawning block notify task");
628        let block_notify_task_handle: tokio::task::JoinHandle<Result<(), BlockNotifyError>> =
629            if let Some(command) = config.notify.block_notify_command.clone() {
630                tokio::spawn(
631                    notify::run_block_notify(
632                        command,
633                        sync_status.clone(),
634                        chain_tip_change.clone(),
635                    )
636                    .in_current_span(),
637                )
638            } else {
639                tokio::spawn(std::future::pending().in_current_span())
640            };
641
642        info!("spawning mempool queue checker task");
643        let mempool_queue_checker_task_handle =
644            mempool::QueueChecker::spawn(mempool.clone(), mempool_transaction_verified);
645
646        info!("spawning mempool transaction gossip task");
647        let tx_gossip_task_handle = tokio::spawn(
648            mempool::gossip_mempool_transaction_id(mempool_change_receiver, peer_set.clone())
649                .in_current_span(),
650        );
651
652        info!("spawning delete old databases task");
653        let mut old_databases_task_handle = zebra_state::check_and_delete_old_state_databases(
654            &config.state,
655            &config.network.network,
656        );
657
658        info!("spawning progress logging task");
659        let (chain_tip_metrics_sender, chain_tip_metrics_receiver) =
660            health::ChainTipMetrics::channel();
661        let progress_task_handle = tokio::spawn(
662            show_block_chain_progress(
663                config.network.network.clone(),
664                latest_chain_tip.clone(),
665                sync_status.clone(),
666                chain_tip_metrics_sender,
667                config.health.ready_max_tip_age,
668            )
669            .in_current_span(),
670        );
671
672        // Like the health endpoint, this task only reports metrics, so Zebra doesn't stop when it exits.
673        info!("spawning tip block delay metrics task");
674        node_context::set_network(&config.network.network);
675        let tip_delay_task_handle =
676            tokio::spawn(record_tip_block_delay(chain_tip_change.clone()).in_current_span());
677
678        // Like the tip block delay task, this task only reports metrics.
679        info!("spawning process memory metrics task");
680        let process_memory_task_handle =
681            tokio::spawn(crate::components::metrics::record_process_memory().in_current_span());
682
683        // Start health server if configured
684        info!("initializing health endpoints");
685        let (health_task_handle, _) = health::init(
686            config.health.clone(),
687            config.network.network.clone(),
688            chain_tip_metrics_receiver,
689            sync_status.clone(),
690            address_book.clone(),
691        )
692        .await;
693
694        // Spawn never ending end of support task.
695        info!("spawning end of support checking task");
696        let end_of_support_task_handle = tokio::spawn(
697            sync::end_of_support::start(config.network.network.clone(), latest_chain_tip.clone())
698                .in_current_span(),
699        );
700
701        // Give the inbound service more time to clear its queue,
702        // then start concurrent tasks that can add load to the inbound service
703        // (by opening more peer connections, so those peers send us requests)
704        tokio::task::yield_now().await;
705
706        // The crawler only activates immediately in tests that use mempool debug mode
707        info!("spawning mempool crawler task");
708        let mempool_crawler_task_handle = mempool::Crawler::spawn(
709            &config.mempool,
710            peer_set,
711            mempool.clone(),
712            sync_status.clone(),
713            chain_tip_change.clone(),
714        );
715
716        info!("spawning syncer task");
717        // In regtest, commit the genesis block directly (bypassing the syncer's genesis
718        // download, which requires a connected peer). Then run the syncer normally so
719        // that multi-hop block propagation works: gossiped blocks that arrive out of
720        // order (e.g. only the latest tip hash was gossiped) will be recovered by the
721        // syncer using block locators within Regtest's sync restart delay (2 seconds).
722        if is_regtest
723            && !syncer
724                .state_contains(config.network.network.genesis_hash())
725                .await?
726        {
727            let genesis_hash = block_verifier_router
728                .clone()
729                .oneshot(zebra_consensus::Request::Commit(regtest_genesis_block()))
730                .await
731                .expect("should validate Regtest genesis block");
732
733            assert_eq!(
734                genesis_hash,
735                config.network.network.genesis_hash(),
736                "validated block hash should match network genesis hash"
737            )
738        }
739        let syncer_task_handle = tokio::spawn(syncer.sync().in_current_span());
740
741        // And finally, spawn the internal Zcash miner, if it is enabled.
742        //
743        // TODO: add a config to enable the miner rather than a feature.
744        #[cfg(feature = "internal-miner")]
745        let miner_task_handle = if config.mining.is_internal_miner_enabled() {
746            info!("spawning Zcash miner");
747            components::miner::spawn_init(&config.metrics, rpc_impl)
748        } else {
749            tokio::spawn(std::future::pending().in_current_span())
750        };
751
752        #[cfg(not(feature = "internal-miner"))]
753        // Spawn a dummy miner task which doesn't do anything and never finishes.
754        let miner_task_handle: tokio::task::JoinHandle<Result<(), Report>> =
755            tokio::spawn(std::future::pending().in_current_span());
756
757        info!("spawned initial Zebra tasks");
758
759        // TODO: put tasks into an ongoing FuturesUnordered and a startup FuturesUnordered?
760
761        // ongoing tasks
762        pin!(rpc_task_handle);
763        pin!(indexer_rpc_task_handle);
764        pin!(lightwalletd_rpc_task_handle);
765        pin!(syncer_task_handle);
766        pin!(block_gossip_task_handle);
767        pin!(block_notify_task_handle);
768        pin!(mempool_crawler_task_handle);
769        pin!(mempool_queue_checker_task_handle);
770        pin!(tx_gossip_task_handle);
771        pin!(progress_task_handle);
772        pin!(end_of_support_task_handle);
773        pin!(miner_task_handle);
774        pin!(block_template_task_handle);
775
776        // startup tasks
777        let BackgroundTaskHandles {
778            mut state_checkpoint_verify_handle,
779        } = consensus_task_handles;
780
781        let state_checkpoint_verify_handle_fused = (&mut state_checkpoint_verify_handle).fuse();
782        pin!(state_checkpoint_verify_handle_fused);
783
784        let old_databases_task_handle_fused = (&mut old_databases_task_handle).fuse();
785        pin!(old_databases_task_handle_fused);
786
787        // The zcashd-compat supervisor exits when supervision is disabled or fails,
788        // but Zebra keeps running, so its handle must be fused.
789        let mut zcashd_compat_task_finished = false;
790        let zcashd_compat_task_handle_fused = (&mut zcashd_compat_task_handle).fuse();
791        pin!(zcashd_compat_task_handle_fused);
792
793        // Wait for tasks to finish
794        let exit_status = loop {
795            let mut exit_when_task_finishes = true;
796
797            let result = select! {
798                rpc_join_result = &mut rpc_task_handle => {
799                    let rpc_server_result = rpc_join_result
800                        .expect("unexpected panic in the rpc task");
801                    info!(?rpc_server_result, "rpc task exited");
802                    Ok(())
803                }
804
805                rpc_tx_queue_result = &mut rpc_tx_queue_handle => {
806                    rpc_tx_queue_result
807                        .expect("unexpected panic in the rpc transaction queue task");
808                    info!("rpc transaction queue task exited");
809                    Ok(())
810                }
811
812                indexer_rpc_join_result = &mut indexer_rpc_task_handle => {
813                    let indexer_rpc_server_result = indexer_rpc_join_result
814                        .expect("unexpected panic in the indexer task");
815                    info!(?indexer_rpc_server_result, "indexer rpc task exited");
816                    Ok(())
817                }
818
819                lightwalletd_rpc_join_result = &mut lightwalletd_rpc_task_handle => {
820                    let lightwalletd_rpc_server_result = lightwalletd_rpc_join_result
821                        .expect("unexpected panic in the lightwalletd gRPC task");
822                    info!(?lightwalletd_rpc_server_result, "lightwalletd gRPC task exited");
823                    Ok(())
824                }
825
826                sync_result = &mut syncer_task_handle => sync_result
827                    .expect("unexpected panic in the syncer task")
828                    .map(|_| info!("syncer task exited")),
829
830                block_gossip_result = &mut block_gossip_task_handle => block_gossip_result
831                    .expect("unexpected panic in the chain tip block gossip task")
832                    .map(|_| info!("chain tip block gossip task exited"))
833                    .map_err(|e| eyre!(e)),
834
835                block_notify_result = &mut block_notify_task_handle => block_notify_result
836                    .expect("unexpected panic in the block notify task")
837                    .map(|_| info!("block notify task exited"))
838                    .map_err(|e| eyre!(e)),
839
840                mempool_crawl_result = &mut mempool_crawler_task_handle => mempool_crawl_result
841                    .expect("unexpected panic in the mempool crawler")
842                    .map(|_| info!("mempool crawler task exited"))
843                    .map_err(|e| eyre!(e)),
844
845                mempool_queue_result = &mut mempool_queue_checker_task_handle => mempool_queue_result
846                    .expect("unexpected panic in the mempool queue checker")
847                    .map(|_| info!("mempool queue checker task exited"))
848                    .map_err(|e| eyre!(e)),
849
850                tx_gossip_result = &mut tx_gossip_task_handle => tx_gossip_result
851                    .expect("unexpected panic in the transaction gossip task")
852                    .map(|_| info!("transaction gossip task exited"))
853                    .map_err(|e| eyre!(e)),
854
855                // The progress task runs forever, unless it panics.
856                // So we don't need to provide an exit status for it.
857                progress_result = &mut progress_task_handle => {
858                    info!("chain progress task exited");
859                    progress_result
860                        .expect("unexpected panic in the chain progress task");
861                }
862
863                end_of_support_result = &mut end_of_support_task_handle => end_of_support_result
864                    .expect("unexpected panic in the end of support task")
865                    .map(|_| info!("end of support task exited")),
866
867                // We also expect the state checkpoint verify task to finish.
868                state_checkpoint_verify_result = &mut state_checkpoint_verify_handle_fused => {
869                    state_checkpoint_verify_result
870                        .unwrap_or_else(|_| panic!(
871                            "unexpected panic in checkpoint validation or Orchard tree precomputation"));
872
873                    exit_when_task_finishes = false;
874                    Ok(())
875                }
876
877                // And the old databases task should finish while Zebra is running.
878                old_databases_result = &mut old_databases_task_handle_fused => {
879                    old_databases_result
880                        .unwrap_or_else(|_| panic!(
881                            "unexpected panic deleting old database directories"));
882
883                    exit_when_task_finishes = false;
884                    Ok(())
885                }
886
887                block_template_result = &mut block_template_task_handle => {
888                    block_template_result
889                        .expect("unexpected panic in the block template updater task");
890                    info!("block template updater task exited");
891
892                    Ok(())
893                }
894
895                miner_result = &mut miner_task_handle => miner_result
896                    .expect("unexpected panic in the miner task")
897                    .map(|_| info!("miner task exited")),
898
899                zcashd_compat_result = &mut zcashd_compat_task_handle_fused => {
900                    zcashd_compat_task_finished = true;
901                    exit_when_task_finishes =
902                        Self::zcashd_compat_supervisor_should_exit(zcashd_compat_result);
903                    Ok(())
904                },
905            };
906
907            // Stop Zebra if a task finished and returned an error,
908            // or if an ongoing task exited.
909            if let Err(err) = result {
910                break Err(err);
911            }
912
913            if exit_when_task_finishes {
914                break Ok(());
915            }
916        };
917
918        info!("exiting Zebra because an ongoing task exited: asking other tasks to stop");
919
920        // ongoing tasks
921        rpc_task_handle.abort();
922        rpc_tx_queue_handle.abort();
923        block_template_task_handle.abort();
924        health_task_handle.abort();
925        tip_delay_task_handle.abort();
926        process_memory_task_handle.abort();
927        syncer_task_handle.abort();
928        block_gossip_task_handle.abort();
929        block_notify_task_handle.abort();
930        mempool_crawler_task_handle.abort();
931        mempool_queue_checker_task_handle.abort();
932        tx_gossip_task_handle.abort();
933        progress_task_handle.abort();
934        end_of_support_task_handle.abort();
935        miner_task_handle.abort();
936        if zcashd_compat_task_finished {
937            debug!("zcashd-compat supervisor task already exited before shutdown");
938        } else if let Some(zcashd_compat_shutdown_timeout) = zcashd_compat_shutdown_timeout {
939            info!(
940                ?zcashd_compat_shutdown_timeout,
941                "requesting zcashd-compat supervisor shutdown"
942            );
943            if zcashd_compat_shutdown_tx.send(true).is_err() {
944                warn!("zcashd-compat supervisor shutdown request was not delivered");
945            }
946            if tokio::time::timeout(
947                zcashd_compat_shutdown_timeout,
948                &mut zcashd_compat_task_handle,
949            )
950            .await
951            .is_err()
952            {
953                warn!(
954                    ?zcashd_compat_shutdown_timeout,
955                    "zcashd-compat supervisor did not finish before shutdown timeout; \
956                     abandoning child process handle"
957                );
958                // The supervisor spawns zcashd without kill_on_drop, so this
959                // abort abandons an already-signalled child rather than
960                // SIGKILLing it mid-flush.
961                zcashd_compat_task_handle.abort();
962            }
963        } else {
964            debug!("aborting zcashd-compat supervisor task without managed child shutdown");
965            zcashd_compat_task_handle.abort();
966        }
967
968        // startup tasks
969        state_checkpoint_verify_handle.abort();
970        old_databases_task_handle.abort();
971
972        info!(
973            "exiting Zebra: all tasks have been asked to stop, waiting for remaining tasks to finish"
974        );
975
976        exit_status
977    }
978
979    /// Returns the bound for the state service buffer,
980    /// based on the configurations of the services that use the state concurrently.
981    fn state_buffer_bound() -> usize {
982        let config = APPLICATION.config();
983
984        // Ignore the checkpoint verify limit, because it is very large.
985        //
986        // TODO: do we also need to account for concurrent use across services?
987        //       we could multiply the maximum by 3/2, or add a fixed constant
988        [
989            config.sync.download_concurrency_limit,
990            config.sync.full_verify_concurrency_limit,
991            inbound::downloads::MAX_INBOUND_CONCURRENCY,
992            mempool::downloads::MAX_INBOUND_CONCURRENCY,
993        ]
994        .into_iter()
995        .max()
996        .unwrap()
997    }
998}
999
1000impl Runnable for StartCmd {
1001    /// Start the application.
1002    fn run(&self) {
1003        info!("Starting zebrad");
1004        let rt = APPLICATION
1005            .state()
1006            .components_mut()
1007            .get_downcast_mut::<TokioComponent>()
1008            .expect("TokioComponent should be available")
1009            .rt
1010            .take();
1011
1012        rt.expect("runtime should not already be taken")
1013            .run(self.start());
1014
1015        info!("stopping zebrad");
1016    }
1017}
1018
1019impl config::Override<ZebradConfig> for StartCmd {
1020    // Process the given command line options, overriding settings from
1021    // a configuration file using explicit flags taken from command-line
1022    // arguments.
1023    fn override_config(&self, mut config: ZebradConfig) -> Result<ZebradConfig, FrameworkError> {
1024        if !self.filters.is_empty() {
1025            config.tracing.filter = Some(self.filters.join(","));
1026        }
1027
1028        // `--zcashd-compat` is a one-way override that enables zcashd-compat mode.
1029        // The actual zcashd-compat guardrails are applied below using
1030        // `config.zcashd_compat.enabled` so CLI and config-file activation share one path.
1031        if self.zcashd_compat {
1032            config.zcashd_compat.enabled = true;
1033        }
1034
1035        if !config.zcashd_compat.enabled && !config.zcashd_compat.block_gossip_peer_ips.is_empty() {
1036            return Err(std::io::Error::other(
1037                "zcashd_compat.block_gossip_peer_ips requires zcashd_compat.enabled = true",
1038            )
1039            .into());
1040        }
1041
1042        if config.zcashd_compat.enabled && config.zcashd_compat.manage_zcashd {
1043            zcashd_compat::reject_peer_selection_extra_args(
1044                &config.zcashd_compat.zcashd_extra_args,
1045            )
1046            .map_err(|err| std::io::Error::other(err.to_string()))?;
1047
1048            match zcashd_compat::effective_zcashd_source(&config.zcashd_compat) {
1049                Ok(zcashd_compat::ZcashdBinarySource::Path(path))
1050                    if !zcashd_compat::is_command_resolvable(Path::new(&path)) =>
1051                {
1052                    return Err(std::io::Error::other(format!(
1053                        "zcashd-compat mode could not resolve zcashd_path={}",
1054                        path.display()
1055                    ))
1056                    .into());
1057                }
1058                Ok(_) => {}
1059                Err(err) => return Err(std::io::Error::other(err.to_string()).into()),
1060            }
1061        }
1062
1063        Ok(config)
1064    }
1065}
1066
1067#[cfg(test)]
1068mod tests {
1069    use abscissa_core::config::Override;
1070    use color_eyre::eyre::eyre;
1071
1072    use super::StartCmd;
1073    use crate::components::zcashd_compat;
1074    use crate::config::ZebradConfig;
1075
1076    #[test]
1077    fn zcashd_compat_flag_enables_mode() {
1078        let cmd = StartCmd {
1079            filters: Vec::new(),
1080            zcashd_compat: true,
1081            unsafe_low_specs: false,
1082        };
1083        let mut config = ZebradConfig::default();
1084        config.zcashd_compat.manage_zcashd = false;
1085
1086        let config = cmd
1087            .override_config(config)
1088            .expect("zcashd-compat override config should succeed");
1089
1090        assert!(config.zcashd_compat.enabled);
1091    }
1092
1093    #[test]
1094    fn zcashd_compat_config_enables_mode() {
1095        let cmd = StartCmd {
1096            filters: Vec::new(),
1097            zcashd_compat: false,
1098            unsafe_low_specs: false,
1099        };
1100        let mut config = ZebradConfig::default();
1101        config.zcashd_compat.enabled = true;
1102        config.zcashd_compat.manage_zcashd = false;
1103
1104        let config = cmd
1105            .override_config(config)
1106            .expect("zcashd-compat override config should succeed");
1107
1108        assert!(config.zcashd_compat.enabled);
1109    }
1110
1111    #[test]
1112    fn block_gossip_peer_ips_require_zcashd_compat() {
1113        let cmd = StartCmd {
1114            filters: Vec::new(),
1115            zcashd_compat: false,
1116            unsafe_low_specs: false,
1117        };
1118        let mut config = ZebradConfig::default();
1119        config.zcashd_compat.block_gossip_peer_ips =
1120            vec![std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)];
1121
1122        let error = cmd
1123            .override_config(config)
1124            .expect_err("block gossip peers should require zcashd-compat");
1125
1126        assert!(
1127            error
1128                .to_string()
1129                .contains("zcashd_compat.block_gossip_peer_ips requires"),
1130            "error should explain the zcashd-compat requirement: {error}"
1131        );
1132    }
1133
1134    #[test]
1135    fn zcashd_compat_config_rejects_peer_selection_extra_args() {
1136        let cmd = StartCmd {
1137            filters: Vec::new(),
1138            zcashd_compat: false,
1139            unsafe_low_specs: false,
1140        };
1141        let mut config = ZebradConfig::default();
1142        config.zcashd_compat.enabled = true;
1143        config.zcashd_compat.manage_zcashd = true;
1144        config.zcashd_compat.zcashd_source = zcashd_compat::ConfigZcashdBinarySource::Embedded;
1145        config.zcashd_compat.zcashd_extra_args = vec!["-addnode=1.2.3.4".to_string()];
1146
1147        let error = cmd
1148            .override_config(config)
1149            .expect_err("peer-selection extra args should be rejected");
1150        assert!(
1151            error.to_string().contains("peer-selection"),
1152            "unexpected error: {error}"
1153        );
1154    }
1155
1156    #[test]
1157    fn zcashd_compat_manage_zcashd_requires_resolvable_path() {
1158        let cmd = StartCmd {
1159            filters: Vec::new(),
1160            zcashd_compat: true,
1161            unsafe_low_specs: false,
1162        };
1163        let mut config = ZebradConfig::default();
1164        config.zcashd_compat.manage_zcashd = true;
1165        config.zcashd_compat.zcashd_path = Some("/definitely/missing/zcashd-compat".into());
1166
1167        let error = cmd
1168            .override_config(config)
1169            .expect_err("zcashd-compat override should fail for an unresolvable zcashd path");
1170
1171        assert!(
1172            error
1173                .to_string()
1174                .contains("zcashd-compat mode could not resolve zcashd_path"),
1175            "unexpected error: {error}"
1176        );
1177    }
1178
1179    #[test]
1180    fn zcashd_compat_path_source_requires_explicit_path() {
1181        let cmd = StartCmd {
1182            filters: Vec::new(),
1183            zcashd_compat: true,
1184            unsafe_low_specs: false,
1185        };
1186        let mut config = ZebradConfig::default();
1187        config.zcashd_compat.manage_zcashd = true;
1188        config.zcashd_compat.zcashd_source = zcashd_compat::ConfigZcashdBinarySource::Path;
1189        config.zcashd_compat.zcashd_path = None;
1190
1191        let error = cmd
1192            .override_config(config)
1193            .expect_err("path source should require explicit zcashd_path");
1194        assert!(
1195            error.to_string().contains("zcashd_source=path"),
1196            "unexpected error: {error}"
1197        );
1198    }
1199
1200    #[test]
1201    fn zcashd_compat_embedded_source_allows_missing_local_path() {
1202        let cmd = StartCmd {
1203            filters: Vec::new(),
1204            zcashd_compat: true,
1205            unsafe_low_specs: false,
1206        };
1207        let mut config = ZebradConfig::default();
1208        config.zcashd_compat.manage_zcashd = true;
1209        config.zcashd_compat.zcashd_source = zcashd_compat::ConfigZcashdBinarySource::Embedded;
1210        config.zcashd_compat.zcashd_path = None;
1211
1212        cmd.override_config(config)
1213            .expect("embedded source should be validated at runtime, not override-time");
1214    }
1215
1216    #[test]
1217    fn zcashd_compat_config_manage_zcashd_requires_resolvable_path() {
1218        let cmd = StartCmd {
1219            filters: Vec::new(),
1220            zcashd_compat: false,
1221            unsafe_low_specs: false,
1222        };
1223        let mut config = ZebradConfig::default();
1224        config.zcashd_compat.enabled = true;
1225        config.zcashd_compat.manage_zcashd = true;
1226        config.zcashd_compat.zcashd_path = Some("/definitely/missing/zcashd-compat".into());
1227
1228        let error = cmd
1229            .override_config(config)
1230            .expect_err("zcashd-compat config should fail for an unresolvable zcashd path");
1231
1232        assert!(
1233            error
1234                .to_string()
1235                .contains("zcashd-compat mode could not resolve zcashd_path"),
1236            "unexpected error: {error}"
1237        );
1238    }
1239
1240    #[test]
1241    fn zcashd_compat_supervisor_shutdown_timeout_matches_config() {
1242        let mut config = ZebradConfig::default();
1243
1244        config.zcashd_compat.enabled = true;
1245        config.zcashd_compat.manage_zcashd = true;
1246        config.zcashd_compat.shutdown_grace_period = std::time::Duration::from_secs(42);
1247        assert_eq!(
1248            StartCmd::zcashd_compat_supervisor_shutdown_timeout(&config),
1249            Some(
1250                std::time::Duration::from_secs(42)
1251                    + StartCmd::ZCASHD_COMPAT_SHUTDOWN_TIMEOUT_MARGIN
1252            ),
1253            "outer supervisor wait must exceed the child grace period so task \
1254             abort cannot preempt graceful termination",
1255        );
1256
1257        config.zcashd_compat.manage_zcashd = false;
1258        assert_eq!(
1259            StartCmd::zcashd_compat_supervisor_shutdown_timeout(&config),
1260            None
1261        );
1262
1263        config.zcashd_compat.enabled = false;
1264        config.zcashd_compat.manage_zcashd = true;
1265        assert_eq!(
1266            StartCmd::zcashd_compat_supervisor_shutdown_timeout(&config),
1267            None
1268        );
1269    }
1270
1271    #[test]
1272    fn zcashd_compat_supervisor_ok_exit_does_not_exit_zebra() {
1273        assert!(!StartCmd::zcashd_compat_supervisor_should_exit(Ok(Ok(()))));
1274    }
1275
1276    #[test]
1277    fn zcashd_compat_supervisor_error_does_not_exit_zebra() {
1278        assert!(!StartCmd::zcashd_compat_supervisor_should_exit(Ok(Err(
1279            eyre!("simulated zcashd supervisor runtime failure"),
1280        ))));
1281    }
1282
1283    #[tokio::test]
1284    async fn zcashd_compat_supervisor_panic_does_not_exit_zebra() {
1285        let join_err = tokio::spawn(async {
1286            panic!("simulated zcashd supervisor panic");
1287        })
1288        .await
1289        .expect_err("task should panic");
1290
1291        assert!(!StartCmd::zcashd_compat_supervisor_should_exit(Err(
1292            join_err
1293        )));
1294    }
1295}