use sha2::{Digest, Sha256};
use super::token;
pub const COMMIT_LABEL: &[u8] = b"sendspin-pair-commit-v1";
pub const DERIVE_LABEL: &[u8] = b"sendspin-pairing-code-derive-v1";
pub const DIGITS_LEN: usize = 6;
pub const QR_CODE_LEN: usize = 24;
const DIGITS_MODULUS: u64 = 1_000_000;
pub fn commitment(nonce_b: &[u8; 32]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(COMMIT_LABEL);
hasher.update(nonce_b);
hasher.finalize().into()
}
pub struct DynamicCode {
digest: [u8; 32],
}
impl DynamicCode {
pub fn derive(h: &[u8; 32], nonce_a: &[u8; 32], nonce_b: &[u8; 32]) -> DynamicCode {
let mut hasher = Sha256::new();
hasher.update(DERIVE_LABEL);
hasher.update(h);
hasher.update(nonce_a);
hasher.update(nonce_b);
DynamicCode {
digest: hasher.finalize().into(),
}
}
pub fn digits(&self) -> [u8; DIGITS_LEN] {
let mut value = 0u64;
for &byte in &self.digest {
value = (value * 256 + u64::from(byte)) % DIGITS_MODULUS;
}
let mut digits = [0u8; DIGITS_LEN];
for (index, digit) in digits.iter_mut().enumerate() {
let divisor = 10u64.pow((DIGITS_LEN - 1 - index) as u32);
*digit = b'0' + ((value / divisor) % 10) as u8;
}
digits
}
#[must_use]
pub fn digits_text(&self) -> String {
let digits = self.digits();
String::from_utf8(digits.to_vec()).expect("the digits format is six ASCII digits")
}
#[must_use]
pub fn qr_payload(&self) -> [u8; QR_CODE_LEN] {
self.digest[..QR_CODE_LEN]
.try_into()
.expect("the digest is 32 bytes, longer than the 24-byte code")
}
#[must_use]
pub fn qr_token(&self) -> String {
token::encode_v1(&self.qr_payload())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_digits_fold_keeps_the_whole_digest() {
let code = DynamicCode {
digest: std::array::from_fn(|index| index as u8),
};
let mut value = 0u64;
for &byte in &code.digest {
value = (value * 256 + u64::from(byte)) % DIGITS_MODULUS;
}
assert_eq!(
code.digits_text(),
format!("{value:06}"),
"the digits are the digest modulo 10^6, zero-padded"
);
}
#[test]
fn an_all_zero_digest_yields_six_zeroes() {
let code = DynamicCode { digest: [0u8; 32] };
assert_eq!(code.digits(), *b"000000");
assert_eq!(code.digits_text(), "000000");
}
#[test]
fn the_qr_payload_is_the_first_24_digest_bytes() {
let digest: [u8; 32] = std::array::from_fn(|index| 0xf0 - index as u8);
let code = DynamicCode { digest };
assert_eq!(code.qr_payload(), digest[..24]);
assert_eq!(
code.qr_token(),
token::encode_v1(&digest[..24].try_into().expect("24 bytes"))
);
}
}