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
use crate::addr::{PubAddr, MultiAddr};

/// The `ping_pong` module defines a basic implementation of the P2P interface.
/// Every peer continuously pings its `MultiAddr` to a random subset of its
/// known peers. Whenever a peer is pinged about a new `MultiAddr`, it will ping
/// a random subset of its known peers to inform them about that new
/// `MultiAddr`, and it will pong its own `MultiAddr` to that new `MultiAddr`.
/// This results in a basic gossip algorithm with back channeling.
pub mod ping_pong;

pub enum Error {
    Timeout,
    NotFound,
}

/// The `P2P` trait defines a standard inteface that all P2P implementation must
/// expose.
pub trait P2P {
    fn send_to<M: Send>(&self, to: PubAddr, message: M);
    fn send_to_all<M: Send>(&self, message: M);

    fn query_peer(&self, query: PubAddr) -> MultiAddr;
    fn query_peers(&self) -> Vec<MultiAddr>;
    fn query_num_peers(&self) -> usize;
}

/// A `Client` can send data frames over the network. Generally, this interface
/// is implemented by an external networking driver that is injected into a
/// `P2P` implementation. 
pub trait Client {
    fn send(&self, to: MultiAddr, data: &[u8]) -> Result<(), Error>;
}

/// A `Server` can accept data frames over the network. Generally, this
/// interface is implemented by a `P2P` implementation and passed to an external
/// network driver.
pub trait Server {
    fn accept(&self, from: MultiAddr, data: &[u8]);
}