soma-som-core 0.1.0

Universal soma(som) structural primitives — Quad / Tree / Ring / Genesis / Fingerprint / TemporalLedger / CrossingRecord
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
// SPDX-License-Identifier: LGPL-3.0-only
#![allow(missing_docs)]

//! Federation types for Meta-Ring descriptor exchange.
//!
//! Defines the wire types from META-RING-CROSSING-PROTOCOL §3:
//! `RingAnnounce`, `DescriptorEnvelope`, `OrientationSummary`,
//! and the `federation_ns` namespace constants.
//!
//! All types support serde (JSON + bincode) and Ed25519 signature
//! creation/verification.

use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use serde::{Deserialize, Serialize};

/// A ring's unique identity: BLAKE3 hash of genesis state.
pub type RingFingerprint = [u8; 32];

/// Connection status of a federation peer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum PeerStatus {
    /// Peer registered but never successfully connected.
    Unknown,
    /// Peer has sent at least one envelope recently.
    Connected,
    /// Peer was previously connected but exceeded the staleness threshold.
    Disconnected,
}

/// A known federation peer's identity and connection state.
///
/// Stored in the ring's federation peers table (keyed by hex fingerprint).
/// Injected into FU.Data as part of the `federation.peers` key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRecord {
    pub fingerprint: RingFingerprint,
    /// Network address (e.g., "192.168.1.10:9100").
    pub address: String,
    /// Ed25519 public key for envelope signature verification — the ring's
    /// signing key at the FU position. Application example: DIRECTOR's
    /// signing key.
    pub ring_signer_pubkey: [u8; 32],
    /// Current connection status.
    pub status: PeerStatus,
    /// Timestamp (ns since epoch) of last received envelope.
    pub last_seen_ns: u64,
    /// Optional human-readable name for this peer ring.
    pub ring_name: Option<String>,
}

/// Announces a ring's presence and capabilities to the federation.
///
/// Signed by the ring's Ed25519 signing key. Receivers verify the
/// signature before trusting any field.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RingAnnounce {
    pub ring_fingerprint: RingFingerprint,
    /// Ed25519 public key — the ring's signing key at the FU position.
    /// Application example: DIRECTOR's signing key.
    pub ring_signer_pubkey: [u8; 32],
    pub ring_name: String,
    pub capabilities: Vec<String>,
    pub cycle_count: u64,
    pub orientation: OrientationSummary,
    #[serde(with = "sig_bytes")]
    pub signature: [u8; 64],
}

/// Summary of a ring's current orientation — what it knows about itself.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OrientationSummary {
    pub ring_type: String,
    pub organs: Vec<String>,
    pub siblings: Vec<String>,
    pub command_namespaces: Vec<String>,
    pub last_cycle_ns: u64,
}

/// Carries a descriptor (or command, or orientation) between rings.
///
/// Signed by the source ring's Ed25519 signing key. The Body Problem
/// applies: receivers see the descriptor, never the internal crossing chain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DescriptorEnvelope {
    pub source_fingerprint: RingFingerprint,
    pub destination: EnvelopeDestination,
    pub payload: DescriptorPayload,
    pub source_cycle: u64,
    pub timestamp_ns: u64,
    #[serde(with = "sig_bytes")]
    pub signature: [u8; 64],
}

/// Where an envelope is headed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum EnvelopeDestination {
    Ring(RingFingerprint),
    Broadcast,
}

/// What an envelope carries.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum DescriptorPayload {
    Descriptor(Vec<u8>),
    Command { namespace: String, tree: Vec<u8> },
    Orientation(OrientationSummary),
}

/// FU.Data namespace constants for federation keys.
///
/// Matches META-RING-CROSSING-PROTOCOL §3.8.
pub mod federation_ns {
    pub const ANNOUNCE: &str = "federation.announce";
    pub const DESCRIPTOR: &str = "federation.descriptor";
    pub const HEALTH: &str = "federation.health";
    pub const TOPOLOGY: &str = "federation.topology";
    pub const COMMAND: &str = "federation.command";
    pub const PEERS: &str = "federation.peers";
}

// ── Serde helper for [u8; 64] ──────────────────────────────────────────────

mod sig_bytes {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S: Serializer>(bytes: &[u8; 64], s: S) -> Result<S::Ok, S::Error> {
        bytes.as_slice().serialize(s)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 64], D::Error> {
        let v: Vec<u8> = Deserialize::deserialize(d)?;
        v.try_into()
            .map_err(|v: Vec<u8>| serde::de::Error::custom(format!("expected 64 bytes, got {}", v.len())))
    }
}

// ── Signing helpers ────────────────────────────────────────────────────────

impl RingAnnounce {
    /// Returns the bytes that are covered by the signature:
    /// all fields except `signature` itself.
    fn signable_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&self.ring_fingerprint);
        buf.extend_from_slice(&self.ring_signer_pubkey);
        buf.extend_from_slice(self.ring_name.as_bytes());
        for cap in &self.capabilities {
            buf.extend_from_slice(cap.as_bytes());
        }
        buf.extend_from_slice(&self.cycle_count.to_le_bytes());
        buf.extend_from_slice(&orientation_bytes(&self.orientation));
        buf
    }

    /// Sign this announce with the given Ed25519 signing key.
    /// Populates `self.signature` with the Ed25519 signature.
    pub fn sign(&mut self, key: &SigningKey) {
        let msg = self.signable_bytes();
        let sig = key.sign(&msg);
        self.signature = sig.to_bytes();
    }

    /// Verify the signature against the given verifying key.
    pub fn verify(&self, key: &VerifyingKey) -> Result<(), ed25519_dalek::SignatureError> {
        let msg = self.signable_bytes();
        let sig = Signature::from_bytes(&self.signature);
        key.verify(&msg, &sig)
    }
}

impl DescriptorEnvelope {
    /// Returns the bytes that are covered by the signature.
    fn signable_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&self.source_fingerprint);
        match &self.destination {
            EnvelopeDestination::Ring(fp) => {
                buf.push(0x01);
                buf.extend_from_slice(fp);
            }
            EnvelopeDestination::Broadcast => {
                buf.push(0x02);
            }
        }
        match &self.payload {
            DescriptorPayload::Descriptor(data) => {
                buf.push(0x01);
                buf.extend_from_slice(data);
            }
            DescriptorPayload::Command { namespace, tree } => {
                buf.push(0x02);
                buf.extend_from_slice(namespace.as_bytes());
                buf.extend_from_slice(tree);
            }
            DescriptorPayload::Orientation(o) => {
                buf.push(0x03);
                buf.extend_from_slice(&orientation_bytes(o));
            }
        }
        buf.extend_from_slice(&self.source_cycle.to_le_bytes());
        buf.extend_from_slice(&self.timestamp_ns.to_le_bytes());
        buf
    }

    /// Sign this envelope with the given Ed25519 signing key.
    pub fn sign(&mut self, key: &SigningKey) {
        let msg = self.signable_bytes();
        let sig = key.sign(&msg);
        self.signature = sig.to_bytes();
    }

    /// Verify the signature against the given verifying key.
    pub fn verify(&self, key: &VerifyingKey) -> Result<(), ed25519_dalek::SignatureError> {
        let msg = self.signable_bytes();
        let sig = Signature::from_bytes(&self.signature);
        key.verify(&msg, &sig)
    }
}

/// Deterministic byte representation of an OrientationSummary for signing.
fn orientation_bytes(o: &OrientationSummary) -> Vec<u8> {
    let mut buf = Vec::new();
    buf.extend_from_slice(o.ring_type.as_bytes());
    for organ in &o.organs {
        buf.extend_from_slice(organ.as_bytes());
    }
    for sibling in &o.siblings {
        buf.extend_from_slice(sibling.as_bytes());
    }
    for ns in &o.command_namespaces {
        buf.extend_from_slice(ns.as_bytes());
    }
    buf.extend_from_slice(&o.last_cycle_ns.to_le_bytes());
    buf
}

// inline: exercises module-private items via super::*
#[cfg(test)]
mod tests {
    use super::*;
    use ed25519_dalek::SigningKey;

    fn test_orientation() -> OrientationSummary {
        OrientationSummary {
            ring_type: "test-ring".into(),
            organs: vec!["organ-a".into(), "organ-b".into(), "organ-c".into()],
            siblings: vec!["sibling-x".into()],
            command_namespaces: vec!["ns_a".into(), "ns_b".into()],
            last_cycle_ns: 1_000_000,
        }
    }

    fn test_signing_key() -> SigningKey {
        SigningKey::from_bytes(&[42u8; 32])
    }

    fn test_announce(key: &SigningKey) -> RingAnnounce {
        RingAnnounce {
            ring_fingerprint: [1u8; 32],
            ring_signer_pubkey: key.verifying_key().to_bytes(),
            ring_name: "test-ring".into(),
            capabilities: vec!["deploy".into(), "observe".into()],
            cycle_count: 100,
            orientation: test_orientation(),
            signature: [0u8; 64],
        }
    }

    fn test_envelope() -> DescriptorEnvelope {
        DescriptorEnvelope {
            source_fingerprint: [2u8; 32],
            destination: EnvelopeDestination::Broadcast,
            payload: DescriptorPayload::Descriptor(vec![10, 20, 30]),
            source_cycle: 42,
            timestamp_ns: 999_999,
            signature: [0u8; 64],
        }
    }

    // S1 — RingAnnounce JSON serde roundtrip
    #[test]
    fn announce_json_roundtrip() {
        let key = test_signing_key();
        let mut a = test_announce(&key);
        a.sign(&key);
        let json = serde_json::to_string(&a).unwrap();
        let b: RingAnnounce = serde_json::from_str(&json).unwrap();
        assert_eq!(a, b);
    }

    // S2 — RingAnnounce bincode serde roundtrip
    #[test]
    fn announce_bincode_roundtrip() {
        let key = test_signing_key();
        let mut a = test_announce(&key);
        a.sign(&key);
        let bytes = bincode_legacy::serialize(&a).unwrap();
        let b: RingAnnounce = bincode_legacy::deserialize(&bytes).unwrap();
        assert_eq!(a, b);
    }

    // S3 — DescriptorEnvelope JSON serde roundtrip (Descriptor variant)
    #[test]
    fn envelope_descriptor_json_roundtrip() {
        let key = test_signing_key();
        let mut e = test_envelope();
        e.sign(&key);
        let json = serde_json::to_string(&e).unwrap();
        let f: DescriptorEnvelope = serde_json::from_str(&json).unwrap();
        assert_eq!(e, f);
    }

    // S4 — DescriptorEnvelope bincode serde roundtrip (Command variant)
    #[test]
    fn envelope_command_bincode_roundtrip() {
        let key = test_signing_key();
        let mut e = DescriptorEnvelope {
            source_fingerprint: [3u8; 32],
            destination: EnvelopeDestination::Ring([4u8; 32]),
            payload: DescriptorPayload::Command {
                namespace: "ns_a.create".into(),
                tree: vec![0xCA, 0xFE],
            },
            source_cycle: 7,
            timestamp_ns: 12345,
            signature: [0u8; 64],
        };
        e.sign(&key);
        let bytes = bincode_legacy::serialize(&e).unwrap();
        let f: DescriptorEnvelope = bincode_legacy::deserialize(&bytes).unwrap();
        assert_eq!(e, f);
    }

    // S5 — DescriptorEnvelope serde roundtrip (Orientation variant)
    #[test]
    fn envelope_orientation_bincode_roundtrip() {
        let key = test_signing_key();
        let mut e = DescriptorEnvelope {
            source_fingerprint: [5u8; 32],
            destination: EnvelopeDestination::Broadcast,
            payload: DescriptorPayload::Orientation(test_orientation()),
            source_cycle: 99,
            timestamp_ns: 777,
            signature: [0u8; 64],
        };
        e.sign(&key);
        let bytes = bincode_legacy::serialize(&e).unwrap();
        let f: DescriptorEnvelope = bincode_legacy::deserialize(&bytes).unwrap();
        assert_eq!(e, f);
    }

    // S6 — RingAnnounce Ed25519 signature creation
    #[test]
    fn announce_sign_populates_signature() {
        let key = test_signing_key();
        let mut a = test_announce(&key);
        assert_eq!(a.signature, [0u8; 64]);
        a.sign(&key);
        assert_ne!(a.signature, [0u8; 64]);
    }

    // S7 — RingAnnounce Ed25519 signature verification (valid)
    #[test]
    fn announce_verify_valid() {
        let key = test_signing_key();
        let mut a = test_announce(&key);
        a.sign(&key);
        assert!(a.verify(&key.verifying_key()).is_ok());
    }

    // S8 — RingAnnounce Ed25519 signature verification (tampered)
    #[test]
    fn announce_verify_tampered() {
        let key = test_signing_key();
        let mut a = test_announce(&key);
        a.sign(&key);
        a.cycle_count = 999;
        assert!(a.verify(&key.verifying_key()).is_err());
    }

    // S9 — DescriptorEnvelope Ed25519 signature creation
    #[test]
    fn envelope_sign_populates_signature() {
        let key = test_signing_key();
        let mut e = test_envelope();
        assert_eq!(e.signature, [0u8; 64]);
        e.sign(&key);
        assert_ne!(e.signature, [0u8; 64]);
    }

    // S10 — DescriptorEnvelope Ed25519 signature verification (valid)
    #[test]
    fn envelope_verify_valid() {
        let key = test_signing_key();
        let mut e = test_envelope();
        e.sign(&key);
        assert!(e.verify(&key.verifying_key()).is_ok());
    }

    // S11 — DescriptorEnvelope Ed25519 signature verification (tampered)
    #[test]
    fn envelope_verify_tampered() {
        let key = test_signing_key();
        let mut e = test_envelope();
        e.sign(&key);
        e.source_cycle = 0;
        assert!(e.verify(&key.verifying_key()).is_err());
    }

    // S12 — Namespace constants match META-RING-CROSSING-PROTOCOL
    #[test]
    fn namespace_constants() {
        assert_eq!(federation_ns::ANNOUNCE, "federation.announce");
        assert_eq!(federation_ns::DESCRIPTOR, "federation.descriptor");
        assert_eq!(federation_ns::HEALTH, "federation.health");
        assert_eq!(federation_ns::TOPOLOGY, "federation.topology");
        assert_eq!(federation_ns::COMMAND, "federation.command");
    }

    // S13 — OrientationSummary serde roundtrip
    #[test]
    fn orientation_json_roundtrip() {
        let o = test_orientation();
        let json = serde_json::to_string(&o).unwrap();
        let p: OrientationSummary = serde_json::from_str(&json).unwrap();
        assert_eq!(o, p);
    }

    // S14 — EnvelopeDestination::Broadcast serde roundtrip
    #[test]
    fn envelope_broadcast_bincode_roundtrip() {
        let key = test_signing_key();
        let mut e = test_envelope();
        assert!(matches!(e.destination, EnvelopeDestination::Broadcast));
        e.sign(&key);
        let bytes = bincode_legacy::serialize(&e).unwrap();
        let f: DescriptorEnvelope = bincode_legacy::deserialize(&bytes).unwrap();
        assert_eq!(e, f);
    }

    // S15 — RingFingerprint is [u8; 32] type alias
    #[test]
    fn ring_fingerprint_is_u8_32() {
        let fp: RingFingerprint = [0xABu8; 32];
        let raw: [u8; 32] = fp;
        assert_eq!(raw, [0xABu8; 32]);
    }

    // S16 — PeerRecord JSON serde roundtrip
    #[test]
    fn peer_record_json_roundtrip() {
        let record = PeerRecord {
            fingerprint: [0xAAu8; 32],
            address: "192.168.1.10:9100".into(),
            ring_signer_pubkey: [0xBBu8; 32],
            status: PeerStatus::Connected,
            last_seen_ns: 1_000_000,
            ring_name: Some("test-ring".into()),
        };
        let json = serde_json::to_string(&record).unwrap();
        let decoded: PeerRecord = serde_json::from_str(&json).unwrap();
        assert_eq!(record, decoded);
    }

    // S17 — PeerRecord bincode serde roundtrip
    #[test]
    fn peer_record_bincode_roundtrip() {
        let record = PeerRecord {
            fingerprint: [0xCCu8; 32],
            address: "10.0.0.1:9100".into(),
            ring_signer_pubkey: [0xDDu8; 32],
            status: PeerStatus::Unknown,
            last_seen_ns: 0,
            ring_name: None,
        };
        let bytes = bincode_legacy::serialize(&record).unwrap();
        let decoded: PeerRecord = bincode_legacy::deserialize(&bytes).unwrap();
        assert_eq!(record, decoded);
    }

    // S18 — PeerStatus transitions
    #[test]
    fn peer_status_variants() {
        assert_ne!(PeerStatus::Unknown, PeerStatus::Connected);
        assert_ne!(PeerStatus::Connected, PeerStatus::Disconnected);
        assert_ne!(PeerStatus::Unknown, PeerStatus::Disconnected);
    }

    // S19 — federation_ns::PEERS constant
    #[test]
    fn namespace_peers_constant() {
        assert_eq!(federation_ns::PEERS, "federation.peers");
    }

    // S20 — federation types are agnostic to
    // organ-name conventions. An application may label its six organs (e.g., DIRECTOR / MIRROR
    // / STORE / GUARD / WALL / ORCHESTRATOR; another ring application picks
    // its own labels. soma-som-core must sign + verify identically regardless.
    //
    // Field name `ring_signer_pubkey` (renamed from `director_pubkey` per
    // wire-protocol field-rename carries the FU-position signing
    // key. Application example: DIRECTOR's signing key.
    #[test]
    fn federation_signs_with_arbitrary_organ_labels() {
        let key = test_signing_key();
        let mut announce = RingAnnounce {
            ring_fingerprint: [7u8; 32],
            ring_signer_pubkey: key.verifying_key().to_bytes(),
            ring_name: "custom-ring-application".into(),
            capabilities: vec!["domain-specific".into()],
            cycle_count: 1,
            orientation: OrientationSummary {
                ring_type: "alt-app".into(),
                organs: vec![
                    "α".into(),
                    "β".into(),
                    "γ".into(),
                    "δ".into(),
                    "ε".into(),
                    "ζ".into(),
                ],
                siblings: vec!["arbitrary-sibling".into()],
                command_namespaces: vec!["custom_ns_x".into(), "custom_ns_y".into()],
                last_cycle_ns: 0,
            },
            signature: [0u8; 64],
        };
        announce.sign(&key);
        assert!(announce.verify(&key.verifying_key()).is_ok());

        // Tamper an organ label — signature must fail (proves organs are
        // covered by the signature, i.e., they round-trip identically; the
        // production code does not strip or normalize them).
        announce.orientation.organs[0] = "ω".into();
        assert!(announce.verify(&key.verifying_key()).is_err());
    }

    // S21 — wire-format stability across the
    // `director_pubkey` → `ring_signer_pubkey` source rename. Bincode is
    // positional (field names are not part of the encoded bytes), so the
    // rename must NOT change wire bytes. This test pins the wire format
    // by asserting exact bincode output for a known-fixture announce.
    //
    // If any future schema change alters the byte layout — re-order, type
    // change, new field — this test will fail and force a deliberate
    // wire-protocol decision. Federation peers running pre-rename code
    // interop with post-rename code at the byte level.
    #[test]
    fn federation_byte_format_unchanged_across_rename() {
        // Construct a fully-deterministic announce (no signature applied —
        // signature would depend on the private key and add entropy).
        let announce = RingAnnounce {
            ring_fingerprint: [0x11u8; 32],
            ring_signer_pubkey: [0x22u8; 32],
            ring_name: "wire-fixture".into(),
            capabilities: vec!["cap-a".into()],
            cycle_count: 1234,
            orientation: OrientationSummary {
                ring_type: "fixture".into(),
                organs: vec!["A".into()],
                siblings: vec![],
                command_namespaces: vec!["ns".into()],
                last_cycle_ns: 999,
            },
            signature: [0u8; 64],
        };
        let bytes = bincode_legacy::serialize(&announce).unwrap();

        // Critical position invariants (bincode-1 default config):
        //   ring_fingerprint: bytes 0..32 (raw [u8;32])
        //   ring_signer_pubkey: bytes 32..64 (raw [u8;32]) — was `director_pubkey`
        // The ring_fingerprint is 0x11 × 32; the ring_signer_pubkey is 0x22 × 32.
        // If the rename had changed serde encoding order, byte 32 would differ.
        for i in 0..32 {
            assert_eq!(bytes[i], 0x11, "ring_fingerprint byte {i} drift");
        }
        for i in 32..64 {
            assert_eq!(bytes[i], 0x22, "ring_signer_pubkey byte {i} drift");
        }

        // Round-trip via the same codec confirms decode-side compatibility.
        let decoded: RingAnnounce = bincode_legacy::deserialize(&bytes).unwrap();
        assert_eq!(decoded, announce);

        // Same check for PeerRecord: fingerprint (32) + address (len-prefix +
        // utf8) + ring_signer_pubkey (32) at a computable offset.
        let peer = PeerRecord {
            fingerprint: [0x33u8; 32],
            address: "abc".into(),
            ring_signer_pubkey: [0x44u8; 32],
            status: PeerStatus::Connected,
            last_seen_ns: 0,
            ring_name: None,
        };
        let pbytes = bincode_legacy::serialize(&peer).unwrap();
        // fingerprint at 0..32 = 0x33
        for i in 0..32 {
            assert_eq!(pbytes[i], 0x33, "PeerRecord fingerprint byte {i} drift");
        }
        // address: bincode-1 default config encodes length as fixint u64 LE
        // (8 bytes) followed by raw utf8 ("abc" = 3 bytes). Total 11 bytes.
        // So ring_signer_pubkey begins at offset 32 + 8 + 3 = 43.
        let signer_off = 43;
        for i in 0..32 {
            assert_eq!(
                pbytes[signer_off + i],
                0x44,
                "PeerRecord ring_signer_pubkey byte {i} drift"
            );
        }

        let pdecoded: PeerRecord = bincode_legacy::deserialize(&pbytes).unwrap();
        assert_eq!(pdecoded, peer);
    }
}