Skip to main content

agave_validator/
bootstrap.rs

1use {
2    agave_snapshots::{
3        SnapshotArchiveKind, paths as snapshot_paths,
4        snapshot_archive_info::SnapshotArchiveInfoGetter as _,
5    },
6    itertools::Itertools,
7    log::*,
8    rand::{Rng, rng, seq::SliceRandom},
9    rayon::prelude::*,
10    solana_account::ReadableAccount,
11    solana_clock::Slot,
12    solana_commitment_config::CommitmentConfig,
13    solana_core::validator::{ValidatorConfig, ValidatorStartProgress},
14    solana_download_utils::{DownloadProgressRecord, download_snapshot_archive},
15    solana_genesis_utils::download_then_check_genesis_hash,
16    solana_gossip::{
17        cluster_info::ClusterInfo,
18        contact_info::{ContactInfo, Protocol},
19        crds_data,
20        gossip_service::GossipService,
21        node::Node,
22    },
23    solana_hash::Hash,
24    solana_keypair::Keypair,
25    solana_metrics::datapoint_info,
26    solana_net_utils::SocketAddrSpace,
27    solana_pubkey::Pubkey,
28    solana_rpc_client::rpc_client::RpcClient,
29    solana_signer::Signer,
30    solana_vote_program::vote_state::VoteStateV4,
31    std::{
32        collections::{HashMap, HashSet, hash_map::RandomState},
33        net::{SocketAddr, TcpListener, TcpStream, UdpSocket},
34        path::Path,
35        process::exit,
36        sync::{
37            Arc, RwLock,
38            atomic::{AtomicBool, Ordering},
39        },
40        time::{Duration, Instant},
41    },
42    thiserror::Error,
43};
44
45/// When downloading snapshots, wait at most this long for snapshot hashes from
46/// _all_ known validators.  Afterwards, wait for snapshot hashes from _any_
47/// known validator.
48const WAIT_FOR_ALL_KNOWN_VALIDATORS: Duration = Duration::from_secs(60);
49/// If we don't have any alternative peers after this long, better off trying
50/// blacklisted peers again.
51const BLACKLIST_CLEAR_THRESHOLD: Duration = Duration::from_secs(60);
52/// If we can't find a good snapshot download candidate after this time, just
53/// give up.
54const NEWER_SNAPSHOT_THRESHOLD: Duration = Duration::from_secs(180);
55/// If we haven't found any RPC peers after this time, just give up.
56const GET_RPC_PEERS_TIMEOUT: Duration = Duration::from_secs(300);
57
58pub const MAX_RPC_CONNECTIONS_EVALUATED_PER_ITERATION: usize = 32;
59
60pub const PING_TIMEOUT: Duration = Duration::from_secs(2);
61
62#[derive(Debug, PartialEq, Clone)]
63pub struct RpcBootstrapConfig {
64    pub no_genesis_fetch: bool,
65    pub no_snapshot_fetch: bool,
66    pub only_known_rpc: bool,
67    pub max_genesis_archive_unpacked_size: u64,
68    pub check_vote_account: Option<String>,
69    pub incremental_snapshot_fetch: bool,
70}
71
72fn verify_reachable_ports(
73    node: &Node,
74    cluster_entrypoint: &ContactInfo,
75    validator_config: &ValidatorConfig,
76    socket_addr_space: &SocketAddrSpace,
77) -> bool {
78    let verify_address = |addr: &Option<SocketAddr>| -> bool {
79        addr.as_ref()
80            .map(|addr| socket_addr_space.check(addr))
81            .unwrap_or_default()
82    };
83
84    let mut udp_sockets = vec![&node.sockets.repair];
85    udp_sockets.extend(node.sockets.gossip.iter());
86
87    if verify_address(&node.info.serve_repair(Protocol::UDP)) {
88        udp_sockets.push(&node.sockets.serve_repair);
89    }
90    if verify_address(&node.info.tpu_vote(Protocol::UDP)) {
91        udp_sockets.extend(node.sockets.tpu_vote.iter());
92    }
93    if verify_address(&node.info.tvu(Protocol::UDP)) {
94        udp_sockets.extend(node.sockets.tvu.iter());
95        udp_sockets.extend(node.sockets.broadcast.iter());
96        udp_sockets.extend(node.sockets.retransmit_sockets.iter());
97    }
98    if !solana_net_utils::verify_all_reachable_udp(
99        &cluster_entrypoint.gossip().unwrap(),
100        &udp_sockets,
101    ) {
102        return false;
103    }
104
105    let mut tcp_listeners = vec![];
106    if let Some((rpc_addr, rpc_pubsub_addr)) = validator_config.rpc_addrs {
107        for (purpose, bind_addr, public_addr) in &[
108            ("RPC", rpc_addr, node.info.rpc()),
109            ("RPC pubsub", rpc_pubsub_addr, node.info.rpc_pubsub()),
110        ] {
111            if verify_address(public_addr) {
112                tcp_listeners.push(TcpListener::bind(bind_addr).unwrap_or_else(|err| {
113                    error!("Unable to bind to tcp {bind_addr:?} for {purpose}: {err}");
114                    exit(1);
115                }));
116            }
117        }
118    }
119
120    if let Some(ip_echo) = &node.sockets.ip_echo {
121        let ip_echo = ip_echo.try_clone().expect("unable to clone tcp_listener");
122        tcp_listeners.push(ip_echo);
123    }
124
125    solana_net_utils::verify_all_reachable_tcp(&cluster_entrypoint.gossip().unwrap(), tcp_listeners)
126}
127
128fn is_known_validator(id: &Pubkey, known_validators: &Option<HashSet<Pubkey>>) -> bool {
129    if let Some(known_validators) = known_validators {
130        known_validators.contains(id)
131    } else {
132        false
133    }
134}
135
136#[allow(clippy::too_many_arguments)]
137fn start_gossip_node(
138    identity_keypair: Arc<Keypair>,
139    cluster_entrypoints: &[ContactInfo],
140    known_validators: Option<HashSet<Pubkey>>,
141    ledger_path: &Path,
142    gossip_addr: &SocketAddr,
143    gossip_sockets: Arc<[UdpSocket]>,
144    expected_shred_version: u16,
145    gossip_validators: Option<HashSet<Pubkey>>,
146    should_check_duplicate_instance: bool,
147    socket_addr_space: SocketAddrSpace,
148) -> (Arc<ClusterInfo>, Arc<AtomicBool>, GossipService) {
149    let contact_info = ClusterInfo::gossip_contact_info(
150        identity_keypair.pubkey(),
151        *gossip_addr,
152        expected_shred_version,
153    );
154    let mut cluster_info = ClusterInfo::new(contact_info, identity_keypair, socket_addr_space);
155    if let Some(known_validators) = known_validators {
156        cluster_info
157            .set_trim_keep_pubkeys(known_validators)
158            .expect("set_trim_keep_pubkeys should succeed as ClusterInfo was just created");
159    }
160    cluster_info.set_entrypoints(cluster_entrypoints.to_vec());
161    cluster_info.restore_contact_info(ledger_path, 0);
162    let cluster_info = Arc::new(cluster_info);
163
164    let gossip_exit_flag = Arc::new(AtomicBool::new(false));
165    let gossip_service = GossipService::new(
166        &cluster_info,
167        None,
168        gossip_sockets,
169        None,
170        gossip_validators,
171        should_check_duplicate_instance,
172        None,
173        gossip_exit_flag.clone(),
174    );
175    (cluster_info, gossip_exit_flag, gossip_service)
176}
177
178fn get_rpc_peers(
179    cluster_info: &ClusterInfo,
180    validator_config: &ValidatorConfig,
181    blacklisted_rpc_nodes: &mut HashSet<Pubkey>,
182    blacklist_timeout: &Instant,
183    retry_reason: &mut Option<String>,
184    bootstrap_config: &RpcBootstrapConfig,
185) -> Vec<ContactInfo> {
186    let shred_version = validator_config
187        .expected_shred_version
188        .unwrap_or_else(|| cluster_info.my_shred_version());
189
190    info!(
191        "Searching for an RPC service with shred version {shred_version}{}...",
192        retry_reason
193            .as_ref()
194            .map(|s| format!(" (Retrying: {s})"))
195            .unwrap_or_default()
196    );
197
198    let mut rpc_peers = cluster_info.rpc_peers();
199    if bootstrap_config.only_known_rpc {
200        rpc_peers.retain(|rpc_peer| {
201            is_known_validator(rpc_peer.pubkey(), &validator_config.known_validators)
202        });
203    }
204
205    let rpc_peers_total = rpc_peers.len();
206
207    // Filter out blacklisted nodes
208    let rpc_peers: Vec<_> = rpc_peers
209        .into_iter()
210        .filter(|rpc_peer| !blacklisted_rpc_nodes.contains(rpc_peer.pubkey()))
211        .collect();
212    let rpc_peers_blacklisted = rpc_peers_total - rpc_peers.len();
213    let rpc_known_peers = rpc_peers
214        .iter()
215        .filter(|rpc_peer| {
216            is_known_validator(rpc_peer.pubkey(), &validator_config.known_validators)
217        })
218        .count();
219
220    info!(
221        "Total {rpc_peers_total} RPC nodes found. {rpc_known_peers} known, \
222         {rpc_peers_blacklisted} blacklisted"
223    );
224
225    if rpc_peers_blacklisted == rpc_peers_total {
226        *retry_reason = if !blacklisted_rpc_nodes.is_empty()
227            && blacklist_timeout.elapsed() > BLACKLIST_CLEAR_THRESHOLD
228        {
229            // All nodes are blacklisted and no additional nodes recently discovered.
230            // Remove all nodes from the blacklist and try them again.
231            blacklisted_rpc_nodes.clear();
232            Some("Blacklist timeout expired".to_owned())
233        } else {
234            Some("Wait for known rpc peers".to_owned())
235        };
236        return vec![];
237    }
238    rpc_peers
239}
240
241fn check_vote_account(
242    rpc_client: &RpcClient,
243    identity_pubkey: &Pubkey,
244    vote_account_address: &Pubkey,
245    authorized_voter_pubkeys: &[Pubkey],
246) -> Result<(), String> {
247    let vote_account = rpc_client
248        .get_account_with_commitment(vote_account_address, CommitmentConfig::confirmed())
249        .map_err(|err| format!("failed to fetch vote account: {err}"))?
250        .value
251        .ok_or_else(|| format!("vote account does not exist: {vote_account_address}"))?;
252
253    if vote_account.owner != solana_vote_program::id() {
254        return Err(format!(
255            "not a vote account (owned by {}): {}",
256            vote_account.owner, vote_account_address
257        ));
258    }
259
260    let identity_account = rpc_client
261        .get_account_with_commitment(identity_pubkey, CommitmentConfig::confirmed())
262        .map_err(|err| format!("failed to fetch identity account: {err}"))?
263        .value
264        .ok_or_else(|| format!("identity account does not exist: {identity_pubkey}"))?;
265
266    let vote_state = VoteStateV4::deserialize(vote_account.data(), vote_account_address).ok();
267    if let Some(vote_state) = vote_state {
268        if vote_state.authorized_voters.is_empty() {
269            return Err("Vote account not yet initialized".to_string());
270        }
271
272        if vote_state.node_pubkey != *identity_pubkey {
273            return Err(format!(
274                "vote account's identity ({}) does not match the validator's identity {}).",
275                vote_state.node_pubkey, identity_pubkey
276            ));
277        }
278
279        for (_, vote_account_authorized_voter_pubkey) in vote_state.authorized_voters.iter() {
280            if !authorized_voter_pubkeys.contains(vote_account_authorized_voter_pubkey) {
281                return Err(format!(
282                    "authorized voter {vote_account_authorized_voter_pubkey} not available"
283                ));
284            }
285        }
286    } else {
287        return Err(format!(
288            "invalid vote account data for {vote_account_address}"
289        ));
290    }
291
292    // Maybe we can calculate minimum voting fee; rather than 1 lamport
293    if identity_account.lamports <= 1 {
294        return Err(format!(
295            "underfunded identity account ({}): only {} lamports available",
296            identity_pubkey, identity_account.lamports
297        ));
298    }
299
300    Ok(())
301}
302
303#[derive(Error, Debug)]
304pub enum GetRpcNodeError {
305    #[error("Unable to find any RPC peers")]
306    NoRpcPeersFound,
307
308    #[error("Giving up, did not get newer snapshots from the cluster")]
309    NoNewerSnapshots,
310}
311
312/// Struct to wrap the return value from get_rpc_nodes().  The `rpc_contact_info` is the peer to
313/// download from, and `snapshot_hash` is the (optional) full and (optional) incremental
314/// snapshots to download.
315#[derive(Debug)]
316struct GetRpcNodeResult {
317    rpc_contact_info: ContactInfo,
318    snapshot_hash: Option<SnapshotHash>,
319}
320
321/// Struct to wrap the peers & snapshot hashes together.
322#[derive(Debug, PartialEq, Eq, Clone)]
323struct PeerSnapshotHash {
324    rpc_contact_info: ContactInfo,
325    snapshot_hash: SnapshotHash,
326}
327
328/// A snapshot hash.  In this context (bootstrap *with* incremental snapshots), a snapshot hash
329/// is _both_ a full snapshot hash and an (optional) incremental snapshot hash.
330#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
331pub struct SnapshotHash {
332    full: (Slot, Hash),
333    incr: Option<(Slot, Hash)>,
334}
335
336pub fn fail_rpc_node(
337    err: String,
338    known_validators: &Option<HashSet<Pubkey, RandomState>>,
339    rpc_id: &Pubkey,
340    blacklisted_rpc_nodes: &mut HashSet<Pubkey, RandomState>,
341) {
342    warn!("{err}");
343    if let Some(known_validators) = known_validators
344        && known_validators.contains(rpc_id)
345    {
346        return;
347    }
348
349    info!("Excluding {rpc_id} as a future RPC candidate");
350    blacklisted_rpc_nodes.insert(*rpc_id);
351}
352
353fn shutdown_gossip_service(gossip: (Arc<ClusterInfo>, Arc<AtomicBool>, GossipService)) {
354    let (cluster_info, gossip_exit_flag, gossip_service) = gossip;
355    cluster_info.save_contact_info();
356    gossip_exit_flag.store(true, Ordering::Relaxed);
357    gossip_service.join().unwrap();
358}
359
360#[allow(clippy::too_many_arguments)]
361pub fn attempt_download_genesis_and_snapshot(
362    rpc_contact_info: &ContactInfo,
363    ledger_path: &Path,
364    validator_config: &mut ValidatorConfig,
365    bootstrap_config: &RpcBootstrapConfig,
366    use_progress_bar: bool,
367    gossip: &mut Option<(Arc<ClusterInfo>, Arc<AtomicBool>, GossipService)>,
368    rpc_client: &RpcClient,
369    maximum_local_snapshot_age: Slot,
370    start_progress: &Arc<RwLock<ValidatorStartProgress>>,
371    minimal_snapshot_download_speed: f32,
372    maximum_snapshot_download_abort: u64,
373    download_abort_count: &mut u64,
374    snapshot_hash: Option<SnapshotHash>,
375    identity_keypair: &Arc<Keypair>,
376    vote_account: &Pubkey,
377    authorized_voter_keypairs: Arc<RwLock<Vec<Arc<Keypair>>>>,
378) -> Result<(), String> {
379    download_then_check_genesis_hash(
380        &rpc_contact_info
381            .rpc()
382            .ok_or_else(|| String::from("Invalid RPC address"))?,
383        ledger_path,
384        &mut validator_config.expected_genesis_hash,
385        bootstrap_config.max_genesis_archive_unpacked_size,
386        bootstrap_config.no_genesis_fetch,
387        use_progress_bar,
388        rpc_client,
389    )?;
390
391    if let Some(gossip) = gossip.take() {
392        shutdown_gossip_service(gossip);
393    }
394
395    let rpc_client_slot = rpc_client
396        .get_slot_with_commitment(CommitmentConfig::finalized())
397        .map_err(|err| format!("Failed to get RPC node slot: {err}"))?;
398    info!("RPC node root slot: {rpc_client_slot}");
399
400    download_snapshots(
401        validator_config,
402        bootstrap_config,
403        use_progress_bar,
404        maximum_local_snapshot_age,
405        start_progress,
406        minimal_snapshot_download_speed,
407        maximum_snapshot_download_abort,
408        download_abort_count,
409        snapshot_hash,
410        rpc_contact_info,
411    )?;
412
413    if let Some(url) = bootstrap_config.check_vote_account.as_ref() {
414        let rpc_client = RpcClient::new(url);
415        check_vote_account(
416            &rpc_client,
417            &identity_keypair.pubkey(),
418            vote_account,
419            &authorized_voter_keypairs
420                .read()
421                .unwrap()
422                .iter()
423                .map(|k| k.pubkey())
424                .collect::<Vec<_>>(),
425        )
426        .unwrap_or_else(|err| {
427            // Consider failures here to be more likely due to user error (eg,
428            // incorrect `agave-validator` command-line arguments) rather than the
429            // RPC node failing.
430            //
431            // Power users can always use the `--no-check-vote-account` option to
432            // bypass this check entirely
433            error!("{err}");
434            exit(1);
435        });
436    }
437    Ok(())
438}
439
440/// simple ping helper function which returns the time to connect
441fn ping(addr: &SocketAddr) -> Option<Duration> {
442    let start = Instant::now();
443    match TcpStream::connect_timeout(addr, PING_TIMEOUT) {
444        Ok(_) => Some(start.elapsed()),
445        Err(_) => None,
446    }
447}
448
449// Populates `vetted_rpc_nodes` with a list of RPC nodes that are ready to be
450// used for downloading latest snapshots and/or the genesis block. Guaranteed to
451// find at least one viable node or terminate the process.
452fn get_vetted_rpc_nodes(
453    vetted_rpc_nodes: &mut Vec<(ContactInfo, Option<SnapshotHash>, RpcClient)>,
454    cluster_info: &Arc<ClusterInfo>,
455    validator_config: &ValidatorConfig,
456    blacklisted_rpc_nodes: &mut HashSet<Pubkey>,
457    bootstrap_config: &RpcBootstrapConfig,
458) {
459    while vetted_rpc_nodes.is_empty() {
460        let rpc_node_details = match get_rpc_nodes(
461            cluster_info,
462            validator_config,
463            blacklisted_rpc_nodes,
464            bootstrap_config,
465        ) {
466            Ok(rpc_node_details) => rpc_node_details,
467            Err(err) => {
468                error!(
469                    "Failed to get RPC nodes: {err}. Consider checking system clock, removing \
470                     `--no-port-check`, or adjusting `--known-validator ...` arguments as \
471                     applicable"
472                );
473                exit(1);
474            }
475        };
476
477        let newly_blacklisted_rpc_nodes = RwLock::new(HashSet::new());
478        vetted_rpc_nodes.extend(
479            rpc_node_details
480                .into_par_iter()
481                .filter_map(|rpc_node_details| {
482                    let GetRpcNodeResult {
483                        rpc_contact_info,
484                        snapshot_hash,
485                    } = rpc_node_details;
486
487                    info!(
488                        "Using RPC service from node {}: {:?}",
489                        rpc_contact_info.pubkey(),
490                        rpc_contact_info.rpc()
491                    );
492
493                    let rpc_addr = rpc_contact_info.rpc()?;
494                    let ping_time = ping(&rpc_addr);
495
496                    let rpc_client =
497                        RpcClient::new_socket_with_timeout(rpc_addr, Duration::from_secs(5));
498
499                    Some((rpc_contact_info, snapshot_hash, rpc_client, ping_time))
500                })
501                .filter(
502                    |(rpc_contact_info, _snapshot_hash, rpc_client, ping_time)| match rpc_client
503                        .get_version()
504                    {
505                        Ok(rpc_version) => {
506                            if let Some(ping_time) = ping_time {
507                                info!(
508                                    "RPC node version: {} Ping: {}ms",
509                                    rpc_version.solana_core,
510                                    ping_time.as_millis()
511                                );
512                                true
513                            } else {
514                                fail_rpc_node(
515                                    "Failed to ping RPC".to_string(),
516                                    &validator_config.known_validators,
517                                    rpc_contact_info.pubkey(),
518                                    &mut newly_blacklisted_rpc_nodes.write().unwrap(),
519                                );
520                                false
521                            }
522                        }
523                        Err(err) => {
524                            fail_rpc_node(
525                                format!("Failed to get RPC node version: {err}"),
526                                &validator_config.known_validators,
527                                rpc_contact_info.pubkey(),
528                                &mut newly_blacklisted_rpc_nodes.write().unwrap(),
529                            );
530                            false
531                        }
532                    },
533                )
534                .collect::<Vec<(
535                    ContactInfo,
536                    Option<SnapshotHash>,
537                    RpcClient,
538                    Option<Duration>,
539                )>>()
540                .into_iter()
541                .sorted_by_key(|(_, _, _, ping_time)| ping_time.unwrap())
542                .map(|(rpc_contact_info, snapshot_hash, rpc_client, _)| {
543                    (rpc_contact_info, snapshot_hash, rpc_client)
544                })
545                .collect::<Vec<(ContactInfo, Option<SnapshotHash>, RpcClient)>>(),
546        );
547        blacklisted_rpc_nodes.extend(newly_blacklisted_rpc_nodes.into_inner().unwrap());
548    }
549}
550
551#[allow(clippy::too_many_arguments)]
552pub fn rpc_bootstrap(
553    node: &Node,
554    identity_keypair: &Arc<Keypair>,
555    ledger_path: &Path,
556    vote_account: &Pubkey,
557    authorized_voter_keypairs: Arc<RwLock<Vec<Arc<Keypair>>>>,
558    cluster_entrypoints: &[ContactInfo],
559    validator_config: &mut ValidatorConfig,
560    bootstrap_config: RpcBootstrapConfig,
561    do_port_check: bool,
562    use_progress_bar: bool,
563    maximum_local_snapshot_age: Slot,
564    start_progress: &Arc<RwLock<ValidatorStartProgress>>,
565    minimal_snapshot_download_speed: f32,
566    maximum_snapshot_download_abort: u64,
567    socket_addr_space: SocketAddrSpace,
568) {
569    if do_port_check {
570        let mut order: Vec<_> = (0..cluster_entrypoints.len()).collect();
571        order.shuffle(&mut rng());
572        if order.into_iter().all(|i| {
573            !verify_reachable_ports(
574                node,
575                &cluster_entrypoints[i],
576                validator_config,
577                &socket_addr_space,
578            )
579        }) {
580            exit(1);
581        }
582    }
583
584    if bootstrap_config.no_genesis_fetch && bootstrap_config.no_snapshot_fetch {
585        return;
586    }
587
588    let total_snapshot_download_time = Instant::now();
589    let mut get_rpc_nodes_time = Duration::new(0, 0);
590    let mut snapshot_download_time = Duration::new(0, 0);
591    let mut blacklisted_rpc_nodes = HashSet::new();
592    let mut gossip = None;
593    let mut vetted_rpc_nodes = vec![];
594    let mut download_abort_count = 0;
595    loop {
596        if gossip.is_none() {
597            *start_progress.write().unwrap() = ValidatorStartProgress::SearchingForRpcService;
598
599            gossip = Some(start_gossip_node(
600                identity_keypair.clone(),
601                cluster_entrypoints,
602                validator_config.known_validators.clone(),
603                ledger_path,
604                &node
605                    .info
606                    .gossip()
607                    .expect("Operator must spin up node with valid gossip address"),
608                node.sockets.gossip.clone(),
609                validator_config
610                    .expected_shred_version
611                    .expect("expected_shred_version should not be None"),
612                validator_config.gossip_validators.clone(),
613                validator_config.should_check_duplicate_instance,
614                socket_addr_space,
615            ));
616        }
617
618        let get_rpc_nodes_start = Instant::now();
619        get_vetted_rpc_nodes(
620            &mut vetted_rpc_nodes,
621            &gossip.as_ref().unwrap().0,
622            validator_config,
623            &mut blacklisted_rpc_nodes,
624            &bootstrap_config,
625        );
626        let (rpc_contact_info, snapshot_hash, rpc_client) = vetted_rpc_nodes.pop().unwrap();
627        get_rpc_nodes_time += get_rpc_nodes_start.elapsed();
628
629        let snapshot_download_start = Instant::now();
630        let download_result = attempt_download_genesis_and_snapshot(
631            &rpc_contact_info,
632            ledger_path,
633            validator_config,
634            &bootstrap_config,
635            use_progress_bar,
636            &mut gossip,
637            &rpc_client,
638            maximum_local_snapshot_age,
639            start_progress,
640            minimal_snapshot_download_speed,
641            maximum_snapshot_download_abort,
642            &mut download_abort_count,
643            snapshot_hash,
644            identity_keypair,
645            vote_account,
646            authorized_voter_keypairs.clone(),
647        );
648        snapshot_download_time += snapshot_download_start.elapsed();
649        match download_result {
650            Ok(()) => break,
651            Err(err) => {
652                fail_rpc_node(
653                    err,
654                    &validator_config.known_validators,
655                    rpc_contact_info.pubkey(),
656                    &mut blacklisted_rpc_nodes,
657                );
658            }
659        }
660    }
661
662    if let Some(gossip) = gossip.take() {
663        shutdown_gossip_service(gossip);
664    }
665
666    datapoint_info!(
667        "bootstrap-snapshot-download",
668        (
669            "total_time_secs",
670            total_snapshot_download_time.elapsed().as_secs(),
671            i64
672        ),
673        ("get_rpc_nodes_time_secs", get_rpc_nodes_time.as_secs(), i64),
674        (
675            "snapshot_download_time_secs",
676            snapshot_download_time.as_secs(),
677            i64
678        ),
679        ("download_abort_count", download_abort_count, i64),
680        ("blacklisted_nodes_count", blacklisted_rpc_nodes.len(), i64),
681    );
682}
683
684/// Get RPC peer node candidates to download from.
685///
686/// This function finds the highest compatible snapshots from the cluster and returns RPC peers.
687fn get_rpc_nodes(
688    cluster_info: &ClusterInfo,
689    validator_config: &ValidatorConfig,
690    blacklisted_rpc_nodes: &mut HashSet<Pubkey>,
691    bootstrap_config: &RpcBootstrapConfig,
692) -> Result<Vec<GetRpcNodeResult>, GetRpcNodeError> {
693    let mut blacklist_timeout = Instant::now();
694    let mut get_rpc_peers_timout = Instant::now();
695    let mut newer_cluster_snapshot_timeout = None;
696    let mut retry_reason = None;
697    loop {
698        // Give gossip some time to populate and not spin on grabbing the crds lock
699        std::thread::sleep(Duration::from_secs(1));
700        info!("\n{}", cluster_info.rpc_info_trace());
701
702        let rpc_peers = get_rpc_peers(
703            cluster_info,
704            validator_config,
705            blacklisted_rpc_nodes,
706            &blacklist_timeout,
707            &mut retry_reason,
708            bootstrap_config,
709        );
710        if rpc_peers.is_empty() {
711            if get_rpc_peers_timout.elapsed() > GET_RPC_PEERS_TIMEOUT {
712                return Err(GetRpcNodeError::NoRpcPeersFound);
713            }
714            continue;
715        }
716
717        // Reset timeouts if we found any viable RPC peers.
718        blacklist_timeout = Instant::now();
719        get_rpc_peers_timout = Instant::now();
720        if bootstrap_config.no_snapshot_fetch {
721            let random_peer = &rpc_peers[rng().random_range(0..rpc_peers.len())];
722            return Ok(vec![GetRpcNodeResult {
723                rpc_contact_info: random_peer.clone(),
724                snapshot_hash: None,
725            }]);
726        }
727
728        let known_validators_to_wait_for = if newer_cluster_snapshot_timeout
729            .as_ref()
730            .map(|timer: &Instant| timer.elapsed() < WAIT_FOR_ALL_KNOWN_VALIDATORS)
731            .unwrap_or(true)
732        {
733            KnownValidatorsToWaitFor::All
734        } else {
735            KnownValidatorsToWaitFor::Any
736        };
737        let peer_snapshot_hashes = get_peer_snapshot_hashes(
738            cluster_info,
739            &rpc_peers,
740            validator_config.known_validators.as_ref(),
741            known_validators_to_wait_for,
742            bootstrap_config.incremental_snapshot_fetch,
743        );
744        if peer_snapshot_hashes.is_empty() {
745            match newer_cluster_snapshot_timeout {
746                None => newer_cluster_snapshot_timeout = Some(Instant::now()),
747                Some(newer_cluster_snapshot_timeout) => {
748                    if newer_cluster_snapshot_timeout.elapsed() > NEWER_SNAPSHOT_THRESHOLD {
749                        return Err(GetRpcNodeError::NoNewerSnapshots);
750                    }
751                }
752            }
753            retry_reason = Some("No snapshots available".to_owned());
754            continue;
755        } else {
756            let rpc_peers = peer_snapshot_hashes
757                .iter()
758                .map(|peer_snapshot_hash| peer_snapshot_hash.rpc_contact_info.pubkey())
759                .collect::<Vec<_>>();
760            let final_snapshot_hash = peer_snapshot_hashes[0].snapshot_hash;
761            info!(
762                "Highest available snapshot slot is {}, available from {} node{}: {:?}",
763                final_snapshot_hash
764                    .incr
765                    .map(|(slot, _hash)| slot)
766                    .unwrap_or(final_snapshot_hash.full.0),
767                rpc_peers.len(),
768                if rpc_peers.len() > 1 { "s" } else { "" },
769                rpc_peers,
770            );
771            let rpc_node_results = peer_snapshot_hashes
772                .iter()
773                .map(|peer_snapshot_hash| GetRpcNodeResult {
774                    rpc_contact_info: peer_snapshot_hash.rpc_contact_info.clone(),
775                    snapshot_hash: Some(peer_snapshot_hash.snapshot_hash),
776                })
777                .take(MAX_RPC_CONNECTIONS_EVALUATED_PER_ITERATION)
778                .collect();
779            return Ok(rpc_node_results);
780        }
781    }
782}
783
784/// Get the Slot and Hash of the local snapshot with the highest slot.  Can be either a full
785/// snapshot or an incremental snapshot.
786fn get_highest_local_snapshot_hash(
787    full_snapshot_archives_dir: impl AsRef<Path>,
788    incremental_snapshot_archives_dir: impl AsRef<Path>,
789    incremental_snapshot_fetch: bool,
790) -> Option<(Slot, Hash)> {
791    snapshot_paths::get_highest_full_snapshot_archive_info(full_snapshot_archives_dir)
792        .and_then(|full_snapshot_info| {
793            if incremental_snapshot_fetch {
794                snapshot_paths::get_highest_incremental_snapshot_archive_info(
795                    incremental_snapshot_archives_dir,
796                    full_snapshot_info.slot(),
797                )
798                .map(|incremental_snapshot_info| {
799                    (
800                        incremental_snapshot_info.slot(),
801                        *incremental_snapshot_info.hash(),
802                    )
803                })
804            } else {
805                None
806            }
807            .or_else(|| Some((full_snapshot_info.slot(), *full_snapshot_info.hash())))
808        })
809        .map(|(slot, snapshot_hash)| (slot, snapshot_hash.0))
810}
811
812/// Get peer snapshot hashes
813///
814/// The result is a vector of peers with snapshot hashes that:
815/// 1. match a snapshot hash from the known validators
816/// 2. have the highest incremental snapshot slot
817/// 3. have the highest full snapshot slot of (2)
818fn get_peer_snapshot_hashes(
819    cluster_info: &ClusterInfo,
820    rpc_peers: &[ContactInfo],
821    known_validators: Option<&HashSet<Pubkey>>,
822    known_validators_to_wait_for: KnownValidatorsToWaitFor,
823    incremental_snapshot_fetch: bool,
824) -> Vec<PeerSnapshotHash> {
825    let mut peer_snapshot_hashes = get_eligible_peer_snapshot_hashes(cluster_info, rpc_peers);
826    if let Some(known_validators) = known_validators {
827        let known_snapshot_hashes = get_snapshot_hashes_from_known_validators(
828            cluster_info,
829            known_validators,
830            known_validators_to_wait_for,
831        );
832        retain_peer_snapshot_hashes_that_match_known_snapshot_hashes(
833            &known_snapshot_hashes,
834            &mut peer_snapshot_hashes,
835        );
836    }
837    if incremental_snapshot_fetch {
838        // Only filter by highest incremental snapshot slot if we're actually going to download an
839        // incremental snapshot.  Otherwise this could remove higher full snapshot slots from
840        // being selected.  For example, if there are two peer snapshot hashes:
841        // (A) full snapshot slot: 100, incremental snapshot slot: 160
842        // (B) full snapshot slot: 150, incremental snapshot slot: None
843        // Then (A) has the highest overall snapshot slot.  But if we're not downloading and
844        // incremental snapshot, (B) should be selected since it's full snapshot of 150 is highest.
845        retain_peer_snapshot_hashes_with_highest_incremental_snapshot_slot(
846            &mut peer_snapshot_hashes,
847        );
848    }
849    retain_peer_snapshot_hashes_with_highest_full_snapshot_slot(&mut peer_snapshot_hashes);
850
851    peer_snapshot_hashes
852}
853
854/// Map full snapshot hashes to a set of incremental snapshot hashes.  Each full snapshot hash
855/// is treated as the base for its set of incremental snapshot hashes.
856type KnownSnapshotHashes = HashMap<(Slot, Hash), HashSet<(Slot, Hash)>>;
857
858/// Get the snapshot hashes from known validators.
859///
860/// The snapshot hashes are put into a map from full snapshot hash to a set of incremental
861/// snapshot hashes.  This map will be used as the "known snapshot hashes"; when peers are
862/// queried for their individual snapshot hashes, their results will be checked against this
863/// map to verify correctness.
864///
865/// NOTE: Only a single snapshot hash is allowed per slot.  If somehow two known validators have
866/// a snapshot hash with the same slot and _different_ hashes, the second will be skipped.
867/// This applies to both full and incremental snapshot hashes.
868fn get_snapshot_hashes_from_known_validators(
869    cluster_info: &ClusterInfo,
870    known_validators: &HashSet<Pubkey>,
871    known_validators_to_wait_for: KnownValidatorsToWaitFor,
872) -> KnownSnapshotHashes {
873    // Get the snapshot hashes for a node from CRDS
874    let get_snapshot_hashes_for_node = |node| get_snapshot_hashes_for_node(cluster_info, node);
875
876    if !do_known_validators_have_all_snapshot_hashes(
877        known_validators,
878        known_validators_to_wait_for,
879        get_snapshot_hashes_for_node,
880    ) {
881        debug!(
882            "Snapshot hashes have not been discovered from known validators. This likely means \
883             the gossip tables are not fully populated. We will sleep and retry..."
884        );
885        return KnownSnapshotHashes::default();
886    }
887
888    build_known_snapshot_hashes(known_validators, get_snapshot_hashes_for_node)
889}
890
891/// Check if we can discover snapshot hashes for the known validators.
892///
893/// This is a heuristic to ensure the gossip tables are populated enough so that the bootstrap
894/// process will download snapshots.
895///
896/// This function will return false if we do not yet have snapshot hashes from known validators;
897/// and true otherwise.  Either require snapshot hashes from *all* or *any* of the known validators
898/// based on the `KnownValidatorsToWaitFor` parameter.
899fn do_known_validators_have_all_snapshot_hashes<'a>(
900    known_validators: impl IntoIterator<Item = &'a Pubkey>,
901    known_validators_to_wait_for: KnownValidatorsToWaitFor,
902    get_snapshot_hashes_for_node: impl Fn(&'a Pubkey) -> Option<SnapshotHash>,
903) -> bool {
904    let node_has_snapshot_hashes = |node| get_snapshot_hashes_for_node(node).is_some();
905
906    match known_validators_to_wait_for {
907        KnownValidatorsToWaitFor::All => known_validators.into_iter().all(node_has_snapshot_hashes),
908        KnownValidatorsToWaitFor::Any => known_validators.into_iter().any(node_has_snapshot_hashes),
909    }
910}
911
912/// When waiting for snapshot hashes from the known validators, should we wait for *all* or *any*
913/// of them?
914#[derive(Debug, Copy, Clone, Eq, PartialEq)]
915enum KnownValidatorsToWaitFor {
916    All,
917    Any,
918}
919
920/// Build the known snapshot hashes from a set of nodes.
921///
922/// The `get_snapshot_hashes_for_node` parameter is a function that map a pubkey to its snapshot
923/// hashes.  This parameter exist to provide a way to test the inner algorithm without needing
924/// runtime information such as the ClusterInfo or ValidatorConfig.
925fn build_known_snapshot_hashes<'a>(
926    nodes: impl IntoIterator<Item = &'a Pubkey>,
927    get_snapshot_hashes_for_node: impl Fn(&'a Pubkey) -> Option<SnapshotHash>,
928) -> KnownSnapshotHashes {
929    let mut known_snapshot_hashes = KnownSnapshotHashes::new();
930
931    /// Check to see if there exists another snapshot hash in the haystack with the *same* slot
932    /// but *different* hash as the needle.
933    fn is_any_same_slot_and_different_hash<'a>(
934        needle: &(Slot, Hash),
935        haystack: impl IntoIterator<Item = &'a (Slot, Hash)>,
936    ) -> bool {
937        haystack
938            .into_iter()
939            .any(|hay| needle.0 == hay.0 && needle.1 != hay.1)
940    }
941
942    'to_next_node: for node in nodes {
943        let Some(SnapshotHash {
944            full: full_snapshot_hash,
945            incr: incremental_snapshot_hash,
946        }) = get_snapshot_hashes_for_node(node)
947        else {
948            continue 'to_next_node;
949        };
950
951        // Do not add this snapshot hash if there's already a full snapshot hash with the
952        // same slot but with a _different_ hash.
953        // NOTE: Nodes should not produce snapshots at the same slot with _different_
954        // hashes.  So if it happens, keep the first and ignore the rest.
955        if is_any_same_slot_and_different_hash(&full_snapshot_hash, known_snapshot_hashes.keys()) {
956            warn!(
957                "Ignoring all snapshot hashes from node {node} since we've seen a different full \
958                 snapshot hash with this slot. full snapshot hash: {full_snapshot_hash:?}"
959            );
960            debug!(
961                "known full snapshot hashes: {:#?}",
962                known_snapshot_hashes.keys(),
963            );
964            continue 'to_next_node;
965        }
966
967        // Insert a new full snapshot hash into the known snapshot hashes IFF an entry
968        // doesn't already exist.  This is to ensure we don't overwrite existing
969        // incremental snapshot hashes that may be present for this full snapshot hash.
970        let known_incremental_snapshot_hashes =
971            known_snapshot_hashes.entry(full_snapshot_hash).or_default();
972
973        if let Some(incremental_snapshot_hash) = incremental_snapshot_hash {
974            // Do not add this snapshot hash if there's already an incremental snapshot
975            // hash with the same slot, but with a _different_ hash.
976            // NOTE: Nodes should not produce snapshots at the same slot with _different_
977            // hashes.  So if it happens, keep the first and ignore the rest.
978            if is_any_same_slot_and_different_hash(
979                &incremental_snapshot_hash,
980                known_incremental_snapshot_hashes.iter(),
981            ) {
982                warn!(
983                    "Ignoring incremental snapshot hash from node {node} since we've seen a \
984                     different incremental snapshot hash with this slot. full snapshot hash: \
985                     {full_snapshot_hash:?}, incremental snapshot hash: \
986                     {incremental_snapshot_hash:?}"
987                );
988                debug!(
989                    "known incremental snapshot hashes based on this slot: {:#?}",
990                    known_incremental_snapshot_hashes.iter(),
991                );
992                continue 'to_next_node;
993            }
994
995            known_incremental_snapshot_hashes.insert(incremental_snapshot_hash);
996        };
997    }
998
999    trace!("known snapshot hashes: {known_snapshot_hashes:?}");
1000    known_snapshot_hashes
1001}
1002
1003/// Get snapshot hashes from all eligible peers.
1004///
1005/// This fn will get only one snapshot hash per peer (the one with the highest slot).
1006/// This may be just a full snapshot hash, or a combo full snapshot hash and
1007/// incremental snapshot hash.
1008fn get_eligible_peer_snapshot_hashes(
1009    cluster_info: &ClusterInfo,
1010    rpc_peers: &[ContactInfo],
1011) -> Vec<PeerSnapshotHash> {
1012    let peer_snapshot_hashes = rpc_peers
1013        .iter()
1014        .flat_map(|rpc_peer| {
1015            get_snapshot_hashes_for_node(cluster_info, rpc_peer.pubkey()).map(|snapshot_hash| {
1016                PeerSnapshotHash {
1017                    rpc_contact_info: rpc_peer.clone(),
1018                    snapshot_hash,
1019                }
1020            })
1021        })
1022        .collect();
1023
1024    trace!("peer snapshot hashes: {peer_snapshot_hashes:?}");
1025    peer_snapshot_hashes
1026}
1027
1028/// Retain the peer snapshot hashes that match a snapshot hash from the known snapshot hashes
1029fn retain_peer_snapshot_hashes_that_match_known_snapshot_hashes(
1030    known_snapshot_hashes: &KnownSnapshotHashes,
1031    peer_snapshot_hashes: &mut Vec<PeerSnapshotHash>,
1032) {
1033    peer_snapshot_hashes.retain(|peer_snapshot_hash| {
1034        known_snapshot_hashes
1035            .get(&peer_snapshot_hash.snapshot_hash.full)
1036            .map(|known_incremental_hashes| {
1037                if let Some(incr) = peer_snapshot_hash.snapshot_hash.incr.as_ref() {
1038                    known_incremental_hashes.contains(incr)
1039                } else {
1040                    // If the peer's full snapshot hashes match, but doesn't have any
1041                    // incremental snapshots, that's fine; keep 'em!
1042                    true
1043                }
1044            })
1045            .unwrap_or(false)
1046    });
1047
1048    trace!(
1049        "retain peer snapshot hashes that match known snapshot hashes: {peer_snapshot_hashes:?}"
1050    );
1051}
1052
1053/// Retain the peer snapshot hashes with the highest full snapshot slot
1054fn retain_peer_snapshot_hashes_with_highest_full_snapshot_slot(
1055    peer_snapshot_hashes: &mut Vec<PeerSnapshotHash>,
1056) {
1057    let highest_full_snapshot_hash = peer_snapshot_hashes
1058        .iter()
1059        .map(|peer_snapshot_hash| peer_snapshot_hash.snapshot_hash.full)
1060        .max_by_key(|(slot, _hash)| *slot);
1061    let Some(highest_full_snapshot_hash) = highest_full_snapshot_hash else {
1062        // `max_by_key` will only be `None` IFF the input `peer_snapshot_hashes` is empty.
1063        // In that case there's nothing to do (additionally, without a valid 'max' value, there
1064        // will be nothing to compare against within the `retain()` predicate).
1065        return;
1066    };
1067
1068    peer_snapshot_hashes.retain(|peer_snapshot_hash| {
1069        peer_snapshot_hash.snapshot_hash.full == highest_full_snapshot_hash
1070    });
1071
1072    trace!("retain peer snapshot hashes with highest full snapshot slot: {peer_snapshot_hashes:?}");
1073}
1074
1075/// Retain the peer snapshot hashes with the highest incremental snapshot slot
1076fn retain_peer_snapshot_hashes_with_highest_incremental_snapshot_slot(
1077    peer_snapshot_hashes: &mut Vec<PeerSnapshotHash>,
1078) {
1079    let highest_incremental_snapshot_hash = peer_snapshot_hashes
1080        .iter()
1081        .flat_map(|peer_snapshot_hash| peer_snapshot_hash.snapshot_hash.incr)
1082        .max_by_key(|(slot, _hash)| *slot);
1083
1084    peer_snapshot_hashes.retain(|peer_snapshot_hash| {
1085        peer_snapshot_hash.snapshot_hash.incr == highest_incremental_snapshot_hash
1086    });
1087
1088    trace!(
1089        "retain peer snapshot hashes with highest incremental snapshot slot: \
1090         {peer_snapshot_hashes:?}"
1091    );
1092}
1093
1094/// Check to see if we can use our local snapshots, otherwise download newer ones.
1095#[allow(clippy::too_many_arguments)]
1096fn download_snapshots(
1097    validator_config: &ValidatorConfig,
1098    bootstrap_config: &RpcBootstrapConfig,
1099    use_progress_bar: bool,
1100    maximum_local_snapshot_age: Slot,
1101    start_progress: &Arc<RwLock<ValidatorStartProgress>>,
1102    minimal_snapshot_download_speed: f32,
1103    maximum_snapshot_download_abort: u64,
1104    download_abort_count: &mut u64,
1105    snapshot_hash: Option<SnapshotHash>,
1106    rpc_contact_info: &ContactInfo,
1107) -> Result<(), String> {
1108    if snapshot_hash.is_none() {
1109        return Ok(());
1110    }
1111    let SnapshotHash {
1112        full: full_snapshot_hash,
1113        incr: incremental_snapshot_hash,
1114    } = snapshot_hash.unwrap();
1115    let full_snapshot_archives_dir = &validator_config.snapshot_config.full_snapshot_archives_dir;
1116    let incremental_snapshot_archives_dir = &validator_config
1117        .snapshot_config
1118        .incremental_snapshot_archives_dir;
1119
1120    // If the local snapshots are new enough, then use 'em; no need to download new snapshots
1121    if should_use_local_snapshot(
1122        full_snapshot_archives_dir,
1123        incremental_snapshot_archives_dir,
1124        maximum_local_snapshot_age,
1125        full_snapshot_hash,
1126        incremental_snapshot_hash,
1127        bootstrap_config.incremental_snapshot_fetch,
1128    ) {
1129        return Ok(());
1130    }
1131
1132    // Check and see if we've already got the full snapshot; if not, download it
1133    if snapshot_paths::full_snapshot_archives_iter(full_snapshot_archives_dir).any(
1134        |snapshot_archive| {
1135            snapshot_archive.slot() == full_snapshot_hash.0
1136                && snapshot_archive.hash().0 == full_snapshot_hash.1
1137        },
1138    ) {
1139        info!(
1140            "Full snapshot archive already exists locally. Skipping download. slot: {}, hash: {}",
1141            full_snapshot_hash.0, full_snapshot_hash.1
1142        );
1143    } else {
1144        download_snapshot(
1145            validator_config,
1146            bootstrap_config,
1147            use_progress_bar,
1148            start_progress,
1149            minimal_snapshot_download_speed,
1150            maximum_snapshot_download_abort,
1151            download_abort_count,
1152            rpc_contact_info,
1153            full_snapshot_hash,
1154            SnapshotArchiveKind::Full,
1155        )?;
1156    }
1157
1158    if bootstrap_config.incremental_snapshot_fetch {
1159        // Check and see if we've already got the incremental snapshot; if not, download it
1160        if let Some(incremental_snapshot_hash) = incremental_snapshot_hash {
1161            if snapshot_paths::incremental_snapshot_archives_iter(incremental_snapshot_archives_dir)
1162                .any(|snapshot_archive| {
1163                    snapshot_archive.slot() == incremental_snapshot_hash.0
1164                        && snapshot_archive.hash().0 == incremental_snapshot_hash.1
1165                        && snapshot_archive.base_slot() == full_snapshot_hash.0
1166                })
1167            {
1168                info!(
1169                    "Incremental snapshot archive already exists locally. Skipping download. \
1170                     slot: {}, hash: {}",
1171                    incremental_snapshot_hash.0, incremental_snapshot_hash.1
1172                );
1173            } else {
1174                download_snapshot(
1175                    validator_config,
1176                    bootstrap_config,
1177                    use_progress_bar,
1178                    start_progress,
1179                    minimal_snapshot_download_speed,
1180                    maximum_snapshot_download_abort,
1181                    download_abort_count,
1182                    rpc_contact_info,
1183                    incremental_snapshot_hash,
1184                    SnapshotArchiveKind::Incremental(full_snapshot_hash.0),
1185                )?;
1186            }
1187        }
1188    }
1189
1190    Ok(())
1191}
1192
1193/// Download a snapshot
1194#[allow(clippy::too_many_arguments)]
1195fn download_snapshot(
1196    validator_config: &ValidatorConfig,
1197    bootstrap_config: &RpcBootstrapConfig,
1198    use_progress_bar: bool,
1199    start_progress: &Arc<RwLock<ValidatorStartProgress>>,
1200    minimal_snapshot_download_speed: f32,
1201    maximum_snapshot_download_abort: u64,
1202    download_abort_count: &mut u64,
1203    rpc_contact_info: &ContactInfo,
1204    desired_snapshot_hash: (Slot, Hash),
1205    snapshot_kind: SnapshotArchiveKind,
1206) -> Result<(), String> {
1207    let maximum_full_snapshot_archives_to_retain = validator_config
1208        .snapshot_config
1209        .maximum_full_snapshot_archives_to_retain;
1210    let maximum_incremental_snapshot_archives_to_retain = validator_config
1211        .snapshot_config
1212        .maximum_incremental_snapshot_archives_to_retain;
1213    let full_snapshot_archives_dir = &validator_config.snapshot_config.full_snapshot_archives_dir;
1214    let incremental_snapshot_archives_dir = &validator_config
1215        .snapshot_config
1216        .incremental_snapshot_archives_dir;
1217
1218    *start_progress.write().unwrap() = ValidatorStartProgress::DownloadingSnapshot {
1219        slot: desired_snapshot_hash.0,
1220        rpc_addr: rpc_contact_info
1221            .rpc()
1222            .ok_or_else(|| String::from("Invalid RPC address"))?,
1223    };
1224    let desired_snapshot_hash = (
1225        desired_snapshot_hash.0,
1226        agave_snapshots::snapshot_hash::SnapshotHash(desired_snapshot_hash.1),
1227    );
1228    download_snapshot_archive(
1229        &rpc_contact_info
1230            .rpc()
1231            .ok_or_else(|| String::from("Invalid RPC address"))?,
1232        full_snapshot_archives_dir,
1233        incremental_snapshot_archives_dir,
1234        desired_snapshot_hash,
1235        snapshot_kind,
1236        maximum_full_snapshot_archives_to_retain,
1237        maximum_incremental_snapshot_archives_to_retain,
1238        use_progress_bar,
1239        &mut Some(Box::new(|download_progress: &DownloadProgressRecord| {
1240            debug!("Download progress: {download_progress:?}");
1241            if download_progress.last_throughput < minimal_snapshot_download_speed
1242                && download_progress.notification_count <= 1
1243                && download_progress.percentage_done <= 2_f32
1244                && download_progress.estimated_remaining_time > 60_f32
1245                && *download_abort_count < maximum_snapshot_download_abort
1246            {
1247                if let Some(ref known_validators) = validator_config.known_validators
1248                    && known_validators.contains(rpc_contact_info.pubkey())
1249                    && known_validators.len() == 1
1250                    && bootstrap_config.only_known_rpc
1251                {
1252                    warn!(
1253                        "The snapshot download is too slow, throughput: {} < min speed {} \
1254                         bytes/sec, but will NOT abort and try a different node as it is the only \
1255                         known validator and the --only-known-rpc flag is set. Abort count: {}, \
1256                         Progress detail: {:?}",
1257                        download_progress.last_throughput,
1258                        minimal_snapshot_download_speed,
1259                        download_abort_count,
1260                        download_progress,
1261                    );
1262                    return true; // Do not abort download from the one-and-only known validator
1263                }
1264                warn!(
1265                    "The snapshot download is too slow, throughput: {} < min speed {} bytes/sec, \
1266                     will abort and try a different node. Abort count: {}, Progress detail: {:?}",
1267                    download_progress.last_throughput,
1268                    minimal_snapshot_download_speed,
1269                    download_abort_count,
1270                    download_progress,
1271                );
1272                *download_abort_count += 1;
1273                false
1274            } else {
1275                true
1276            }
1277        })),
1278    )
1279}
1280
1281/// Check to see if bootstrap should load from its local snapshots or not.  If not, then snapshots
1282/// will be downloaded.
1283fn should_use_local_snapshot(
1284    full_snapshot_archives_dir: &Path,
1285    incremental_snapshot_archives_dir: &Path,
1286    maximum_local_snapshot_age: Slot,
1287    full_snapshot_hash: (Slot, Hash),
1288    incremental_snapshot_hash: Option<(Slot, Hash)>,
1289    incremental_snapshot_fetch: bool,
1290) -> bool {
1291    let cluster_snapshot_slot = incremental_snapshot_hash
1292        .map(|(slot, _)| slot)
1293        .unwrap_or(full_snapshot_hash.0);
1294
1295    match get_highest_local_snapshot_hash(
1296        full_snapshot_archives_dir,
1297        incremental_snapshot_archives_dir,
1298        incremental_snapshot_fetch,
1299    ) {
1300        None => {
1301            info!(
1302                "Downloading a snapshot for slot {cluster_snapshot_slot} since there is not a \
1303                 local snapshot."
1304            );
1305            false
1306        }
1307        Some((local_snapshot_slot, _)) => {
1308            if local_snapshot_slot
1309                >= cluster_snapshot_slot.saturating_sub(maximum_local_snapshot_age)
1310            {
1311                info!(
1312                    "Reusing local snapshot at slot {local_snapshot_slot} instead of downloading \
1313                     a snapshot for slot {cluster_snapshot_slot}."
1314                );
1315                true
1316            } else {
1317                info!(
1318                    "Local snapshot from slot {local_snapshot_slot} is too old. Downloading a \
1319                     newer snapshot for slot {cluster_snapshot_slot}."
1320                );
1321                false
1322            }
1323        }
1324    }
1325}
1326
1327/// Get the node's highest snapshot hashes from CRDS
1328fn get_snapshot_hashes_for_node(cluster_info: &ClusterInfo, node: &Pubkey) -> Option<SnapshotHash> {
1329    cluster_info.get_snapshot_hashes_for_node(node).map(
1330        |crds_data::SnapshotHashes {
1331             full, incremental, ..
1332         }| {
1333            let highest_incremental_snapshot_hash = incremental.into_iter().max();
1334            SnapshotHash {
1335                full,
1336                incr: highest_incremental_snapshot_hash,
1337            }
1338        },
1339    )
1340}
1341
1342#[cfg(test)]
1343mod tests {
1344    use super::*;
1345
1346    impl PeerSnapshotHash {
1347        fn new(
1348            rpc_contact_info: ContactInfo,
1349            full_snapshot_hash: (Slot, Hash),
1350            incremental_snapshot_hash: Option<(Slot, Hash)>,
1351        ) -> Self {
1352            Self {
1353                rpc_contact_info,
1354                snapshot_hash: SnapshotHash {
1355                    full: full_snapshot_hash,
1356                    incr: incremental_snapshot_hash,
1357                },
1358            }
1359        }
1360    }
1361
1362    fn default_contact_info_for_tests() -> ContactInfo {
1363        ContactInfo::new_localhost(&Pubkey::default(), /*now:*/ 1_681_834_947_321)
1364    }
1365
1366    #[test]
1367    fn test_build_known_snapshot_hashes() {
1368        agave_logger::setup();
1369        let full_snapshot_hash1 = (400_000, Hash::new_unique());
1370        let full_snapshot_hash2 = (400_000, Hash::new_unique());
1371
1372        let incremental_snapshot_hash1 = (400_800, Hash::new_unique());
1373        let incremental_snapshot_hash2 = (400_800, Hash::new_unique());
1374
1375        // simulate a set of known validators with various snapshot hashes
1376        let oracle = {
1377            let mut oracle = HashMap::new();
1378
1379            for (full, incr) in [
1380                // only a full snapshot
1381                (full_snapshot_hash1, None),
1382                // full and incremental snapshots
1383                (full_snapshot_hash1, Some(incremental_snapshot_hash1)),
1384                // full and incremental snapshots, with different incremental hash
1385                (full_snapshot_hash1, Some(incremental_snapshot_hash2)),
1386                // ...and now with different full hashes
1387                (full_snapshot_hash2, None),
1388                (full_snapshot_hash2, Some(incremental_snapshot_hash1)),
1389                (full_snapshot_hash2, Some(incremental_snapshot_hash2)),
1390            ] {
1391                // also simulate multiple known validators having the same snapshot hashes
1392                oracle.insert(Pubkey::new_unique(), Some(SnapshotHash { full, incr }));
1393                oracle.insert(Pubkey::new_unique(), Some(SnapshotHash { full, incr }));
1394                oracle.insert(Pubkey::new_unique(), Some(SnapshotHash { full, incr }));
1395            }
1396
1397            // no snapshots at all
1398            oracle.insert(Pubkey::new_unique(), None);
1399            oracle.insert(Pubkey::new_unique(), None);
1400            oracle.insert(Pubkey::new_unique(), None);
1401
1402            oracle
1403        };
1404
1405        let node_to_snapshot_hashes = |node| *oracle.get(node).unwrap();
1406
1407        let known_snapshot_hashes =
1408            build_known_snapshot_hashes(oracle.keys(), node_to_snapshot_hashes);
1409
1410        // ensure there's only one full snapshot hash, since they all used the same slot and there
1411        // can be only one snapshot hash per slot
1412        let known_full_snapshot_hashes = known_snapshot_hashes.keys();
1413        assert_eq!(known_full_snapshot_hashes.len(), 1);
1414        let known_full_snapshot_hash = known_full_snapshot_hashes.into_iter().next().unwrap();
1415
1416        // and for the same reasons, ensure there is only one incremental snapshot hash
1417        let known_incremental_snapshot_hashes =
1418            known_snapshot_hashes.get(known_full_snapshot_hash).unwrap();
1419        assert_eq!(known_incremental_snapshot_hashes.len(), 1);
1420        let known_incremental_snapshot_hash =
1421            known_incremental_snapshot_hashes.iter().next().unwrap();
1422
1423        // The resulting `known_snapshot_hashes` can be different from run-to-run due to how
1424        // `oracle.keys()` returns nodes during iteration.  Because of that, we cannot just assert
1425        // the full and incremental snapshot hashes are `full_snapshot_hash1` and
1426        // `incremental_snapshot_hash1`.  Instead, we assert that the full and incremental
1427        // snapshot hashes are exactly one or the other, since it depends on which nodes are seen
1428        // "first" when building the known snapshot hashes.
1429        assert!(
1430            known_full_snapshot_hash == &full_snapshot_hash1
1431                || known_full_snapshot_hash == &full_snapshot_hash2
1432        );
1433        assert!(
1434            known_incremental_snapshot_hash == &incremental_snapshot_hash1
1435                || known_incremental_snapshot_hash == &incremental_snapshot_hash2
1436        );
1437    }
1438
1439    #[test]
1440    fn test_retain_peer_snapshot_hashes_that_match_known_snapshot_hashes() {
1441        let known_snapshot_hashes: KnownSnapshotHashes = [
1442            (
1443                (200_000, Hash::new_unique()),
1444                [
1445                    (200_200, Hash::new_unique()),
1446                    (200_400, Hash::new_unique()),
1447                    (200_600, Hash::new_unique()),
1448                    (200_800, Hash::new_unique()),
1449                ]
1450                .iter()
1451                .cloned()
1452                .collect(),
1453            ),
1454            (
1455                (300_000, Hash::new_unique()),
1456                [
1457                    (300_200, Hash::new_unique()),
1458                    (300_400, Hash::new_unique()),
1459                    (300_600, Hash::new_unique()),
1460                ]
1461                .iter()
1462                .cloned()
1463                .collect(),
1464            ),
1465        ]
1466        .iter()
1467        .cloned()
1468        .collect();
1469
1470        let known_snapshot_hash = known_snapshot_hashes.iter().next().unwrap();
1471        let known_full_snapshot_hash = known_snapshot_hash.0;
1472        let known_incremental_snapshot_hash = known_snapshot_hash.1.iter().next().unwrap();
1473
1474        let contact_info = default_contact_info_for_tests();
1475        let peer_snapshot_hashes = vec![
1476            // bad full snapshot hash, no incremental snapshot hash
1477            PeerSnapshotHash::new(contact_info.clone(), (111_000, Hash::default()), None),
1478            // bad everything
1479            PeerSnapshotHash::new(
1480                contact_info.clone(),
1481                (111_000, Hash::default()),
1482                Some((111_111, Hash::default())),
1483            ),
1484            // good full snapshot hash, no incremental snapshot hash
1485            PeerSnapshotHash::new(contact_info.clone(), *known_full_snapshot_hash, None),
1486            // bad full snapshot hash, good (not possible) incremental snapshot hash
1487            PeerSnapshotHash::new(
1488                contact_info.clone(),
1489                (111_000, Hash::default()),
1490                Some(*known_incremental_snapshot_hash),
1491            ),
1492            // good full snapshot hash, bad incremental snapshot hash
1493            PeerSnapshotHash::new(
1494                contact_info.clone(),
1495                *known_full_snapshot_hash,
1496                Some((111_111, Hash::default())),
1497            ),
1498            // good everything
1499            PeerSnapshotHash::new(
1500                contact_info.clone(),
1501                *known_full_snapshot_hash,
1502                Some(*known_incremental_snapshot_hash),
1503            ),
1504        ];
1505
1506        let expected = vec![
1507            PeerSnapshotHash::new(contact_info.clone(), *known_full_snapshot_hash, None),
1508            PeerSnapshotHash::new(
1509                contact_info,
1510                *known_full_snapshot_hash,
1511                Some(*known_incremental_snapshot_hash),
1512            ),
1513        ];
1514        let mut actual = peer_snapshot_hashes;
1515        retain_peer_snapshot_hashes_that_match_known_snapshot_hashes(
1516            &known_snapshot_hashes,
1517            &mut actual,
1518        );
1519        assert_eq!(expected, actual);
1520    }
1521
1522    #[test]
1523    fn test_retain_peer_snapshot_hashes_with_highest_full_snapshot_slot() {
1524        let contact_info = default_contact_info_for_tests();
1525        let peer_snapshot_hashes = vec![
1526            // old
1527            PeerSnapshotHash::new(contact_info.clone(), (100_000, Hash::default()), None),
1528            PeerSnapshotHash::new(
1529                contact_info.clone(),
1530                (100_000, Hash::default()),
1531                Some((100_100, Hash::default())),
1532            ),
1533            PeerSnapshotHash::new(
1534                contact_info.clone(),
1535                (100_000, Hash::default()),
1536                Some((100_200, Hash::default())),
1537            ),
1538            PeerSnapshotHash::new(
1539                contact_info.clone(),
1540                (100_000, Hash::default()),
1541                Some((100_300, Hash::default())),
1542            ),
1543            // new
1544            PeerSnapshotHash::new(contact_info.clone(), (200_000, Hash::default()), None),
1545            PeerSnapshotHash::new(
1546                contact_info.clone(),
1547                (200_000, Hash::default()),
1548                Some((200_100, Hash::default())),
1549            ),
1550            PeerSnapshotHash::new(
1551                contact_info.clone(),
1552                (200_000, Hash::default()),
1553                Some((200_200, Hash::default())),
1554            ),
1555            PeerSnapshotHash::new(
1556                contact_info.clone(),
1557                (200_000, Hash::default()),
1558                Some((200_300, Hash::default())),
1559            ),
1560        ];
1561
1562        let expected = vec![
1563            PeerSnapshotHash::new(contact_info.clone(), (200_000, Hash::default()), None),
1564            PeerSnapshotHash::new(
1565                contact_info.clone(),
1566                (200_000, Hash::default()),
1567                Some((200_100, Hash::default())),
1568            ),
1569            PeerSnapshotHash::new(
1570                contact_info.clone(),
1571                (200_000, Hash::default()),
1572                Some((200_200, Hash::default())),
1573            ),
1574            PeerSnapshotHash::new(
1575                contact_info,
1576                (200_000, Hash::default()),
1577                Some((200_300, Hash::default())),
1578            ),
1579        ];
1580        let mut actual = peer_snapshot_hashes;
1581        retain_peer_snapshot_hashes_with_highest_full_snapshot_slot(&mut actual);
1582        assert_eq!(expected, actual);
1583    }
1584
1585    #[test]
1586    fn test_retain_peer_snapshot_hashes_with_highest_incremental_snapshot_slot_some() {
1587        let contact_info = default_contact_info_for_tests();
1588        let peer_snapshot_hashes = vec![
1589            PeerSnapshotHash::new(contact_info.clone(), (200_000, Hash::default()), None),
1590            PeerSnapshotHash::new(
1591                contact_info.clone(),
1592                (200_000, Hash::default()),
1593                Some((200_100, Hash::default())),
1594            ),
1595            PeerSnapshotHash::new(
1596                contact_info.clone(),
1597                (200_000, Hash::default()),
1598                Some((200_200, Hash::default())),
1599            ),
1600            PeerSnapshotHash::new(
1601                contact_info.clone(),
1602                (200_000, Hash::default()),
1603                Some((200_300, Hash::default())),
1604            ),
1605            PeerSnapshotHash::new(
1606                contact_info.clone(),
1607                (200_000, Hash::default()),
1608                Some((200_010, Hash::default())),
1609            ),
1610            PeerSnapshotHash::new(
1611                contact_info.clone(),
1612                (200_000, Hash::default()),
1613                Some((200_020, Hash::default())),
1614            ),
1615            PeerSnapshotHash::new(
1616                contact_info.clone(),
1617                (200_000, Hash::default()),
1618                Some((200_030, Hash::default())),
1619            ),
1620        ];
1621
1622        let expected = vec![PeerSnapshotHash::new(
1623            contact_info,
1624            (200_000, Hash::default()),
1625            Some((200_300, Hash::default())),
1626        )];
1627        let mut actual = peer_snapshot_hashes;
1628        retain_peer_snapshot_hashes_with_highest_incremental_snapshot_slot(&mut actual);
1629        assert_eq!(expected, actual);
1630    }
1631
1632    /// Ensure that retaining the highest incremental snapshot hashes works as expected even if
1633    /// there are *zero* peers with incremental snapshots.
1634    #[test]
1635    fn test_retain_peer_snapshot_hashes_with_highest_incremental_snapshot_slot_none() {
1636        let contact_info = default_contact_info_for_tests();
1637        let peer_snapshot_hashes = vec![
1638            PeerSnapshotHash::new(contact_info.clone(), (200_000, Hash::new_unique()), None),
1639            PeerSnapshotHash::new(contact_info.clone(), (200_000, Hash::new_unique()), None),
1640            PeerSnapshotHash::new(contact_info, (200_000, Hash::new_unique()), None),
1641        ];
1642
1643        let expected = peer_snapshot_hashes.clone();
1644        let mut actual = peer_snapshot_hashes;
1645        retain_peer_snapshot_hashes_with_highest_incremental_snapshot_slot(&mut actual);
1646        assert_eq!(expected, actual);
1647    }
1648
1649    /// Ensure that retaining the highest snapshot hashes works (i.e. doesn't crash) even if the
1650    /// peer snapshot hashes input is empty.
1651    #[test]
1652    fn test_retain_peer_snapshot_hashes_with_highest_slot_empty() {
1653        {
1654            let mut actual = vec![];
1655            let expected = actual.clone();
1656            retain_peer_snapshot_hashes_with_highest_full_snapshot_slot(&mut actual);
1657            assert_eq!(expected, actual);
1658        }
1659        {
1660            let mut actual = vec![];
1661            let expected = actual.clone();
1662            retain_peer_snapshot_hashes_with_highest_incremental_snapshot_slot(&mut actual);
1663            assert_eq!(expected, actual);
1664        }
1665    }
1666}