k256/
schnorr.rs

1//! Taproot Schnorr signatures as defined in [BIP340].
2//!
3//! # About
4//!
5//! [Schnorr signatures] are a simple group-based digital signature scheme with
6//! a number of desirable properties relating to security and composability:
7//!
8//! - Provably secure: strongly unforgable under chosen message attack (SUF-CMA).
9//! - Non-malleable: signatures cannot be altered by an attacker and still verify.
10//! - Linear: multiple parties can collaborate to produce a valid signature
11//!   a.k.a. multisignatures.
12//!
13//! Originally described in the late 1980s by their eponymous creator Claus
14//! Schnorr, they were patent-encumbered and thus lingered in obscurity until
15//! the [relevant patents] expired in 2010.
16//!
17//! Since then, Schnorr signatures have seen something of a resurgence, with
18//! [EdDSA] and its concrete instantiation Ed25519 over the Curve25519 elliptic
19//! curve becoming the first Schnorr variant to see mainstream standardization.
20//!
21//! The Taproot upgrade to Bitcoin includes a variant of Schnorr which operates
22//! over the secp256k1 elliptic curve, and is specified in [BIP340].
23//! That is the variant which is implemented by this crate.
24//!
25//! Because Taproot Schnorr is intended for use in consensus-critical
26//! applications (e.g. Bitcoin), it is fully specified such that no two
27//! implementations should disagree on the validity of a signature.
28//!
29//! # Usage
30//!
31#![cfg_attr(feature = "std", doc = "```")]
32#![cfg_attr(not(feature = "std"), doc = "```ignore")]
33//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
34//! use k256::schnorr::{
35//!     signature::{Signer, Verifier},
36//!     SigningKey, VerifyingKey
37//! };
38//! use rand_core::OsRng; // requires 'getrandom' feature
39//!
40//! //
41//! // Signing
42//! //
43//! let signing_key = SigningKey::random(&mut OsRng); // serialize with `.to_bytes()`
44//! let verifying_key_bytes = signing_key.verifying_key().to_bytes(); // 32-bytes
45//!
46//! let message = b"Schnorr signatures prove knowledge of a secret in the random oracle model";
47//! let signature = signing_key.sign(message); // returns `k256::schnorr::Signature`
48//!
49//! //
50//! // Verification
51//! //
52//! let verifying_key = VerifyingKey::from_bytes(&verifying_key_bytes)?;
53//! verifying_key.verify(message, &signature)?;
54//! # Ok(())
55//! # }
56//! ```
57//!
58//! [Schnorr signatures]: https://en.wikipedia.org/wiki/Schnorr_signature
59//! [BIP340]: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
60//! [relevant patents]: https://patents.google.com/patent/US4995082
61//! [EdDSA]: https://en.wikipedia.org/wiki/EdDSA
62
63#![allow(non_snake_case, clippy::many_single_char_names)]
64
65mod signing;
66mod verifying;
67
68pub use self::{signing::SigningKey, verifying::VerifyingKey};
69pub use signature::{self, rand_core::CryptoRngCore, Error};
70
71use crate::{arithmetic::FieldElement, NonZeroScalar};
72use core::fmt;
73use elliptic_curve::subtle::ConstantTimeEq;
74use sha2::{Digest, Sha256};
75use signature::Result;
76
77const AUX_TAG: &[u8] = b"BIP0340/aux";
78const NONCE_TAG: &[u8] = b"BIP0340/nonce";
79const CHALLENGE_TAG: &[u8] = b"BIP0340/challenge";
80
81/// Taproot Schnorr signature serialized as bytes.
82pub type SignatureBytes = [u8; Signature::BYTE_SIZE];
83
84/// Taproot Schnorr signature as defined in [BIP340].
85///
86/// [BIP340]: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
87#[derive(Copy, Clone)]
88pub struct Signature {
89    r: FieldElement,
90    s: NonZeroScalar,
91}
92
93impl Signature {
94    /// Size of a Taproot Schnorr signature in bytes.
95    pub const BYTE_SIZE: usize = 64;
96
97    /// Serialize this signature as bytes.
98    pub fn to_bytes(&self) -> SignatureBytes {
99        let mut ret = [0; Self::BYTE_SIZE];
100        let (r_bytes, s_bytes) = ret.split_at_mut(Self::BYTE_SIZE / 2);
101        r_bytes.copy_from_slice(&self.r.to_bytes());
102        s_bytes.copy_from_slice(&self.s.to_bytes());
103        ret
104    }
105
106    /// Get the `r` component of this signature.
107    fn r(&self) -> &FieldElement {
108        &self.r
109    }
110
111    /// Get the `s` component of this signature.
112    fn s(&self) -> &NonZeroScalar {
113        &self.s
114    }
115
116    /// Split this signature into its `r` and `s` components.
117    fn split(&self) -> (&FieldElement, &NonZeroScalar) {
118        (self.r(), self.s())
119    }
120}
121
122impl Eq for Signature {}
123
124impl From<Signature> for SignatureBytes {
125    fn from(signature: Signature) -> SignatureBytes {
126        signature.to_bytes()
127    }
128}
129
130impl From<&Signature> for SignatureBytes {
131    fn from(signature: &Signature) -> SignatureBytes {
132        signature.to_bytes()
133    }
134}
135
136impl PartialEq for Signature {
137    fn eq(&self, other: &Self) -> bool {
138        (self.r == other.r) && (self.s.ct_eq(&other.s).into())
139    }
140}
141
142impl TryFrom<&[u8]> for Signature {
143    type Error = Error;
144
145    fn try_from(bytes: &[u8]) -> Result<Signature> {
146        let (r_bytes, s_bytes) = bytes.split_at(Self::BYTE_SIZE / 2);
147
148        let r: FieldElement =
149            Option::from(FieldElement::from_bytes(r_bytes.into())).ok_or_else(Error::new)?;
150
151        // one of the rules for valid signatures: !is_infinite(R);
152        if r.is_zero().into() {
153            return Err(Error::new());
154        }
155
156        let s = NonZeroScalar::try_from(s_bytes).map_err(|_| Error::new())?;
157
158        Ok(Self { r, s })
159    }
160}
161
162impl fmt::Debug for Signature {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        write!(f, "{:?}", self.to_bytes())
165    }
166}
167
168impl signature::SignatureEncoding for Signature {
169    type Repr = SignatureBytes;
170
171    fn to_bytes(&self) -> Self::Repr {
172        self.into()
173    }
174}
175
176impl signature::PrehashSignature for Signature {
177    type Digest = Sha256;
178}
179
180fn tagged_hash(tag: &[u8]) -> Sha256 {
181    let tag_hash = Sha256::digest(tag);
182    let mut digest = Sha256::new();
183    digest.update(tag_hash);
184    digest.update(tag_hash);
185    digest
186}
187
188// Test vectors from:
189// https://github.com/bitcoin/bips/blob/master/bip-0340/test-vectors.csv
190#[cfg(test)]
191mod tests {
192    use super::{Signature, SigningKey, VerifyingKey};
193    use hex_literal::hex;
194    use signature::hazmat::PrehashVerifier;
195
196    /// Signing test vector
197    struct SignVector {
198        /// Index of test case
199        index: u8,
200
201        /// Signing key
202        secret_key: [u8; 32],
203
204        /// Verifying key
205        public_key: [u8; 32],
206
207        /// Auxiliary randomness value
208        aux_rand: [u8; 32],
209
210        /// Message digest
211        message: [u8; 32],
212
213        /// Expected signature
214        signature: [u8; 64],
215    }
216
217    /// BIP340 signing test vectors: index 0-3
218    const BIP340_SIGN_VECTORS: &[SignVector] = &[
219        SignVector {
220            index: 0,
221            secret_key: hex!("0000000000000000000000000000000000000000000000000000000000000003"),
222            public_key: hex!("F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9"),
223            aux_rand: hex!("0000000000000000000000000000000000000000000000000000000000000000"),
224            message: hex!("0000000000000000000000000000000000000000000000000000000000000000"),
225            signature: hex!(
226                "E907831F80848D1069A5371B402410364BDF1C5F8307B0084C55F1CE2DCA8215
227                 25F66A4A85EA8B71E482A74F382D2CE5EBEEE8FDB2172F477DF4900D310536C0"
228            ),
229        },
230        SignVector {
231            index: 1,
232            secret_key: hex!("B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF"),
233            public_key: hex!("DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659"),
234            aux_rand: hex!("0000000000000000000000000000000000000000000000000000000000000001"),
235            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
236            signature: hex!(
237                "6896BD60EEAE296DB48A229FF71DFE071BDE413E6D43F917DC8DCF8C78DE3341
238                 8906D11AC976ABCCB20B091292BFF4EA897EFCB639EA871CFA95F6DE339E4B0A"
239            ),
240        },
241        SignVector {
242            index: 2,
243            secret_key: hex!("C90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B14E5C9"),
244            public_key: hex!("DD308AFEC5777E13121FA72B9CC1B7CC0139715309B086C960E18FD969774EB8"),
245            aux_rand: hex!("C87AA53824B4D7AE2EB035A2B5BBBCCC080E76CDC6D1692C4B0B62D798E6D906"),
246            message: hex!("7E2D58D8B3BCDF1ABADEC7829054F90DDA9805AAB56C77333024B9D0A508B75C"),
247            signature: hex!(
248                "5831AAEED7B44BB74E5EAB94BA9D4294C49BCF2A60728D8B4C200F50DD313C1B
249                 AB745879A5AD954A72C45A91C3A51D3C7ADEA98D82F8481E0E1E03674A6F3FB7"
250            ),
251        },
252        // test fails if msg is reduced modulo p or n
253        SignVector {
254            index: 3,
255            secret_key: hex!("0B432B2677937381AEF05BB02A66ECD012773062CF3FA2549E44F58ED2401710"),
256            public_key: hex!("25D1DFF95105F5253C4022F628A996AD3A0D95FBF21D468A1B33F8C160D8F517"),
257            aux_rand: hex!("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
258            message: hex!("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
259            signature: hex!(
260                "7EB0509757E246F19449885651611CB965ECC1A187DD51B64FDA1EDC9637D5EC
261                 97582B9CB13DB3933705B32BA982AF5AF25FD78881EBB32771FC5922EFC66EA3"
262            ),
263        },
264    ];
265
266    #[test]
267    fn bip340_sign_vectors() {
268        for vector in BIP340_SIGN_VECTORS {
269            let sk = SigningKey::from_bytes(&vector.secret_key).unwrap();
270            assert_eq!(sk.verifying_key().to_bytes().as_slice(), &vector.public_key);
271
272            let sig = sk
273                .sign_raw(&vector.message, &vector.aux_rand)
274                .unwrap_or_else(|_| {
275                    panic!(
276                        "low-level Schnorr signing failure for index {}",
277                        vector.index
278                    )
279                });
280
281            assert_eq!(
282                vector.signature,
283                sig.to_bytes(),
284                "wrong signature for index {}",
285                vector.index
286            );
287        }
288    }
289
290    #[test]
291    fn bip340_ext_sign_vectors() {
292        // Test indexes 15-18 from https://github.com/bitcoin/bips/blob/master/bip-0340/test-vectors.csv
293        //
294        // These tests all use the same key and aux
295        let sk = SigningKey::from_bytes(&hex!(
296            "0340034003400340034003400340034003400340034003400340034003400340"
297        ))
298        .unwrap();
299
300        let aux_rand = [0u8; 32];
301
302        struct Bip340ExtTest {
303            index: usize,
304            msg: alloc::vec::Vec<u8>,
305            signature: [u8; 64],
306        }
307
308        let bip340_ext_sign_vectors = [
309            Bip340ExtTest {
310                index: 15,
311                msg: vec![],
312                signature: hex!(
313                   "71535DB165ECD9FBBC046E5FFAEA61186BB6AD436732FCCC25291A55895464CF
314                    6069CE26BF03466228F19A3A62DB8A649F2D560FAC652827D1AF0574E427AB63"
315                )
316            },
317            Bip340ExtTest {
318                index: 16,
319                msg: hex!("11").to_vec(),
320                signature: hex!("08A20A0AFEF64124649232E0693C583AB1B9934AE63B4C3511F3AE1134C6A303EA3173BFEA6683BD101FA5AA5DBC1996FE7CACFC5A577D33EC14564CEC2BACBF")
321            },
322            Bip340ExtTest {
323                index: 17,
324                msg: hex!("0102030405060708090A0B0C0D0E0F1011").to_vec(),
325                signature: hex!("5130F39A4059B43BC7CAC09A19ECE52B5D8699D1A71E3C52DA9AFDB6B50AC370C4A482B77BF960F8681540E25B6771ECE1E5A37FD80E5A51897C5566A97EA5A5"),
326            },
327            Bip340ExtTest {
328                index: 18,
329                msg: vec![0x99; 100],
330                signature: hex!("403B12B0D8555A344175EA7EC746566303321E5DBFA8BE6F091635163ECA79A8585ED3E3170807E7C03B720FC54C7B23897FCBA0E9D0B4A06894CFD249F22367"),
331            },
332        ];
333
334        for vector in bip340_ext_sign_vectors {
335            let sig = sk.sign_raw(&vector.msg, &aux_rand).unwrap_or_else(|_| {
336                panic!(
337                    "low-level Schnorr signing failure for index {}",
338                    vector.index
339                )
340            });
341
342            assert_eq!(
343                vector.signature,
344                sig.to_bytes(),
345                "wrong signature for index {}",
346                vector.index
347            );
348        }
349    }
350
351    /// Verification test vector
352    struct VerifyVector {
353        /// Index of test case
354        index: u8,
355
356        /// Verifying key
357        public_key: [u8; 32],
358
359        /// Message digest
360        message: [u8; 32],
361
362        /// Claimed signature
363        signature: [u8; 64],
364
365        /// Is signature valid
366        valid: bool,
367    }
368
369    /// BIP340 verification test vectors: index 4-14
370    const BIP340_VERIFY_VECTORS: &[VerifyVector] = &[
371        VerifyVector {
372            index: 4,
373            public_key: hex!("D69C3509BB99E412E68B0FE8544E72837DFA30746D8BE2AA65975F29D22DC7B9"),
374            message: hex!("4DF3C3F68FCC83B27E9D42C90431A72499F17875C81A599B566C9889B9696703"),
375            signature: hex!(
376                "00000000000000000000003B78CE563F89A0ED9414F5AA28AD0D96D6795F9C63
377                 76AFB1548AF603B3EB45C9F8207DEE1060CB71C04E80F593060B07D28308D7F4"
378            ),
379            valid: true,
380        },
381        // public key not on curve
382        VerifyVector {
383            index: 5,
384            public_key: hex!("EEFDEA4CDB677750A420FEE807EACF21EB9898AE79B9768766E4FAA04A2D4A34"),
385            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
386            signature: hex!(
387                "6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769
388                 69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B"
389            ),
390            valid: false,
391        },
392        // has_even_y(R) is false
393        VerifyVector {
394            index: 6,
395            public_key: hex!("DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659"),
396            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
397            signature: hex!(
398                "FFF97BD5755EEEA420453A14355235D382F6472F8568A18B2F057A1460297556
399                 3CC27944640AC607CD107AE10923D9EF7A73C643E166BE5EBEAFA34B1AC553E2"
400            ),
401            valid: false,
402        },
403        // negated message
404        VerifyVector {
405            index: 7,
406            public_key: hex!("DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659"),
407            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
408            signature: hex!(
409                "1FA62E331EDBC21C394792D2AB1100A7B432B013DF3F6FF4F99FCB33E0E1515F
410                 28890B3EDB6E7189B630448B515CE4F8622A954CFE545735AAEA5134FCCDB2BD"
411            ),
412            valid: false,
413        },
414        // negated s value
415        VerifyVector {
416            index: 8,
417            public_key: hex!("DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659"),
418            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
419            signature: hex!(
420                "6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769
421                 961764B3AA9B2FFCB6EF947B6887A226E8D7C93E00C5ED0C1834FF0D0C2E6DA6"
422            ),
423            valid: false,
424        },
425        // sG - eP is infinite. Test fails in single verification if has_even_y(inf) is defined as true and x(inf) as 0
426        VerifyVector {
427            index: 9,
428            public_key: hex!("DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659"),
429            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
430            signature: hex!(
431                "0000000000000000000000000000000000000000000000000000000000000000
432                 123DDA8328AF9C23A94C1FEECFD123BA4FB73476F0D594DCB65C6425BD186051"
433            ),
434            valid: false,
435        },
436        // sG - eP is infinite. Test fails in single verification if has_even_y(inf) is defined as true and x(inf) as 1
437        VerifyVector {
438            index: 10,
439            public_key: hex!("DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659"),
440            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
441            signature: hex!(
442                "0000000000000000000000000000000000000000000000000000000000000001
443                 7615FBAF5AE28864013C099742DEADB4DBA87F11AC6754F93780D5A1837CF197"
444            ),
445            valid: false,
446        },
447        // sig[0:32] is not an X coordinate on the curve
448        VerifyVector {
449            index: 11,
450            public_key: hex!("DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659"),
451            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
452            signature: hex!(
453                "4A298DACAE57395A15D0795DDBFD1DCB564DA82B0F269BC70A74F8220429BA1D
454                 69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B"
455            ),
456            valid: false,
457        },
458        // sig[0:32] is equal to field size
459        VerifyVector {
460            index: 12,
461            public_key: hex!("DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659"),
462            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
463            signature: hex!(
464                "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
465                 69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B"
466            ),
467            valid: false,
468        },
469        // sig[32:64] is equal to curve order
470        VerifyVector {
471            index: 13,
472            public_key: hex!("DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659"),
473            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
474            signature: hex!(
475                "6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769
476                 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"
477            ),
478            valid: false,
479        },
480        // public key is not a valid X coordinate because it exceeds the field size
481        VerifyVector {
482            index: 14,
483            public_key: hex!("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC30"),
484            message: hex!("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"),
485            signature: hex!(
486                "6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769
487                 69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B"
488            ),
489            valid: false,
490        },
491    ];
492
493    #[test]
494    fn bip340_verify_vectors() {
495        for vector in BIP340_VERIFY_VECTORS {
496            let valid = match (
497                VerifyingKey::from_bytes(&vector.public_key),
498                Signature::try_from(vector.signature.as_slice()),
499            ) {
500                (Ok(pk), Ok(sig)) => pk.verify_prehash(&vector.message, &sig).is_ok(),
501                _ => false,
502            };
503
504            assert_eq!(
505                vector.valid, valid,
506                "incorrect validation for index {}",
507                vector.index
508            );
509        }
510    }
511}