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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#![feature(external_doc)]
#![doc(include = "../README.md")]
#![no_std]
#![allow(non_snake_case)]

#[cfg(all(feature = "alloc", not(feature = "std")))]
#[macro_use]
extern crate alloc;

#[cfg(feature = "std")]
#[macro_use]
extern crate std;

#[cfg(feature = "libsecp_compat")]
mod libsecp_compat;

#[cfg(feature = "serde")]
extern crate serde_crate as serde;

use fun::{derive_nonce, g, hash::AddTag, marker::*, nonce::NonceGen, s, Point, Scalar, G};
pub use secp256kfun as fun;
pub use secp256kfun::nonce;
mod signature;
pub use signature::Signature;
pub mod adaptor;

/// An instance of the ECDSA signature scheme.
#[derive(Default, Clone, Debug)]
pub struct ECDSA<NG> {
    /// An instance of [`NonceGen`] to produce nonces.
    ///
    /// [`NonceGen`]: crate::nonce::NonceGen
    pub nonce_gen: NG,
    /// `enforce_low_s`: Whether the verify algorithm should enforce that the `s` component of the signature is low (see [BIP-146]).
    ///
    /// [BIP-146]: https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki#low_s
    pub enforce_low_s: bool,
}

impl ECDSA<()> {
    /// Creates an `ECDSA` instance that cannot be used to sign messages but can
    /// verify signatures.
    pub fn verify_only() -> Self {
        ECDSA {
            nonce_gen: (),
            enforce_low_s: false,
        }
    }
}

impl<NG> ECDSA<NG> {
    /// Creates a ECDSA instance.
    ///
    /// The caller chooses how nonces are generated by providing a [`NonceGen`].
    ///
    /// # Example
    /// ```
    /// use ecdsa_fun::{nonce, ECDSA};
    /// use rand::rngs::ThreadRng;
    /// use sha2::Sha256;
    /// let nonce_gen = nonce::Synthetic::<Sha256, nonce::GlobalRng<ThreadRng>>::default();
    /// let ecdsa = ECDSA::new(nonce_gen);
    /// ```
    ///
    /// [`NonceGen`]: crate::nonce::NonceGen
    pub fn new(nonce_gen: NG) -> Self
    where
        NG: AddTag,
    {
        ECDSA {
            nonce_gen: nonce_gen.add_protocol_tag("ECDSA"),
            enforce_low_s: false,
        }
    }

    /// Transforms the ECDSA instance into one which enforces the [BIP-146] low
    /// s constraint **when verifying** (it is always low s when signing).
    ///
    /// *** DO NOT USE THIS IF VERIFYING BITCOIN TRANSACTIONS FROM THE CHAIN***:
    /// [BIP-146] is only enforced for transaction relay so you can still have
    /// valid high s signatures. This is especially true if you are using the
    /// ECDSA [`adaptor`] scheme.
    ///
    /// [BIP-146]: https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki#low_s
    /// [`adaptor`]: crate::adaptor
    pub fn enforce_low_s(self) -> Self {
        ECDSA {
            nonce_gen: self.nonce_gen,
            enforce_low_s: true,
        }
    }
}

impl<NG> ECDSA<NG> {
    /// Get the corresponding verification key for a secret key
    ///
    /// # Example
    /// ```
    /// use ecdsa_fun::{fun::Scalar, ECDSA};
    /// let ecdsa = ECDSA::verify_only();
    /// let secret_key = Scalar::random(&mut rand::thread_rng());
    /// let verification_key = ecdsa.verification_key_for(&secret_key);
    /// ```
    pub fn verification_key_for(&self, secret_key: &Scalar) -> Point {
        g!(secret_key * G).mark::<Normal>()
    }
    /// Verify an ECDSA signature.
    #[must_use]
    pub fn verify(
        &self,
        verification_key: &Point<impl PointType, Public, NonZero>,
        message: &[u8; 32],
        signature: &Signature<impl Secrecy>,
    ) -> bool {
        let (R_x, s) = signature.as_tuple();
        // This ensures that there is only one valid s value per R_x for any given message.
        if s.is_high() && self.enforce_low_s {
            return false;
        }

        let m = Scalar::from_bytes_mod_order(message.clone()).mark::<Public>();
        let s_inv = s.invert();

        g!((s_inv * m) * G + (s_inv * R_x) * verification_key)
            .mark::<NonZero>()
            .map_or(false, |implied_R| implied_R.x_eq_scalar(R_x))
    }
}

impl<NG: NonceGen> ECDSA<NG> {
    /// Deterministically produce a ECDSA signature on a message hash.
    ///
    /// # Examples
    ///
    /// ```
    /// use ecdsa_fun::{
    ///     fun::{digest::Digest, g, marker::*, Scalar, G},
    ///     nonce, ECDSA,
    /// };
    /// use rand::rngs::ThreadRng;
    /// use sha2::Sha256;
    /// let secret_key = Scalar::random(&mut rand::thread_rng());
    /// let nonce_gen = nonce::Synthetic::<Sha256, nonce::GlobalRng<ThreadRng>>::default();
    /// let ecdsa = ECDSA::new(nonce_gen);
    /// let verification_key = ecdsa.verification_key_for(&secret_key);
    /// let message_hash = {
    ///     let message = b"Attack at dawn";
    ///     let mut message_hash = [0u8; 32];
    ///     let hash = Sha256::default().chain(message);
    ///     message_hash.copy_from_slice(hash.finalize().as_ref());
    ///     message_hash
    /// };
    /// let signature = ecdsa.sign(&secret_key, &message_hash);
    /// assert!(ecdsa.verify(&verification_key, &message_hash, &signature));
    /// ```
    pub fn sign(&self, secret_key: &Scalar, message_hash: &[u8; 32]) -> Signature {
        let x = secret_key;
        let m = Scalar::from_bytes_mod_order(message_hash.clone()).mark::<Public>();
        let r = derive_nonce!(
            nonce_gen => self.nonce_gen,
            secret => x,
            public => [&message_hash[..]]
        );
        let R = g!(r * G).mark::<Normal>(); // Must be normal so we can get x-coordinate

        // This coverts R is its x-coordinate mod q. This acts as a kind of poor
        // man's version of the Fiat-Shamir challenge in a Schnorr
        // signature. The lack of any known algebraic relationship between r and
        // R_x is what makes ECDSA signatures difficult to forge.
        let R_x = Scalar::from_bytes_mod_order(R.to_xonly().into_bytes())
            // There *is* a single point that will be zero here but since we're
            // choosing R pseudorandomly it won't occur.
            .mark::<(Public, NonZero)>()
            .expect("computationally unreachable");

        let mut s = s!({ r.invert() } * (m + R_x * x))
            // Given R_x is determined by x and m through a hash, reaching
            // (m + R_x * x) = 0 is intractable.
            .mark::<NonZero>()
            .expect("computationally unreachable");

        // s values must be low (less than half group order), otherwise signatures
        // would be malleable i.e. (R,s) and (R,-s) would both be valid signatures.
        s.conditional_negate(s.is_high());

        Signature {
            R_x,
            s: s.mark::<Public>(),
        }
    }
}

#[macro_export]
#[doc(hidden)]
macro_rules! test_instance {
    () => {
        $crate::ECDSA::new($crate::nonce::Deterministic::<sha2::Sha256>::default())
    };
}

#[cfg(test)]
mod test {
    use super::*;
    use rand::RngCore;
    use secp256kfun::TEST_SOUNDNESS;

    #[test]
    fn repeated_sign_and_verify() {
        let ecdsa = test_instance!();
        for _ in 0..20 {
            let mut message = [0u8; 32];
            rand::thread_rng().fill_bytes(&mut message);
            let secret_key = Scalar::random(&mut rand::thread_rng());
            let public_key = g!(secret_key * G).mark::<Normal>();
            let sig = ecdsa.sign(&secret_key, &message);
            assert!(ecdsa.verify(&public_key, &message, &sig))
        }
    }

    #[test]
    fn low_s() {
        let ecdsa_enforce_low_s = test_instance!().enforce_low_s();
        let ecdsa = test_instance!();
        for _ in 0..TEST_SOUNDNESS {
            let mut message = [0u8; 32];
            rand::thread_rng().fill_bytes(&mut message);
            let secret_key = Scalar::random(&mut rand::thread_rng());
            let public_key = ecdsa.verification_key_for(&secret_key);
            let mut sig = ecdsa.sign(&secret_key, &message);
            assert!(ecdsa.verify(&public_key, &message, &sig));
            assert!(ecdsa_enforce_low_s.verify(&public_key, &message, &sig));
            sig.s = -sig.s;
            assert!(!ecdsa_enforce_low_s.verify(&public_key, &message, &sig));
            assert!(ecdsa.verify(&public_key, &message, &sig));
        }
    }
}