pea2pea 0.52.0

A simple, low-level, and customizable implementation of a TCP P2P node.
Documentation
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! An minimal node capable of communicating with libp2p nodes.
//!
//! The supported libp2p protocol is ping.

mod common;

use std::{cmp, collections::HashMap, io, net::SocketAddr, sync::Arc, time::Duration};

use bytes::{Bytes, BytesMut};
use common::{noise, yamux};
use futures_util::{SinkExt, StreamExt, TryStreamExt};
use libp2p::{PeerId, core::multiaddr::Protocol, identity, ping};
use libp2p::{SwarmBuilder, swarm::SwarmEvent};
use parking_lot::{Mutex, RwLock};
use pea2pea::{
    Connection, ConnectionSide, Node, Pea2Pea,
    protocols::{Handshake, OnDisconnect, Reading, Writing},
};
use prost::Message;
use tokio::{sync::oneshot, time::sleep};
use tokio_util::codec::{Decoder, Encoder, Framed, FramedParts};
use tracing::*;
use tracing_subscriber::filter::LevelFilter;
use unsigned_varint::codec::UviBytes;

// the protocol string of libp2p::ping
const PROTOCOL_PING: &[u8] = b"\x13/multistream/1.0.0\n\x11/ipfs/ping/1.0.0\n";

// the libp2p-cabable node
#[derive(Clone)]
struct Libp2pNode {
    // the pea2pea node
    node: Node,
    // the libp2p keypair
    keypair: identity::Keypair,
    // the libp2p PeerId
    #[allow(dead_code)]
    peer_id: PeerId,
    // holds noise states between the handshake and the other protocols
    noise_states: Arc<Mutex<HashMap<SocketAddr, noise::State>>>,
    // holds the state related to peers
    peer_states: Arc<RwLock<HashMap<SocketAddr, PeerState>>>,
}

impl Pea2Pea for Libp2pNode {
    fn node(&self) -> &Node {
        &self.node
    }
}

impl Libp2pNode {
    fn new() -> Self {
        let keypair = identity::Keypair::generate_ed25519();
        let peer_id = keypair.public().to_peer_id();

        let node = Node::new(Default::default());

        info!(parent: node.span(), "started a node with PeerId {peer_id}");

        Self {
            node,
            keypair,
            peer_id,
            noise_states: Default::default(),
            peer_states: Default::default(),
        }
    }

    async fn process_event(&self, event: Event, source: SocketAddr) -> io::Result<()> {
        let reply = match event {
            Event::NewStream(stream_id, protocol_info) => {
                // reply to SYN flag with the ACK one
                Some(yamux::Frame::data(
                    stream_id,
                    vec![yamux::Flag::Ack],
                    Some(protocol_info),
                ))
            }
            Event::StreamHalfClosed(stream_id) => {
                // reply with own half-close
                Some(yamux::Frame::data(stream_id, vec![yamux::Flag::Fin], None))
            }
            Event::ReceivedPing(stream_id, payload) => {
                // reply to pings with the same payload
                Some(yamux::Frame::data(stream_id, vec![], Some(payload)))
            }
            _ => None,
        };

        if let Some(reply_msg) = reply {
            info!(parent: self.node().span(), " sending a {:?}", &reply_msg);
            let _ = self.unicast(source, reply_msg)?.await;
        }

        Ok(())
    }
}

// a set of yamux streams belonging to a single connection
pub type Streams = HashMap<yamux::StreamId, Bytes>;

// the state applicable to a single peer
struct PeerState {
    #[allow(dead_code)]
    id: PeerId,
    streams: Streams,
}

// the event indicated by the contents of a yamux message
#[derive(Debug, Clone, PartialEq, Eq)]
enum Event {
    NewStream(yamux::StreamId, Bytes),
    StreamHalfClosed(yamux::StreamId),
    StreamTerminated(yamux::StreamId),
    ReceivedPing(yamux::StreamId, Bytes),
    Unknown(yamux::Frame),
}

// a codec capable of (de/en)coding libp2p messages with noise and yamux protocols
struct Codec {
    noise: noise::Codec,
    yamux: yamux::Codec,
}

impl Codec {
    fn new(noise: noise::Codec, yamux: yamux::Codec) -> Self {
        Self { noise, yamux }
    }
}

impl Decoder for Codec {
    type Item = yamux::Frame;
    type Error = io::Error;

    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        // decrypt raw bytes using noise
        let mut bytes = if let Some(bytes) = self.noise.decode(src)? {
            bytes
        } else {
            return Ok(None);
        };

        // decode the Yamux frame
        self.yamux.decode(&mut bytes)
    }
}

impl Encoder<yamux::Frame> for Codec {
    type Error = io::Error;

    fn encode(&mut self, msg: yamux::Frame, dst: &mut BytesMut) -> Result<(), Self::Error> {
        // encode the Yamux frame
        self.yamux.encode(msg, dst)?;
        let mut bytes = dst.split().freeze();

        // split the frame into noise-compatible chunks
        while !bytes.is_empty() {
            let chunk = bytes.split_to(cmp::min(bytes.len(), noise::MAX_MESSAGE_LEN));
            self.noise.encode(chunk, dst)?;
        }

        Ok(())
    }
}

// payloads for Noise handshake messages
// note: this struct was auto-generated using prost-build based on
// the proto file from the libp2p-noise repository
#[derive(Clone, PartialEq, Eq, ::prost::Message)]
pub struct NoiseHandshakePayload {
    #[prost(bytes = "vec", tag = "1")]
    pub identity_key: ::prost::alloc::vec::Vec<u8>,
    #[prost(bytes = "vec", tag = "2")]
    pub identity_sig: ::prost::alloc::vec::Vec<u8>,
    #[prost(bytes = "vec", tag = "3")]
    pub data: ::prost::alloc::vec::Vec<u8>,
}

impl Handshake for Libp2pNode {
    const TIMEOUT_MS: u64 = 5_000;

    async fn perform_handshake(&self, mut conn: Connection) -> io::Result<Connection> {
        let node_conn_side = !conn.side();
        let addr = conn.addr();

        // TODO: try to use it post-handshake too when parsing protocol info
        let mut negotiation_codec = Framed::new(self.borrow_stream(&mut conn), UviBytes::default());

        // exchange libp2p protocol params
        match node_conn_side {
            ConnectionSide::Initiator => {
                // -> protocol info (1/2)
                negotiation_codec
                    .send(Bytes::from("/multistream/1.0.0\n"))
                    .await?;
                debug!(parent: self.node().span(), "sent protocol params (1/2)");

                // <- protocol info (1/2)
                let protocol_info = negotiation_codec
                    .try_next()
                    .await?
                    .ok_or(io::ErrorKind::InvalidData)?;
                debug!(parent: self.node().span(), "received protocol params (1/2): {:?}", protocol_info);

                // -> protocol info (2/2)
                negotiation_codec.send(Bytes::from("/noise\n")).await?;
                debug!(parent: self.node().span(), "sent protocol params (2/2)");

                // <- protocol info (2/2)
                let protocol_info = negotiation_codec
                    .try_next()
                    .await?
                    .ok_or(io::ErrorKind::InvalidData)?;
                debug!(parent: self.node().span(), "received protocol params (2/2): {:?}", protocol_info);
            }
            ConnectionSide::Responder => {
                // <- protocol info (1/2)
                let _protocol_info = negotiation_codec.try_next().await?;
                debug!(parent: self.node().span(), "received protocol params (1/2)");

                // -> protocol info (1/2)
                negotiation_codec
                    .send(Bytes::from("/multistream/1.0.0\n"))
                    .await?;
                debug!(parent: self.node().span(), "sent protocol params (1/2)");

                // <- protocol info (2/2)
                let _protocol_info = negotiation_codec.try_next().await?;
                debug!(parent: self.node().span(), "received protocol params (2/2)");

                // -> protocol info (2/2)
                negotiation_codec.send(Bytes::from("/noise\n")).await?;
                debug!(parent: self.node().span(), "sent protocol params (2/2)");
            }
        };

        // create the noise objects
        let noise_builder = snow::Builder::new("Noise_XX_25519_ChaChaPoly_SHA256".parse().unwrap());
        let noise_keypair = noise_builder.generate_keypair().unwrap();
        let noise_builder = noise_builder
            .local_private_key(&noise_keypair.private)
            .unwrap();

        // prepare the expected handshake payload
        let noise_payload = {
            let protobuf_payload = NoiseHandshakePayload {
                identity_key: identity::PublicKey::encode_protobuf(&self.keypair.public()),
                identity_sig: self
                    .keypair
                    .sign(&[&b"noise-libp2p-static-key:"[..], &noise_keypair.public].concat())
                    .unwrap(),
                data: vec![],
            };
            let mut bytes = Vec::with_capacity(protobuf_payload.encoded_len());
            protobuf_payload.encode(&mut bytes).unwrap();
            bytes
        };

        // perform the noise handshake
        let (noise_state, secure_payload) =
            noise::handshake_xx(self, &mut conn, noise_builder, noise_payload.into()).await?;

        // obtain the PeerId from the handshake payload
        let secure_payload = NoiseHandshakePayload::decode(&secure_payload[..])?;
        let peer_key = identity::PublicKey::try_decode_protobuf(&secure_payload.identity_key)
            .map_err(|_| io::ErrorKind::InvalidData)?;
        let peer_id = PeerId::from(peer_key);
        info!(parent: self.node().span(), "the PeerId of {addr} is {peer_id}");

        // reconstruct the Framed with the post-handshake noise state
        let mut framed = Framed::new(
            self.borrow_stream(&mut conn),
            noise::Codec::new(
                2,
                u16::MAX as usize,
                noise_state,
                self.node().span().clone(),
            ),
        );

        // exchange further protocol params
        match node_conn_side {
            ConnectionSide::Initiator => {
                // -> protocol info (1/2)
                framed
                    .send(Bytes::from(&b"\x13/multistream/1.0.0\n"[..]))
                    .await?;
                debug!(parent: self.node().span(), "sent protocol params (1/2)");

                // <- protocol info (1/2)
                let protocol_info = framed.try_next().await?.ok_or(io::ErrorKind::InvalidData)?;
                debug!(parent: self.node().span(), "received protocol params (1/2): {:?}", protocol_info);

                // -> protocol info (2/2)
                framed.send(Bytes::from(&b"\r/yamux/1.0.0\n"[..])).await?;
                debug!(parent: self.node().span(), "sent protocol params (2/2)");

                // <- protocol info (2/2)
                let protocol_info = framed.try_next().await?.ok_or(io::ErrorKind::InvalidData)?;
                debug!(parent: self.node().span(), "received protocol params (2/2): {:?}", protocol_info);
            }
            ConnectionSide::Responder => {
                // <- protocol info
                let protocol_info = framed.try_next().await?.ok_or(io::ErrorKind::InvalidData)?;
                debug!(parent: self.node().span(), "received protocol params: {:?}", protocol_info);

                // echo the protocol params back to the sender
                framed.send(protocol_info.freeze()).await?;
                debug!(parent: self.node().span(), "echoed the protocol params back to the sender");
            }
        }

        // deconstruct the framed (again) to preserve the noise state
        let FramedParts {
            codec, read_buf, ..
        } = framed.into_parts();
        let noise::Codec { mut noise, .. } = codec;

        // preserve any unprocessed bytes
        noise.save_buffer(read_buf);

        // save the noise state
        self.noise_states.lock().insert(conn.addr(), noise);
        // register the peer's state
        self.peer_states.write().insert(
            addr,
            PeerState {
                id: peer_id,
                streams: Default::default(),
            },
        );

        Ok(conn)
    }
}

macro_rules! get_streams_mut {
    ($self:expr, $addr:expr) => {
        $self
            .peer_states
            .write()
            .get_mut(&$addr)
            .map(|state| &mut state.streams)
    };
}

impl Reading for Libp2pNode {
    type Message = yamux::Frame;
    type Codec = Codec;

    fn codec(&self, addr: SocketAddr, side: ConnectionSide) -> Self::Codec {
        let noise_state = self.noise_states.lock().get(&addr).cloned().unwrap();

        Self::Codec::new(
            noise::Codec::new(
                2,
                u16::MAX as usize,
                noise_state,
                self.node().span().clone(),
            ),
            yamux::Codec::new(side, self.node().span().clone()),
        )
    }

    async fn process_message(&self, source: SocketAddr, message: Self::Message) {
        info!(parent: self.node().span(), "received a {:?}", message);

        // deconstruct the yamux frame
        let yamux::Header {
            stream_id, flags, ..
        } = &message.header;
        let payload = message.payload;

        // register the discovered events
        let mut events = vec![];

        match &flags[..] {
            &[yamux::Flag::Syn] => {
                // a new stream is being created
                if get_streams_mut!(self, source)
                    .and_then(|streams| streams.insert(*stream_id, payload.clone()))
                    .is_none()
                {
                    events.push(Event::NewStream(*stream_id, payload.clone()));
                } else {
                    error!(parent: self.node().span(), "yamux stream {stream_id} had already been registered", );
                }
            }
            &[yamux::Flag::Rst] => {
                // a stream is being terminated
                if get_streams_mut!(self, source)
                    .and_then(|streams| streams.remove(stream_id))
                    .is_some()
                {
                    events.push(Event::StreamTerminated(*stream_id));
                } else {
                    error!(parent: self.node().span(), "yamux stream {stream_id} is unknown");
                }
            }
            &[yamux::Flag::Ack] => {
                todo!(); // TODO: only matters when starting own streams
            }
            &[yamux::Flag::Fin] => {
                // a stream is being half-closed
                if get_streams_mut!(self, source)
                    .and_then(|streams| streams.remove(stream_id))
                    .is_some()
                {
                    events.push(Event::StreamHalfClosed(*stream_id));
                } else {
                    error!(parent: self.node().span(), "yamux stream {stream_id} is unknown");
                }
            }
            &[] => {
                // a regular message in an established stream
                let protocol = if let Some(p) = self
                    .peer_states
                    .read()
                    .get(&source)
                    .and_then(|source| source.streams.get(stream_id))
                {
                    p.clone()
                } else {
                    error!(parent: self.node().span(), "yamux stream {stream_id} is unknown");
                    Default::default()
                };

                if protocol == PROTOCOL_PING {
                    events.push(Event::ReceivedPing(*stream_id, payload));
                } else {
                    events.push(Event::Unknown(yamux::Frame {
                        header: message.header,
                        payload,
                    }));
                }
            }
            flags => {
                warn!(parent: self.node().span(), "unexpected combination of yamux flags: {flags:?}");
            }
        }

        for event in events {
            if let Err(e) = self.process_event(event, source).await {
                error!("Couldn't process an event: {e}");
            }
        }
    }
}

impl Writing for Libp2pNode {
    type Message = yamux::Frame;
    type Codec = Codec;

    fn codec(&self, addr: SocketAddr, side: ConnectionSide) -> Self::Codec {
        let noise_state = self.noise_states.lock().remove(&addr).unwrap();

        Self::Codec::new(
            noise::Codec::new(
                2,
                u16::MAX as usize,
                noise_state,
                self.node().span().clone(),
            ),
            yamux::Codec::new(side, self.node().span().clone()),
        )
    }
}

impl OnDisconnect for Libp2pNode {
    async fn on_disconnect(&self, addr: SocketAddr) {
        self.peer_states.write().remove(&addr);
    }
}

#[tokio::main(flavor = "multi_thread")]
async fn main() {
    common::start_logger(LevelFilter::DEBUG);

    // prepare the pea2pea node
    let pea2pea_node = Libp2pNode::new();

    // enable the pea2pea protocols
    pea2pea_node.enable_handshake().await;
    pea2pea_node.enable_reading().await;
    pea2pea_node.enable_writing().await;

    // prepare and start a ping-enabled libp2p swarm
    let mut swarm = SwarmBuilder::with_new_identity()
        .with_tokio()
        .with_tcp(
            libp2p::tcp::Config::default(),
            libp2p::noise::Config::new,
            libp2p::yamux::Config::default,
        )
        .unwrap()
        .with_behaviour(|_| ping::Behaviour::default())
        .unwrap()
        .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(u64::MAX)))
        .build();

    swarm
        .listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap())
        .unwrap();

    // this channel will allow us to discover the swarm's listening port
    let (tx, rx) = oneshot::channel();

    tokio::spawn(async move {
        let mut tx = Some(tx);
        loop {
            let event = swarm.select_next_some().await;
            debug!("   libp2p node: {:?}", event);
            if let SwarmEvent::NewListenAddr { address, .. } = event {
                tx.take().unwrap().send(address).unwrap();
            }
        }
    });

    let mut swarm_addr = rx.await.unwrap();
    let swarm_port = if let Some(Protocol::Tcp(port)) = swarm_addr.pop() {
        port
    } else {
        panic!("the libp2p swarm did not return a listening TCP port");
    };

    // connect the pea2pea node to the libp2p swarm
    let swarm_addr = format!("127.0.0.1:{swarm_port}").parse().unwrap();
    pea2pea_node.node().connect(swarm_addr).await.unwrap();

    // allow a few messages to be exchanged
    sleep(Duration::from_secs(60)).await;
}