Files
arcanum/tests/sig_composite.rs
mnovak 99db18af16 test: pin verify_strict, the verify_binding order and independent seeds (QA S-01 to S-03)
Ported from QA's proof tests for PR #2 (qa_s03 to qa_s05):

- S-01, sig_halves: an Ed25519 half with a small-order R (the identity,
  s = H(R || A || M')·a from a throwaway key's own scalar) is accepted by
  plain verify and refused by verify_strict; Arcanum must refuse it.
- S-02, sig_every_byte: a forged window that also excludes now gives
  InvalidSignature, never OutsideValidity.
- S-03, sig_composite: generate draws exactly 64 bytes, and the two seeds
  are those bytes in order (RFC 10073 3.1, independent component keys).

Each mutation QA describes now fails (applied to src/sign.rs, reverted):
Q1 verify_strict -> verify fails the S-01 test; Q3 now checked before the
signature fails the S-02 test; Q4 the Ed25519 seed copied from the ML-DSA
seed fails the S-03 test. Adds curve25519-dalek =5.0.0 as a dev-dependency
(already in the lock) for the scalar arithmetic.
2026-11-26 03:42:56 +01:00

211 lines
9.3 KiB
Rust

//! Mandatory test 3 (v0.2.0): the composite is RFC 10073 `id-MLDSA65-Ed25519-SHA512`, byte for byte.
//!
//! - The RFC's own signatures (`s`, empty ctx; `sWithContext`) verify, from Appendix E as
//! published in `lamps-wg/draft-composite-sigs` `testvectors.json` at `f0627ab`, and the RFC's
//! 64-byte private key derives the RFC's 1984-byte public key.
//! - Arcanum's own signatures verify under an **independent rebuild** of M' written here, against
//! the component crates directly: ML-DSA-65 with ctx = Label, and Ed25519 `verify_strict`.
//! - The ML-DSA half is hedged (two signatures of the same message differ) and the Ed25519 half
//! is pure Ed25519 (deterministic, so equal).
//!
//! The RFC vectors are hedged, so there is no byte-exact composite signing KAT (docs gap).
mod common;
use arcanum::Error;
use arcanum::sign::{
self, AppContext, SIGNATURE_LEN, SIGNING_KEY_LEN, Signature, SigningKey, VERIFYING_KEY_LEN, VerifyingKey,
};
use common::{assert_sha256, b64, rng};
use ml_dsa::MlDsa65;
use ml_dsa::common::array::Array;
use serde_json::Value;
use sha2::{Digest, Sha512};
const VECTORS: &[u8] = include_bytes!("vectors/composite-sigs-testvectors-MLDSA65-Ed25519.subset.json");
const VECTORS_SHA256: &str = "33311f63d2c5a21d5dd4b05eb864de38bd7572108b38de713a40312d2b893b34";
/// RFC 10073 §2.2 and §6, written out here independently of `src/sign.rs`.
const PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
const LABEL: &[u8] = b"COMPSIG-MLDSA65-Ed25519-SHA512";
const ML_DSA_SIG_LEN: usize = 3309;
const ML_DSA_PK_LEN: usize = 1952;
/// M' = Prefix || Label || u8(len(ctx)) || ctx || SHA-512(M) (RFC 10073 §3.2)
fn m_prime(msg: &[u8], ctx: &[u8]) -> Vec<u8> {
assert!(ctx.len() <= 255);
let mut m = Vec::new();
m.extend_from_slice(PREFIX);
m.extend_from_slice(LABEL);
m.push(ctx.len() as u8);
m.extend_from_slice(ctx);
m.extend_from_slice(&Sha512::digest(msg));
m
}
/// Verify a composite signature with the component crates only, not with Arcanum.
fn independent_verify(pk: &[u8], msg: &[u8], ctx: &[u8], sig: &[u8]) -> (bool, bool) {
assert_eq!(pk.len(), ML_DSA_PK_LEN + 32);
assert_eq!(sig.len(), ML_DSA_SIG_LEN + 64);
let mp = m_prime(msg, ctx);
let ml_vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_DSA_PK_LEN]).unwrap());
let ml_ok = ml_dsa::Signature::<MlDsa65>::try_from(&sig[..ML_DSA_SIG_LEN])
.is_ok_and(|s| ml_vk.verify_with_context(&mp, LABEL, &s));
let ed_vk = ed25519_dalek::VerifyingKey::from_bytes(pk[ML_DSA_PK_LEN..].try_into().unwrap()).unwrap();
let ed_sig = ed25519_dalek::Signature::from_slice(&sig[ML_DSA_SIG_LEN..]).unwrap();
let ed_ok = ed_vk.verify_strict(&mp, &ed_sig).is_ok();
(ml_ok, ed_ok)
}
struct Rfc {
m: Vec<u8>,
ctx: Vec<u8>,
pk: Vec<u8>,
sk: Vec<u8>,
s: Vec<u8>,
s_with_context: Vec<u8>,
}
fn rfc() -> Rfc {
assert_sha256(VECTORS, VECTORS_SHA256, "RFC 10073 composite vectors subset");
let v: Value = serde_json::from_slice(VECTORS).unwrap();
let tests = v["tests"].as_array().unwrap();
assert_eq!(tests.len(), 1);
let t = &tests[0];
assert_eq!(t["tcId"], "id-MLDSA65-Ed25519-SHA512");
let f = |name: &str| b64(t[name].as_str().unwrap());
Rfc {
m: b64(v["m"].as_str().unwrap()),
ctx: b64(v["ctx"].as_str().unwrap()),
pk: f("pk"),
sk: f("sk"),
s: f("s"),
s_with_context: f("sWithContext"),
}
}
#[test]
fn sizes_are_the_rfcs() {
let r = rfc();
assert_eq!((VERIFYING_KEY_LEN, SIGNATURE_LEN, SIGNING_KEY_LEN), (1984, 3373, 64));
assert_eq!((r.pk.len(), r.s.len(), r.s_with_context.len(), r.sk.len()), (1984, 3373, 3373, 64));
assert_eq!(sign::PREFIX, PREFIX);
assert_eq!(sign::LABEL, LABEL);
}
#[test]
fn rfc_private_key_derives_the_rfc_public_key() {
let r = rfc();
let sk = SigningKey::from_bytes(&r.sk).unwrap();
assert_eq!(sk.verifying_key().as_bytes().as_slice(), r.pk.as_slice());
assert_eq!(sk.to_bytes().as_slice(), r.sk.as_slice(), "the private key round-trips (mldsaSeed || edSK)");
}
/// The gap in docs/02_signatures.md: does `verify_strict` accept the RFC's vectors? This answers it.
#[test]
fn rfc_signatures_verify() {
let r = rfc();
let vk = VerifyingKey::from_bytes(&r.pk).unwrap();
let s = Signature::from_bytes(&r.s).unwrap();
let swc = Signature::from_bytes(&r.s_with_context).unwrap();
// Arcanum's raw (hazmat) interface, with the RFC's bare ctx.
assert_eq!(sign::verify_composite_raw(&vk, &r.m, b"", &s), Ok(()), "s (empty ctx)");
assert_eq!(sign::verify_composite_raw(&vk, &r.m, &r.ctx, &swc), Ok(()), "sWithContext");
// The contexts are not interchangeable.
assert_eq!(sign::verify_composite_raw(&vk, &r.m, &r.ctx, &s), Err(Error::InvalidSignature));
assert_eq!(sign::verify_composite_raw(&vk, &r.m, b"", &swc), Err(Error::InvalidSignature));
// The independent rebuild agrees, half by half.
assert_eq!(independent_verify(&r.pk, &r.m, b"", &r.s), (true, true));
assert_eq!(independent_verify(&r.pk, &r.m, &r.ctx, &r.s_with_context), (true, true));
}
#[test]
fn own_signatures_verify_under_an_independent_rebuild_of_m_prime() {
let mut rng = rng(30);
let sk = SigningKey::generate(&mut rng);
let pk = sk.verifying_key().as_bytes().to_vec();
let msg = b"a plan, signed by its author";
// Release API: the ctx is Arcanum's app prefix plus the caller's label.
let ctx = AppContext::new(b"plans").unwrap();
assert_eq!(ctx.as_bytes(), b"domi/arcanum/v2/sig/app/plans");
let sig = sk.sign(msg, &ctx, &mut rng).unwrap();
assert_eq!(independent_verify(&pk, msg, ctx.as_bytes(), sig.as_bytes()), (true, true));
assert_eq!(sk.verifying_key().verify(msg, &ctx, &sig), Ok(()));
// Raw interface: an empty ctx and the longest ctx, 255 bytes.
for ctx in [&b""[..], &[0xa5; 255][..]] {
let sig = sign::sign_composite_raw(&sk, msg, ctx, &mut rng).unwrap();
assert_eq!(independent_verify(&pk, msg, ctx, sig.as_bytes()), (true, true), "ctx of {} bytes", ctx.len());
assert_eq!(sign::verify_composite_raw(sk.verifying_key(), msg, ctx, &sig), Ok(()));
}
// The RFC's own private key, signing the RFC's message: verifies under the RFC's public key.
let r = rfc();
let rfc_sk = SigningKey::from_bytes(&r.sk).unwrap();
let sig = sign::sign_composite_raw(&rfc_sk, &r.m, &r.ctx, &mut rng).unwrap();
assert_eq!(independent_verify(&r.pk, &r.m, &r.ctx, sig.as_bytes()), (true, true));
}
#[test]
fn ml_dsa_half_is_hedged_and_ed25519_half_is_pure() {
let sk = SigningKey::generate(&mut rng(31));
let ctx = AppContext::new(b"hedge").unwrap();
let a = sk.sign(b"same message", &ctx, &mut rng(32)).unwrap();
let b = sk.sign(b"same message", &ctx, &mut rng(33)).unwrap();
let (a, b) = (a.as_bytes(), b.as_bytes());
assert_ne!(a[..ML_DSA_SIG_LEN], b[..ML_DSA_SIG_LEN], "ML-DSA must be hedged: fresh rnd per signature");
assert_eq!(a[ML_DSA_SIG_LEN..], b[ML_DSA_SIG_LEN..], "Ed25519 over the same M' is deterministic");
// The same RNG state gives the same signature: the RNG is the only source of randomness.
let c = sk.sign(b"same message", &ctx, &mut rng(32)).unwrap();
assert_eq!(a, c.as_bytes());
}
#[test]
fn ml_dsa_half_uses_the_label_as_its_context() {
let mut rng = rng(34);
let sk = SigningKey::generate(&mut rng);
let pk = sk.verifying_key().as_bytes().to_vec();
let ctx = AppContext::new(b"label").unwrap();
let sig = sk.sign(b"m", &ctx, &mut rng).unwrap();
let mp = m_prime(b"m", ctx.as_bytes());
let ml_vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_DSA_PK_LEN]).unwrap());
let ml_sig = ml_dsa::Signature::<MlDsa65>::try_from(&sig.as_bytes()[..ML_DSA_SIG_LEN]).unwrap();
assert!(ml_vk.verify_with_context(&mp, LABEL, &ml_sig), "ctx = Label");
assert!(!ml_vk.verify_with_context(&mp, b"", &ml_sig), "not the empty ctx");
assert!(!ml_vk.verify_with_context(&mp, ctx.as_bytes(), &ml_sig), "not the application ctx");
}
/// An RNG that records what it hands out (backed by the test ChaCha20).
struct Recording(chacha20::ChaCha20Rng, Vec<u8>);
impl rand_core::TryRng for Recording {
type Error = core::convert::Infallible;
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
unimplemented!("signing draws bytes, not words")
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
unimplemented!("signing draws bytes, not words")
}
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
rand_core::Rng::fill_bytes(&mut self.0, dst);
self.1.extend_from_slice(dst);
Ok(())
}
}
impl rand_core::TryCryptoRng for Recording {}
/// QA S-03 (their `qa_s05`), RFC 10073 §3.1: `generate` draws 64 fresh bytes, the ML-DSA seed then
/// the Ed25519 seed, independently. Kills deriving one seed from the other, or drawing only 32.
#[test]
fn generate_draws_two_independent_seeds() {
let mut rec = Recording(rng(35), Vec::new());
let sk = SigningKey::generate(&mut rec);
assert_eq!(rec.1.len(), 64, "exactly 64 bytes drawn");
assert_eq!(sk.to_bytes().as_slice(), rec.1.as_slice(), "the seeds are the RNG output, in order");
assert_ne!(rec.1[..32], rec.1[32..], "two different seeds");
let again = SigningKey::from_bytes(&rec.1).unwrap();
assert_eq!(again.verifying_key(), sk.verifying_key());
}