Skip to main content

nimiq_network_interface/
network.rs

1use std::{
2    fmt::{Debug, Display},
3    future::Future,
4    hash::Hash,
5    time::Duration,
6};
7
8use futures::stream::BoxStream;
9use nimiq_serde::{Deserialize, DeserializeError, Serialize};
10use nimiq_utils::tagged_signing::{TaggedKeyPair, TaggedSignable};
11use thiserror::Error;
12use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
13
14use crate::{
15    peer_info::*,
16    request::{Message, Request, RequestError},
17};
18
19/// Network events that the network will report when subscribing
20#[derive(Clone, Debug)]
21pub enum NetworkEvent<P> {
22    /// A connection to a new peer has been started
23    PeerJoined(P, PeerInfo),
24    /// A peer disconnected
25    PeerLeft(P),
26    /// DHT is ready (bootstrapped and in server mode) to publish records
27    DhtReady,
28}
29
30pub type SubscribeEvents<PeerId> =
31    BoxStream<'static, Result<NetworkEvent<PeerId>, BroadcastStreamRecvError>>;
32
33const DEFAULT_GOSSIPSUB_RATE_LIMIT_TIME_WINDOW: Duration = Duration::from_secs(10);
34
35pub trait Topic {
36    type Item: Serialize + Deserialize + Send + Sync + Debug + 'static;
37
38    const BUFFER_SIZE: usize;
39    const NAME: &'static str;
40    const VALIDATE: bool;
41    const MAX_MESSAGES: u32;
42    const TIME_WINDOW: Duration = DEFAULT_GOSSIPSUB_RATE_LIMIT_TIME_WINDOW;
43    /// Maximum size in bytes of a serialized message on this topic. Larger messages are
44    /// dropped before they are deserialized.
45    const MAX_MESSAGE_SIZE: usize = MIN_SUPPORTED_MSG_SIZE;
46}
47
48/// Network implementations have to at least support messages of this size.
49pub const MIN_SUPPORTED_MSG_SIZE: usize = 1024 * 1024;
50
51#[derive(Copy, Clone, Debug)]
52pub enum MsgAcceptance {
53    Accept,
54    Reject,
55    Ignore,
56}
57
58pub trait PubsubId<PeerId>: Clone + Send + Sync + Debug {
59    fn propagation_source(&self) -> PeerId;
60}
61
62/// Network implementations have to at least support requests of this size.
63pub const MIN_SUPPORTED_REQ_SIZE: usize = 20 * 1024;
64/// Network implementations have to at least support responses of this size.
65pub const MIN_SUPPORTED_RESP_SIZE: usize = 10 * 1024 * 1024;
66
67#[derive(Copy, Clone, Debug)]
68/// Reasons for closing a connection
69pub enum CloseReason {
70    /// Reason is unknown or doesn't fit the other reasons
71    Other,
72    /// The other peer closed the connection
73    RemoteClosed,
74    /// We need to close the connection to this peer because we are going offline
75    /// and don't want new connections.
76    GoingOffline,
77    /// There was an error and there is need to close the connection
78    Error,
79    /// Peer is malicious. This will cause the peer ID and address to get banned.
80    MaliciousPeer,
81}
82
83#[derive(Debug, Error)]
84pub enum SendError {
85    #[error("{0}")]
86    Serialization(#[from] DeserializeError),
87    #[error("Peer connection already closed")]
88    AlreadyClosed,
89}
90
91pub trait Network: Send + Sync + Unpin + 'static {
92    type PeerId: Copy + Debug + Display + Ord + Hash + Send + Sync + Unpin + 'static;
93    type AddressType: Debug + Display + 'static;
94    type Error: std::error::Error;
95    type PubsubId: PubsubId<Self::PeerId> + Send + Sync + Unpin;
96    type RequestId: Copy + Debug + Display + Eq + Send + Sync + 'static;
97
98    /// Gets the set of connected peers
99    fn get_peers(&self) -> Vec<Self::PeerId>;
100
101    /// Returns whether the current peer has a connection to another peer
102    fn has_peer(&self, peer_id: Self::PeerId) -> bool;
103
104    /// Gets a peer information.
105    /// If the peer isn't found, `None` is returned.
106    fn get_peer_info(&self, peer_id: Self::PeerId) -> Option<PeerInfo>;
107
108    /// Gets the set of connected peers that provide the supplied services.
109    /// If we currently don't have min number of connected peer that provides those services,
110    /// we dial peers.
111    /// If there aren't enough peers in the network that provides the required services, we return an error
112    fn get_peers_by_services(
113        &self,
114        services: Services,
115        min_peers: usize,
116    ) -> impl Future<Output = Result<Vec<Self::PeerId>, Self::Error>> + Send;
117
118    /// Returns true when the given peer provides the services flags that are required by us
119    fn peer_provides_required_services(&self, peer_id: Self::PeerId) -> bool;
120
121    /// Returns true when the given peer provides the services flags that are required by us
122    fn peer_provides_services(&self, peer_id: Self::PeerId, services: Services) -> bool;
123
124    /// Disconnects a peer with a close reason
125    fn disconnect_peer(
126        &self,
127        peer_id: Self::PeerId,
128        close_reason: CloseReason,
129    ) -> impl Future<Output = ()> + Send;
130
131    /// Subscribes to network events
132    fn subscribe_events(&self) -> SubscribeEvents<Self::PeerId>;
133
134    /// Subscribes to a Gossipsub topic
135    fn subscribe<T>(
136        &self,
137    ) -> impl Future<Output = Result<BoxStream<'static, (T::Item, Self::PubsubId)>, Self::Error>> + Send
138    where
139        T: Topic + Sync;
140
141    /// Unsubscribes from a Gossipsub topic
142    fn unsubscribe<T>(&self) -> impl Future<Output = Result<(), Self::Error>> + Send
143    where
144        T: Topic + Sync;
145
146    /// Publishes a message to a Gossipsub topic
147    fn publish<T>(&self, item: T::Item) -> impl Future<Output = Result<(), Self::Error>> + Send
148    where
149        T: Topic + Sync;
150
151    /// Subscribes to a Gossipsub subtopic, providing the subtopic name
152    fn subscribe_subtopic<T>(
153        &self,
154        subtopic: String,
155    ) -> impl Future<Output = Result<BoxStream<'static, (T::Item, Self::PubsubId)>, Self::Error>> + Send
156    where
157        T: Topic + Sync;
158
159    /// Unsubscribes from a Gossipsub subtopic
160    fn unsubscribe_subtopic<T>(
161        &self,
162        subtopic: String,
163    ) -> impl Future<Output = Result<(), Self::Error>> + Send
164    where
165        T: Topic + Sync;
166
167    /// Publishes a message to a Gossipsub subtopic
168    fn publish_subtopic<T>(
169        &self,
170        subtopic: String,
171        item: T::Item,
172    ) -> impl Future<Output = Result<(), Self::Error>> + Send
173    where
174        T: Topic + Sync;
175
176    /// Validates a message received from a Gossipsub topic
177    fn validate_message<T>(&self, id: Self::PubsubId, acceptance: MsgAcceptance)
178    where
179        T: Topic + Sync;
180
181    /// Gets a value from the distributed hash table
182    fn dht_get<K, V, T>(
183        &self,
184        k: &K,
185    ) -> impl Future<Output = Result<Option<V>, Self::Error>> + Send
186    where
187        K: AsRef<[u8]> + Send + Sync,
188        V: Deserialize + Send + Sync + TaggedSignable + Ord,
189        T: TaggedKeyPair + Send + Sync + Serialize + Deserialize;
190
191    /// Puts a value to the distributed hash table
192    fn dht_put<K, V, T>(
193        &self,
194        k: &K,
195        v: &V,
196        keypair: &T,
197    ) -> impl Future<Output = Result<(), Self::Error>> + Send
198    where
199        K: AsRef<[u8]> + Send + Sync,
200        V: Serialize + Send + Sync + TaggedSignable + Clone + Ord,
201        T: TaggedKeyPair + Send + Sync + Serialize + Deserialize;
202
203    /// Dials a peer
204    fn dial_peer(
205        &self,
206        peer_id: Self::PeerId,
207    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
208
209    /// Dials an address
210    fn dial_address(
211        &self,
212        address: Self::AddressType,
213    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
214
215    /// Gets the local peer ID
216    fn get_local_peer_id(&self) -> Self::PeerId;
217
218    /// Sends a message to a specific peer
219    fn message<M: Message>(
220        &self,
221        request: M,
222        peer_id: Self::PeerId,
223    ) -> impl Future<Output = Result<(), RequestError>> + Send;
224
225    /// Requests data from a specific peer
226    fn request<Req: Request>(
227        &self,
228        request: Req,
229        peer_id: Self::PeerId,
230    ) -> impl Future<Output = Result<Req::Response, RequestError>> + Send;
231
232    /// Receives messages from peers.
233    /// This function returns a stream where the messages are going to be propagated.
234    fn receive_messages<M: Message>(&self) -> BoxStream<'static, (M, Self::PeerId)>;
235
236    /// Receives requests from peers.
237    /// This function returns a stream where the requests are going to be propagated.
238    fn receive_requests<Req: Request>(
239        &self,
240    ) -> BoxStream<'static, (Req, Self::RequestId, Self::PeerId)>;
241
242    /// Sends a response to a specific request
243    fn respond<Req: Request>(
244        &self,
245        request_id: Self::RequestId,
246        response: Req::Response,
247    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
248}