1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// secp256k1-zkp bindings
// Written in 2019 by
//   Jonas Nick
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//

//! # Schnorrsig
//! Support for bip-schnorr compliant signatures
//!
//! ```rust
//! extern crate secp256k1;
//! extern crate secp256k1_zkp_dev;
//! extern crate rand;
//!
//! #
//! # fn main() {
//! # use secp256k1_zkp_dev::GenerateKeypair;
//! use rand::rngs::OsRng;
//! use secp256k1::{Secp256k1, Message};
//!
//! let secp = Secp256k1::new();
//! let mut rng = OsRng::new().expect("OsRng");
//! let (secret_key, public_key) = secp.generate_keypair(&mut rng);
//! let message = Message::from_slice(&[0xab; 32]).expect("32 bytes");
//!
//! let sig = secp.sign(&message, &secret_key);
//! assert!(secp.verify(&message, &sig, &public_key).is_ok());
//! # }
//! ```
//!
//! The above code requires `secp256k1` to be compiled with the `rand`
//! feature enabled, to get access to [`generate_keypair`](struct.Secp256k1.html#method.generate_keypair)
//! Alternately, keys can be parsed from slices.

use std::{error, fmt};

use secp256k1::key::PublicKey;
use secp256k1::{Message, Secp256k1, Verification};

use secp256k1_zkp_sys::schnorrsig as schnorrsig_sys;

pub use secp256k1_zkp_sys::schnorrsig::Error as SysError;
pub use secp256k1_zkp_sys::schnorrsig::Sign;
pub use secp256k1_zkp_sys::ScratchSpace;

#[derive(Copy, PartialEq, Eq, Clone, Debug)]
/// A schnorrsig error
pub enum Error {
    /// Error from the underlying secp256k_zkp_sys library.
    SysError(schnorrsig_sys::Error),
}

impl error::Error for Error {
    fn cause(&self) -> Option<&error::Error> {
        None
    }

    fn description(&self) -> &str {
        match *self {
            Error::SysError(ref e) => e.as_str(),
        }
    }
}

impl From<schnorrsig_sys::Error> for Error {
    fn from(err: schnorrsig_sys::Error) -> Self {
        Error::SysError(err)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            Error::SysError(e) => f.write_str(e.as_str()),
        }
    }
}

/// A Schnorr signature
pub type Signature = schnorrsig_sys::Signature;

/// Schnorrsig verification trait
pub trait Verify {
    /// Verifies a Schnorr signature as defined by BIP-schnorr
    fn schnorrsig_verify(
        &self,
        msg: &Message,
        sig: &Signature,
        pk: &PublicKey,
    ) -> Result<(), Error>;

    /// Takes slices of messages, Schnorr signatures and public keys and verifies them all at once.
    /// That's faster than if they would have been verified one by one. Returns an Error if a
    /// single Signature fails verification. If the scratch space is not provided, this function
    /// will create a scratch space on its own of size 8192 bytes.
    fn schnorrsig_verify_batch(
        &self,
        scratch_space: Option<ScratchSpace>,
        msgs: &[Message],
        sigs: &[Signature],
        pks: &[PublicKey],
    ) -> Result<(), Error>;
}

impl<C: Verification> Verify for Secp256k1<C> {
    fn schnorrsig_verify(
        &self,
        msg: &Message,
        sig: &Signature,
        pk: &PublicKey,
    ) -> Result<(), Error> {
        schnorrsig_sys::Verify::schnorrsig_verify(self, msg, sig, pk).map_err(|e| e.into())
    }
    fn schnorrsig_verify_batch(
        &self,
        scratch_space: Option<ScratchSpace>,
        msgs: &[Message],
        sigs: &[Signature],
        pks: &[PublicKey],
    ) -> Result<(), Error> {
        if msgs.len() != sigs.len() || msgs.len() != pks.len() {
            return Err(schnorrsig_sys::Error::ArgumentLength.into());
        }
        let scratch_space = scratch_space.unwrap_or(ScratchSpace::new(self, 8192));
        let n = msgs.len();
        let mut msgptrs = Vec::with_capacity(n);
        let mut sigptrs = Vec::with_capacity(n);
        let mut pkptrs = Vec::with_capacity(n);
        for i in 0..n {
            msgptrs.push(msgs[i].as_ptr() as *const _);
            sigptrs.push(&sigs[i] as *const _);
            pkptrs.push(pks[i].as_ptr() as *const _);
        }
        schnorrsig_sys::Verify::schnorrsig_verify_batch(
            self,
            &scratch_space,
            &msgptrs[..],
            &sigptrs[..],
            &pkptrs[..],
        )
        .map_err(|e| e.into())
    }
}

#[cfg(test)]
mod tests {
    use super::{Sign, Signature, SysError, Verify};
    use rand::{thread_rng, RngCore};
    use secp256k1::{Message, Secp256k1};
    use secp256k1_zkp_dev::GenerateKeypair;

    #[test]
    fn sign_and_verify() {
        let s = Secp256k1::new();

        let mut msg = [0; 32];
        for _ in 0..100 {
            thread_rng().fill_bytes(&mut msg);
            let msg = Message::from_slice(&msg).unwrap();

            let (sk, pk) = s.generate_keypair(&mut thread_rng());
            let sig = s.schnorrsig_sign(&msg, &sk);
            Signature::serialize(&sig);
            assert_eq!(s.schnorrsig_verify(&msg, &sig, &pk), Ok(()));
            assert_eq!(
                s.schnorrsig_verify_batch(None, &[msg], &[sig], &[pk]),
                Ok(())
            );
            assert_eq!(
                s.schnorrsig_verify_batch(None, &[msg], &[], &[pk]),
                Err(SysError::ArgumentLength.into())
            );
        }
    }
}