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