wire-mesh-wire 0.1.0

Wire types and canonical CBOR codec for the wire-mesh protocol (spec/*.cddl), hand-written against RFC 8949 4.2 core deterministic encoding
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
//! `transport.cddl` — domain-independent frames every peer speaks
//! regardless of the negotiated capability set: liveness, peer discovery,
//! NAT traversal, relay, and the redesigned gossiped coordinator-election
//! claim.

use minicbor::{Decode, Decoder, Encode, Encoder};

use crate::error::DecodeError;
use crate::identity::{device_id_from, identity_key_from, DeviceId, IdentityKey};
use crate::strict;
use crate::value::{CanonicalMap, CborValue, CdeKey, CdeMapBuilder};

/// `ping-frame = { type: "ping" }`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PingFrame;

impl PingFrame {
    pub const TYPE: &'static str = "ping";
}

impl Encode<()> for PingFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.map(1)?;
        e.str("type")?.str(Self::TYPE)?;
        e.ok()
    }
}

impl Decode<'_, ()> for PingFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        ping_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn ping_from(d: &mut Decoder<'_>) -> Result<PingFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, PingFrame::TYPE)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(PingFrame)
}

/// `pong-frame = { type: "pong" }` (wire-mesh#181) -- a bare echo of
/// ping-frame, sent by a hub in reply to a ping it receives, deliberately
/// below the manage-command/capability layer entirely. This crate carries
/// only the wire shape; the Rust session runtime
/// (`wire_mesh_core::domain::session`) deliberately has no relay/hub role
/// at all (see that module's own scope comment), so nothing here answers a
/// ping with a pong -- that behaviour lives in the TypeScript core's
/// `relay-hub.ts` only.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PongFrame;

impl PongFrame {
    pub const TYPE: &'static str = "pong";
}

impl Encode<()> for PongFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.map(1)?;
        e.str("type")?.str(Self::TYPE)?;
        e.ok()
    }
}

impl Decode<'_, ()> for PongFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        pong_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn pong_from(d: &mut Decoder<'_>) -> Result<PongFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, PongFrame::TYPE)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(PongFrame)
}

/// `close-frame = { type: "close", ? reason }`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CloseFrame {
    pub reason: Option<String>,
}

impl CloseFrame {
    pub const TYPE: &'static str = "close";
}

impl Encode<()> for CloseFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        let len = 1 + usize::from(self.reason.is_some());
        e.map(len as u64)?;
        e.str("type")?.str(Self::TYPE)?;
        if let Some(reason) = &self.reason {
            e.str("reason")?.str(reason)?;
        }
        e.ok()
    }
}

impl Decode<'_, ()> for CloseFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        close_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn close_from(d: &mut Decoder<'_>) -> Result<CloseFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut reason: Option<String> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, CloseFrame::TYPE)?,
            "reason" => strict::set_once(&mut reason, strict::text_value(d)?)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(CloseFrame { reason })
}

/// The domain-separation prefix a `peer-advert` signature is computed over,
/// per `spec/transport.cddl`: the ASCII string `wire-mesh/peer-advert/v1`
/// followed by one zero byte.
///
/// Deliberately not `tokens.cddl`'s COSE `Sig_structure`, which every other
/// signature in this protocol reuses. An advert's extension tail is an open
/// `* tstr => any` map, so an attacker can craft an advert whose canonical
/// encoding also satisfies `token-claims`, and a `Sig_structure` over that
/// encoding would then be replayable as a capability token's own signed
/// payload. This prefix makes the two byte strings disjoint by construction:
/// a `Sig_structure` always begins with the head of a 4-element CBOR array,
/// never the ASCII `w` this one starts with.
pub const PEER_ADVERT_SIGNING_CONTEXT: &[u8] = b"wire-mesh/peer-advert/v1\0";

/// `peer-advert = { device, addresses, snapshot-seconds, identity-key,
/// signature, * tstr => any }`.
///
/// CDE key order: `device` (7 encoded bytes), `addresses` (10), `signature`
/// (10), `identity-key` (13), `snapshot-seconds` (17), with any extension
/// key interleaved by its own encoded-key order (see `spec/CONVENTIONS.md`'s
/// gossip-extension-namespacing convention for the `<domain>/<field>` key
/// shape a well-behaved extension key must use).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PeerAdvert {
    pub device: DeviceId,
    /// `host:port` strings.
    pub addresses: Vec<String>,
    /// Unix-seconds snapshot time.
    pub snapshot_seconds: i64,
    /// The advertised device's own key, travelling inside the signed content
    /// exactly as `token-claims`' own `issuer-key` does. A verifier MUST
    /// check that `sha256(public_key)` equals `device` before trusting
    /// anything else here, which is what makes an advert checkable with no
    /// prior contact with the device it names and no directory to consult.
    pub identity_key: IdentityKey,
    /// Over [`peer_advert_signing_input`]'s bytes, under `identity_key`. The
    /// only entry the signature does not itself cover.
    pub signature: Vec<u8>,
    /// Forward-compatible extension bag (presence status, an accept/refuse
    /// policy, or any future gossiped fact). Covered by the signature like
    /// every other entry, so a key here is authentic but still self-asserted:
    /// per the verifier obligation `spec/transport.cddl` states directly, an
    /// unrecognised key is ignored, never acted on without understanding it,
    /// and never an error.
    pub extra: CanonicalMap<String, CborValue>,
}

impl PeerAdvert {
    /// This advert's own entries in CDE order, minus `signature`: the map the
    /// signing input encodes. Shared by [`Encode`] and
    /// [`peer_advert_signing_input`] so the bytes a verifier reconstructs can
    /// never drift from the bytes that went on the wire.
    fn builder_without_signature(&self) -> CdeMapBuilder {
        let mut builder = CdeMapBuilder::new();
        builder.push("device", &self.device);
        builder.push("addresses", &self.addresses);
        builder.push("snapshot-seconds", &self.snapshot_seconds);
        builder.push("identity-key", &self.identity_key);
        for (key, value) in self.extra.iter() {
            let mut value_buf = Vec::new();
            let mut value_enc = Encoder::new(&mut value_buf);
            value
                .encode(&mut value_enc, &mut ())
                .unwrap_or_else(|_| unreachable!("Vec<u8> writes are infallible"));
            builder.push_raw(key.encoded(), value_buf);
        }
        builder
    }
}

/// The exact bytes a `peer-advert`'s signature is computed over:
/// [`PEER_ADVERT_SIGNING_CONTEXT`] followed by the canonical CDE encoding of
/// the advert with its `signature` entry removed and nothing else changed.
/// Every other entry is therefore covered, extension tail included.
pub fn peer_advert_signing_input(advert: &PeerAdvert) -> Vec<u8> {
    let mut encoded = Vec::new();
    let mut e = Encoder::new(&mut encoded);
    advert
        .builder_without_signature()
        .write(&mut e)
        .unwrap_or_else(|_| unreachable!("Vec<u8> writes are infallible"));
    let mut input = Vec::with_capacity(PEER_ADVERT_SIGNING_CONTEXT.len() + encoded.len());
    input.extend_from_slice(PEER_ADVERT_SIGNING_CONTEXT);
    input.extend_from_slice(&encoded);
    input
}

impl Encode<()> for PeerAdvert {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        let mut builder = self.builder_without_signature();
        builder.push_bytes("signature", &self.signature);
        builder.write(e)
    }
}

impl Decode<'_, ()> for PeerAdvert {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        peer_advert_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn peer_advert_from(d: &mut Decoder<'_>) -> Result<PeerAdvert, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut device: Option<DeviceId> = None;
    let mut addresses: Option<Vec<String>> = None;
    let mut snapshot_seconds: Option<i64> = None;
    let mut identity_key: Option<IdentityKey> = None;
    let mut signature: Option<Vec<u8>> = None;
    let mut extra = CanonicalMap::new();
    while let Some(key) = map.next_key(d)? {
        match key {
            "device" => strict::set_once(&mut device, device_id_from(d)?)?,
            "addresses" => {
                let count = strict::definite_array(d)?;
                let mut list = Vec::new();
                for _ in 0..count {
                    list.push(strict::text_value(d)?);
                }
                addresses = Some(list);
            }
            "snapshot-seconds" => strict::set_once(&mut snapshot_seconds, strict::int_value(d)?)?,
            "identity-key" => strict::set_once(&mut identity_key, identity_key_from(d)?)?,
            "signature" => strict::set_once(&mut signature, strict::bytes_value(d)?)?,
            other => {
                let value = CborValue::decode_strict(d)?;
                extra.insert(other.to_owned(), value)?;
            }
        }
    }
    Ok(PeerAdvert {
        device: device.ok_or(DecodeError::MissingField("device"))?,
        addresses: addresses.ok_or(DecodeError::MissingField("addresses"))?,
        snapshot_seconds: snapshot_seconds.ok_or(DecodeError::MissingField("snapshot-seconds"))?,
        identity_key: identity_key.ok_or(DecodeError::MissingField("identity-key"))?,
        signature: signature.ok_or(DecodeError::MissingField("signature"))?,
        extra,
    })
}

/// `gossip-frame = { type: "gossip", peers }`. CDE key order: `type` (5),
/// `peers` (8).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct GossipFrame {
    pub peers: Vec<PeerAdvert>,
}

impl GossipFrame {
    pub const TYPE: &'static str = "gossip";
}

impl Encode<()> for GossipFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.map(2)?;
        e.str("type")?.str(Self::TYPE)?;
        e.str("peers")?.array(self.peers.len() as u64)?;
        for peer in &self.peers {
            peer.encode(e, &mut ())?;
        }
        e.ok()
    }
}

impl Decode<'_, ()> for GossipFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        gossip_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn gossip_from(d: &mut Decoder<'_>) -> Result<GossipFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut peers: Option<Vec<PeerAdvert>> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, GossipFrame::TYPE)?,
            "peers" => {
                let count = strict::definite_array(d)?;
                let mut list = Vec::new();
                for _ in 0..count {
                    list.push(peer_advert_from(d)?);
                }
                peers = Some(list);
            }
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(GossipFrame {
        peers: peers.ok_or(DecodeError::MissingField("peers"))?,
    })
}

/// `candidate-kind = "host" / "server-reflexive" / "relayed"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CandidateKind {
    Host,
    ServerReflexive,
    Relayed,
}

impl CandidateKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            CandidateKind::Host => "host",
            CandidateKind::ServerReflexive => "server-reflexive",
            CandidateKind::Relayed => "relayed",
        }
    }
}

impl Encode<()> for CandidateKind {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.str(self.as_str())?.ok()
    }
}

impl Decode<'_, ()> for CandidateKind {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        let found = strict::text_value(d).map_err(minicbor::decode::Error::custom)?;
        match found.as_str() {
            "host" => Ok(CandidateKind::Host),
            "server-reflexive" => Ok(CandidateKind::ServerReflexive),
            "relayed" => Ok(CandidateKind::Relayed),
            other => Err(minicbor::decode::Error::custom(DecodeError::BadLiteral {
                expected: "host | server-reflexive | relayed",
                found: other.to_owned(),
            })),
        }
    }
}

/// `wire-candidate = { address, kind, priority }`. CDE key order: `kind`
/// (5), `address` (8), `priority` (9).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WireCandidate {
    /// `ip:port`.
    pub address: String,
    pub kind: CandidateKind,
    pub priority: u64,
}

impl Encode<()> for WireCandidate {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.map(3)?;
        e.str("kind")?.encode(self.kind)?;
        e.str("address")?.str(&self.address)?;
        e.str("priority")?.u64(self.priority)?;
        e.ok()
    }
}

impl Decode<'_, ()> for WireCandidate {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        wire_candidate_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn wire_candidate_from(d: &mut Decoder<'_>) -> Result<WireCandidate, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut address: Option<String> = None;
    let mut kind: Option<CandidateKind> = None;
    let mut priority: Option<u64> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "address" => strict::set_once(&mut address, strict::text_value(d)?)?,
            "kind" => {
                kind = Some(
                    CandidateKind::decode(d, &mut ())
                        .map_err(|e| DecodeError::Malformed(e.to_string()))?,
                )
            }
            "priority" => strict::set_once(&mut priority, strict::uint_value(d)?)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(WireCandidate {
        address: address.ok_or(DecodeError::MissingField("address"))?,
        kind: kind.ok_or(DecodeError::MissingField("kind"))?,
        priority: priority.ok_or(DecodeError::MissingField("priority"))?,
    })
}

/// `candidates-frame = { type: "candidates", candidates }`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CandidatesFrame {
    pub candidates: Vec<WireCandidate>,
}

impl CandidatesFrame {
    pub const TYPE: &'static str = "candidates";
}

impl Encode<()> for CandidatesFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.map(2)?;
        e.str("type")?.str(Self::TYPE)?;
        e.str("candidates")?.array(self.candidates.len() as u64)?;
        for candidate in &self.candidates {
            candidate.encode(e, &mut ())?;
        }
        e.ok()
    }
}

impl Decode<'_, ()> for CandidatesFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        candidates_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn candidates_from(d: &mut Decoder<'_>) -> Result<CandidatesFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut candidates: Option<Vec<WireCandidate>> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, CandidatesFrame::TYPE)?,
            "candidates" => {
                let count = strict::definite_array(d)?;
                let mut list = Vec::new();
                for _ in 0..count {
                    list.push(wire_candidate_from(d)?);
                }
                candidates = Some(list);
            }
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(CandidatesFrame {
        candidates: candidates.ok_or(DecodeError::MissingField("candidates"))?,
    })
}

/// `sync-punch-frame = { type, nonce, deadline-unix-ms }`. CDE key order:
/// `type` (5), `nonce` (6), `deadline-unix-ms` (18).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SyncPunchFrame {
    pub nonce: u64,
    pub deadline_unix_ms: u64,
}

impl SyncPunchFrame {
    pub const TYPE: &'static str = "sync-punch";
}

impl Encode<()> for SyncPunchFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.map(3)?;
        e.str("type")?.str(Self::TYPE)?;
        e.str("nonce")?.u64(self.nonce)?;
        e.str("deadline-unix-ms")?.u64(self.deadline_unix_ms)?;
        e.ok()
    }
}

impl Decode<'_, ()> for SyncPunchFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        sync_punch_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn sync_punch_from(d: &mut Decoder<'_>) -> Result<SyncPunchFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut nonce: Option<u64> = None;
    let mut deadline_unix_ms: Option<u64> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, SyncPunchFrame::TYPE)?,
            "nonce" => strict::set_once(&mut nonce, strict::uint_value(d)?)?,
            "deadline-unix-ms" => strict::set_once(&mut deadline_unix_ms, strict::uint_value(d)?)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(SyncPunchFrame {
        nonce: nonce.ok_or(DecodeError::MissingField("nonce"))?,
        deadline_unix_ms: deadline_unix_ms.ok_or(DecodeError::MissingField("deadline-unix-ms"))?,
    })
}

/// `observed-address-frame = { type, address }`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObservedAddressFrame {
    pub address: String,
}

impl ObservedAddressFrame {
    pub const TYPE: &'static str = "observed-address";
}

impl Encode<()> for ObservedAddressFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.map(2)?;
        e.str("type")?.str(Self::TYPE)?;
        e.str("address")?.str(&self.address)?;
        e.ok()
    }
}

impl Decode<'_, ()> for ObservedAddressFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        observed_address_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn observed_address_from(
    d: &mut Decoder<'_>,
) -> Result<ObservedAddressFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut address: Option<String> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, ObservedAddressFrame::TYPE)?,
            "address" => strict::set_once(&mut address, strict::text_value(d)?)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(ObservedAddressFrame {
        address: address.ok_or(DecodeError::MissingField("address"))?,
    })
}

/// `relay-offer-frame = { type, addresses }`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RelayOfferFrame {
    pub addresses: Vec<String>,
}

impl RelayOfferFrame {
    pub const TYPE: &'static str = "relay-offer";
}

impl Encode<()> for RelayOfferFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.map(2)?;
        e.str("type")?.str(Self::TYPE)?;
        e.str("addresses")?.array(self.addresses.len() as u64)?;
        for address in &self.addresses {
            e.str(address)?;
        }
        e.ok()
    }
}

impl Decode<'_, ()> for RelayOfferFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        relay_offer_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn relay_offer_from(d: &mut Decoder<'_>) -> Result<RelayOfferFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut addresses: Option<Vec<String>> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, RelayOfferFrame::TYPE)?,
            "addresses" => {
                let count = strict::definite_array(d)?;
                let mut list = Vec::new();
                for _ in 0..count {
                    list.push(strict::text_value(d)?);
                }
                addresses = Some(list);
            }
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(RelayOfferFrame {
        addresses: addresses.ok_or(DecodeError::MissingField("addresses"))?,
    })
}

/// `relay-connect-frame = { type, target-device, ? source-device }`.
/// `source-device` names which of a fronting connection's devices is the
/// initiator; absent, the initiator is the device the hub attributes to the
/// connection itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelayConnectFrame {
    pub target_device: DeviceId,
    pub source_device: Option<DeviceId>,
}

impl RelayConnectFrame {
    pub const TYPE: &'static str = "relay-connect";
}

impl Encode<()> for RelayConnectFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.map(2 + self.source_device.is_some() as u64)?;
        e.str("type")?.str(Self::TYPE)?;
        if let Some(source_device) = self.source_device {
            e.str("source-device")?.encode(source_device)?;
        }
        e.str("target-device")?.encode(self.target_device)?;
        e.ok()
    }
}

impl Decode<'_, ()> for RelayConnectFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        relay_connect_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn relay_connect_from(d: &mut Decoder<'_>) -> Result<RelayConnectFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut target_device: Option<DeviceId> = None;
    let mut source_device: Option<DeviceId> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, RelayConnectFrame::TYPE)?,
            "target-device" => strict::set_once(&mut target_device, device_id_from(d)?)?,
            "source-device" => strict::set_once(&mut source_device, device_id_from(d)?)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(RelayConnectFrame {
        target_device: target_device.ok_or(DecodeError::MissingField("target-device"))?,
        source_device,
    })
}

/// `relay-data-frame = { type, payload, ? to-device, ? from-device }`. The
/// payload is ciphertext established one layer above the transport; this
/// layer never interprets it. `to-device`/`from-device` disambiguate which
/// pairing a frame belongs to when a connection holds more than one relay
/// pairing at once; a connection with exactly one pairing may omit
/// `to-device`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelayDataFrame {
    pub payload: Vec<u8>,
    pub to_device: Option<DeviceId>,
    pub from_device: Option<DeviceId>,
}

impl RelayDataFrame {
    pub const TYPE: &'static str = "relay-data";
}

impl Encode<()> for RelayDataFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        let field_count = 2 + self.to_device.is_some() as u64 + self.from_device.is_some() as u64;
        e.map(field_count)?;
        e.str("type")?.str(Self::TYPE)?;
        e.str("payload")?.bytes(&self.payload)?;
        if let Some(to_device) = self.to_device {
            e.str("to-device")?.encode(to_device)?;
        }
        if let Some(from_device) = self.from_device {
            e.str("from-device")?.encode(from_device)?;
        }
        e.ok()
    }
}

impl Decode<'_, ()> for RelayDataFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        relay_data_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn relay_data_from(d: &mut Decoder<'_>) -> Result<RelayDataFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut payload: Option<Vec<u8>> = None;
    let mut to_device: Option<DeviceId> = None;
    let mut from_device: Option<DeviceId> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, RelayDataFrame::TYPE)?,
            "payload" => strict::set_once(&mut payload, strict::bytes_value(d)?)?,
            "to-device" => strict::set_once(&mut to_device, device_id_from(d)?)?,
            "from-device" => strict::set_once(&mut from_device, device_id_from(d)?)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(RelayDataFrame {
        payload: payload.ok_or(DecodeError::MissingField("payload"))?,
        to_device,
        from_device,
    })
}

/// `relay-inbound-frame = { type, source-device, ? target-device }`.
/// `target-device` names which of the receiving connection's own devices the
/// pairing is for, so a fronting connection can tell which was paired.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelayInboundFrame {
    pub source_device: DeviceId,
    pub target_device: Option<DeviceId>,
}

impl RelayInboundFrame {
    pub const TYPE: &'static str = "relay-inbound";
}

impl Encode<()> for RelayInboundFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        e.map(2 + self.target_device.is_some() as u64)?;
        e.str("type")?.str(Self::TYPE)?;
        e.str("source-device")?.encode(self.source_device)?;
        if let Some(target_device) = self.target_device {
            e.str("target-device")?.encode(target_device)?;
        }
        e.ok()
    }
}

impl Decode<'_, ()> for RelayInboundFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        relay_inbound_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn relay_inbound_from(d: &mut Decoder<'_>) -> Result<RelayInboundFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut source_device: Option<DeviceId> = None;
    let mut target_device: Option<DeviceId> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, RelayInboundFrame::TYPE)?,
            "source-device" => strict::set_once(&mut source_device, device_id_from(d)?)?,
            "target-device" => strict::set_once(&mut target_device, device_id_from(d)?)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(RelayInboundFrame {
        source_device: source_device.ok_or(DecodeError::MissingField("source-device"))?,
        target_device,
    })
}

/// `coordinator-frame = { type: "coordinator", term, coordinator, ? capacity-hint }`.
///
/// The redesigned gossiped election claim: `term` is a monotonically
/// increasing epoch a peer raises when claiming the introduction/
/// rendezvous role; a higher term always supersedes a lower one, and equal
/// terms break by lowest device-id — a receiver obligation, not a wire
/// constraint. CDE key order: `term` (5; bytewise before `type`), `type`
/// (5), `coordinator` (12), `capacity-hint` (14).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoordinatorFrame {
    pub term: u64,
    pub coordinator: DeviceId,
    pub capacity_hint: Option<u64>,
}

impl CoordinatorFrame {
    pub const TYPE: &'static str = "coordinator";
}

impl Encode<()> for CoordinatorFrame {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        let len = 3 + usize::from(self.capacity_hint.is_some());
        e.map(len as u64)?;
        e.str("term")?.u64(self.term)?;
        e.str("type")?.str(Self::TYPE)?;
        e.str("coordinator")?.encode(self.coordinator)?;
        if let Some(hint) = self.capacity_hint {
            e.str("capacity-hint")?.u64(hint)?;
        }
        e.ok()
    }
}

impl Decode<'_, ()> for CoordinatorFrame {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        coordinator_from(d).map_err(minicbor::decode::Error::custom)
    }
}

pub(crate) fn coordinator_from(d: &mut Decoder<'_>) -> Result<CoordinatorFrame, DecodeError> {
    let mut map = strict::MapDecoder::new(d)?;
    let mut term: Option<u64> = None;
    let mut coordinator: Option<DeviceId> = None;
    let mut capacity_hint: Option<u64> = None;
    while let Some(key) = map.next_key(d)? {
        match key {
            "type" => strict::literal(d, CoordinatorFrame::TYPE)?,
            "term" => strict::set_once(&mut term, strict::uint_value(d)?)?,
            "coordinator" => strict::set_once(&mut coordinator, device_id_from(d)?)?,
            "capacity-hint" => strict::set_once(&mut capacity_hint, strict::uint_value(d)?)?,
            other => return Err(DecodeError::UnknownKey(other.to_owned())),
        }
    }
    Ok(CoordinatorFrame {
        term: term.ok_or(DecodeError::MissingField("term"))?,
        coordinator: coordinator.ok_or(DecodeError::MissingField("coordinator"))?,
        capacity_hint,
    })
}

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

    #[test]
    fn close_frame_rejects_unsorted_keys() {
        // { "reason": "b", "type": "close" }: "type" (5 bytes) sorts before
        // "reason" (7), so reason-first is out of CDE order.
        let bytes = [
            0xa2, 0x66, b'r', b'e', b'a', b's', b'o', b'n', 0x61, b'b', 0x64, b't', b'y', b'p',
            b'e', 0x65, b'c', b'l', b'o', b's', b'e',
        ];
        let mut d = Decoder::new(&bytes);
        assert_eq!(close_from(&mut d), Err(DecodeError::UnsortedMapKeys));
    }

    fn round_trip<T>(value: T) -> Vec<u8>
    where
        T: Encode<()> + PartialEq + core::fmt::Debug + for<'a> Decode<'a, ()>,
    {
        let bytes = minicbor::to_vec(&value).expect("encode");
        let back: T = minicbor::decode(&bytes).expect("decode");
        assert_eq!(back, value, "round trip");
        bytes
    }

    #[test]
    fn ping_encodes_exactly() {
        let bytes = round_trip(PingFrame);
        assert_eq!(
            bytes,
            [0xa1, 0x64, b't', b'y', b'p', b'e', 0x64, b'p', b'i', b'n', b'g']
        );
    }

    #[test]
    fn pong_encodes_exactly() {
        let bytes = round_trip(PongFrame);
        assert_eq!(
            bytes,
            [0xa1, 0x64, b't', b'y', b'p', b'e', 0x64, b'p', b'o', b'n', b'g']
        );
    }

    #[test]
    fn close_reason_after_type() {
        let bytes = round_trip(CloseFrame {
            reason: Some("bye".to_owned()),
        });
        // type (5 encoded bytes) before reason (9).
        let type_at = bytes
            .windows(4)
            .position(|w| w == b"type")
            .expect("type key");
        let reason_at = bytes
            .windows(6)
            .position(|w| w == b"reason")
            .expect("reason key");
        assert!(type_at < reason_at);
    }

    /// Clearly-synthetic filler key material, matching the conformance
    /// vectors' own repeated-byte convention: these tests pin the wire shape
    /// and the signing input's own bytes, neither of which involves checking
    /// that a signature is real.
    fn filler_advert(device: u8, snapshot_seconds: i64) -> PeerAdvert {
        PeerAdvert {
            device: DeviceId([device; 32]),
            addresses: vec!["203.0.113.5:4433".to_owned()],
            snapshot_seconds,
            identity_key: IdentityKey {
                alg: IdentityKey::ALG_ED25519,
                public_key: vec![0xee; 32],
            },
            signature: vec![0xaa; 64],
            extra: CanonicalMap::new(),
        }
    }

    #[test]
    fn peer_advert_cde_order() {
        let bytes = round_trip(filler_advert(1, 1861833600));
        let device_at = bytes
            .windows(6)
            .position(|w| w == b"device")
            .expect("device key");
        let addresses_at = bytes
            .windows(9)
            .position(|w| w == b"addresses")
            .expect("addresses key");
        let signature_at = bytes
            .windows(9)
            .position(|w| w == b"signature")
            .expect("signature key");
        let identity_key_at = bytes
            .windows(12)
            .position(|w| w == b"identity-key")
            .expect("identity-key key");
        let snapshot_at = bytes
            .windows(16)
            .position(|w| w == b"snapshot-seconds")
            .expect("snapshot key");
        assert!(device_at < addresses_at);
        assert!(addresses_at < signature_at);
        assert!(signature_at < identity_key_at);
        assert!(identity_key_at < snapshot_at);
    }

    #[test]
    fn peer_advert_carries_extension_fields() {
        // An unrecognised key is accepted into the open `* tstr => any` tail, the same forward-compatible-extension pattern room-notice-claims/token-claims already carry -- a TS peer's sendGossipUpdate(...) extensions must not disconnect a Rust peer.
        let mut advert = filler_advert(3, 1861920000);
        advert.addresses = vec![];
        advert
            .extra
            .insert(
                "presence/status".to_owned(),
                CborValue::Text("idle".to_owned()),
            )
            .expect("insert");
        round_trip(advert);
    }

    #[test]
    fn peer_advert_rejects_an_advert_with_no_signature() {
        // Both new fields are mandatory, so an advert built the pre-authentication way does not decode at all rather than decoding into something a verifier then has to refuse.
        let mut bytes = Vec::new();
        let mut e = Encoder::new(&mut bytes);
        e.map(3).expect("map");
        e.str("device").expect("key");
        DeviceId([1; 32]).encode(&mut e, &mut ()).expect("device");
        e.str("addresses").expect("key");
        e.array(0).expect("addresses");
        e.str("snapshot-seconds").expect("key");
        e.i64(1861833600).expect("snapshot");
        let decoded: Result<PeerAdvert, _> = minicbor::decode(&bytes);
        assert!(decoded.is_err());
    }

    #[test]
    fn peer_advert_signing_input_prefixes_the_context_and_drops_only_the_signature() {
        let advert = filler_advert(7, 1861833600);
        let input = peer_advert_signing_input(&advert);
        assert!(input.starts_with(PEER_ADVERT_SIGNING_CONTEXT));
        let encoded_content = &input[PEER_ADVERT_SIGNING_CONTEXT.len()..];
        // The content carries every other entry, so only the signature is absent from what is signed over.
        assert!(encoded_content.windows(12).any(|w| w == b"identity-key"));
        assert!(!encoded_content.windows(9).any(|w| w == b"signature"));
    }

    #[test]
    fn peer_advert_signing_input_ignores_the_signature_it_carries() {
        // Two adverts differing only in their signature bytes sign over identical content, which is what lets a verifier reconstruct the input from exactly the advert it received.
        let advert = filler_advert(7, 1861833600);
        let mut resigned = advert.clone();
        resigned.signature = vec![0xbb; 64];
        assert_eq!(
            peer_advert_signing_input(&advert),
            peer_advert_signing_input(&resigned)
        );
    }

    #[test]
    fn peer_advert_signing_input_covers_the_extension_tail() {
        let advert = filler_advert(7, 1861833600);
        let mut extended = advert.clone();
        extended
            .extra
            .insert(
                "presence/status".to_owned(),
                CborValue::Text("idle".to_owned()),
            )
            .expect("insert");
        assert_ne!(
            peer_advert_signing_input(&advert),
            peer_advert_signing_input(&extended)
        );
    }

    #[test]
    fn candidate_kind_literals() {
        assert_eq!(CandidateKind::Host.as_str(), "host");
        let bytes = round_trip(WireCandidate {
            address: "198.51.100.2:7000".to_owned(),
            kind: CandidateKind::Relayed,
            priority: 10,
        });
        // kind (5) before address (8) before priority (9).
        let kind_at = bytes
            .windows(4)
            .position(|w| w == b"kind")
            .expect("kind key");
        let address_at = bytes
            .windows(7)
            .position(|w| w == b"address")
            .expect("address key");
        let priority_at = bytes
            .windows(8)
            .position(|w| w == b"priority")
            .expect("priority key");
        assert!(kind_at < address_at && address_at < priority_at);
        let bad: Result<CandidateKind, _> = minicbor::decode(&[0x6d, b'p', b'e', b'e', b'r']);
        assert!(bad.is_err());
    }

    #[test]
    fn coordinator_term_before_type_before_coordinator() {
        let bytes = round_trip(CoordinatorFrame {
            term: 3,
            coordinator: DeviceId([0x11; 32]),
            capacity_hint: Some(64),
        });
        let term_at = bytes
            .windows(4)
            .position(|w| w == b"term")
            .expect("term key");
        let type_at = bytes
            .windows(4)
            .position(|w| w == b"type")
            .expect("type key");
        let coord_at = bytes
            .windows(11)
            .position(|w| w == b"coordinator")
            .expect("coordinator key");
        let hint_at = bytes
            .windows(13)
            .position(|w| w == b"capacity-hint")
            .expect("hint key");
        assert!(term_at < type_at && type_at < coord_at && coord_at < hint_at);
        assert_eq!(bytes[0], 0xa4);
    }

    #[test]
    fn relay_frames_round_trip() {
        round_trip(RelayOfferFrame {
            addresses: vec!["relay.example.com:4433".to_owned()],
        });
        round_trip(RelayConnectFrame {
            target_device: DeviceId([2; 32]),
            source_device: None,
        });
        round_trip(RelayConnectFrame {
            target_device: DeviceId([2; 32]),
            source_device: Some(DeviceId([6; 32])),
        });
        round_trip(RelayDataFrame {
            payload: vec![9, 9, 9],
            to_device: None,
            from_device: None,
        });
        round_trip(RelayDataFrame {
            payload: vec![9, 9, 9],
            to_device: Some(DeviceId([4; 32])),
            from_device: Some(DeviceId([5; 32])),
        });
        round_trip(RelayInboundFrame {
            source_device: DeviceId([3; 32]),
            target_device: None,
        });
        round_trip(RelayInboundFrame {
            source_device: DeviceId([3; 32]),
            target_device: Some(DeviceId([7; 32])),
        });
    }

    #[test]
    fn unknown_key_rejected() {
        // {"type": "ping", "extra": 1}
        let bytes: Vec<u8> = [
            0xa2u8, 0x64, b't', b'y', b'p', b'e', 0x64, b'p', b'i', b'n', b'g', 0x65, b'e', b'x',
            b't', b'r', b'a', 0x01,
        ]
        .to_vec();
        assert!(minicbor::decode::<PingFrame>(&bytes).is_err());
    }
}