Skip to main content

syncspin_core/pairing/
code.rs

1//! The dynamic pairing code: its commitment and the derivation both sides repeat.
2//!
3//! `pairing.md` binds a per-session code to the Noise handshake and to one nonce from each side:
4//!
5//! ```text
6//! commit_B = SHA-256("sendspin-pair-commit-v1" || nonce_B)
7//! digest   = SHA-256("sendspin-pairing-code-derive-v1" || h || nonce_A || nonce_B)
8//! ```
9//!
10//! `commit_B` travels in `client/pair-init`, before any value from the server is known, so the
11//! client is bound to the `nonce_B` it later reveals under the CPace output. The digest yields the
12//! code in one of two emission formats: the six ASCII digits of `digits` (also CPace's `PRS`) or
13//! the first 24 bytes of the digest, carried as a version-1 [token] in `qr_code`.
14//!
15//! # Secret handling
16//!
17//! `nonce_B` is a secret until it is revealed, sealed, in `client/pair-confirm`; [`commitment`]
18//! takes it as bytes and neither function here formats any input. [`DynamicCode`] has no `Debug`
19//! implementation, so the code - which the operator is meant to see - cannot reach a log line by
20//! accident either: a caller emits it deliberately, through the client's event stream.
21//!
22//! The module is behind the `pairing-code` feature with [`pake`](super::pake) and
23//! [`wrap`](super::wrap): only the code flows derive a code.
24
25use sha2::{Digest, Sha256};
26
27use super::token;
28
29/// The label that prefixes the commitment of `nonce_B`.
30pub const COMMIT_LABEL: &[u8] = b"sendspin-pair-commit-v1";
31
32/// The label that prefixes the code derivation.
33pub const DERIVE_LABEL: &[u8] = b"sendspin-pairing-code-derive-v1";
34
35/// Number of digits the `digits` emission format carries.
36pub const DIGITS_LEN: usize = 6;
37
38/// Number of bytes the `qr_code` emission format carries.
39pub const QR_CODE_LEN: usize = 24;
40
41/// The divisor the digest is reduced by for the `digits` emission format.
42const DIGITS_MODULUS: u64 = 1_000_000;
43
44/// Computes `commit_B = SHA-256(label || nonce_B)`.
45///
46/// The label and the raw 32-byte nonce are concatenated without a separator, exactly as the spec
47/// writes them. The value is public - it travels in `client/pair-init` - and reveals nothing about
48/// `nonce_B` before the seal is opened.
49pub fn commitment(nonce_b: &[u8; 32]) -> [u8; 32] {
50    let mut hasher = Sha256::new();
51    hasher.update(COMMIT_LABEL);
52    hasher.update(nonce_b);
53    hasher.finalize().into()
54}
55
56/// The digest both sides derive the pairing code from.
57///
58/// One value serves both emission formats, so neither side has to know which format the client
59/// chose before it derives. The digest does not include the emission format: the `digits` code and
60/// the `qr_code` code of one digest are two views of the same binding.
61pub struct DynamicCode {
62    /// `SHA-256(label || h || nonce_A || nonce_B)`.
63    digest: [u8; 32],
64}
65
66impl DynamicCode {
67    /// Derives the digest from the handshake hash and the two nonces.
68    ///
69    /// All three are raw, concatenated after the label without a separator. `h` is the Noise
70    /// handshake hash, `nonce_a` the server's nonce from the first round's `server/pair-init` and
71    /// `nonce_b` this client's own nonce, which stays private until `client/pair-confirm`.
72    pub fn derive(h: &[u8; 32], nonce_a: &[u8; 32], nonce_b: &[u8; 32]) -> DynamicCode {
73        let mut hasher = Sha256::new();
74        hasher.update(DERIVE_LABEL);
75        hasher.update(h);
76        hasher.update(nonce_a);
77        hasher.update(nonce_b);
78        DynamicCode {
79            digest: hasher.finalize().into(),
80        }
81    }
82
83    /// Returns the six ASCII digits of the `digits` emission format.
84    ///
85    /// The digest is read as an unsigned big-endian 256-bit integer and reduced modulo `10^6`,
86    /// then written left-padded with zeroes to exactly six characters. Those six bytes are also
87    /// the code's CPace `PRS`.
88    ///
89    /// ```
90    /// use syncspin_core::pairing::code::DynamicCode;
91    ///
92    /// // Fixed inputs, so the digits are a vector: h = 0x00..=0x1f, nonce_A = 0x40..=0x5f,
93    /// // nonce_B = 0x80..=0x9f.
94    /// let code = DynamicCode::derive(
95    ///     &std::array::from_fn(|index| index as u8),
96    ///     &std::array::from_fn(|index| 0x40 + index as u8),
97    ///     &std::array::from_fn(|index| 0x80 + index as u8),
98    /// );
99    /// assert_eq!(code.digits_text(), "782070");
100    /// ```
101    pub fn digits(&self) -> [u8; DIGITS_LEN] {
102        let mut value = 0u64;
103        for &byte in &self.digest {
104            // `value < 10^6` before every step, so `value * 256 + 255` stays below 2.6ยท10^8.
105            value = (value * 256 + u64::from(byte)) % DIGITS_MODULUS;
106        }
107        let mut digits = [0u8; DIGITS_LEN];
108        for (index, digit) in digits.iter_mut().enumerate() {
109            let divisor = 10u64.pow((DIGITS_LEN - 1 - index) as u32);
110            *digit = b'0' + ((value / divisor) % 10) as u8;
111        }
112        digits
113    }
114
115    /// Returns the six digits as text, ready for a display or a speaker.
116    #[must_use]
117    pub fn digits_text(&self) -> String {
118        let digits = self.digits();
119        // Six ASCII digits from `digits`, which cannot fail.
120        String::from_utf8(digits.to_vec()).expect("the digits format is six ASCII digits")
121    }
122
123    /// Returns the 24-byte code of the `qr_code` emission format.
124    ///
125    /// These are `digest[0..24]`, raw: they are the code's CPace `PRS` and the payload of the
126    /// version-1 token a display renders.
127    #[must_use]
128    pub fn qr_payload(&self) -> [u8; QR_CODE_LEN] {
129        self.digest[..QR_CODE_LEN]
130            .try_into()
131            .expect("the digest is 32 bytes, longer than the 24-byte code")
132    }
133
134    /// Returns the `qr_code` emission of the code: a version-1 pairing token string.
135    #[must_use]
136    pub fn qr_token(&self) -> String {
137        token::encode_v1(&self.qr_payload())
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn the_digits_fold_keeps_the_whole_digest() {
147        // The fold reads every byte: a version that dropped the last byte would differ here.
148        let code = DynamicCode {
149            digest: std::array::from_fn(|index| index as u8),
150        };
151        let mut value = 0u64;
152        for &byte in &code.digest {
153            value = (value * 256 + u64::from(byte)) % DIGITS_MODULUS;
154        }
155        assert_eq!(
156            code.digits_text(),
157            format!("{value:06}"),
158            "the digits are the digest modulo 10^6, zero-padded"
159        );
160    }
161
162    #[test]
163    fn an_all_zero_digest_yields_six_zeroes() {
164        let code = DynamicCode { digest: [0u8; 32] };
165        assert_eq!(code.digits(), *b"000000");
166        assert_eq!(code.digits_text(), "000000");
167    }
168
169    #[test]
170    fn the_qr_payload_is_the_first_24_digest_bytes() {
171        let digest: [u8; 32] = std::array::from_fn(|index| 0xf0 - index as u8);
172        let code = DynamicCode { digest };
173        assert_eq!(code.qr_payload(), digest[..24]);
174        assert_eq!(
175            code.qr_token(),
176            token::encode_v1(&digest[..24].try_into().expect("24 bytes"))
177        );
178    }
179}