Skip to main content

offline_protocol_core/
address.rs

1//! Self-certifying protocol addresses.
2//!
3//! An address is a bech32m encoding of `0x01 ‖ SHA-256(ed25519_pub)[..20]`,
4//! rendered as `off1…` (44 characters). Because the payload is a hash of the
5//! identity key, an address authenticates itself: a peer claiming an address
6//! can be checked by re-deriving it from the public key it presents, with no
7//! trust-on-first-use pin store in between.
8//!
9//! This module never touches key material — hashing happens upstream (see
10//! `MlsManager::derive_address`); [`Address`] is constructed from the already
11//! truncated hash.
12//!
13//! # Exactly one string form
14//!
15//! Every payload has exactly one accepted spelling. [`Address::from_str`]
16//! rejects uppercase input, the non-`m` bech32 checksum, wrong HRP, wrong
17//! version byte, wrong payload length, and — critically — encodings that
18//! decode to the right payload but are not the canonical spelling of it.
19//! The last class is not hypothetical: the `bech32` crate's decoder discards
20//! the trailing sub-byte bits without checking they are zero, and its
21//! fes-to-bytes length rule (`n * 5 / 8`) maps both 34- and 35-character data
22//! parts onto a 21-byte payload. Both shapes are checksum-valid and both are
23//! caught here by re-encoding and requiring byte-for-byte equality with the
24//! input. Briar's "spare bit" address bug is the reference failure for what
25//! happens when this is skipped.
26
27use std::fmt;
28use std::str::FromStr;
29
30use bech32::primitives::decode::CheckedHrpstring;
31use bech32::{Bech32m, Hrp};
32use serde::{Deserialize, Serialize};
33
34/// Why an address string was rejected by [`Address::from_str`].
35// Adding a variant to a public error enum is a breaking change without
36// this attribute; downstream crates must carry a wildcard arm.
37#[non_exhaustive]
38#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
39pub enum AddressError {
40    /// The string contains ASCII uppercase.
41    ///
42    /// BIP-173 permits an all-uppercase spelling and the `bech32` crate
43    /// accepts it; the protocol admits the lowercase form only.
44    #[error("address is not lowercase (the canonical form is lowercase-only)")]
45    NotLowercase,
46    /// The string is not structurally valid bech32m: bad charset, missing or
47    /// misplaced separator, mixed case, or a checksum that is absent, corrupt,
48    /// or computed with the original bech32 constant instead of bech32m.
49    #[error("address is not valid bech32m: {reason}")]
50    InvalidBech32m {
51        /// Rendering of the underlying `bech32` decode error.
52        reason: String,
53    },
54    /// Valid bech32m, but the human-readable part is not [`Address::HRP_STR`].
55    #[error("address has human-readable part '{found}', expected '{expected}'")]
56    HrpMismatch {
57        /// Human-readable part found in the input.
58        found: String,
59        /// The required human-readable part.
60        expected: &'static str,
61    },
62    /// The decoded payload is not [`Address::PAYLOAD_LEN`] bytes.
63    #[error("address payload is {len} bytes, expected {expected}")]
64    PayloadLength {
65        /// Decoded payload length.
66        len: usize,
67        /// Required payload length.
68        expected: usize,
69    },
70    /// The payload does not start with a supported version byte.
71    #[error("address version byte is {found:#04x}, expected {expected:#04x}")]
72    VersionMismatch {
73        /// Version byte found in the payload.
74        found: u8,
75        /// The only version byte this build understands.
76        expected: u8,
77    },
78    /// The string decodes to a well-formed payload but is not that payload's
79    /// canonical spelling — non-zero padding bits, or a data part padded out
80    /// with extra characters that truncate to the same bytes.
81    ///
82    /// Accepting these would give one identity several valid addresses, so
83    /// they are rejected rather than normalized.
84    #[error("address is a non-canonical encoding of its payload")]
85    NonCanonical,
86}
87
88/// A self-certifying protocol address: `off1…`.
89///
90/// # Ordering
91///
92/// [`Ord`] compares the underlying hash bytes, **not** the rendered string.
93/// The two orders differ: the bech32 charset (`qpzry9x8gf2tvdw0s3jn54khce6mua7l`)
94/// is not monotonic in ASCII — value 4 renders as `y` (0x79) and value 5 as
95/// `9` (0x39) — and a string comparison would also weigh the checksum
96/// characters. Protocol tiebreakers (both-create session ownership, leave
97/// election, admin auto-promotion, fork leader) must therefore compare
98/// `Address` values, never their `Display` output.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
100pub struct Address {
101    hash: [u8; Address::HASH_LEN],
102}
103
104impl Address {
105    /// Human-readable part carried by every address.
106    pub const HRP_STR: &'static str = "off";
107
108    /// The only address version this build understands.
109    pub const VERSION: u8 = 0x01;
110
111    /// Length of the truncated identity-key hash, in bytes.
112    ///
113    /// 160 bits, which is a **second-preimage** margin of ~2^160 and a
114    /// **collision** margin of ~2^80 — the birthday bound on the same
115    /// truncation. Both are stated here because they buy different things and
116    /// only the first is what the impersonation claim rests on:
117    ///
118    /// - ~2^160 is the cost of aiming at an address that already exists:
119    ///   producing a key that derives to *someone else's* address. That is the
120    ///   attack the sender-derivation gate replaced the trust-pin store to
121    ///   stop, and it is the figure the guides and changelog quote.
122    /// - ~2^80 is the cost of producing *two* identity keys that share one
123    ///   address, neither fixed in advance. It impersonates nobody, but it does
124    ///   let a single entity hold two signing keys that are indistinguishable
125    ///   at the address layer — enough to equivocate, and enough to defeat the
126    ///   "one identity cannot hold two leaves" property that the MLS leaf
127    ///   binding otherwise inherits from MLS signature-key uniqueness.
128    ///
129    /// ~2^80 is below the ~2^128 a greenfield design would target, and is a
130    /// deliberate trade rather than an oversight: every mesh frame carries a
131    /// sender and a recipient address, and BLE budget is the binding
132    /// constraint. Widening the hash changes the wire, so it is a [`VERSION`]
133    /// bump and a migration, not a patch.
134    ///
135    /// [`VERSION`]: Address::VERSION
136    pub const HASH_LEN: usize = 20;
137
138    /// Length of the encoded payload: version byte followed by the hash.
139    pub const PAYLOAD_LEN: usize = 1 + Self::HASH_LEN;
140
141    /// Length of the canonical string form.
142    ///
143    /// `off` (3) + separator (1) + data (34) + checksum (6). The data part is
144    /// 34 characters because 21 bytes is 168 bits, which needs 34 five-bit
145    /// groups and leaves 2 padding bits.
146    pub const ENCODED_LEN: usize = 44;
147
148    /// `Hrp` form of [`Self::HRP_STR`].
149    ///
150    /// `parse_unchecked` is the only `const` constructor and performs no
151    /// validation; `hrp_const_matches_parsed` pins it against the checked
152    /// parser.
153    const HRP: Hrp = Hrp::parse_unchecked(Self::HRP_STR);
154
155    /// Builds an address from a truncated identity-key hash.
156    ///
157    /// Infallible: every 20-byte value is a valid address payload.
158    pub fn from_hash_bytes(hash: [u8; Self::HASH_LEN]) -> Self {
159        Self { hash }
160    }
161
162    /// Builds an address from a `version ‖ hash` payload.
163    pub fn from_payload(payload: &[u8]) -> Result<Self, AddressError> {
164        if payload.len() != Self::PAYLOAD_LEN {
165            return Err(AddressError::PayloadLength {
166                len: payload.len(),
167                expected: Self::PAYLOAD_LEN,
168            });
169        }
170        if payload[0] != Self::VERSION {
171            return Err(AddressError::VersionMismatch {
172                found: payload[0],
173                expected: Self::VERSION,
174            });
175        }
176        let mut hash = [0u8; Self::HASH_LEN];
177        hash.copy_from_slice(&payload[1..]);
178        Ok(Self { hash })
179    }
180
181    /// Returns the truncated identity-key hash.
182    pub fn hash_bytes(&self) -> &[u8; Self::HASH_LEN] {
183        &self.hash
184    }
185
186    /// Returns the `version ‖ hash` payload.
187    pub fn payload(&self) -> [u8; Self::PAYLOAD_LEN] {
188        let mut payload = [0u8; Self::PAYLOAD_LEN];
189        payload[0] = Self::VERSION;
190        payload[1..].copy_from_slice(&self.hash);
191        payload
192    }
193
194    /// Returns the address version byte.
195    pub fn version(&self) -> u8 {
196        Self::VERSION
197    }
198}
199
200impl fmt::Display for Address {
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        // `encode_lower_to_fmt` writes straight to the formatter and always
203        // emits lowercase. Its error covers only a formatter failure and an
204        // over-long code, the latter unreachable for a fixed 21-byte payload.
205        bech32::encode_lower_to_fmt::<Bech32m, _>(f, Self::HRP, &self.payload())
206            .map_err(|_| fmt::Error)
207    }
208}
209
210impl FromStr for Address {
211    type Err = AddressError;
212
213    fn from_str(s: &str) -> Result<Self, Self::Err> {
214        // The crate rejects mixed case but accepts an all-uppercase string;
215        // the protocol accepts one spelling, so screen case out first.
216        if s.bytes().any(|b| b.is_ascii_uppercase()) {
217            return Err(AddressError::NotLowercase);
218        }
219
220        // `CheckedHrpstring::new::<Bech32m>` pins the checksum algorithm.
221        // `bech32::decode` must never be used here: it validates bech32m and
222        // then silently falls back to the original bech32 constant.
223        let checked =
224            CheckedHrpstring::new::<Bech32m>(s).map_err(|e| AddressError::InvalidBech32m {
225                reason: e.to_string(),
226            })?;
227
228        if checked.hrp() != Self::HRP {
229            return Err(AddressError::HrpMismatch {
230                found: checked.hrp().to_string(),
231                expected: Self::HRP_STR,
232            });
233        }
234
235        let payload: Vec<u8> = checked.byte_iter().collect();
236        let address = Self::from_payload(&payload)?;
237
238        // Every remaining degree of freedom — the two padding bits, and a
239        // 35-character data part that truncates to the same 21 bytes — leaves
240        // a checksum-valid string that decodes to this exact payload, so no
241        // earlier check can see it. Re-encoding and requiring byte equality
242        // collapses them all: one payload, one string.
243        if address.to_string() != s {
244            return Err(AddressError::NonCanonical);
245        }
246
247        Ok(address)
248    }
249}
250
251impl Serialize for Address {
252    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
253        serializer.collect_str(self)
254    }
255}
256
257impl<'de> Deserialize<'de> for Address {
258    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
259        let s = String::deserialize(deserializer)?;
260        s.parse().map_err(serde::de::Error::custom)
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    // Golden vectors. Generated with the BIP-350 reference implementation
269    // (github.com/sipa/bech32, ref/python/segwit_addr.py) — an implementation
270    // independent of the `bech32` crate, so agreement between these literals
271    // and the code below is a genuine two-implementation cross-check.
272    //
273    // These strings are the protocol's addressing format. Changing one means
274    // every peer's identity changed: re-derive them from the reference
275    // implementation, never edit them to match new code output.
276
277    /// SHA-256 of the RFC 8032 §7.1 TEST 1 Ed25519 public key, truncated.
278    const RFC8032_TV1_HASH: [u8; 20] = [
279        0x21, 0xfe, 0x31, 0xdf, 0xa1, 0x54, 0xa2, 0x61, 0x62, 0x6b, 0xf8, 0x54, 0x04, 0x6f, 0xd2,
280        0x27, 0x1b, 0x7b, 0xed, 0x4b,
281    ];
282    const RFC8032_TV1_ADDR: &str = "off1qysluvwl5922yctzd0u9gpr06gn3k7ldfvgtwgvn";
283
284    const ZEROS_HASH: [u8; 20] = [0u8; 20];
285    const ZEROS_ADDR: &str = "off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqn8antf";
286
287    const FF_HASH: [u8; 20] = [0xffu8; 20];
288    const FF_ADDR: &str = "off1q8llllllllllllllllllllllllllllllluvweh4p";
289
290    const RAMP_HASH: [u8; 20] = [
291        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
292    ];
293    const RAMP_ADDR: &str = "off1qyqqzqsrqszsvpcgpy9qkrqdpc83qygjzvpgkpr5";
294
295    fn vectors() -> [([u8; 20], &'static str); 4] {
296        [
297            (RFC8032_TV1_HASH, RFC8032_TV1_ADDR),
298            (ZEROS_HASH, ZEROS_ADDR),
299            (FF_HASH, FF_ADDR),
300            (RAMP_HASH, RAMP_ADDR),
301        ]
302    }
303
304    #[test]
305    fn encodes_reference_vectors() {
306        for (hash, expected) in vectors() {
307            let rendered = Address::from_hash_bytes(hash).to_string();
308            assert_eq!(rendered, expected);
309            assert_eq!(rendered.len(), Address::ENCODED_LEN);
310        }
311    }
312
313    #[test]
314    fn decodes_reference_vectors() {
315        for (hash, encoded) in vectors() {
316            let address: Address = encoded.parse().expect("reference vector must parse");
317            assert_eq!(address.hash_bytes(), &hash);
318            assert_eq!(address.version(), Address::VERSION);
319        }
320    }
321
322    #[test]
323    fn reencoding_a_parsed_vector_is_byte_identical() {
324        for (_, encoded) in vectors() {
325            let address: Address = encoded.parse().expect("reference vector must parse");
326            assert_eq!(address.to_string(), encoded);
327        }
328    }
329
330    #[test]
331    fn roundtrips_arbitrary_hashes() {
332        // Deterministic spread without pulling in a rng dev-dependency.
333        let mut state: u64 = 0x2545_F491_4F6C_DD1D;
334        for _ in 0..256 {
335            let mut hash = [0u8; Address::HASH_LEN];
336            for byte in hash.iter_mut() {
337                state = state
338                    .wrapping_mul(6364136223846793005)
339                    .wrapping_add(1442695040888963407);
340                *byte = (state >> 33) as u8;
341            }
342            let address = Address::from_hash_bytes(hash);
343            let encoded = address.to_string();
344            assert_eq!(encoded.len(), Address::ENCODED_LEN);
345            assert_eq!(encoded.parse::<Address>().expect("roundtrip"), address);
346        }
347    }
348
349    #[test]
350    fn payload_roundtrips() {
351        let address = Address::from_hash_bytes(RAMP_HASH);
352        let payload = address.payload();
353        assert_eq!(payload[0], Address::VERSION);
354        assert_eq!(&payload[1..], &RAMP_HASH);
355        assert_eq!(Address::from_payload(&payload), Ok(address));
356    }
357
358    #[test]
359    fn hrp_const_matches_parsed() {
360        // `Hrp::parse_unchecked` performs no validation, so pin the const
361        // against the checked parser.
362        let parsed = Hrp::parse(Address::HRP_STR).expect("hrp must be valid");
363        assert_eq!(parsed, Address::HRP);
364    }
365
366    #[test]
367    fn serde_uses_the_canonical_string() {
368        let address = Address::from_hash_bytes(RFC8032_TV1_HASH);
369        let json = serde_json::to_string(&address).expect("serialize");
370        assert_eq!(json, format!("\"{RFC8032_TV1_ADDR}\""));
371        let back: Address = serde_json::from_str(&json).expect("deserialize");
372        assert_eq!(back, address);
373    }
374
375    #[test]
376    fn serde_rejects_non_canonical_forms() {
377        for bad in [
378            ZEROS_ADDR.to_uppercase(),
379            // Non-zero padding bits, valid checksum.
380            "off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqra5g99k".to_string(),
381        ] {
382            let json = format!("\"{bad}\"");
383            assert!(serde_json::from_str::<Address>(&json).is_err(), "{bad}");
384        }
385    }
386
387    #[test]
388    fn ord_follows_hash_bytes_not_the_rendered_string() {
389        let low = Address::from_hash_bytes(ZEROS_HASH);
390        let high = Address::from_hash_bytes(FF_HASH);
391        assert!(low < high);
392        assert_eq!(low.hash_bytes() < high.hash_bytes(), low < high);
393
394        // The two orders genuinely disagree, which is why tiebreakers must not
395        // compare rendered strings: value 4 encodes as 'y' (0x79) and value 5
396        // as '9' (0x39), inverting the comparison.
397        let mut a = ZEROS_HASH;
398        a[0] = 0x20; // leading fe = 4 -> 'y'
399        let mut b = ZEROS_HASH;
400        b[0] = 0x28; // leading fe = 5 -> '9'
401        let (a, b) = (Address::from_hash_bytes(a), Address::from_hash_bytes(b));
402        assert!(a < b, "byte order");
403        assert!(a.to_string() > b.to_string(), "string order inverts");
404    }
405
406    #[test]
407    fn rejects_uppercase_and_mixed_case() {
408        // All-uppercase is a valid bech32m string per BIP-173 and the crate
409        // accepts it; the protocol must not.
410        assert_eq!(
411            ZEROS_ADDR.to_uppercase().parse::<Address>(),
412            Err(AddressError::NotLowercase)
413        );
414        let mixed = format!("{}N8antf", &ZEROS_ADDR[..ZEROS_ADDR.len() - 6]);
415        assert_eq!(mixed.parse::<Address>(), Err(AddressError::NotLowercase));
416    }
417
418    #[test]
419    fn rejects_wrong_hrp() {
420        // Same payload, HRP "ofx", freshly checksummed.
421        let other = "ofx1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2e32t6";
422        assert_eq!(
423            other.parse::<Address>(),
424            Err(AddressError::HrpMismatch {
425                found: "ofx".to_string(),
426                expected: Address::HRP_STR,
427            })
428        );
429    }
430
431    #[test]
432    fn rejects_the_original_bech32_checksum() {
433        // Same payload and HRP, checksummed with bech32 instead of bech32m.
434        // `bech32::decode` would accept this; `CheckedHrpstring::<Bech32m>`
435        // must not.
436        let bech32_variant = "off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqxmdlwt";
437        assert!(matches!(
438            bech32_variant.parse::<Address>(),
439            Err(AddressError::InvalidBech32m { .. })
440        ));
441    }
442
443    #[test]
444    fn rejects_corrupted_characters() {
445        let mut corrupted = ZEROS_ADDR.to_string();
446        corrupted.pop();
447        corrupted.push('p'); // valid charset member, wrong checksum
448        assert!(matches!(
449            corrupted.parse::<Address>(),
450            Err(AddressError::InvalidBech32m { .. })
451        ));
452
453        // 'b', 'i', 'o' and '1' are excluded from the bech32 charset.
454        for bad_char in ['b', 'i', 'o'] {
455            let mut off_charset = ZEROS_ADDR.to_string();
456            off_charset.pop();
457            off_charset.push(bad_char);
458            assert!(
459                matches!(
460                    off_charset.parse::<Address>(),
461                    Err(AddressError::InvalidBech32m { .. })
462                ),
463                "{bad_char}"
464            );
465        }
466    }
467
468    #[test]
469    fn rejects_unsupported_version_bytes() {
470        for (encoded, expected_version) in [
471            ("off1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqkynkkv", 0x00u8),
472            ("off1qgqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqquz0u9x", 0x02),
473            ("off1luqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqn347dq", 0xff),
474        ] {
475            assert_eq!(
476                encoded.parse::<Address>(),
477                Err(AddressError::VersionMismatch {
478                    found: expected_version,
479                    expected: Address::VERSION,
480                })
481            );
482        }
483    }
484
485    #[test]
486    fn rejects_wrong_payload_lengths() {
487        // 20-byte payload (19-byte hash) and 22-byte payload (21-byte hash),
488        // each correctly checksummed.
489        for (encoded, len) in [
490            ("off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqxfx3pw", 20usize),
491            ("off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqkev2nx", 22),
492        ] {
493            assert_eq!(
494                encoded.parse::<Address>(),
495                Err(AddressError::PayloadLength {
496                    len,
497                    expected: Address::PAYLOAD_LEN,
498                })
499            );
500        }
501    }
502
503    #[test]
504    fn rejects_non_zero_padding_bits() {
505        // 21 bytes is 168 bits carried in 34 five-bit groups, leaving 2
506        // padding bits. Each mutant sets those bits and carries a freshly
507        // computed, valid bech32m checksum, so it decodes to exactly the
508        // all-zeros payload — the `bech32` crate discards the dirty bits
509        // without complaint. This is the Briar "spare bit" bug; these three
510        // assertions are the regression guard against reintroducing it.
511        for mutant in [
512            "off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpw3fxkm",
513            "off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzqzuscy",
514            "off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqra5g99k",
515        ] {
516            assert_eq!(
517                mutant.parse::<Address>(),
518                Err(AddressError::NonCanonical),
519                "{mutant}"
520            );
521            // The canonical form of that payload parses, proving the mutant is
522            // a second spelling rather than a different address.
523            assert!(ZEROS_ADDR.parse::<Address>().is_ok());
524        }
525    }
526
527    #[test]
528    fn rejects_over_long_data_parts() {
529        // The crate's fes-to-bytes rule is `n * 5 / 8`, so a 35-character data
530        // part also yields 21 bytes: a checksum-valid second spelling that the
531        // length and version checks cannot see.
532        for mutant in [
533            "off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqj7v8n5",
534            "off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqp0gcjwx",
535            "off1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlcjhrel",
536        ] {
537            assert_eq!(
538                mutant.parse::<Address>(),
539                Err(AddressError::NonCanonical),
540                "{mutant}"
541            );
542        }
543    }
544
545    #[test]
546    fn rejects_structural_garbage() {
547        for bad in [
548            "",
549            "off",
550            "off1",
551            "off1qqq",
552            "1qyqqqq",
553            ZEROS_ADDR.trim_end_matches('f'),
554        ] {
555            assert!(
556                matches!(
557                    bad.parse::<Address>(),
558                    Err(AddressError::InvalidBech32m { .. })
559                ),
560                "{bad:?}"
561            );
562        }
563    }
564
565    #[test]
566    fn from_payload_rejects_bad_input() {
567        assert_eq!(
568            Address::from_payload(&[]),
569            Err(AddressError::PayloadLength {
570                len: 0,
571                expected: Address::PAYLOAD_LEN,
572            })
573        );
574        let mut payload = [0u8; Address::PAYLOAD_LEN];
575        payload[0] = 0x02;
576        assert_eq!(
577            Address::from_payload(&payload),
578            Err(AddressError::VersionMismatch {
579                found: 0x02,
580                expected: Address::VERSION,
581            })
582        );
583    }
584}