synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-bench / src / crypto_vectors.rs
| 1 | //! Digest and signature test vectors for the Omega port: ADR 0003 section 9 step J3. |
| 2 | //! |
| 3 | //! The Rust crates are the specification-by-test for the Omega port (ADR 0003 |
| 4 | //! section 5.12). This module fixes what "match the Rust crates exactly" means for |
| 5 | //! the two primitives J3 ports: |
| 6 | //! |
| 7 | //! - SHA-256: the digest the `sha2` crate gives for each message. |
| 8 | //! - Ed25519 verification: the three decisions `ed25519-dalek` makes for each |
| 9 | //! (public key, signature, message): whether the key decodes |
| 10 | //! (`VerifyingKey::from_bytes`), whether `Verifier::verify` accepts (used by |
| 11 | //! `synapse-core`, `synapse-auth`, `synapse-radicle`), and whether `verify_strict` |
| 12 | //! accepts (used by `synapse-evidence`). The two verification calls disagree on |
| 13 | //! some inputs (small-order keys), so a port must reproduce both. |
| 14 | //! |
| 15 | //! The corpus is a language-neutral binary file (ADR 0003 P5: fixed width, little |
| 16 | //! endian, length prefixed), written by [`encode`] and read by [`decode`]: |
| 17 | //! |
| 18 | //! ```text |
| 19 | //! header magic "SYNJ3VEC" (8) | version u16 = 1 | reserved u16 = 0 | count u32 |
| 20 | //! record kind u8 = 1 (SHA-256) | len u32 | message[len] | digest[32] |
| 21 | //! kind u8 = 2 (Ed25519) | verdict u8 | public_key[32] | signature[64] |
| 22 | //! | len u32 | message[len] |
| 23 | //! verdict bits: 0 key decodes, 1 verify accepts, 2 verify_strict accepts; |
| 24 | //! bits 3 to 7 are zero |
| 25 | //! trailer SHA-256 of every preceding byte (32) |
| 26 | //! ``` |
| 27 | //! |
| 28 | //! A message longer than [`MAX_MESSAGE_BYTES`] is refused before anything is |
| 29 | //! allocated for it. |
| 30 | |
| 31 | use ed25519_dalek::{Signature, Verifier, VerifyingKey}; |
| 32 | use sha2::{Digest, Sha256}; |
| 33 | use std::fmt; |
| 34 | |
| 35 | pub const CORPUS_MAGIC: [u8; 8] = *b"SYNJ3VEC"; |
| 36 | pub const CORPUS_VERSION: u16 = 1; |
| 37 | /// Largest message a corpus record may declare. |
| 38 | pub const MAX_MESSAGE_BYTES: u32 = 1 << 20; |
| 39 | /// The sealed corpus, relative to the repository root. |
| 40 | pub const CORPUS_PATH: &str = "evidence/j3-crypto-vectors/vectors.bin"; |
| 41 | /// SHA-256 of the sealed corpus, so the seal is checked by a test, not by hand. |
| 42 | pub const CORPUS_SHA256: &str = "523a6199b9dcc383573c38e3dac9c1480ef85ad3c03ec436786207978721c94b"; |
| 43 | |
| 44 | pub const KIND_SHA256: u8 = 1; |
| 45 | pub const KIND_ED25519: u8 = 2; |
| 46 | /// Message of the small-order key case. |
| 47 | pub const SMALL_ORDER_MESSAGE: &[u8] = b"synapse j3 small-order key"; |
| 48 | |
| 49 | /// The decisions `ed25519-dalek` makes for one (key, signature, message). |
| 50 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 51 | pub struct Ed25519Verdict { |
| 52 | pub key_decodes: bool, |
| 53 | pub verify: bool, |
| 54 | pub verify_strict: bool, |
| 55 | } |
| 56 | |
| 57 | /// One corpus record. |
| 58 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 59 | pub enum Vector { |
| 60 | Sha256 { |
| 61 | message: Vec<u8>, |
| 62 | digest: [u8; 32], |
| 63 | }, |
| 64 | Ed25519 { |
| 65 | public_key: [u8; 32], |
| 66 | signature: [u8; 64], |
| 67 | message: Vec<u8>, |
| 68 | verdict: Ed25519Verdict, |
| 69 | }, |
| 70 | } |
| 71 | |
| 72 | /// Why a corpus file was refused. |
| 73 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 74 | pub enum CorpusError { |
| 75 | BadMagic, |
| 76 | UnsupportedVersion(u16), |
| 77 | ReservedHeaderBits(u16), |
| 78 | Truncated { at: usize }, |
| 79 | UnknownKind { at: usize, kind: u8 }, |
| 80 | ReservedVerdictBits { at: usize, verdict: u8 }, |
| 81 | MessageTooLong { at: usize, len: u32 }, |
| 82 | TrailingBytes { at: usize }, |
| 83 | ChecksumMismatch, |
| 84 | } |
| 85 | |
| 86 | impl fmt::Display for CorpusError { |
| 87 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 88 | write!(f, "{self:?}") |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | /// A corpus record whose recorded answer differs from the Rust crates. |
| 93 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 94 | pub struct Mismatch { |
| 95 | pub index: usize, |
| 96 | pub detail: String, |
| 97 | } |
| 98 | /// The SHA-256 record for `message`, digest from the `sha2` crate. |
| 99 | pub fn sha256_vector(message: &[u8]) -> Vector { |
| 100 | Vector::Sha256 { |
| 101 | message: message.to_vec(), |
| 102 | digest: Sha256::digest(message).into(), |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | /// The decisions `ed25519-dalek` makes for (key, signature, message). |
| 107 | pub fn ed25519_verdict( |
| 108 | public_key: &[u8; 32], |
| 109 | signature: &[u8; 64], |
| 110 | message: &[u8], |
| 111 | ) -> Ed25519Verdict { |
| 112 | let sig = Signature::from_bytes(signature); |
| 113 | match VerifyingKey::from_bytes(public_key) { |
| 114 | Err(_) => Ed25519Verdict { |
| 115 | key_decodes: false, |
| 116 | verify: false, |
| 117 | verify_strict: false, |
| 118 | }, |
| 119 | Ok(key) => Ed25519Verdict { |
| 120 | key_decodes: true, |
| 121 | verify: key.verify(message, &sig).is_ok(), |
| 122 | verify_strict: key.verify_strict(message, &sig).is_ok(), |
| 123 | }, |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | /// The Ed25519 record for (key, signature, message), verdict from `ed25519-dalek`. |
| 128 | pub fn ed25519_vector(public_key: [u8; 32], signature: [u8; 64], message: &[u8]) -> Vector { |
| 129 | Vector::Ed25519 { |
| 130 | verdict: ed25519_verdict(&public_key, &signature, message), |
| 131 | public_key, |
| 132 | signature, |
| 133 | message: message.to_vec(), |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /// Deterministic message of `len` bytes. |
| 138 | fn pattern(len: usize, salt: u8) -> Vec<u8> { |
| 139 | (0..len) |
| 140 | .map(|j| (j as u8).wrapping_mul(31).wrapping_add(salt) ^ (j >> 8) as u8) |
| 141 | .collect() |
| 142 | } |
| 143 | |
| 144 | fn unhex<const N: usize>(s: &str) -> [u8; N] { |
| 145 | let v = hex::decode(s).expect("fixed hex literal"); |
| 146 | v.try_into().expect("fixed hex literal length") |
| 147 | } |
| 148 | |
| 149 | /// RFC 8032 section 7.1 TEST 1 to TEST 3: (public key, message, signature). |
| 150 | const RFC8032: [(&str, &str, &str); 3] = [ |
| 151 | ( |
| 152 | "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", |
| 153 | "", |
| 154 | "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", |
| 155 | ), |
| 156 | ( |
| 157 | "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", |
| 158 | "72", |
| 159 | "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00", |
| 160 | ), |
| 161 | ( |
| 162 | "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", |
| 163 | "af82", |
| 164 | "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a", |
| 165 | ), |
| 166 | ]; |
| 167 | |
| 168 | /// L, the order of the Ed25519 base point (RFC 8032 section 5.1), little endian. |
| 169 | const ED25519_L: &str = "edd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010"; |
| 170 | |
| 171 | /// `signature` with L added to its S half: the same point equation, non-canonical S. |
| 172 | fn with_s_plus_l(signature: [u8; 64]) -> [u8; 64] { |
| 173 | let l: [u8; 32] = unhex(ED25519_L); |
| 174 | let mut out = signature; |
| 175 | let mut carry = 0u16; |
| 176 | for i in 0..32 { |
| 177 | let t = signature[32 + i] as u16 + l[i] as u16 + carry; |
| 178 | out[32 + i] = t as u8; |
| 179 | carry = t >> 8; |
| 180 | } |
| 181 | out |
| 182 | } |
| 183 | |
| 184 | /// The fixed list of cases, every answer computed by the Rust crates. |
| 185 | pub fn rust_corpus() -> Vec<Vector> { |
| 186 | let mut c = Vec::new(); |
| 187 | |
| 188 | // SHA-256: FIPS 180-4 examples, every length from 1 to 257 bytes (across the |
| 189 | // 55/56 padding split and the 64-byte block edges), larger sizes including the |
| 190 | // Gate 4 change (11,949 bytes) and the A0 probe block (16 KiB), and constant |
| 191 | // all-zero and all-one messages. |
| 192 | for m in [ |
| 193 | &b""[..], |
| 194 | b"abc", |
| 195 | b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", |
| 196 | b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", |
| 197 | ] { |
| 198 | c.push(sha256_vector(m)); |
| 199 | } |
| 200 | for len in 1..=257 { |
| 201 | c.push(sha256_vector(&pattern(len, 7))); |
| 202 | } |
| 203 | for len in [1000, 4096, 11_949, 16_384, 65_536] { |
| 204 | c.push(sha256_vector(&pattern(len, 11))); |
| 205 | } |
| 206 | for byte in [0x00, 0xff] { |
| 207 | for len in [64, 1024] { |
| 208 | c.push(sha256_vector(&vec![byte; len])); |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | // Ed25519: the RFC 8032 vectors. |
| 213 | for (pk, msg, sig) in RFC8032 { |
| 214 | let msg = hex::decode(msg).expect("fixed hex literal"); |
| 215 | c.push(ed25519_vector(unhex(pk), unhex(sig), &msg)); |
| 216 | } |
| 217 | // Signatures by deterministic keys over messages of several sizes. |
| 218 | for (i, len) in [0usize, 1, 63, 64, 65, 256, 1024, 11_949] |
| 219 | .into_iter() |
| 220 | .enumerate() |
| 221 | { |
| 222 | let mut seed = [0u8; 32]; |
| 223 | seed[0] = 0x4a; |
| 224 | seed[1] = i as u8; |
| 225 | let key = ed25519_dalek::SigningKey::from_bytes(&seed); |
| 226 | let msg = pattern(len, i as u8); |
| 227 | let sig = ed25519_dalek::Signer::sign(&key, &msg).to_bytes(); |
| 228 | c.push(ed25519_vector(key.verifying_key().to_bytes(), sig, &msg)); |
| 229 | } |
| 230 | // Refusals and edge cases around RFC 8032 TEST 1. |
| 231 | let pk1: [u8; 32] = unhex(RFC8032[0].0); |
| 232 | let sig1: [u8; 64] = unhex(RFC8032[0].2); |
| 233 | let pk2: [u8; 32] = unhex(RFC8032[1].0); |
| 234 | let flip = |i: usize, bit: u8| { |
| 235 | let mut s = sig1; |
| 236 | s[i] ^= bit; |
| 237 | s |
| 238 | }; |
| 239 | c.push(ed25519_vector(pk1, sig1, b"\x01")); // changed message |
| 240 | c.push(ed25519_vector(pk1, flip(0, 1), b"")); // changed R |
| 241 | c.push(ed25519_vector(pk1, flip(32, 1), b"")); // changed S |
| 242 | c.push(ed25519_vector(pk1, flip(63, 0x80), b"")); // high bit of S set |
| 243 | c.push(ed25519_vector(pk2, sig1, b"")); // another key |
| 244 | |
| 245 | // Small-order keys with R = identity and S = 0: the identity, and the point of |
| 246 | // order 2 (y = -1). `verify` and `verify_strict` disagree here. |
| 247 | let mut identity = [0u8; 32]; |
| 248 | identity[0] = 1; |
| 249 | let mut small_sig = [0u8; 64]; |
| 250 | small_sig[..32].copy_from_slice(&identity); |
| 251 | c.push(ed25519_vector(identity, small_sig, SMALL_ORDER_MESSAGE)); |
| 252 | let order2: [u8; 32] = |
| 253 | unhex("ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"); |
| 254 | c.push(ed25519_vector(order2, small_sig, SMALL_ORDER_MESSAGE)); |
| 255 | // Non-canonical encoding of the identity (y = p + 1). |
| 256 | let noncanonical: [u8; 32] = |
| 257 | unhex("eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"); |
| 258 | c.push(ed25519_vector(noncanonical, small_sig, SMALL_ORDER_MESSAGE)); |
| 259 | // The first key of the form [k, 0, ..., 0] that does not decode to a point. |
| 260 | if let Some(bad) = (2u8..=255) |
| 261 | .map(|k| { |
| 262 | let mut b = [0u8; 32]; |
| 263 | b[0] = k; |
| 264 | b |
| 265 | }) |
| 266 | .find(|b| VerifyingKey::from_bytes(b).is_err()) |
| 267 | { |
| 268 | c.push(ed25519_vector(bad, sig1, b"")); |
| 269 | } |
| 270 | c.extend(ed25519_edge_cases().into_iter().map(|(_, v)| v)); |
| 271 | c |
| 272 | } |
| 273 | |
| 274 | /// Named Ed25519 cases that separate implementations which agree on ordinary |
| 275 | /// signatures (see the tests for the wrong implementation each one catches). |
| 276 | /// |
| 277 | /// The classes follow Chalkias, Garillot and Nikolaenko, "Taming the many EdDSAs" |
| 278 | /// (SSR 2020, IACR ePrint 2020/1244): non-canonical R and A, small-order A and R, |
| 279 | /// mixed-order A and R, S >= L, and the cofactored versus cofactorless split. The |
| 280 | /// points are built here with `curve25519-dalek`; the verdicts come from |
| 281 | /// `ed25519-dalek` like every other record. |
| 282 | pub fn ed25519_edge_cases() -> Vec<(&'static str, Vector)> { |
| 283 | use curve25519_dalek::constants::{ED25519_BASEPOINT_POINT, EIGHT_TORSION}; |
| 284 | use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint}; |
| 285 | use curve25519_dalek::scalar::Scalar; |
| 286 | use curve25519_dalek::traits::IsIdentity; |
| 287 | |
| 288 | let b = ED25519_BASEPOINT_POINT; |
| 289 | let enc = |p: &EdwardsPoint| p.compress().0; |
| 290 | let sig = |r: [u8; 32], s: Scalar| { |
| 291 | let mut out = [0u8; 64]; |
| 292 | out[..32].copy_from_slice(&r); |
| 293 | out[32..].copy_from_slice(s.as_bytes()); |
| 294 | out |
| 295 | }; |
| 296 | // k = SHA-512(R || A || M) mod L over the encodings as given (RFC 8032 5.1.7). |
| 297 | let k = |r: &[u8; 32], a: &[u8; 32], m: &[u8]| { |
| 298 | let mut h = sha2::Sha512::new(); |
| 299 | h.update(r); |
| 300 | h.update(a); |
| 301 | h.update(m); |
| 302 | Scalar::from_bytes_mod_order_wide(&h.finalize().into()) |
| 303 | }; |
| 304 | // The first message "j3/<name>/<n>" for which `ok` holds. Each predicate below |
| 305 | // holds with probability at least 1/8 per message, so 4096 tries cannot all fail |
| 306 | // in practice; if they did, the corpus would lose the case and the tests fail. |
| 307 | let find = |name: &str, ok: &dyn Fn(&[u8]) -> bool| { |
| 308 | (0u32..4096) |
| 309 | .map(|n| format!("j3/{name}/{n}").into_bytes()) |
| 310 | .find(|m| ok(m)) |
| 311 | }; |
| 312 | let decode = |bytes: [u8; 32]| CompressedEdwardsY(bytes).decompress(); |
| 313 | let scalar = |tag: u8| Scalar::from_bytes_mod_order([tag; 32]); |
| 314 | |
| 315 | let mut identity = [0u8; 32]; |
| 316 | identity[0] = 1; |
| 317 | let t8 = EIGHT_TORSION[1]; // order 8 |
| 318 | let t4 = EIGHT_TORSION[2]; // order 4 |
| 319 | let mut cases = Vec::new(); |
| 320 | |
| 321 | // Non-canonical R: the identity as y = p + 1, and as x = -0 (sign bit set). With |
| 322 | // A = identity and S = 0 the equation gives the identity, whose canonical |
| 323 | // encoding differs from the R bytes. |
| 324 | let mut r_p_plus_1 = [0xffu8; 32]; |
| 325 | r_p_plus_1[0] = 0xee; |
| 326 | r_p_plus_1[31] = 0x7f; |
| 327 | let mut r_neg_zero = identity; |
| 328 | r_neg_zero[31] = 0x80; |
| 329 | for (name, r) in [ |
| 330 | ("noncanonical_r_y_p_plus_1", r_p_plus_1), |
| 331 | ("noncanonical_r_negative_zero", r_neg_zero), |
| 332 | ] { |
| 333 | let m = format!("j3/{name}").into_bytes(); |
| 334 | cases.push((name, ed25519_vector(identity, sig(r, Scalar::ZERO), &m))); |
| 335 | } |
| 336 | |
| 337 | // Non-canonical A: the order-4 point (y = 0) encoded as y = p. R = identity, |
| 338 | // S = 0, and a message where [k]A is the identity with k over the given bytes but |
| 339 | // not with k over the canonical re-encoding. |
| 340 | let mut a_y_p = [0xffu8; 32]; |
| 341 | a_y_p[0] = 0xed; |
| 342 | a_y_p[31] = 0x7f; |
| 343 | if let Some(a) = decode(a_y_p) { |
| 344 | let canonical = enc(&a); |
| 345 | let ok = |m: &[u8]| { |
| 346 | (k(&identity, &a_y_p, m) * a).is_identity() |
| 347 | && !(k(&identity, &canonical, m) * a).is_identity() |
| 348 | }; |
| 349 | if let Some(m) = find("noncanonical_a_y_p", &ok) { |
| 350 | cases.push(( |
| 351 | "noncanonical_a_y_p", |
| 352 | ed25519_vector(a_y_p, sig(identity, Scalar::ZERO), &m), |
| 353 | )); |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | // Small-order A (order 8) and small-order R (order 4), S = 0: R = -[k]A. |
| 358 | let (a8, r4) = (enc(&t8), enc(&t4)); |
| 359 | if let Some(m) = find("small_order_a_and_r", &|m| { |
| 360 | enc(&-(k(&r4, &a8, m) * t8)) == r4 |
| 361 | }) { |
| 362 | cases.push(( |
| 363 | "small_order_a_and_r", |
| 364 | ed25519_vector(a8, sig(r4, Scalar::ZERO), &m), |
| 365 | )); |
| 366 | } |
| 367 | |
| 368 | // Small-order R (the identity) under an ordinary key: S = k a makes |
| 369 | // [S]B - [k]A the identity. |
| 370 | let a = scalar(0x31); |
| 371 | let a_pt = enc(&(a * b)); |
| 372 | let m = b"j3/small_order_r_valid_key".to_vec(); |
| 373 | cases.push(( |
| 374 | "small_order_r_valid_key", |
| 375 | ed25519_vector(a_pt, sig(identity, k(&identity, &a_pt, &m) * a), &m), |
| 376 | )); |
| 377 | |
| 378 | // Mixed-order A = aB + T8, R = rB, S = r + k a. Cofactorless verification holds |
| 379 | // exactly when [k]T8 is the identity (k a multiple of 8); cofactored always holds. |
| 380 | let r = scalar(0x52); |
| 381 | let r_pt = enc(&(r * b)); |
| 382 | let a_mixed = enc(&(a * b + t8)); |
| 383 | for (name, multiple_of_8) in [ |
| 384 | ("mixed_order_a_k_not_multiple_of_8", false), |
| 385 | ("mixed_order_a_k_multiple_of_8", true), |
| 386 | ] { |
| 387 | let ok = |m: &[u8]| (k(&r_pt, &a_mixed, m) * t8).is_identity() == multiple_of_8; |
| 388 | if let Some(m) = find(name, &ok) { |
| 389 | let s = r + k(&r_pt, &a_mixed, &m) * a; |
| 390 | cases.push((name, ed25519_vector(a_mixed, sig(r_pt, s), &m))); |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | // Mixed-order R = rB + T8 under an ordinary key, S = r + k a: [S]B - [k]A = rB, |
| 395 | // which differs from R by the small-order part. |
| 396 | let r_mixed = enc(&(r * b + t8)); |
| 397 | let m = b"j3/mixed_order_r".to_vec(); |
| 398 | let s = r + k(&r_mixed, &a_pt, &m) * a; |
| 399 | cases.push(("mixed_order_r", ed25519_vector(a_pt, sig(r_mixed, s), &m))); |
| 400 | |
| 401 | // Non-canonical S: RFC 8032 TEST 1 with L added to S. |
| 402 | let pk1: [u8; 32] = unhex(RFC8032[0].0); |
| 403 | let sig1: [u8; 64] = unhex(RFC8032[0].2); |
| 404 | cases.push(( |
| 405 | "noncanonical_s_plus_l", |
| 406 | ed25519_vector(pk1, with_s_plus_l(sig1), b""), |
| 407 | )); |
| 408 | cases |
| 409 | } |
| 410 | |
| 411 | const HEADER_BYTES: usize = 16; |
| 412 | const TRAILER_BYTES: usize = 32; |
| 413 | |
| 414 | pub fn encode(vectors: &[Vector]) -> Vec<u8> { |
| 415 | let mut b = Vec::new(); |
| 416 | b.extend_from_slice(&CORPUS_MAGIC); |
| 417 | b.extend_from_slice(&CORPUS_VERSION.to_le_bytes()); |
| 418 | b.extend_from_slice(&0u16.to_le_bytes()); |
| 419 | b.extend_from_slice(&(vectors.len() as u32).to_le_bytes()); |
| 420 | for v in vectors { |
| 421 | match v { |
| 422 | Vector::Sha256 { message, digest } => { |
| 423 | b.push(KIND_SHA256); |
| 424 | b.extend_from_slice(&(message.len() as u32).to_le_bytes()); |
| 425 | b.extend_from_slice(message); |
| 426 | b.extend_from_slice(digest); |
| 427 | } |
| 428 | Vector::Ed25519 { |
| 429 | public_key, |
| 430 | signature, |
| 431 | message, |
| 432 | verdict, |
| 433 | } => { |
| 434 | b.push(KIND_ED25519); |
| 435 | b.push( |
| 436 | verdict.key_decodes as u8 |
| 437 | | (verdict.verify as u8) << 1 |
| 438 | | (verdict.verify_strict as u8) << 2, |
| 439 | ); |
| 440 | b.extend_from_slice(public_key); |
| 441 | b.extend_from_slice(signature); |
| 442 | b.extend_from_slice(&(message.len() as u32).to_le_bytes()); |
| 443 | b.extend_from_slice(message); |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 | let sum: [u8; 32] = Sha256::digest(&b).into(); |
| 448 | b.extend_from_slice(&sum); |
| 449 | b |
| 450 | } |
| 451 | |
| 452 | /// Bounds-checked reader over the record area. |
| 453 | struct Reader<'a> { |
| 454 | b: &'a [u8], |
| 455 | at: usize, |
| 456 | } |
| 457 | |
| 458 | impl<'a> Reader<'a> { |
| 459 | fn take(&mut self, n: usize) -> Result<&'a [u8], CorpusError> { |
| 460 | let end = self |
| 461 | .at |
| 462 | .checked_add(n) |
| 463 | .filter(|&e| e <= self.b.len()) |
| 464 | .ok_or(CorpusError::Truncated { at: self.at })?; |
| 465 | let s = &self.b[self.at..end]; |
| 466 | self.at = end; |
| 467 | Ok(s) |
| 468 | } |
| 469 | |
| 470 | fn array<const N: usize>(&mut self) -> Result<[u8; N], CorpusError> { |
| 471 | let mut out = [0u8; N]; |
| 472 | out.copy_from_slice(self.take(N)?); |
| 473 | Ok(out) |
| 474 | } |
| 475 | |
| 476 | fn message(&mut self) -> Result<Vec<u8>, CorpusError> { |
| 477 | let at = self.at; |
| 478 | let len = u32::from_le_bytes(self.array()?); |
| 479 | if len > MAX_MESSAGE_BYTES { |
| 480 | return Err(CorpusError::MessageTooLong { at, len }); |
| 481 | } |
| 482 | Ok(self.take(len as usize)?.to_vec()) |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | pub fn decode(bytes: &[u8]) -> Result<Vec<Vector>, CorpusError> { |
| 487 | if bytes.len() < HEADER_BYTES + TRAILER_BYTES { |
| 488 | return Err(CorpusError::Truncated { at: bytes.len() }); |
| 489 | } |
| 490 | if bytes[..8] != CORPUS_MAGIC { |
| 491 | return Err(CorpusError::BadMagic); |
| 492 | } |
| 493 | let version = u16::from_le_bytes([bytes[8], bytes[9]]); |
| 494 | if version != CORPUS_VERSION { |
| 495 | return Err(CorpusError::UnsupportedVersion(version)); |
| 496 | } |
| 497 | let reserved = u16::from_le_bytes([bytes[10], bytes[11]]); |
| 498 | if reserved != 0 { |
| 499 | return Err(CorpusError::ReservedHeaderBits(reserved)); |
| 500 | } |
| 501 | let body = &bytes[..bytes.len() - TRAILER_BYTES]; |
| 502 | if Sha256::digest(body)[..] != bytes[body.len()..] { |
| 503 | return Err(CorpusError::ChecksumMismatch); |
| 504 | } |
| 505 | let count = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); |
| 506 | let mut r = Reader { |
| 507 | b: body, |
| 508 | at: HEADER_BYTES, |
| 509 | }; |
| 510 | let mut out = Vec::new(); |
| 511 | for _ in 0..count { |
| 512 | let at = r.at; |
| 513 | let kind = r.array::<1>()?[0]; |
| 514 | out.push(match kind { |
| 515 | KIND_SHA256 => { |
| 516 | let message = r.message()?; |
| 517 | Vector::Sha256 { |
| 518 | message, |
| 519 | digest: r.array()?, |
| 520 | } |
| 521 | } |
| 522 | KIND_ED25519 => { |
| 523 | let verdict_at = r.at; |
| 524 | let v = r.array::<1>()?[0]; |
| 525 | if v & !0b111 != 0 { |
| 526 | return Err(CorpusError::ReservedVerdictBits { |
| 527 | at: verdict_at, |
| 528 | verdict: v, |
| 529 | }); |
| 530 | } |
| 531 | Vector::Ed25519 { |
| 532 | verdict: Ed25519Verdict { |
| 533 | key_decodes: v & 1 != 0, |
| 534 | verify: v & 2 != 0, |
| 535 | verify_strict: v & 4 != 0, |
| 536 | }, |
| 537 | public_key: r.array()?, |
| 538 | signature: r.array()?, |
| 539 | message: r.message()?, |
| 540 | } |
| 541 | } |
| 542 | kind => return Err(CorpusError::UnknownKind { at, kind }), |
| 543 | }); |
| 544 | } |
| 545 | if r.at != body.len() { |
| 546 | return Err(CorpusError::TrailingBytes { at: r.at }); |
| 547 | } |
| 548 | Ok(out) |
| 549 | } |
| 550 | |
| 551 | /// Recompute every record with the Rust crates; the first difference is returned. |
| 552 | pub fn check_against_rust_crates(vectors: &[Vector]) -> Result<(), Mismatch> { |
| 553 | for (index, v) in vectors.iter().enumerate() { |
| 554 | let again = match v { |
| 555 | Vector::Sha256 { message, .. } => sha256_vector(message), |
| 556 | Vector::Ed25519 { |
| 557 | public_key, |
| 558 | signature, |
| 559 | message, |
| 560 | .. |
| 561 | } => ed25519_vector(*public_key, *signature, message), |
| 562 | }; |
| 563 | if &again != v { |
| 564 | return Err(Mismatch { |
| 565 | index, |
| 566 | detail: format!("recorded {v:?}, Rust crates give {again:?}"), |
| 567 | }); |
| 568 | } |
| 569 | } |
| 570 | Ok(()) |
| 571 | } |
| 572 | |
| 573 | #[cfg(test)] |
| 574 | mod tests; |