enlace 0.2.0

Encrypted mailbox and latest-value slot fan-out.
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
//! Channel addressing.
//!
//! From a 32-byte seed plus a channel kind (mailbox or slot) and a channel name,
//! derives:
//!
//! - a 32-byte AEAD subkey (per kind, per name) — used by `crypto::seal/unseal`
//! - a 16-byte transport-level channel id (per transport, per kind, per name)
//! - a 32-byte iroh gossip topic id (per kind, per name)
//!
//! The HKDF info-string prefixes used for these derivations are deliberately
//! disjoint so a key, transport id, and gossip topic for the same channel cannot
//! collide: domain separation is enforced at the HKDF info layer, not by
//! trimming output bits.
//!
//! Names are restricted to a narrow ASCII subset so that two endpoints that
//! pass byte-equal names derive byte-equal keys/ids without any Unicode
//! normalization step.

use crate::crypto::{AeadKeyBytes, derive_key32, hkdf_sha256};

/// Channel id length in bytes.
pub const CHANNEL_ID_LEN: usize = 16;

/// Iroh gossip topic id length in bytes.
pub const IROH_TOPIC_ID_LEN: usize = 32;

/// Channel name length cap in bytes.
pub const MAX_NAME_LEN: usize = 64;

/// Distinguishes mailbox channels from slot channels in the HKDF context.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ChannelKind {
    Mailbox,
    Slot,
}

impl ChannelKind {
    #[inline]
    pub const fn as_bytes(self) -> &'static [u8] {
        match self {
            ChannelKind::Mailbox => b"mailbox",
            ChannelKind::Slot => b"slot",
        }
    }
}

/// One of the four transport adapters.
///
/// Used both as the discriminator in the channel-id HKDF context (so the same
/// channel name on the same seed yields a distinct 16-byte id per transport)
/// and as the runtime identifier surfaced on received messages and errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TransportKind {
    Http,
    Pkarr,
    Dht,
    Iroh,
}

impl TransportKind {
    #[inline]
    pub const fn as_bytes(self) -> &'static [u8] {
        match self {
            TransportKind::Http => b"http",
            TransportKind::Pkarr => b"pkarr",
            TransportKind::Dht => b"dht",
            TransportKind::Iroh => b"iroh",
        }
    }

    #[inline]
    pub const fn as_str(self) -> &'static str {
        match self {
            TransportKind::Http => "http",
            TransportKind::Pkarr => "pkarr",
            TransportKind::Dht => "dht",
            TransportKind::Iroh => "iroh",
        }
    }
}

impl core::fmt::Display for TransportKind {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameError {
    Empty,
    TooLong,
    InvalidChar,
}

impl core::fmt::Display for NameError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            NameError::Empty => f.write_str("channel name is empty"),
            NameError::TooLong => f.write_str("channel name exceeds 64 bytes"),
            NameError::InvalidChar => {
                f.write_str("channel name contains a byte outside [0-9 a-z - _ / .]")
            }
        }
    }
}

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

/// Validate a channel name against the allowed charset and length rules.
///
/// Allowed bytes: `0-9`, `a-z`, `-`, `_`, `/`, `.`. Length must be 1..=64.
pub fn validate_name(name: &str) -> Result<(), NameError> {
    if name.is_empty() {
        return Err(NameError::Empty);
    }
    if name.len() > MAX_NAME_LEN {
        return Err(NameError::TooLong);
    }
    for &b in name.as_bytes() {
        let ok = matches!(b, b'0'..=b'9' | b'a'..=b'z' | b'-' | b'_' | b'/' | b'.');
        if !ok {
            return Err(NameError::InvalidChar);
        }
    }
    Ok(())
}

/// Derive the per-channel AEAD key.
///
/// `info = b"enlace/v1/key/aead/" || kind || b"/" || name`
///
/// Returned buffer is wrapped in `Zeroizing` and wiped on drop.
pub fn channel_aead_key(
    seed: &[u8; 32],
    kind: ChannelKind,
    name: &str,
) -> Result<AeadKeyBytes, NameError> {
    validate_name(name)?;
    let kind_bytes = kind.as_bytes();
    let name_bytes = name.as_bytes();
    let mut info =
        Vec::with_capacity(b"enlace/v1/key/aead/".len() + kind_bytes.len() + 1 + name_bytes.len());
    info.extend_from_slice(b"enlace/v1/key/aead/");
    info.extend_from_slice(kind_bytes);
    info.push(b'/');
    info.extend_from_slice(name_bytes);
    Ok(derive_key32(seed, &info))
}

/// Derive the per-transport channel id.
///
/// `info = b"enlace/v1/id/" || transport || b"/" || kind || b"/" || name`
///
/// HKDF output is truncated to `CHANNEL_ID_LEN` (16 bytes).
pub fn channel_id(
    seed: &[u8; 32],
    transport: TransportKind,
    kind: ChannelKind,
    name: &str,
) -> Result<[u8; CHANNEL_ID_LEN], NameError> {
    validate_name(name)?;
    let transport_bytes = transport.as_bytes();
    let kind_bytes = kind.as_bytes();
    let name_bytes = name.as_bytes();
    let mut info = Vec::with_capacity(
        b"enlace/v1/id/".len()
            + transport_bytes.len()
            + 1
            + kind_bytes.len()
            + 1
            + name_bytes.len(),
    );
    info.extend_from_slice(b"enlace/v1/id/");
    info.extend_from_slice(transport_bytes);
    info.push(b'/');
    info.extend_from_slice(kind_bytes);
    info.push(b'/');
    info.extend_from_slice(name_bytes);
    let mut out = [0u8; CHANNEL_ID_LEN];
    hkdf_sha256(seed, b"", &info, &mut out);
    Ok(out)
}

/// Derive the iroh gossip topic id.
///
/// `info = b"enlace/v1/id/iroh-topic/" || kind || b"/" || name`
pub fn iroh_topic_id(
    seed: &[u8; 32],
    kind: ChannelKind,
    name: &str,
) -> Result<[u8; IROH_TOPIC_ID_LEN], NameError> {
    validate_name(name)?;
    let kind_bytes = kind.as_bytes();
    let name_bytes = name.as_bytes();
    let mut info = Vec::with_capacity(
        b"enlace/v1/id/iroh-topic/".len() + kind_bytes.len() + 1 + name_bytes.len(),
    );
    info.extend_from_slice(b"enlace/v1/id/iroh-topic/");
    info.extend_from_slice(kind_bytes);
    info.push(b'/');
    info.extend_from_slice(name_bytes);
    let mut out = [0u8; IROH_TOPIC_ID_LEN];
    hkdf_sha256(seed, b"", &info, &mut out);
    Ok(out)
}

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

    use super::*;

    const SEED_A: [u8; 32] = [0xA1u8; 32];
    const SEED_B: [u8; 32] = [0xB2u8; 32];

    // -- name validation -----------------------------------------------------

    #[test]
    fn name_empty_rejected() {
        assert_eq!(validate_name(""), Err(NameError::Empty));
    }

    #[test]
    fn name_max_length_accepted() {
        let n = "a".repeat(MAX_NAME_LEN);
        assert!(validate_name(&n).is_ok());
    }

    #[test]
    fn name_over_max_rejected() {
        let n = "a".repeat(MAX_NAME_LEN + 1);
        assert_eq!(validate_name(&n), Err(NameError::TooLong));
    }

    #[test]
    fn name_full_charset_accepted() {
        let all_ok = "abcdefghijklmnopqrstuvwxyz0123456789-_./";
        assert!(validate_name(all_ok).is_ok());
    }

    #[test]
    fn name_uppercase_rejected() {
        assert_eq!(validate_name("Foo"), Err(NameError::InvalidChar));
        assert_eq!(validate_name("FOO"), Err(NameError::InvalidChar));
    }

    #[test]
    fn name_space_rejected() {
        assert_eq!(validate_name("a b"), Err(NameError::InvalidChar));
    }

    #[test]
    fn name_special_ascii_bytes_rejected() {
        // Bytes inside printable ASCII that are NOT in the allowed set.
        for bad in [b':', b'+', b'=', b'@', b'#', b'%', b'*', b'~', b' ', b'\t'] {
            let raw = [b'a', bad, b'b'];
            let s = std::str::from_utf8(&raw).expect("ASCII test bytes are valid UTF-8");
            assert_eq!(
                validate_name(s),
                Err(NameError::InvalidChar),
                "byte 0x{bad:02X} should be rejected"
            );
        }
    }

    #[test]
    fn name_uppercase_full_alphabet_rejected() {
        for c in b'A'..=b'Z' {
            let raw = [c];
            let s = std::str::from_utf8(&raw).unwrap();
            assert_eq!(
                validate_name(s),
                Err(NameError::InvalidChar),
                "uppercase {s} should be rejected"
            );
        }
    }

    #[test]
    fn name_single_byte_accepted() {
        assert!(validate_name("a").is_ok());
        assert!(validate_name("0").is_ok());
        assert!(validate_name("-").is_ok());
        assert!(validate_name("/").is_ok());
        assert!(validate_name(".").is_ok());
        assert!(validate_name("_").is_ok());
    }

    // -- channel AEAD key ----------------------------------------------------

    #[test]
    fn aead_key_deterministic() {
        let k1 = channel_aead_key(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        let k2 = channel_aead_key(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        assert_eq!(k1.as_ref(), k2.as_ref());
        assert_eq!(k1.as_ref().len(), crate::crypto::AEAD_KEY_LEN);
    }

    #[test]
    fn aead_key_diverges_by_kind() {
        let mailbox = channel_aead_key(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        let slot = channel_aead_key(&SEED_A, ChannelKind::Slot, "alpha").unwrap();
        assert_ne!(mailbox.as_ref(), slot.as_ref());
    }

    #[test]
    fn aead_key_diverges_by_name() {
        let a = channel_aead_key(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        let b = channel_aead_key(&SEED_A, ChannelKind::Mailbox, "beta").unwrap();
        assert_ne!(a.as_ref(), b.as_ref());
    }

    #[test]
    fn aead_key_diverges_by_seed() {
        let a = channel_aead_key(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        let b = channel_aead_key(&SEED_B, ChannelKind::Mailbox, "alpha").unwrap();
        assert_ne!(a.as_ref(), b.as_ref());
    }

    #[test]
    fn aead_key_rejects_invalid_name() {
        assert_eq!(
            channel_aead_key(&SEED_A, ChannelKind::Mailbox, "").err(),
            Some(NameError::Empty)
        );
        assert_eq!(
            channel_aead_key(&SEED_A, ChannelKind::Slot, "Bad").err(),
            Some(NameError::InvalidChar)
        );
    }

    // -- channel id ----------------------------------------------------------

    #[test]
    fn channel_id_deterministic_and_sized() {
        let id1 = channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, "alpha").unwrap();
        let id2 = channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, "alpha").unwrap();
        assert_eq!(id1, id2);
        assert_eq!(id1.len(), CHANNEL_ID_LEN);
    }

    #[test]
    fn channel_id_diverges_by_transport() {
        let http = channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, "alpha").unwrap();
        let pkarr =
            channel_id(&SEED_A, TransportKind::Pkarr, ChannelKind::Mailbox, "alpha").unwrap();
        let dht = channel_id(&SEED_A, TransportKind::Dht, ChannelKind::Mailbox, "alpha").unwrap();
        let iroh = channel_id(&SEED_A, TransportKind::Iroh, ChannelKind::Mailbox, "alpha").unwrap();
        // All four must be pairwise distinct.
        let all = [http, pkarr, dht, iroh];
        for i in 0..all.len() {
            for j in (i + 1)..all.len() {
                assert_ne!(all[i], all[j], "transports {i} and {j} produced equal ids");
            }
        }
    }

    #[test]
    fn channel_id_diverges_by_kind() {
        let mailbox =
            channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, "alpha").unwrap();
        let slot = channel_id(&SEED_A, TransportKind::Http, ChannelKind::Slot, "alpha").unwrap();
        assert_ne!(mailbox, slot);
    }

    #[test]
    fn channel_id_diverges_by_name() {
        let a = channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, "alpha").unwrap();
        let b = channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, "beta").unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn channel_id_diverges_by_seed() {
        let a = channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, "alpha").unwrap();
        let b = channel_id(&SEED_B, TransportKind::Http, ChannelKind::Mailbox, "alpha").unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn channel_id_rejects_invalid_name() {
        assert_eq!(
            channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, "").err(),
            Some(NameError::Empty)
        );
        let too_long = "a".repeat(MAX_NAME_LEN + 1);
        assert_eq!(
            channel_id(
                &SEED_A,
                TransportKind::Http,
                ChannelKind::Mailbox,
                &too_long
            )
            .err(),
            Some(NameError::TooLong)
        );
    }

    // -- iroh topic id -------------------------------------------------------

    #[test]
    fn iroh_topic_id_deterministic_and_sized() {
        let id1 = iroh_topic_id(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        let id2 = iroh_topic_id(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();

        assert_eq!(id1, id2);
        assert_eq!(id1.len(), IROH_TOPIC_ID_LEN);
    }

    #[test]
    fn iroh_topic_id_diverges_by_kind() {
        let mailbox = iroh_topic_id(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        let slot = iroh_topic_id(&SEED_A, ChannelKind::Slot, "alpha").unwrap();

        assert_ne!(mailbox, slot);
    }

    #[test]
    fn iroh_topic_id_diverges_by_name() {
        let a = iroh_topic_id(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        let b = iroh_topic_id(&SEED_A, ChannelKind::Mailbox, "beta").unwrap();

        assert_ne!(a, b);
    }

    #[test]
    fn iroh_topic_id_diverges_by_seed() {
        let a = iroh_topic_id(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        let b = iroh_topic_id(&SEED_B, ChannelKind::Mailbox, "alpha").unwrap();

        assert_ne!(a, b);
    }

    #[test]
    fn iroh_topic_id_rejects_invalid_name() {
        assert_eq!(
            iroh_topic_id(&SEED_A, ChannelKind::Mailbox, "").err(),
            Some(NameError::Empty)
        );
        assert_eq!(
            iroh_topic_id(&SEED_A, ChannelKind::Mailbox, "Bad").err(),
            Some(NameError::InvalidChar)
        );
    }

    // -- cross-domain separation -------------------------------------------

    #[test]
    fn aead_key_and_channel_id_share_no_prefix() {
        // The AEAD key context (`enlace/v1/key/aead/...`) and the id context
        // (`enlace/v1/id/...`) are disjoint by construction; a sanity check
        // that they don't collide on their first 16 bytes either.
        let key = channel_aead_key(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        let id = channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, "alpha").unwrap();
        assert_ne!(&key.as_ref()[..CHANNEL_ID_LEN], &id[..]);
    }

    #[test]
    fn iroh_topic_id_and_channel_id_share_no_prefix() {
        let topic = iroh_topic_id(&SEED_A, ChannelKind::Mailbox, "alpha").unwrap();
        let id = channel_id(&SEED_A, TransportKind::Iroh, ChannelKind::Mailbox, "alpha").unwrap();

        assert_ne!(&topic[..CHANNEL_ID_LEN], &id[..]);
    }

    proptest! {
        #[test]
        fn valid_names_derive_deterministic_keys_and_ids(name in "[a-z0-9_./-]{1,64}") {
            let key_a = channel_aead_key(&SEED_A, ChannelKind::Mailbox, &name).unwrap();
            let key_b = channel_aead_key(&SEED_A, ChannelKind::Mailbox, &name).unwrap();
            prop_assert_eq!(key_a.as_ref(), key_b.as_ref());

            let id_a = channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, &name).unwrap();
            let id_b = channel_id(&SEED_A, TransportKind::Http, ChannelKind::Mailbox, &name).unwrap();
            prop_assert_eq!(id_a, id_b);

            let topic_a = iroh_topic_id(&SEED_A, ChannelKind::Mailbox, &name).unwrap();
            let topic_b = iroh_topic_id(&SEED_A, ChannelKind::Mailbox, &name).unwrap();
            prop_assert_eq!(topic_a, topic_b);
        }

        #[test]
        fn names_outside_allowed_charset_are_rejected(name in ".{1,64}") {
            prop_assume!(name.as_bytes().iter().any(|b| !matches!(b, b'0'..=b'9' | b'a'..=b'z' | b'-' | b'_' | b'/' | b'.')));
            prop_assert!(validate_name(&name).is_err());
        }
    }
}