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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
//! # Monero P2P
//!
//! This crate is general purpose P2P networking library for working with Monero. This is a low level
//! crate, which means it may seem verbose for a lot of use cases, if you want a crate that handles
//! more of the P2P logic have a look at `cuprate-p2p`.
//!
//! # Network Zones
//!
//! This crate abstracts over network zones, Tor/I2p/clearnet with the [NetworkZone] trait. Currently only clearnet is implemented: [ClearNet](network_zones::ClearNet).
//!
//! # Usage
//!
//! TODO
//!
use std::{fmt::Debug, future::Future, hash::Hash, pin::Pin};

use futures::{Sink, Stream};

use cuprate_wire::{
    levin::LevinMessage, network_address::NetworkAddressIncorrectZone, BucketError, Message,
    NetworkAddress,
};

pub mod client;
mod constants;
pub mod error;
pub mod handles;
pub mod network_zones;
pub mod protocol;
pub mod services;

pub use error::*;
pub use protocol::*;
use services::*;

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ConnectionDirection {
    InBound,
    OutBound,
}

#[cfg(not(feature = "borsh"))]
pub trait NetZoneAddress:
    TryFrom<NetworkAddress, Error = NetworkAddressIncorrectZone>
    + Into<NetworkAddress>
    + std::fmt::Display
    + Hash
    + Eq
    + Copy
    + Send
    + Sync
    + Unpin
    + 'static
{
    /// Cuprate needs to be able to ban peers by IP addresses and not just by SocketAddr as
    /// that include the port, to be able to facilitate this network addresses must have a ban ID
    /// which for hidden services could just be the address it self but for clear net addresses will
    /// be the IP address.
    /// TODO: IP zone banning?
    type BanID: Debug + Hash + Eq + Clone + Copy + Send + 'static;

    /// Changes the port of this address to `port`.
    fn set_port(&mut self, port: u16);

    fn make_canonical(&mut self);

    fn ban_id(&self) -> Self::BanID;

    fn should_add_to_peer_list(&self) -> bool;
}

#[cfg(feature = "borsh")]
pub trait NetZoneAddress:
    TryFrom<NetworkAddress, Error = NetworkAddressIncorrectZone>
    + Into<NetworkAddress>
    + std::fmt::Display
    + borsh::BorshSerialize
    + borsh::BorshDeserialize
    + Hash
    + Eq
    + Copy
    + Send
    + Sync
    + Unpin
    + 'static
{
    /// Cuprate needs to be able to ban peers by IP addresses and not just by SocketAddr as
    /// that include the port, to be able to facilitate this network addresses must have a ban ID
    /// which for hidden services could just be the address it self but for clear net addresses will
    /// be the IP address.
    /// TODO: IP zone banning?
    type BanID: Debug + Hash + Eq + Clone + Copy + Send + 'static;

    /// Changes the port of this address to `port`.
    fn set_port(&mut self, port: u16);

    fn make_canonical(&mut self);

    fn ban_id(&self) -> Self::BanID;

    fn should_add_to_peer_list(&self) -> bool;
}

/// An abstraction over a network zone (tor/i2p/clear)
#[async_trait::async_trait]
pub trait NetworkZone: Clone + Copy + Send + 'static {
    /// The network name.
    const NAME: &'static str;
    /// Allow syncing over this network.
    ///
    /// Not recommended for anonymity networks.
    const ALLOW_SYNC: bool;
    /// Enable dandelion++ for this network.
    ///
    /// This is unneeded on anonymity networks.
    const DANDELION_PP: bool;
    /// Check if our node ID matches the incoming peers node ID for this network.
    ///
    /// This has privacy implications on an anonymity network if true so should be set
    /// to false.
    const CHECK_NODE_ID: bool;
    /// Fixed seed nodes for this network.
    const SEEDS: &'static [Self::Addr];

    /// The address type of this network.
    type Addr: NetZoneAddress;

    /// The stream (incoming data) type for this network.
    type Stream: Stream<Item = Result<Message, BucketError>> + Unpin + Send + 'static;
    /// The sink (outgoing data) type for this network.
    type Sink: Sink<LevinMessage<Message>, Error = BucketError> + Unpin + Send + 'static;
    /// The inbound connection listener for this network.
    type Listener: Stream<Item = Result<(Option<Self::Addr>, Self::Stream, Self::Sink), std::io::Error>>
        + Send
        + 'static;
    /// Config used to start a server which listens for incoming connections.
    type ServerCfg: Clone + Debug + Send + 'static;

    async fn connect_to_peer(
        addr: Self::Addr,
    ) -> Result<(Self::Stream, Self::Sink), std::io::Error>;

    async fn incoming_connection_listener(
        config: Self::ServerCfg,
        port: u16,
    ) -> Result<Self::Listener, std::io::Error>;
}

// ####################################################################################
// Below here is just helper traits, so we don't have to type out tower::Service bounds
// everywhere but still get to use tower.

pub trait PeerSyncSvc<Z: NetworkZone>:
    tower::Service<
        PeerSyncRequest<Z>,
        Response = PeerSyncResponse<Z>,
        Error = tower::BoxError,
        Future = Self::Future2,
    > + Send
    + 'static
{
    // This allows us to put more restrictive bounds on the future without defining the future here
    // explicitly.
    type Future2: Future<Output = Result<Self::Response, Self::Error>> + Send + 'static;
}

impl<T, Z: NetworkZone> PeerSyncSvc<Z> for T
where
    T: tower::Service<PeerSyncRequest<Z>, Response = PeerSyncResponse<Z>, Error = tower::BoxError>
        + Send
        + 'static,
    T::Future: Future<Output = Result<Self::Response, Self::Error>> + Send + 'static,
{
    type Future2 = T::Future;
}

pub trait AddressBook<Z: NetworkZone>:
    tower::Service<
        AddressBookRequest<Z>,
        Response = AddressBookResponse<Z>,
        Error = tower::BoxError,
        Future = Self::Future2,
    > + Send
    + 'static
{
    // This allows us to put more restrictive bounds on the future without defining the future here
    // explicitly.
    type Future2: Future<Output = Result<Self::Response, Self::Error>> + Send + 'static;
}

impl<T, Z: NetworkZone> AddressBook<Z> for T
where
    T: tower::Service<
            AddressBookRequest<Z>,
            Response = AddressBookResponse<Z>,
            Error = tower::BoxError,
        > + Send
        + 'static,
    T::Future: Future<Output = Result<Self::Response, Self::Error>> + Send + 'static,
{
    type Future2 = T::Future;
}

pub trait CoreSyncSvc:
    tower::Service<
        CoreSyncDataRequest,
        Response = CoreSyncDataResponse,
        Error = tower::BoxError,
        Future = Pin<
            Box<
                dyn Future<Output = Result<CoreSyncDataResponse, tower::BoxError>> + Send + 'static,
            >,
        >,
    > + Send
    + 'static
{
}

impl<T> CoreSyncSvc for T where
    T: tower::Service<
            CoreSyncDataRequest,
            Response = CoreSyncDataResponse,
            Error = tower::BoxError,
            Future = Pin<
                Box<
                    dyn Future<Output = Result<CoreSyncDataResponse, tower::BoxError>>
                        + Send
                        + 'static,
                >,
            >,
        > + Send
        + 'static
{
}

pub trait PeerRequestHandler:
    tower::Service<
        PeerRequest,
        Response = PeerResponse,
        Error = tower::BoxError,
        Future = Pin<
            Box<dyn Future<Output = Result<PeerResponse, tower::BoxError>> + Send + 'static>,
        >,
    > + Send
    + 'static
{
}

impl<T> PeerRequestHandler for T where
    T: tower::Service<
            PeerRequest,
            Response = PeerResponse,
            Error = tower::BoxError,
            Future = Pin<
                Box<dyn Future<Output = Result<PeerResponse, tower::BoxError>> + Send + 'static>,
            >,
        > + Send
        + 'static
{
}