cuprate_address_book/
lib.rs

1//! Cuprate Address Book
2//!
3//! This module holds the logic for persistent peer storage.
4//! Cuprates address book is modeled as a [`tower::Service`]
5//! The request is [`AddressBookRequest`](cuprate_p2p_core::services::AddressBookRequest) and the response is
6//! [`AddressBookResponse`](cuprate_p2p_core::services::AddressBookResponse).
7//!
8//! Cuprate, like monerod, actually has multiple address books, one
9//! for each [`NetworkZone`]. This is to reduce the possibility of
10//! clear net peers getting linked to their dark counterparts
11//! and so peers will only get told about peers they can
12//! connect to.
13use std::{io::ErrorKind, path::PathBuf, time::Duration};
14
15use cuprate_p2p_core::{NetZoneAddress, NetworkZone};
16
17mod book;
18mod peer_list;
19mod store;
20
21/// The address book config.
22#[derive(Debug, Clone)]
23pub struct AddressBookConfig {
24    /// The maximum number of white peers in the peer list.
25    ///
26    /// White peers are peers we have connected to before.
27    pub max_white_list_length: usize,
28    /// The maximum number of gray peers in the peer list.
29    ///
30    /// Gray peers are peers we are yet to make a connection to.
31    pub max_gray_list_length: usize,
32    /// The location to store the peer store files.
33    pub peer_store_directory: PathBuf,
34    /// The amount of time between saving the address book to disk.
35    pub peer_save_period: Duration,
36}
37
38/// Possible errors when dealing with the address book.
39/// This is boxed when returning an error in the [`tower::Service`].
40#[derive(Debug, thiserror::Error, Eq, PartialEq)]
41pub enum AddressBookError {
42    /// The peer is already connected.
43    #[error("Peer is already connected")]
44    PeerAlreadyConnected,
45    /// The peer is not in the address book for this zone.
46    #[error("Peer was not found in book")]
47    PeerNotFound,
48    /// Immutable peer data was changed.
49    #[error("Immutable peer data was changed: {0}")]
50    PeersDataChanged(&'static str),
51    /// The peer is banned.
52    #[error("The peer is banned")]
53    PeerIsBanned,
54    /// The channel to the address book has closed unexpectedly.
55    #[error("The address books channel has closed.")]
56    AddressBooksChannelClosed,
57    /// The address book task has exited.
58    #[error("The address book task has exited.")]
59    AddressBookTaskExited,
60}
61
62/// Initializes the P2P address book for a specific network zone.
63pub async fn init_address_book<Z: BorshNetworkZone>(
64    cfg: AddressBookConfig,
65) -> Result<book::AddressBook<Z>, std::io::Error> {
66    let (white_list, gray_list) = match store::read_peers_from_disk::<Z>(&cfg).await {
67        Ok(res) => res,
68        Err(e) if e.kind() == ErrorKind::NotFound => (vec![], vec![]),
69        Err(e) => {
70            tracing::error!("Failed to open peer list, {}", e);
71            panic!("{e}");
72        }
73    };
74
75    let address_book = book::AddressBook::<Z>::new(cfg, white_list, gray_list, Vec::new());
76
77    Ok(address_book)
78}
79
80use sealed::BorshNetworkZone;
81mod sealed {
82    use super::*;
83
84    /// An internal trait for the address book for a [`NetworkZone`] that adds the requirement of [`borsh`] traits
85    /// onto the network address.
86    pub trait BorshNetworkZone: NetworkZone<Addr = Self::BorshAddr> {
87        type BorshAddr: NetZoneAddress + borsh::BorshDeserialize + borsh::BorshSerialize;
88    }
89
90    impl<T: NetworkZone> BorshNetworkZone for T
91    where
92        T::Addr: borsh::BorshDeserialize + borsh::BorshSerialize,
93    {
94        type BorshAddr = T::Addr;
95    }
96}