1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//! Cuprate's P2P Crate.
//!
//! This crate contains a [`NetworkInterface`] which allows interacting with the Monero P2P network on
//! a certain [`NetworkZone`]
use std::sync::Arc;

use futures::FutureExt;
use tokio::{
    sync::{mpsc, watch},
    task::JoinSet,
};
use tokio_stream::wrappers::WatchStream;
use tower::{buffer::Buffer, util::BoxCloneService, Service, ServiceExt};
use tracing::{instrument, Instrument, Span};

use cuprate_async_buffer::BufferStream;
use cuprate_p2p_core::{
    client::Connector,
    client::InternalPeerID,
    services::{AddressBookRequest, AddressBookResponse, PeerSyncRequest},
    CoreSyncSvc, NetworkZone, ProtocolRequestHandler,
};

mod block_downloader;
mod broadcast;
mod client_pool;
pub mod config;
pub mod connection_maintainer;
mod constants;
mod inbound_server;
mod sync_states;

use block_downloader::{BlockBatch, BlockDownloaderConfig, ChainSvcRequest, ChainSvcResponse};
pub use broadcast::{BroadcastRequest, BroadcastSvc};
use client_pool::ClientPoolDropGuard;
pub use config::P2PConfig;
use connection_maintainer::MakeConnectionRequest;

/// Initializes the P2P [`NetworkInterface`] for a specific [`NetworkZone`].
///
/// This function starts all the tasks to maintain/accept/make connections.
///
/// # Usage
/// You must provide:
/// - A protocol request handler, which is given to each connection
/// - A core sync service, which keeps track of the sync state of our node
#[instrument(level = "debug", name = "net", skip_all, fields(zone = N::NAME))]
pub async fn initialize_network<N, PR, CS>(
    protocol_request_handler: PR,
    core_sync_svc: CS,
    config: P2PConfig<N>,
) -> Result<NetworkInterface<N>, tower::BoxError>
where
    N: NetworkZone,
    N::Addr: borsh::BorshDeserialize + borsh::BorshSerialize,
    PR: ProtocolRequestHandler + Clone,
    CS: CoreSyncSvc + Clone,
{
    let address_book =
        cuprate_address_book::init_address_book(config.address_book_config.clone()).await?;
    let address_book = Buffer::new(
        address_book,
        config.max_inbound_connections + config.outbound_connections,
    );

    let (sync_states_svc, top_block_watch) = sync_states::PeerSyncSvc::new();
    let sync_states_svc = Buffer::new(
        sync_states_svc,
        config.max_inbound_connections + config.outbound_connections,
    );

    // Use the default config. Changing the defaults affects tx fluff times, which could affect D++ so for now don't allow changing
    // this.
    let (broadcast_svc, outbound_mkr, inbound_mkr) =
        broadcast::init_broadcast_channels(broadcast::BroadcastConfig::default());

    let mut basic_node_data = config.basic_node_data();

    if !N::CHECK_NODE_ID {
        basic_node_data.peer_id = 1;
    }

    let outbound_handshaker_builder =
        cuprate_p2p_core::client::HandshakerBuilder::new(basic_node_data)
            .with_address_book(address_book.clone())
            .with_peer_sync_svc(sync_states_svc.clone())
            .with_core_sync_svc(core_sync_svc)
            .with_protocol_request_handler(protocol_request_handler)
            .with_broadcast_stream_maker(outbound_mkr)
            .with_connection_parent_span(Span::current());

    let inbound_handshaker = outbound_handshaker_builder
        .clone()
        .with_broadcast_stream_maker(inbound_mkr)
        .build();

    let outbound_handshaker = outbound_handshaker_builder.build();

    let client_pool = client_pool::ClientPool::new();

    let (make_connection_tx, make_connection_rx) = mpsc::channel(3);

    let outbound_connector = Connector::new(outbound_handshaker);
    let outbound_connection_maintainer = connection_maintainer::OutboundConnectionKeeper::new(
        config.clone(),
        client_pool.clone(),
        make_connection_rx,
        address_book.clone(),
        outbound_connector,
    );

    let mut background_tasks = JoinSet::new();

    background_tasks.spawn(
        outbound_connection_maintainer
            .run()
            .instrument(Span::current()),
    );
    background_tasks.spawn(
        inbound_server::inbound_server(
            client_pool.clone(),
            inbound_handshaker,
            address_book.clone(),
            config,
        )
        .map(|res| {
            if let Err(e) = res {
                tracing::error!("Error in inbound connection listener: {e}")
            }

            tracing::info!("Inbound connection listener shutdown")
        })
        .instrument(Span::current()),
    );

    Ok(NetworkInterface {
        pool: client_pool,
        broadcast_svc,
        top_block_watch,
        make_connection_tx,
        sync_states_svc,
        address_book: address_book.boxed_clone(),
        _background_tasks: Arc::new(background_tasks),
    })
}

/// The interface to Monero's P2P network on a certain [`NetworkZone`].
#[derive(Clone)]
pub struct NetworkInterface<N: NetworkZone> {
    /// A pool of free connected peers.
    pool: Arc<client_pool::ClientPool<N>>,
    /// A [`Service`] that allows broadcasting to all connected peers.
    broadcast_svc: BroadcastSvc<N>,
    /// A [`watch`] channel that contains the highest seen cumulative difficulty and other info
    /// on that claimed chain.
    top_block_watch: watch::Receiver<sync_states::NewSyncInfo>,
    /// A channel to request extra connections.
    #[allow(dead_code)] // will be used eventually
    make_connection_tx: mpsc::Sender<MakeConnectionRequest>,
    /// The address book service.
    address_book: BoxCloneService<AddressBookRequest<N>, AddressBookResponse<N>, tower::BoxError>,
    /// The peer's sync states service.
    sync_states_svc: Buffer<sync_states::PeerSyncSvc<N>, PeerSyncRequest<N>>,
    /// Background tasks that will be aborted when this interface is dropped.
    _background_tasks: Arc<JoinSet<()>>,
}

impl<N: NetworkZone> NetworkInterface<N> {
    /// Returns a service which allows broadcasting messages to all the connected peers in a specific [`NetworkZone`].
    pub fn broadcast_svc(&self) -> BroadcastSvc<N> {
        self.broadcast_svc.clone()
    }

    /// Starts the block downloader and returns a stream that will yield sequentially downloaded blocks.
    pub fn block_downloader<C>(
        &self,
        our_chain_service: C,
        config: BlockDownloaderConfig,
    ) -> BufferStream<BlockBatch>
    where
        C: Service<ChainSvcRequest, Response = ChainSvcResponse, Error = tower::BoxError>
            + Send
            + 'static,
        C::Future: Send + 'static,
    {
        block_downloader::download_blocks(
            self.pool.clone(),
            self.sync_states_svc.clone(),
            our_chain_service,
            config,
        )
    }

    /// Returns a stream which yields the highest seen sync state from a connected peer.
    pub fn top_sync_stream(&self) -> WatchStream<sync_states::NewSyncInfo> {
        WatchStream::from_changes(self.top_block_watch.clone())
    }

    /// Returns the address book service.
    pub fn address_book(
        &self,
    ) -> BoxCloneService<AddressBookRequest<N>, AddressBookResponse<N>, tower::BoxError> {
        self.address_book.clone()
    }

    /// Pulls a client from the client pool, returning it in a guard that will return it there when it's
    /// dropped.
    pub fn borrow_client(&self, peer: &InternalPeerID<N::Addr>) -> Option<ClientPoolDropGuard<N>> {
        self.pool.borrow_client(peer)
    }
}