prns-runtime-tokio 0.3.6

Tokio host runtime for Personal Reticulum
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
use super::*;

#[tokio::test]
async fn a_loopback_frame_crosses_the_seam_and_the_rebroadcast_leaves_through_the_peer() {
    let source = InterfaceId::new([0xA1; 8]);
    let peer = InterfaceId::new([0xB2; 8]);
    let interfaces = std::vec![descriptor(source), descriptor(peer)];

    let mut engine = EngineState::<TestStorageLayout>::default();
    pin_transport_id(&mut engine, TEST_TRANSPORT_ID);

    let (notify_tx, notify_rx) = mpsc::unbounded_channel::<InterfaceId>();
    let (source_in_tx, source_in_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let (peer_in_tx, peer_in_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);

    let (source_wire_in_tx, source_wire_in_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (source_wire_out_tx, _source_wire_out_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (source_out_tx, source_out_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let source_iface = LoopbackInterface {
        descriptor: descriptor(source),
        wire_in: source_wire_in_rx,
        wire_out: source_wire_out_tx,
    };
    let source_seam =
        TokioInterfaceSeam::new(source, source_in_tx, notify_tx.clone(), source_out_rx);

    let (_peer_wire_in_tx, peer_wire_in_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (peer_wire_out_tx, mut peer_wire_out_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (peer_out_tx, peer_out_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let peer_iface = LoopbackInterface {
        descriptor: descriptor(peer),
        wire_in: peer_wire_in_rx,
        wire_out: peer_wire_out_tx,
    };
    let peer_seam = TokioInterfaceSeam::new(peer, peer_in_tx, notify_tx.clone(), peer_out_rx);

    drop(notify_tx);

    let egress = Egress::new(std::vec![(source, source_out_tx), (peer, peer_out_tx)]);

    let (_command_tx, command_rx) = mpsc::unbounded_channel::<HostCommand>();
    let (heard_tx, mut heard_rx) = mpsc::unbounded_channel::<()>();
    let app = move |journaled: Journaled<'_>| match journaled {
        Journaled::AnnounceHeard { .. } => {
            let _ = heard_tx.send(());
        }
        Journaled::Delivered(_)
        | Journaled::SelfRatchetRotated { .. }
        | Journaled::CommandSettled { .. }
        | Journaled::AnnounceHeldDropped { .. }
        | Journaled::RouteRemoved { .. }
        | Journaled::LinkEstablished(_)
        | Journaled::PeerIdentified { .. }
        | Journaled::RequestReceived { .. }
        | Journaled::ResponseReceived { .. }
        | Journaled::ResponseSegmentReceived { .. }
        | Journaled::ChannelMessageReceived { .. }
        | Journaled::LinkClosed { .. }
        | Journaled::ResourceReceived { .. }
        | Journaled::ResourceFailed { .. }
        | Journaled::ResourceNeedsDecompression { .. }
        | Journaled::ResourceSegmentReceived { .. }
        | Journaled::ResourceAssembled { .. }
        | Journaled::PersistenceFlushed { .. }
        | Journaled::PersistenceFlushFailed { .. }
        | Journaled::LinkInterfaceMismatch { .. } => {}
    };

    tokio::spawn(run(
        engine,
        TokioHost::new(),
        ManifoldWiring {
            interfaces,
            ifacs: std::vec![],
            notify: notify_rx,
            inbound_lanes: std::vec![(source, source_in_rx), (peer, peer_in_rx)],
            commands: command_rx,
            egress,
        },
        app,
    ));
    tokio::spawn(source_iface.run(source_seam));
    tokio::spawn(peer_iface.run(peer_seam));

    tokio::time::sleep(Duration::from_millis(150)).await;
    assert!(
        heard_rx.try_recv().is_err(),
        "an idle manifold journals nothing"
    );
    assert!(
        peer_wire_out_rx.try_recv().is_err(),
        "an idle interface transmits nothing"
    );

    let raw = bytes_from_hex(RNS_1_4_2_ANNOUNCE);
    let original_hops = WirePacketHeader::parse(&raw)
        .expect("valid announce wire")
        .0
        .hops;
    source_wire_in_tx
        .send(raw)
        .expect("the source interface holds its wire");

    tokio::time::timeout(Duration::from_secs(2), heard_rx.recv())
        .await
        .expect("the deposited frame journals within the window")
        .expect("the manifold task is alive");

    let bytes = tokio::time::timeout(Duration::from_secs(2), peer_wire_out_rx.recv())
        .await
        .expect("the rebroadcast reaches the peer's wire within the window")
        .expect("the peer interface task is alive");
    let (header, _) = WirePacketHeader::parse(&bytes).expect("valid rebroadcast wire");
    assert_eq!(header.packet_type, PacketType::Announce);
    assert_eq!(
        header.hops,
        original_hops + 1,
        "the rebroadcast bumps the hop count"
    );
}

#[tokio::test(start_paused = true)]
async fn a_capped_link_holds_a_rebroadcast_burst_then_drains_it_over_time() {
    let source = InterfaceId::new([0xA1; 8]);
    let peer = InterfaceId::new([0xB2; 8]);
    let slow_peer = InterfaceDescriptor {
        bitrate: BitrateBps::guess(1_000),
        announce_bandwidth_cap: AnnounceBandwidthCap::RNS_DEFAULT,
        ..descriptor(peer)
    };
    let interfaces = std::vec![descriptor(source), slow_peer];

    let mut engine = EngineState::<TestStorageLayout>::default();
    pin_transport_id(&mut engine, TEST_TRANSPORT_ID);

    let (notify_tx, notify_rx) = mpsc::unbounded_channel::<InterfaceId>();
    let (source_in_tx, source_in_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let (peer_in_tx, peer_in_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);

    let (source_wire_in_tx, source_wire_in_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (source_wire_out_tx, _source_wire_out_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (source_out_tx, source_out_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let source_iface = LoopbackInterface {
        descriptor: descriptor(source),
        wire_in: source_wire_in_rx,
        wire_out: source_wire_out_tx,
    };
    let source_seam =
        TokioInterfaceSeam::new(source, source_in_tx, notify_tx.clone(), source_out_rx);

    let (_peer_wire_in_tx, peer_wire_in_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (peer_wire_out_tx, mut peer_wire_out_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (peer_out_tx, peer_out_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let peer_iface = LoopbackInterface {
        descriptor: descriptor(peer),
        wire_in: peer_wire_in_rx,
        wire_out: peer_wire_out_tx,
    };
    let peer_seam = TokioInterfaceSeam::new(peer, peer_in_tx, notify_tx.clone(), peer_out_rx);

    drop(notify_tx);

    let egress = Egress::new(std::vec![(source, source_out_tx), (peer, peer_out_tx)]);
    let (_command_tx, command_rx) = mpsc::unbounded_channel::<HostCommand>();
    let (heard_tx, mut heard_rx) = mpsc::unbounded_channel::<()>();

    tokio::spawn(run(
        engine,
        TokioHost::new(),
        ManifoldWiring {
            interfaces,
            ifacs: std::vec![],
            notify: notify_rx,
            inbound_lanes: std::vec![(source, source_in_rx), (peer, peer_in_rx)],
            commands: command_rx,
            egress,
        },
        move |journaled: Journaled<'_>| {
            if let Journaled::AnnounceHeard { .. } = journaled {
                let _ = heard_tx.send(());
            }
        },
    ));
    tokio::spawn(source_iface.run(source_seam));
    tokio::spawn(peer_iface.run(peer_seam));

    source_wire_in_tx
        .send(bytes_from_hex(RNS_1_4_2_ANNOUNCE))
        .expect("the source interface holds its wire");
    source_wire_in_tx
        .send(bytes_from_hex(RNS_1_4_2_RATCHETED_ANNOUNCE))
        .expect("the source interface holds its wire");

    heard_rx
        .recv()
        .await
        .expect("the first announce reaches the manifold");
    heard_rx
        .recv()
        .await
        .expect("the second announce reaches the manifold");

    let first = tokio::time::timeout(Duration::from_secs(5), peer_wire_out_rx.recv())
        .await
        .expect("the first rebroadcast leaves the idle link within the window")
        .expect("the peer task is alive");
    assert_eq!(
        WirePacketHeader::parse(&first).unwrap().0.packet_type,
        PacketType::Announce
    );

    assert!(
        tokio::time::timeout(Duration::from_secs(5), peer_wire_out_rx.recv())
            .await
            .is_err(),
        "the cap holds the second rebroadcast far short of its spacing window",
    );

    let second = tokio::time::timeout(Duration::from_secs(120), peer_wire_out_rx.recv())
        .await
        .expect("the held rebroadcast drains once the spacing window passes")
        .expect("the peer task is alive");
    assert_eq!(
        WirePacketHeader::parse(&second).unwrap().0.packet_type,
        PacketType::Announce
    );
    assert_ne!(first, second, "the two rebroadcasts are distinct announces");
}

#[tokio::test(start_paused = true)]
async fn the_manifold_re_emits_a_rebroadcast_once_more_then_retires_it() {
    let source = InterfaceId::new([0xA1; 8]);
    let peer = InterfaceId::new([0xB2; 8]);
    let interfaces = std::vec![descriptor(source), descriptor(peer)];

    let mut engine = EngineState::<TestStorageLayout>::default();
    pin_transport_id(&mut engine, TEST_TRANSPORT_ID);

    let (notify_tx, notify_rx) = mpsc::unbounded_channel::<InterfaceId>();
    let (source_in_tx, source_in_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let (peer_in_tx, peer_in_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);

    let (source_wire_in_tx, source_wire_in_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (source_wire_out_tx, _source_wire_out_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (source_out_tx, source_out_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let source_iface = LoopbackInterface {
        descriptor: descriptor(source),
        wire_in: source_wire_in_rx,
        wire_out: source_wire_out_tx,
    };
    let source_seam =
        TokioInterfaceSeam::new(source, source_in_tx, notify_tx.clone(), source_out_rx);

    let (_peer_wire_in_tx, peer_wire_in_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (peer_wire_out_tx, mut peer_wire_out_rx) = mpsc::unbounded_channel::<std::vec::Vec<u8>>();
    let (peer_out_tx, peer_out_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let peer_iface = LoopbackInterface {
        descriptor: descriptor(peer),
        wire_in: peer_wire_in_rx,
        wire_out: peer_wire_out_tx,
    };
    let peer_seam = TokioInterfaceSeam::new(peer, peer_in_tx, notify_tx.clone(), peer_out_rx);

    drop(notify_tx);

    let egress = Egress::new(std::vec![(source, source_out_tx), (peer, peer_out_tx)]);
    let (_command_tx, command_rx) = mpsc::unbounded_channel::<HostCommand>();

    tokio::spawn(run(
        engine,
        TokioHost::new(),
        ManifoldWiring {
            interfaces,
            ifacs: std::vec![],
            notify: notify_rx,
            inbound_lanes: std::vec![(source, source_in_rx), (peer, peer_in_rx)],
            commands: command_rx,
            egress,
        },
        |_journaled: Journaled<'_>| {},
    ));
    tokio::spawn(source_iface.run(source_seam));
    tokio::spawn(peer_iface.run(peer_seam));

    source_wire_in_tx
        .send(bytes_from_hex(RNS_1_4_2_ANNOUNCE))
        .expect("the source interface holds its wire");

    let first = tokio::time::timeout(Duration::from_secs(2), peer_wire_out_rx.recv())
        .await
        .expect("the first emission leaves within the jitter window")
        .expect("the peer task is alive");

    assert!(
        tokio::time::timeout(Duration::from_secs(4), peer_wire_out_rx.recv())
            .await
            .is_err(),
        "the second emission waits the full retransmit interval",
    );

    let second = tokio::time::timeout(Duration::from_secs(120), peer_wire_out_rx.recv())
        .await
        .expect("the manifold re-emits once the retransmit interval passes")
        .expect("the peer task is alive");
    assert_eq!(
        first, second,
        "the retransmit re-emits the same pinned announce, byte for byte",
    );

    assert!(
        tokio::time::timeout(Duration::from_secs(120), peer_wire_out_rx.recv())
            .await
            .is_err(),
        "after two emissions the manifold retires the entry",
    );
}

#[tokio::test]
async fn a_delivery_answers_with_a_proof_directive_on_the_arrival_lane() {
    use crate::crypto::X25519SecretKey;
    use crate::engine::RatchetPolicy;
    use crate::identity::in_memory::InMemoryNodeIdentity;
    use crate::identity::{IdentitySigner, RemoteIdentity, Zeroizing};
    use crate::routing::dedup::PacketHash;
    use crate::routing::proof::IMPLICIT_PROOF_WIRE_LEN;
    use crate::routing::upstream_app_destinations::{LinkRequestPolicy, ProofStrategy};
    use crate::wire::{
        ContextFlag, DestinationType, IfacFlag, PropagationType, WireContext, BROADCAST_MTU,
    };

    let mut secret = [0u8; 64];
    secret[..32].fill(0x22);
    secret[32..].fill(0x11);
    let secret = Zeroizing::new(secret);

    let identity = InMemoryNodeIdentity::from_secret_key_bytes(&secret);
    let mut engine = EngineState::<TestStorageLayout>::new(secret);
    let destination = engine
        .register_single_destination(
            &identity.identity_hash(),
            "personal",
            &["node"],
            b"",
            ProofStrategy::ProveAll,
            LinkRequestPolicy::AcceptAll,
            RatchetPolicy::NoRatchets,
        )
        .expect("registers the single destination");

    let remote = RemoteIdentity::from_public_keys(
        identity.encryption_public_key(),
        identity.signing_public_key(),
    );
    let header = WirePacketHeader {
        ifac_flag: IfacFlag::Open,
        context_flag: ContextFlag::Unset,
        propagation: PropagationType::Broadcast,
        destination_type: DestinationType::Single,
        packet_type: PacketType::Data,
        hops: 0,
        transport_id: None,
        address: destination.to_address(),
        context: WireContext::None,
    };
    let mut wire = [0u8; BROADCAST_MTU];
    let header_len = header.write(&mut wire).expect("writes the header");
    let sealed = remote
        .encrypt(
            &X25519SecretKey::new([0x77; 32]),
            &[0x88; 16],
            b"prove-through-the-stack",
            &mut wire[header_len..],
        )
        .expect("seals the payload");
    let raw = wire[..header_len + sealed].to_vec();
    let packet_hash = PacketHash::of_wire_packet(&raw).expect("hashes the wire packet");

    let mut expected_proof = std::vec::Vec::new();
    expected_proof.push(0x03);
    expected_proof.push(0x00);
    expected_proof.extend_from_slice(packet_hash.proof_destination().as_bytes());
    expected_proof.push(0x00);
    expected_proof.extend_from_slice(&identity.sign(packet_hash.as_bytes()).0);
    assert_eq!(expected_proof.len(), IMPLICIT_PROOF_WIRE_LEN);

    let source = InterfaceId::new([0xA1; 8]);
    let interfaces = std::vec![descriptor(source)];

    let (notify_tx, notify_rx) = mpsc::unbounded_channel::<InterfaceId>();
    let (mut source_in_tx, source_in_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let (_command_tx, command_rx) = mpsc::unbounded_channel::<HostCommand>();
    let (source_out_tx, mut source_out_rx) = tokio_grant_lane(MAX_WIRE_FRAME_LEN, 8);
    let egress = Egress::new(std::vec![(source, source_out_tx)]);

    let (delivered_tx, mut delivered_rx) = mpsc::unbounded_channel::<()>();
    let app = move |journaled: Journaled<'_>| match journaled {
        Journaled::Delivered(_) => {
            let _ = delivered_tx.send(());
        }
        Journaled::AnnounceHeard { .. }
        | Journaled::SelfRatchetRotated { .. }
        | Journaled::CommandSettled { .. }
        | Journaled::AnnounceHeldDropped { .. }
        | Journaled::RouteRemoved { .. }
        | Journaled::LinkEstablished(_)
        | Journaled::PeerIdentified { .. }
        | Journaled::RequestReceived { .. }
        | Journaled::ResponseReceived { .. }
        | Journaled::ResponseSegmentReceived { .. }
        | Journaled::ChannelMessageReceived { .. }
        | Journaled::LinkClosed { .. }
        | Journaled::ResourceReceived { .. }
        | Journaled::ResourceFailed { .. }
        | Journaled::ResourceNeedsDecompression { .. }
        | Journaled::ResourceSegmentReceived { .. }
        | Journaled::ResourceAssembled { .. }
        | Journaled::PersistenceFlushed { .. }
        | Journaled::PersistenceFlushFailed { .. }
        | Journaled::LinkInterfaceMismatch { .. } => {}
    };

    tokio::spawn(run(
        engine,
        TokioHost::new(),
        ManifoldWiring {
            interfaces,
            ifacs: std::vec![],
            notify: notify_rx,
            inbound_lanes: std::vec![(source, source_in_rx)],
            commands: command_rx,
            egress,
        },
        app,
    ));

    source_in_tx
        .try_grant()
        .expect("an empty lane grants")
        .fill(&raw);
    source_in_tx.commit();
    notify_tx
        .send(source)
        .expect("the manifold task holds the receiver");

    tokio::time::timeout(Duration::from_secs(2), delivered_rx.recv())
        .await
        .expect("the delivery journals within the window")
        .expect("the manifold task is alive");

    let frame = tokio::time::timeout(Duration::from_secs(2), source_out_rx.peek())
        .await
        .expect("the owed proof is emitted within the window");
    assert_eq!(
        frame.frame(),
        expected_proof,
        "the proof is byte-identical to the RNS 1.4.2 implicit proof, on the arrival lane"
    );
}