use k256::elliptic_curve::rand_core::{TryCryptoRng, TryRng};
use k256::schnorr::signature::hazmat::RandomizedPrehashSigner;
use k256::schnorr::{Signature, SigningKey, VerifyingKey};
pub(crate) fn is_valid_xonly(bytes: &[u8; 32]) -> bool {
VerifyingKey::from_bytes(&(*bytes).into()).is_ok()
}
pub(crate) fn verify(public_key: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool {
let Ok(key) = VerifyingKey::from_bytes(&(*public_key).into()) else {
return false;
};
let Ok(signature) = Signature::from_bytes(signature) else {
return false;
};
key.verify_raw(message, &signature).is_ok()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SchnorrSignError {
ZeroNonce,
AuxRandNotUsed,
}
pub(crate) fn sign(
key: &SigningKey,
message: &[u8],
aux_rand: &[u8; 32],
) -> Result<[u8; 64], SchnorrSignError> {
let mut rng = AuxRand::new(aux_rand);
let signature = key
.sign_prehash_with_rng(&mut rng, message)
.ok()
.map(|signature| signature.to_bytes());
finish(rng.state, signature)
}
fn finish(state: DrawState, signature: Option<[u8; 64]>) -> Result<[u8; 64], SchnorrSignError> {
match (state, signature) {
(DrawState::Drawn, Some(signature)) => Ok(signature),
(DrawState::Drawn, None) => Err(SchnorrSignError::ZeroNonce),
(DrawState::Fresh | DrawState::Refused, _) => Err(SchnorrSignError::AuxRandNotUsed),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DrawState {
Fresh,
Drawn,
Refused,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("unexpected draw from one-shot auxiliary randomness")]
struct UnexpectedDraw;
struct AuxRand {
bytes: [u8; 32],
state: DrawState,
}
impl AuxRand {
fn new(bytes: &[u8; 32]) -> Self {
Self {
bytes: *bytes,
state: DrawState::Fresh,
}
}
}
impl Drop for AuxRand {
fn drop(&mut self) {
zeroize::Zeroize::zeroize(&mut self.bytes);
}
}
impl TryRng for AuxRand {
type Error = UnexpectedDraw;
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
self.state = DrawState::Refused;
Err(UnexpectedDraw)
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
self.state = DrawState::Refused;
Err(UnexpectedDraw)
}
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
if self.state == DrawState::Fresh && dst.len() == self.bytes.len() {
dst.copy_from_slice(&self.bytes);
self.state = DrawState::Drawn;
Ok(())
} else {
self.state = DrawState::Refused;
Err(UnexpectedDraw)
}
}
}
impl TryCryptoRng for AuxRand {}
#[cfg(test)]
mod tests {
use super::*;
const VECTORS: &str = include_str!("../tests/vectors/bip340-test-vectors.csv");
struct Vector<'a> {
index: &'a str,
secret_key: &'a str,
public_key: &'a str,
aux_rand: &'a str,
message: &'a str,
signature: &'a str,
expected: bool,
}
fn vectors() -> Vec<Vector<'static>> {
VECTORS
.lines()
.skip(1)
.filter(|line| !line.trim().is_empty())
.map(|line| {
let fields: Vec<&str> = line.splitn(8, ',').collect();
assert_eq!(fields.len(), 8, "malformed vector line {line:?}");
Vector {
index: fields[0],
secret_key: fields[1],
public_key: fields[2],
aux_rand: fields[3],
message: fields[4],
signature: fields[5],
expected: match fields[6] {
"TRUE" => true,
"FALSE" => false,
other => panic!("unexpected verification result {other:?}"),
},
}
})
.collect()
}
fn fixed<const N: usize>(hex_text: &str) -> [u8; N] {
let bytes = hex::decode(hex_text).expect("vector field is hex");
bytes
.try_into()
.unwrap_or_else(|b: Vec<u8>| panic!("expected {N} bytes, got {}", b.len()))
}
#[test]
fn all_verification_vectors() {
let vectors = vectors();
assert_eq!(vectors.len(), 19, "the published file has 19 vectors");
for v in &vectors {
let public_key: [u8; 32] = fixed(v.public_key);
let message = hex::decode(v.message).expect("message is hex");
let signature: [u8; 64] = fixed(v.signature);
assert_eq!(
verify(&public_key, &message, &signature),
v.expected,
"vector {}",
v.index
);
}
}
#[test]
fn aux_rand_yields_the_bytes_once_for_a_32_byte_draw() {
let mut rng = AuxRand::new(&[7; 32]);
let mut first = [0u8; 32];
assert!(rng.try_fill_bytes(&mut first).is_ok(), "first draw");
assert_eq!(first, [7; 32], "the supplied bytes");
let mut second = [0u8; 32];
assert!(
rng.try_fill_bytes(&mut second).is_err(),
"second draw fails"
);
}
#[test]
fn aux_rand_refuses_every_other_draw() {
for len in [0usize, 1, 16, 31, 33, 64] {
let mut rng = AuxRand::new(&[7; 32]);
let mut buf = vec![0u8; len];
assert!(rng.try_fill_bytes(&mut buf).is_err(), "{len}-byte draw");
}
assert!(AuxRand::new(&[7; 32]).try_next_u32().is_err(), "next_u32");
assert!(AuxRand::new(&[7; 32]).try_next_u64().is_err(), "next_u64");
}
#[test]
fn aux_rand_refusal_is_final() {
let mut rng = AuxRand::new(&[7; 32]);
let mut short = [0u8; 16];
assert!(rng.try_fill_bytes(&mut short).is_err(), "16-byte draw");
let mut full = [0u8; 32];
assert!(rng.try_fill_bytes(&mut full).is_err(), "later 32-byte draw");
assert_eq!(full, [0; 32], "nothing written");
assert_eq!(rng.state, DrawState::Refused, "state");
}
#[test]
fn signing_requires_exactly_the_one_expected_draw() {
let sig = [3u8; 64];
assert_eq!(finish(DrawState::Drawn, Some(sig)), Ok(sig), "drawn once");
assert_eq!(
finish(DrawState::Drawn, None),
Err(SchnorrSignError::ZeroNonce),
"drawn, no signature"
);
for state in [DrawState::Fresh, DrawState::Refused] {
for signature in [Some(sig), None] {
assert_eq!(
finish(state, signature),
Err(SchnorrSignError::AuxRandNotUsed),
"{state:?} with {:?}",
signature.is_some()
);
}
}
}
#[test]
fn all_signing_vectors() {
let mut signed = 0;
for v in vectors().iter().filter(|v| !v.secret_key.is_empty()) {
let secret: [u8; 32] = fixed(v.secret_key);
let key = SigningKey::from_bytes(&secret.into()).expect("vector secret key is valid");
let public_key: [u8; 32] = fixed(v.public_key);
assert_eq!(
<[u8; 32]>::from(key.verifying_key().to_bytes()),
public_key,
"vector {} public key",
v.index
);
let message = hex::decode(v.message).expect("message is hex");
let aux: [u8; 32] = fixed(v.aux_rand);
let signature = sign(&key, &message, &aux).expect("vector signs");
let want: [u8; 64] = fixed(v.signature);
assert_eq!(signature, want, "vector {} signature", v.index);
signed += 1;
}
assert_eq!(signed, 8, "the published file has 8 signing vectors");
}
}