schnorr_hints.rs
cdk-rsx/crates/crypto/batch/src/schnorr_hints.rs
1//! Checked public-coordinate hints for standard BIP340 verification.2//! The signature remains x(R)||s. Hints prove the unique even lift of the3//! original public x and optional signature x(R); they never replace input4//! validation, change the signed message or enter the coefficient transcript.56use crate::{Algorithm, BatchReport, CryptoRng, Item, RngCore, Workspace};7use k256::elliptic_curve::{8 PrimeField, bigint::U256, group::Group, point::AffineCoordinates, sec1::ToEncodedPoint,9};10use k256::sha2::Digest;11use k256::{AffinePoint, ProjectivePoint, PublicKey, Scalar};1213#[cfg(feature = "wasm-msm-simd")]14mod independent;15#[cfg(feature = "wasm-msm-simd")]16pub use independent::{IndependentChunkWorkspace, verify_independent_chunk16};17#[cfg(feature = "wasm-msm-simd")]18pub use independent::{IndependentSimdWorkspace, verify_independent};1920#[derive(Clone, Copy)]21pub struct HintedItem<'a> {22 pub item: Item<'a>,23 /// Canonical even y(P), checked against the standard x-only public key.24 pub public_y: &'a [u8],25 /// Optional canonical even y(R), checked against the standard signature x.26 pub nonce_y: Option<&'a [u8]>,27}2829#[derive(Clone, Copy, Debug, Eq, PartialEq)]30pub enum Error {31 Input(crate::Error),32 PublicY(usize),33 NonceY(usize),34}3536/// Equivalent checked-lift controls. DirectField avoids SEC1 carrier encoding;37/// Sec1 uses the dependency's ordinary checked uncompressed point decoder.38#[derive(Clone, Copy, Debug, Eq, PartialEq)]39pub enum HintValidation {40 DirectField,41 Sec1,42}4344fn checked_lift(x: &[u8; 32], y: &[u8], validation: HintValidation) -> Option<AffinePoint> {45 let y: &[u8; 32] = y.try_into().ok()?;46 match validation {47 HintValidation::DirectField => k256::public_schnorr_lift_even_with_y(x, y),48 HintValidation::Sec1 => {49 if y[31] & 1 != 0 {50 return None;51 }52 let mut encoded = [0; 65];53 encoded[0] = 4;54 encoded[1..33].copy_from_slice(x);55 encoded[33..].copy_from_slice(y);56 PublicKey::from_sec1_bytes(&encoded)57 .ok()58 .map(|p| *p.as_affine())59 }60 }61}6263/// Derive a public coordinate hint for a canonical 32-byte x-only point. This64/// helper performs the ordinary square root and belongs to client/fixture65/// preparation, never a claim that hint production is free.66pub fn derive_even_y(x: &[u8]) -> Option<[u8; 32]> {67 let point = crate::lift_x(x.try_into().ok()?)?;68 let encoded = point.to_encoded_point(false);69 let y: &[u8] = encoded.y()?;70 y.try_into().ok()71}7273pub(super) fn points(74 item: HintedItem<'_>,75 i: usize,76 validation: HintValidation,77 lift_nonce: bool,78) -> Result<(AffinePoint, Option<AffinePoint>), Error> {79 let public: &[u8; 32] = item.item.public_key.try_into().unwrap();80 let r: &[u8; 32] = item.item.signature[..32].try_into().unwrap();81 // The checked lift already rejects noncanonical field coordinates. Only a82 // failed lift needs the extra range comparison to retain the distinction83 // between malformed original x bytes and an invalid coordinate hint.84 let p = checked_lift(public, item.public_y, validation).ok_or_else(|| {85 if U256::from_be_slice(public) >= crate::FIELD_P {86 Error::Input(crate::Error::PublicKey(i))87 } else {88 Error::PublicY(i)89 }90 })?;91 let r_point = match item.nonce_y {92 Some(y) => Some(checked_lift(r, y, validation).ok_or_else(|| {93 if U256::from_be_slice(r) >= crate::FIELD_P {94 Error::Input(crate::Error::Signature(i))95 } else {96 Error::NonceY(i)97 }98 })?),99 None if lift_nonce => {100 Some(crate::lift_x(r).ok_or(Error::Input(crate::Error::Signature(i)))?)101 }102 None => {103 if U256::from_be_slice(r) >= crate::FIELD_P {104 return Err(Error::Input(crate::Error::Signature(i)));105 }106 None107 }108 };109 Ok((p, r_point))110}111112fn prepare(113 items: &[HintedItem<'_>],114 workspace: &mut Workspace<'_>,115 algorithm: Algorithm,116 validation: HintValidation,117) -> Result<[u8; 32], Error> {118 crate::validate_items(items.len(), items.iter().map(|item| item.item)).map_err(Error::Input)?;119 let count = 2 * items.len() + 1;120 if workspace.terms.len() < count || !workspace.msm.supports(count, algorithm) {121 return Err(Error::Input(crate::Error::Workspace));122 }123 // Valid hints are uniquely fixed by their original canonical x; only the124 // complete standard input transcript determines the established weights.125 let transcript = crate::hash_transcript_items(items.len(), items.iter().map(|item| item.item));126 let challenge = crate::challenge_prefix();127 for (i, item) in items.iter().enumerate() {128 let (p, r) = points(*item, i, validation, true)?;129 crate::store_prepared_item(item.item, i, p, r.unwrap(), workspace.terms, &challenge)130 .map_err(Error::Input)?;131 }132 Ok(transcript)133}134135/// Verify a complete standard BIP340 batch with freshly checked P and optional136/// R hints. P-only and P+R records may be mixed. There is no saved point cache.137pub fn verify_batch(138 items: &[HintedItem<'_>],139 workspace: &mut Workspace<'_>,140 algorithm: Algorithm,141) -> Result<bool, Error> {142 verify_batch_with_validation(items, workspace, algorithm, HintValidation::DirectField)143}144145pub fn verify_batch_with_validation(146 items: &[HintedItem<'_>],147 workspace: &mut Workspace<'_>,148 algorithm: Algorithm,149 validation: HintValidation,150) -> Result<bool, Error> {151 let transcript = prepare(items, workspace, algorithm, validation)?;152 crate::aggregate(workspace, items.len(), &transcript, algorithm).map_err(Error::Input)153}154155/// Same complete transcript and randomized coefficient augmentation as the156/// ordinary batch API. Every hint is checked before caller entropy is drawn.157pub fn verify_batch_randomized<R: CryptoRng + RngCore>(158 items: &[HintedItem<'_>],159 workspace: &mut Workspace<'_>,160 algorithm: Algorithm,161 rng: &mut R,162) -> Result<bool, Error> {163 let transcript = prepare(items, workspace, algorithm, HintValidation::DirectField)?;164 let mut entropy = [0; 32];165 rng.try_fill_bytes(&mut entropy)166 .map_err(|_| Error::Input(crate::Error::Randomness))?;167 let seed = crate::tagged(b"newstack/BIP340/batch-coefficients/randomized/v1")168 .chain_update(transcript)169 .chain_update(entropy)170 .finalize();171 crate::aggregate(workspace, items.len(), &seed.into(), algorithm).map_err(Error::Input)172}173174/// Fresh exact single verification with no aggregate transcript or weights.175/// P-only uses the standard final parity/x equation. P+R compares against the176/// checked even nonce point and avoids the final affine conversion.177pub fn verify_single(item: HintedItem<'_>) -> Result<bool, Error> {178 verify_single_with_validation(item, HintValidation::DirectField)179}180181pub fn verify_single_with_validation(182 item: HintedItem<'_>,183 validation: HintValidation,184) -> Result<bool, Error> {185 verify_single_at(item, 0, validation, None)186}187188fn verify_single_at(189 item: HintedItem<'_>,190 i: usize,191 validation: HintValidation,192 challenge: Option<&k256::sha2::Sha256>,193) -> Result<bool, Error> {194 crate::validate_items(1, [item.item]).map_err(Error::Input)?;195 let (p, r_point) = points(item, i, validation, false)?;196 let r: &[u8; 32] = item.item.signature[..32].try_into().unwrap();197 let s_bytes: [u8; 32] = item.item.signature[32..].try_into().unwrap();198 let s = Option::<Scalar>::from(Scalar::from_repr(s_bytes.into()))199 .ok_or(Error::Input(crate::Error::Signature(i)))?;200 let public = item.item.public_key.try_into().unwrap();201 let e = match challenge {202 Some(prefix) => crate::challenge_with_prefix(prefix, public, r, item.item.message),203 None => crate::challenge_fresh(public, r, item.item.message),204 };205 if let Some(r_point) = r_point {206 return Ok(207 ProjectivePoint::verify_schnorr_equation_fresh_vartime::<10>(&s, &p, &e, &r_point),208 );209 }210 let point = ProjectivePoint::lincomb_generator_vartime(&s, &p.into(), &-e);211 if bool::from(point.is_identity()) {212 return Ok(false);213 }214 let affine = point.to_affine();215 let x: [u8; 32] = affine.x().into();216 Ok(!bool::from(affine.y_is_odd()) && x == *r)217}218219/// On an aggregate failure or malformed input/hint, recheck every row using the220/// exact individual equation and freshly validate its supplied hints again.221/// Acceptance is probabilistic; failed-batch verdicts are complete and exact.222pub fn verify_batch_with_fallback(223 items: &[HintedItem<'_>],224 workspace: &mut Workspace<'_>,225 algorithm: Algorithm,226 verdicts: &mut [bool],227) -> Result<BatchReport, Error> {228 if verdicts.len() < items.len() {229 return Err(Error::Input(crate::Error::Workspace));230 }231 match verify_batch(items, workspace, algorithm) {232 Ok(true) => {233 verdicts[..items.len()].fill(true);234 Ok(BatchReport {235 aggregate_accepted: true,236 aggregate_attempts: 1,237 individual_checks: 0,238 invalid: 0,239 })240 }241 Ok(false)242 | Err(243 Error::PublicY(_)244 | Error::NonceY(_)245 | Error::Input(crate::Error::PublicKey(_) | crate::Error::Signature(_)),246 ) => {247 let mut invalid = 0;248 let challenge = crate::challenge_prefix();249 for (i, item) in items.iter().enumerate() {250 verdicts[i] =251 match verify_single_at(*item, i, HintValidation::DirectField, Some(&challenge))252 {253 Ok(valid) => valid,254 Err(255 Error::PublicY(_)256 | Error::NonceY(_)257 | Error::Input(crate::Error::PublicKey(_) | crate::Error::Signature(_)),258 ) => false,259 Err(error) => return Err(error),260 };261 invalid += usize::from(!verdicts[i]);262 }263 Ok(BatchReport {264 aggregate_accepted: false,265 aggregate_attempts: 1,266 individual_checks: items.len(),267 invalid,268 })269 }270 Err(error) => Err(error),271 }272}273274#[cfg(test)]275pub(crate) mod tests;