macula-rust 0.6.0

Rust SDK for the macula 12 mesh: ML-DSA-87 and LAMPS composite node keys, a post-quantum QUIC transport — mobile first, not mobile-only.
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//! A client's link to one macula station, as macula_station_link and
//! macula-go's stationlink are: a QUIC connection dialed to the station its
//! target pins, one bidirectional control stream, the connection handshake on
//! it (v5, or v4 once after a station refuses v5), then status statements
//! both ways and every frame of the session.
//!
//! After HELLO the link sends its own status statement at every reissue of
//! the node's statement issuer, and ends when the station's statement is five
//! minutes past its expiry or the station's TLS binding reaches its
//! not_after. On a v5 link no frame carries a neighbour signature: the
//! session proofs authenticated the station once, and a neighbour-signed
//! frame ends the link. On a v4 link, in pq_hybrid, every control frame is
//! neighbour-signed with a sequence number per direction, from 0 after HELLO;
//! a frame out of sequence ends the link. A liveness probe every 30 seconds
//! ends the link after two misses in a row: on v5 a liveness_ping, on v4 a
//! `_macula.ping` call.

mod admission;
mod call;
mod dht;
mod framing;
mod pubsub;
mod serve;
mod stream;
mod versions;

pub use admission::{Admission, AdmissionLimits};
pub use call::{Call, DEFAULT_CALL_TIMEOUT, MAX_CALL_TIMEOUT};
pub use pubsub::{Event, EventDedup, Publication, PublicationSeq, SignedPublication, Subscription};
pub use serve::{handler, BoxFuture, Handler, Offer, Request, Served, StreamOffer};
pub use stream::{
    stream_handler, Stream, StreamCall, StreamEvent, StreamHandler, DEFAULT_STREAM_DEADLINE,
};
pub use versions::{forget_v5_peer, handshake_counters};

use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;

use sha2::{Digest, Sha384};
use tokio::sync::watch;

use crate::cbor::{self, Value};
use crate::frame::{self, FrameError, Liveness, NeighbourLink, NeighbourPeer};
use crate::handshake::{
    self, ClientSession, Exporter, HandshakeError, Peer, RefusalCode, Station, VERSION, VERSION_5,
};
use crate::node_key::NodeKey;
use crate::profile::Profile;
use crate::record::RecordError;
use crate::statement_issuer::{IssuerError, StatementIssuer, StatementSubscription};
use crate::transport::{self, DialError, Target};

use framing::{read_frame, FrameWriter, HANDSHAKE_FRAME_BYTES, MAX_FRAME_BYTES};

/// How long the handshake may take, as macula's 30 seconds.
pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);

/// How long Close waits, after its GOODBYE, for the station to close the
/// connection before closing it itself.
const CLOSE_LINGER: Duration = Duration::from_secs(1);

/// How long past a statement's expiry the link keeps a station whose next
/// statement has not arrived: macula's five minutes.
const STATUS_GRACE_MS: i64 = 5 * 60 * 1000;

/// Why a link or one of its operations failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LinkError {
    /// The configuration cannot be dialed: a key of another profile than the
    /// target's, or admission limits macula would not start with.
    InvalidConfig(String),
    /// The dial failed.
    Dial(String),
    /// The handshake refused, or was refused.
    Handshake(HandshakeError),
    /// The handshake did not finish within [`HANDSHAKE_TIMEOUT`].
    HandshakeTimeout,
    /// The issuer had no CONNECT material in force.
    Issuer(IssuerError),
    /// The QUIC connection or a stream failed.
    Io(String),
    /// A frame longer than the cap in force.
    FrameTooLarge(usize),
    /// A frame that could not be built, or one received that does not
    /// verify.
    Frame(FrameError),
    /// A record that could not be built, or one found that does not verify.
    Record(RecordError),
    /// The station's status statement lapsed past the grace.
    StatusExpired,
    /// The station's TLS binding reached its not_after.
    BindingExpired,
    /// The link was closed by its owner.
    Closed,
    /// The station ended the link with a GOODBYE, for this reason.
    Goodbye(String),
    /// The station missed two liveness probes in a row.
    LivenessLost,
    /// A station this process completed handshake v5 with that now answers
    /// v4, or a v4 link to it that a v5 completion ended: refused, not
    /// retried, until [`forget_v5_peer`].
    V5DowngradeRefused,
    /// No verified reply answered the call within its timeout.
    CallTimeout,
    /// A provider's ERROR for the call.
    Provider {
        responded_by: [u8; 32],
        code: String,
        detail: Option<String>,
    },
    /// A relay error the connected station reported for the call.
    Relay { reported_by: [u8; 32], code: String },
    /// A find_record the station answered not_found.
    RecordNotFound,
    /// A station reply to a DHT call in a shape that call never answers with.
    UnexpectedReply(String),
    /// An offer without exactly one handler, or an org procedure's without
    /// the realm key.
    InvalidOffer,
    /// A procedure without a namespace, which nobody can authorize.
    NoOrg,
    /// A procedure already served on this link.
    AlreadyServed,
    /// A served procedure withdrawn by its owner.
    Stopped,
    /// A stream ended by a STREAM_ERROR: the peer's, the station's relay
    /// error (`relay`), or this side's own abort.
    Stream {
        code: String,
        message: String,
        relay: bool,
    },
    /// A stream that ended normally.
    EndOfStream,
    /// A send on a stream this side has ended.
    StreamClosed,
    /// A STREAM_OPEN over the 1 MiB a peer reads of one.
    StreamOpenTooLarge(usize),
}

impl fmt::Display for LinkError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LinkError::Provider {
                code,
                detail: Some(d),
                ..
            } => write!(f, "the provider answered {code}: {d}"),
            LinkError::Provider { code, .. } => write!(f, "the provider answered {code}"),
            LinkError::Relay { code, .. } => {
                write!(f, "the station could not relay the call: {code}")
            }
            LinkError::Stream { code, message, .. } if !message.is_empty() => {
                write!(f, "stream error {code}: {message}")
            }
            LinkError::Stream { code, .. } => write!(f, "stream error {code}"),
            LinkError::Handshake(e) => write!(f, "handshake: {e}"),
            LinkError::Frame(e) => write!(f, "frame: {e}"),
            LinkError::Record(e) => write!(f, "record: {e}"),
            LinkError::Issuer(e) => write!(f, "{e}"),
            LinkError::Goodbye(reason) => write!(f, "the station said goodbye: {reason}"),
            other => write!(f, "{other:?}"),
        }
    }
}

impl std::error::Error for LinkError {}

impl From<FrameError> for LinkError {
    fn from(e: FrameError) -> Self {
        LinkError::Frame(e)
    }
}

impl From<RecordError> for LinkError {
    fn from(e: RecordError) -> Self {
        LinkError::Record(e)
    }
}

impl From<HandshakeError> for LinkError {
    fn from(e: HandshakeError) -> Self {
        LinkError::Handshake(e)
    }
}

impl From<DialError> for LinkError {
    fn from(e: DialError) -> Self {
        LinkError::Dial(e.to_string())
    }
}

/// What a link is dialed with: the station to reach, the node's identity
/// key, the statement issuer that holds its CONNECT key and statements, and
/// the realm membership endorsement to present, empty for none. Links of one
/// node share their publication seq, admission and dedup; a link given none
/// makes its own.
pub struct Config {
    pub target: Target,
    pub identity: Arc<NodeKey>,
    pub issuer: StatementIssuer,
    pub member_endorsement: Vec<u8>,
    pub publication_seq: Option<Arc<PublicationSeq>>,
    pub admission: Option<Arc<Admission>>,
    pub dedup: Option<Arc<EventDedup>>,
    /// This link's place in the admission: the station it dialed, host:port,
    /// when `None`.
    pub share: Option<String>,
}

impl Config {
    /// A link's configuration with none of the shared parts.
    pub fn new(target: Target, identity: Arc<NodeKey>, issuer: StatementIssuer) -> Config {
        Config {
            target,
            identity,
            issuer,
            member_endorsement: Vec::new(),
            publication_seq: None,
            admission: None,
            dedup: None,
            share: None,
        }
    }
}

/// A handshaked link to one station. Cloning it shares the link.
#[derive(Clone)]
pub struct Link {
    inner: Arc<Inner>,
}

struct Inner {
    /// Distinct for every link a process dials.
    serial: u64,
    connection: quinn::Connection,
    _endpoint: quinn::Endpoint,
    control: FrameWriter,
    profile: Profile,
    key: Arc<NodeKey>,
    self_id: [u8; 32],
    station: Station,
    station_capabilities: u64,
    connection_hash: [u8; 48],
    /// The handshake version the link completed: 4 or 5.
    version: i64,
    /// v5 liveness answers, for the probe.
    pongs: tokio::sync::mpsc::Sender<[u8; frame::LIVENESS_NONCE_SIZE]>,
    pongs_rx: tokio::sync::Mutex<tokio::sync::mpsc::Receiver<[u8; frame::LIVENESS_NONCE_SIZE]>>,
    /// Orders a neighbour signature's seq with its write.
    send_seq: tokio::sync::Mutex<u64>,
    status_deadline: AtomicI64,
    publication_seq: Arc<PublicationSeq>,
    admission: Arc<Admission>,
    dedup: Arc<EventDedup>,
    share: String,
    state: Mutex<State>,
    done_tx: watch::Sender<bool>,
    done_rx: watch::Receiver<bool>,
}

struct State {
    ended: Option<LinkError>,
    /// The owner is closing the link: however it then ends, it ends
    /// [`LinkError::Closed`].
    closing: bool,
    unrouted: HashMap<String, u64>,
    pending: HashMap<[u8; 16], call::Pending>,
    subs: HashMap<([u8; 32], String), Vec<pubsub::SubscriberSlot>>,
    served: HashMap<([u8; 32], String), serve::ServedEntry>,
    streams: Vec<std::sync::Weak<stream::StreamInner>>,
}

impl Link {
    /// Dials `cfg.target`, runs the handshake as a client, and returns the
    /// link once the station's HELLO accepts it. It dials with version 5
    /// unless the station refused v5 in the last 10 minutes; a station never
    /// seen on v5 that refuses v5 with `unsupported_version` is dialled once
    /// more, on a new connection, with v4. A station seen on v5 that answers
    /// v4 is [`LinkError::V5DowngradeRefused`]. Each handshake is bounded by
    /// [`HANDSHAKE_TIMEOUT`].
    pub async fn dial(cfg: Config) -> Result<Link, LinkError> {
        if cfg.identity.profile() != cfg.target.profile {
            return Err(LinkError::InvalidConfig(
                "the identity key is of another profile than the target's".into(),
            ));
        }
        if let Some(admission) = &cfg.admission {
            admission.limits().validate()?;
        }
        let node_id = cfg.target.expected_node_id;
        let version = versions::dial_version(&node_id, std::time::Instant::now());
        let linked = dial_once(&cfg, version).await;
        match linked {
            Err(LinkError::Handshake(HandshakeError::Refused(RefusalCode::UnsupportedVersion)))
                if version == VERSION_5 =>
            {
                if !versions::unsupported_version(&node_id, std::time::Instant::now()) {
                    return Err(LinkError::V5DowngradeRefused);
                }
                dial_once(&cfg, VERSION).await
            }
            other => other,
        }
    }

    /// The handshake version the link completed: 4 or 5.
    pub fn handshake_version(&self) -> i64 {
        self.inner.version
    }

    /// The node_id of the station the link reached.
    pub fn station_node_id(&self) -> [u8; 32] {
        self.inner.station.node_id
    }

    /// A number distinct for every link this process dials.
    pub fn serial(&self) -> u64 {
        self.inner.serial
    }

    /// The node_id this link connected as.
    pub fn node_id(&self) -> [u8; 32] {
        self.inner.self_id
    }

    /// The capability bits the station's HELLO announced.
    pub fn station_capabilities(&self) -> u64 {
        self.inner.station_capabilities
    }

    /// The profile the link runs.
    pub fn profile(&self) -> Profile {
        self.inner.profile
    }

    /// Why the link ended, or `None` while it runs.
    pub fn error(&self) -> Option<LinkError> {
        self.inner.lock().ended.clone()
    }

    /// Waits until the link has ended, and says why.
    pub async fn done(&self) -> LinkError {
        let mut done = self.inner.done_rx.clone();
        let _ = done.wait_for(|ended| *ended).await;
        self.error().unwrap_or(LinkError::Closed)
    }

    /// The frames received that nothing on this link handles, by what they
    /// were.
    pub fn unrouted(&self) -> HashMap<String, u64> {
        self.inner.lock().unrouted.clone()
    }

    /// Sends a GOODBYE with `reason`, closes the control stream's sending
    /// side, waits up to a second for the station to close the connection,
    /// and ends the link. Closing an ended link does nothing.
    pub async fn close(&self, reason: &str) -> Result<(), LinkError> {
        {
            let mut state = self.inner.lock();
            if state.ended.is_some() {
                return Ok(());
            }
            state.closing = true;
        }
        let goodbye = frame::goodbye_frame(reason, None)?;
        let sent = self.inner.send_control(&goodbye).await;
        if sent.is_ok() {
            self.inner.control.finish().await;
            let _ = tokio::time::timeout(CLOSE_LINGER, self.inner.connection.closed()).await;
        }
        self.inner.end(LinkError::Closed);
        sent
    }
}

/// One QUIC connection and one handshake in `version`, within
/// [`HANDSHAKE_TIMEOUT`]. A failed handshake closes its connection.
async fn dial_once(cfg: &Config, version: i64) -> Result<Link, LinkError> {
    tokio::time::timeout(HANDSHAKE_TIMEOUT, async {
        let dialed = transport::dial_target(&cfg.target).await?;
        let connection = dialed.connection.clone();
        let linked = handshaken(cfg, dialed, version).await;
        if let Err(e) = &linked {
            versions::count_refusal(e);
            connection.close(0u32.into(), b"handshake failed");
        }
        linked
    })
    .await
    .map_err(|_| LinkError::HandshakeTimeout)
    .and_then(|linked| linked)
}

/// Runs the client's side of the handshake, in `version`, on a new control
/// stream of `dialed`.
async fn handshaken(
    cfg: &Config,
    dialed: transport::Dialed,
    version: i64,
) -> Result<Link, LinkError> {
    let exporter_connection = dialed.connection.clone();
    let export = move |label: &str, context: &[u8], length: usize| {
        let mut out = vec![0; length];
        exporter_connection
            .export_keying_material(&mut out, label.as_bytes(), context)
            .ok()?;
        Some(out)
    };
    let export: &Exporter = &export;
    let (send, mut recv) = dialed
        .connection
        .open_bi()
        .await
        .map_err(|e| LinkError::Io(format!("open the control stream: {e}")))?;
    let control = FrameWriter::new(send);
    control
        .write(&handshake::opener(), HANDSHAKE_FRAME_BYTES)
        .await?;
    let challenge = read_frame(&mut recv, HANDSHAKE_FRAME_BYTES).await?;
    let material = cfg.issuer.connect_material().map_err(LinkError::Issuer)?;
    let (connect, station) = handshake::answer_challenge(
        &challenge,
        &ClientSession {
            profile: cfg.target.profile,
            expected_node_id: cfg.target.expected_node_id,
            leaf: &dialed.leaf,
            identity_key: cfg.identity.public_key(),
            connect_key: &material.key,
            connect_binding: &material.binding,
            connect_status: &material.status,
            capabilities: 0,
            now_ms: now_ms(),
            member_endorsement: cfg.member_endorsement.clone(),
            version,
            export: Some(export),
        },
    )?;
    control.write(&connect, HANDSHAKE_FRAME_BYTES).await?;
    let hello = read_frame(&mut recv, HANDSHAKE_FRAME_BYTES).await?;
    let capabilities = handshake::read_hello(&hello, &station)?;
    let self_id = cfg
        .identity
        .node_id()
        .map_err(|e| LinkError::InvalidConfig(e.to_string()))?;
    let statements = cfg
        .issuer
        .subscribe(&material.binding)
        .map_err(LinkError::Issuer)?;
    let (done_tx, done_rx) = watch::channel(false);
    let share = cfg
        .share
        .clone()
        .unwrap_or_else(|| format!("{}:{}", cfg.target.host, cfg.target.port));
    let (pongs, pongs_rx) = tokio::sync::mpsc::channel(1);
    static SERIALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
    let inner = Arc::new(Inner {
        serial: SERIALS.fetch_add(1, Ordering::Relaxed),
        connection: dialed.connection,
        _endpoint: dialed.endpoint,
        control,
        profile: cfg.target.profile,
        key: cfg.identity.clone(),
        self_id,
        status_deadline: AtomicI64::new(station.status_expires_at + STATUS_GRACE_MS),
        station_capabilities: capabilities,
        connection_hash: Sha384::digest(&challenge).into(),
        version: station.version,
        pongs,
        pongs_rx: tokio::sync::Mutex::new(pongs_rx),
        station,
        send_seq: tokio::sync::Mutex::new(0),
        publication_seq: cfg.publication_seq.clone().unwrap_or_default(),
        admission: cfg
            .admission
            .clone()
            .unwrap_or_else(|| Arc::new(Admission::new(AdmissionLimits::default()))),
        dedup: cfg.dedup.clone().unwrap_or_default(),
        share,
        state: Mutex::new(State {
            ended: None,
            closing: false,
            unrouted: HashMap::new(),
            pending: HashMap::new(),
            subs: HashMap::new(),
            served: HashMap::new(),
            streams: Vec::new(),
        }),
        done_tx,
        done_rx,
    });
    let station_node_id = inner.station.node_id;
    versions::completed(&station_node_id, &inner)?;
    tokio::spawn(send_statements(Arc::downgrade(&inner), statements));
    tokio::spawn(read_control(inner.clone(), recv));
    tokio::spawn(stream::accept_streams(Arc::downgrade(&inner)));
    tokio::spawn(call::probe(Arc::downgrade(&inner)));
    tokio::spawn(watch_expiries(Arc::downgrade(&inner)));
    tokio::spawn(watch_connection(Arc::downgrade(&inner)));
    Ok(Link { inner })
}

impl Inner {
    fn lock(&self) -> MutexGuard<'_, State> {
        self.state
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn count(&self, what: &str) {
        *self.lock().unrouted.entry(what.to_string()).or_default() += 1;
    }

    /// A version-2 frame on the control stream: on v5 as it is, on v4
    /// neighbour-signed with the next seq when the profile signs its type.
    async fn send_control(&self, v: &Value) -> Result<(), LinkError> {
        if self.version == VERSION_5 {
            return self.write_control(v).await;
        }
        let mut seq = self.send_seq.lock().await;
        let signed = frame::sign_neighbour(
            v,
            &self.key,
            &NeighbourLink {
                connection: self.connection_hash,
                seq: *seq,
            },
        )?;
        if frame::neighbour_signed(self.profile, &frame_type_of(v)) {
            *seq += 1;
        }
        self.write_control(&signed).await
    }

    /// A frame on the control stream as it is: a data frame, which carries
    /// its own end-to-end signature and no neighbour signature.
    async fn write_control(&self, v: &Value) -> Result<(), LinkError> {
        let encoded =
            cbor::encode(v).map_err(|e| LinkError::Frame(FrameError::Payload(e.to_string())))?;
        self.control.write(&encoded, MAX_FRAME_BYTES).await
    }

    /// Ends the link once, with `err`: pending calls, subscriptions, served
    /// procedures and streams end with it, and the connection closes.
    fn end(&self, err: LinkError) {
        let (err, pending, subs, served, streams) = {
            let mut state = self.lock();
            if state.ended.is_some() {
                return;
            }
            let err = if state.closing {
                LinkError::Closed
            } else {
                err
            };
            state.ended = Some(err.clone());
            (
                err,
                std::mem::take(&mut state.pending),
                std::mem::take(&mut state.subs),
                std::mem::take(&mut state.served),
                std::mem::take(&mut state.streams),
            )
        };
        for (_, p) in pending {
            let _ = p.outcome.send(Err(err.clone()));
        }
        drop(subs);
        for s in served.into_values() {
            s.end(err.clone());
        }
        for s in streams.into_iter().filter_map(|w| w.upgrade()) {
            stream::StreamInner::end(&s, Some(err.clone()));
        }
        self.connection.close(0u32.into(), b"link ended");
        if self.version == VERSION {
            versions::v4_ended(&self.station.node_id, self.serial);
        }
        let _ = self.done_tx.send_replace(true);
    }
}

/// Sends each statement the issuer reissues as a STATUS, until the link
/// ends. A STATUS carries no neighbour signature and takes no seq.
async fn send_statements(link: std::sync::Weak<Inner>, mut statements: StatementSubscription) {
    loop {
        let Some(done) = link.upgrade().map(|l| l.done_rx.clone()) else {
            return;
        };
        let mut done = done;
        let statement = tokio::select! {
            _ = done.wait_for(|ended| *ended) => return,
            statement = statements.recv() => statement,
        };
        let (Some(statement), Some(inner)) = (statement, link.upgrade()) else {
            return;
        };
        if let Err(e) = inner
            .control
            .write(&handshake::status_frame(&statement), MAX_FRAME_BYTES)
            .await
        {
            inner.end(e);
            return;
        }
    }
}

/// Reads the station's frames until the link ends.
async fn read_control(inner: Arc<Inner>, mut recv: quinn::RecvStream) {
    let mut recv_seq = 0u64;
    let mut done = inner.done_rx.clone();
    loop {
        let payload = tokio::select! {
            _ = done.wait_for(|ended| *ended) => return,
            payload = read_frame(&mut recv, MAX_FRAME_BYTES) => payload,
        };
        let outcome = match payload {
            Ok(payload) => received(&inner, &payload, &mut recv_seq),
            Err(e) => Err(e),
        };
        if let Err(e) = outcome {
            inner.end(e);
            return;
        }
    }
}

/// One frame from the station: a STATUS renews the station's statement, a
/// liveness frame is answered or handed to the probe, every other frame is
/// opened (on v4 from its neighbour signature at the next seq), and a GOODBYE
/// ends the link.
fn received(inner: &Arc<Inner>, payload: &[u8], recv_seq: &mut u64) -> Result<(), LinkError> {
    let v = cbor::decode(payload).map_err(|_| LinkError::Frame(FrameError::Malformed))?;
    let frame_type = frame_type_of(&v);
    if frame_type == "status" {
        let expires_at = handshake::read_status(
            payload,
            &Peer {
                profile: inner.profile,
                identity_key: inner.station.identity_key.clone(),
                binding: inner.station.tls_binding.clone(),
                now_ms: now_ms(),
            },
        )?;
        inner
            .status_deadline
            .store(expires_at + STATUS_GRACE_MS, Ordering::SeqCst);
        return Ok(());
    }
    if let Some((kind, nonce)) = liveness_frame(inner.version, &v)? {
        return liveness(inner, kind, nonce);
    }
    let opened = opened(inner, &v, &frame_type, recv_seq)?;
    match frame_type.as_str() {
        "event" => pubsub::evented(inner, &opened),
        "result" | "error" => call::replied(inner, &opened),
        "call" => serve::called(inner, &opened),
        "goodbye" => {
            let reason = match opened.get("reason") {
                Some(Value::Text(r)) => r.clone(),
                _ => String::new(),
            };
            return Err(LinkError::Goodbye(reason));
        }
        _ => inner.count(&frame_type),
    }
    Ok(())
}

/// A received frame as the link reads it: on v5 with no neighbour signature,
/// on v4 opened from its neighbour signature at the next seq.
fn opened(
    inner: &Inner,
    v: &Value,
    frame_type: &str,
    recv_seq: &mut u64,
) -> Result<Value, LinkError> {
    if inner.version == VERSION_5 {
        return Ok(frame::verify_session_frame(v)?);
    }
    let opened = frame::verify_neighbour(
        v,
        &NeighbourPeer {
            profile: inner.profile,
            peer_key: inner.station.identity_key.clone(),
            connection: inner.connection_hash,
            seq: *recv_seq,
        },
    )?;
    if frame::neighbour_signed(inner.profile, frame_type) {
        *recv_seq += 1;
    }
    Ok(opened)
}

/// A liveness frame as a link of `version` reads it: its kind and nonce, or
/// `None` for any other frame. It exists only on v5, and there it is read as
/// every v5 frame is, so one that carries a neighbour signature ends the link
/// as malformed, as on v4 any liveness frame does.
fn liveness_frame(
    version: i64,
    v: &Value,
) -> Result<Option<(Liveness, [u8; frame::LIVENESS_NONCE_SIZE])>, LinkError> {
    let Some(found) = frame::liveness_nonce(v) else {
        return Ok(None);
    };
    if version != VERSION_5 {
        return Err(LinkError::Frame(FrameError::Malformed));
    }
    frame::verify_session_frame(v)?;
    Ok(Some(found))
}

/// Answers the station's liveness_ping with a liveness_pong of the same
/// nonce, and hands a liveness_pong to the probe. Neither goes further.
fn liveness(
    inner: &Arc<Inner>,
    kind: Liveness,
    nonce: [u8; frame::LIVENESS_NONCE_SIZE],
) -> Result<(), LinkError> {
    match kind {
        Liveness::Ping => {
            let inner = inner.clone();
            tokio::spawn(async move {
                if let Err(e) = inner
                    .send_control(&frame::liveness_pong_frame(&nonce))
                    .await
                {
                    inner.end(e);
                }
            });
        }
        Liveness::Pong => {
            let _ = inner.pongs.try_send(nonce);
        }
    }
    Ok(())
}

/// Ends the link when the station's statement lapses past the grace, or its
/// TLS binding reaches its not_after.
async fn watch_expiries(link: std::sync::Weak<Inner>) {
    loop {
        let Some(inner) = link.upgrade() else { return };
        let now = now_ms();
        if now >= inner.station.binding_not_after {
            inner.end(LinkError::BindingExpired);
            return;
        }
        let status_deadline = inner.status_deadline.load(Ordering::SeqCst);
        if now >= status_deadline {
            inner.end(LinkError::StatusExpired);
            return;
        }
        let wait = (status_deadline.min(inner.station.binding_not_after) - now).clamp(1, 60_000);
        let mut done = inner.done_rx.clone();
        drop(inner);
        tokio::select! {
            _ = done.wait_for(|ended| *ended) => return,
            _ = tokio::time::sleep(Duration::from_millis(wait as u64)) => {}
        }
    }
}

/// Ends the link when its QUIC connection closes.
async fn watch_connection(link: std::sync::Weak<Inner>) {
    let Some(connection) = link.upgrade().map(|l| l.connection.clone()) else {
        return;
    };
    let cause = connection.closed().await;
    if let Some(inner) = link.upgrade() {
        inner.end(LinkError::Io(cause.to_string()));
    }
}

fn frame_type_of(v: &Value) -> String {
    match v.get("frame_type") {
        Some(Value::Text(t)) => t.clone(),
        _ => String::new(),
    }
}

fn now_ms() -> i64 {
    crate::uuid_v7::now_ms() as i64
}

#[cfg(test)]
mod tests {
    use super::*;

    fn with_neighbour(v: Value) -> Value {
        let Value::Map(mut pairs) = v else {
            panic!("a frame is a map");
        };
        pairs.push((Value::text("neighbour"), Value::Map(Vec::new())));
        Value::Map(pairs)
    }

    /// macula-go 2294f25: liveness frames are read after the session-mode
    /// check, so a neighbour-signed one ends a v5 link.
    #[test]
    fn a_liveness_frame_is_read_as_every_v5_frame_and_exists_only_on_v5() {
        let nonce = [9; frame::LIVENESS_NONCE_SIZE];
        let ping = frame::liveness_ping_frame(&nonce);
        let pong = frame::liveness_pong_frame(&nonce);
        assert_eq!(
            liveness_frame(VERSION_5, &ping),
            Ok(Some((Liveness::Ping, nonce)))
        );
        assert_eq!(
            liveness_frame(VERSION_5, &pong),
            Ok(Some((Liveness::Pong, nonce)))
        );
        for signed in [with_neighbour(ping.clone()), with_neighbour(pong.clone())] {
            assert_eq!(
                liveness_frame(VERSION_5, &signed),
                Err(LinkError::Frame(FrameError::Malformed))
            );
        }
        assert_eq!(
            liveness_frame(VERSION, &ping),
            Err(LinkError::Frame(FrameError::Malformed))
        );
        let goodbye = frame::goodbye_frame("bye", None).unwrap();
        assert_eq!(liveness_frame(VERSION_5, &goodbye), Ok(None));
    }
}