crrl/
secp256k1.rs

1//! secp256k1 curve implementation.
2//!
3//! This module implements generic group operations on the secp256k1
4//! elliptic curve, a short Weierstraß curve with equation `y^2 = x^3 + 7`.
5//! This curve is standardized in SEC 2.
6//!
7//! The curve has prime order. "Scalars" are integers modulo that prime
8//! order, and are implemented by the `Scalar` structure. This structure
9//! supports the usual arithmetic operators (`+`, `-`, `*`, `/`, and the
10//! compound assignments `+=`, `-=`, `*=` and `/=`).
11//!
12//! A point on the curve is represented by the `Point` structure. The
13//! additive arithmetic operators can be applied on `Point` instances
14//! (`+`, `-`, `+=`, `-=`); multiplications by an integer (`u64` type) or
15//! by a scalar (`Scalar` type) are also supported with the `*` and `*=`
16//! operators. Point doublings can be performed with the `double()`
17//! function (which is somewhat faster than general addition), and
18//! additional optimizations are obtained in the context of multiple
19//! successive doublings by calling the `xdouble()` function. All these
20//! operations are implemented with fully constant-time code and are
21//! complete, i.e. they work with all points, even when adding a point
22//! with itself or when operations involve the curve point-at-infinity
23//! (the neutral element for the curve as a group).
24//!
25//! Scalars can be encoded over 32 bytes, using unsigned
26//! **little-endian** convention) and decoded back. Encoding is always
27//! canonical, and decoding always verifies that the value is indeed in
28//! the canonical range. Take care that many standards related to
29//! secp256k1 tend to use big-endian for encoding scalars (and often use
30//! a variable-length encoding, e.g. an ASN.1 `INTEGER`).
31//!
32//! Points can be encoded in compressed (33 bytes) or uncompressed (65
33//! bytes) formats. These formats internally use big-endian. The nominal
34//! encoding of the point-at-infinity is a single byte of value 0x00; the
35//! `encode_compressed()` and `encode_uncompressed()` functions cannot
36//! produce that specific encoding (since they produce fixed-length
37//! outputs), and instead yield a sequence of 33 or 65 zeros in that
38//! case. Point decoding accepts compressed and uncompressed formats, and
39//! also the one-byte encoding of the point-at-infinity, but they do not
40//! accept a sequence of 33 or 65 zeros as a valid input. Thus, point
41//! decoding is stricly standards-conforming. All decoding operations
42//! enforce canonicality of encoding, and verify that the point is indeed
43//! on the curve.
44//!
45//! The `PrivateKey` structure represents a private key for the ECDSA
46//! signature algorithm; it is basically a wrapper around a private
47//! scalar value. The `PrivateKey::encode()` and `PrivateKey::decode()`
48//! functions encode a private key to exactly 32 bytes, and decode it
49//! back, this time using unsigned big-endian, as per SEC 1 encoding
50//! rules (which represents private keys with the ASN.1 `OCTET STRING`
51//! type). The `PrivateKey::from_seed()` allows generating a private key
52//! from a source seed, which is presumed to have been obtained
53//! from a cryptographically secure random source.
54//!
55//! The `PublicKey` structure represents a public key for the ECDSA
56//! signature algorithm; it is a wrapper around a `Point`. It has its own
57//! `decode()`, `encode_compressed()` and `encode_uncompressed()` which
58//! only wrap around the corresponding `Point` functions, except that
59//! `decode()` explicitly rejects the point-at-infinity: an ECDSA public
60//! key is never the identity point.
61//!
62//! ECDSA signatures are generated with `PrivateKey::sign_hash()`, and
63//! verified with `PublicKey::verify_hash()`. The signature process is
64//! deterministic, using the SHA-256 function, following the description
65//! in [RFC 6979]. The caller is provides the pre-hashed message
66//! (normally, this hashing uses SHA-256, but the functions accept hash
67//! values of any length). In this implementation, the ECDSA signatures
68//! follow the non-ASN.1 format: the two `r` and `s` halves of the
69//! signature are encoded in unsigned big-endian format and concatenated,
70//! in that order. When generating a signature, exactly 32 bytes are used
71//! for each of `r` and `s`, so the signature has length 64 bytes
72//! exactly. When verifying a signature, any input size is accepted
73//! provided that it is even (so that it is unambiguous where `r` stops
74//! and `s` starts), and that the two `r` and `s` values are still in the
75//! proper range (i.e. lower than the curve order).
76//!
77//! [FIPS 186-4]: https://csrc.nist.gov/publications/detail/fips/186/4/final
78//! [RFC 6979]: https://datatracker.ietf.org/doc/html/rfc6979
79
80// Projective/fractional coordinates traditionally use uppercase letters,
81// using lowercase only for affine coordinates.
82#![allow(non_snake_case)]
83
84use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
85use super::field::{GFsecp256k1, ModInt256};
86use sha2::{Sha512, Digest};
87use super::{CryptoRng, RngCore};
88use core::convert::TryFrom;
89
90/// A point on the short Weierstraß curve secp256k1.
91#[derive(Clone, Copy, Debug)]
92pub struct Point {
93    X: GFsecp256k1,
94    Y: GFsecp256k1,
95    Z: GFsecp256k1,
96}
97
98/// Integers modulo the curve order n (a 256-bit prime).
99pub type Scalar = ModInt256<0xBFD25E8CD0364141, 0xBAAEDCE6AF48A03B,
100                            0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFF>;
101
102impl Scalar {
103    /// Encodes a scalar element into bytes (little-endian).
104    pub fn encode(self) -> [u8; 32] {
105        self.encode32()
106    }
107}
108
109/// Reverses a 32-byte sequence (i.e. switches between big-endian and
110/// little-endian conventions).
111///
112/// Source slice MUST have length at least 32 (only the first 32 bytes
113/// are accessed).
114fn bswap32(x: &[u8]) -> [u8; 32] {
115    let mut y = [0u8; 32];
116    for i in 0..32 {
117        y[i] = x[31 - i];
118    }
119    y
120}
121
122impl Point {
123
124    // Curve equation is: y^2 = x^3 + b  (for a given constant b)
125    // We use projective coordinates:
126    //   (x, y) -> (X:Y:Z) such that x = X/Z and y = Y/Z
127    //   Y is never 0 (not even for the neutral)
128    //   X = 0 and Z = 0 for the neutral
129    //   Z != 0 for all non-neutral points
130    // X = 0 is conceptually feasible for some non-neutral points, but
131    // it does not happen with secp256k1.
132    // 
133    // Note that the curve does not have a point of order 2.
134    //
135    // For point additions, we use the formulas from:
136    //    https://eprint.iacr.org/2015/1060
137    // The formulas are complete (on this curve), with cost 14M (including
138    // two multiplications by the constant 3*b).
139    //
140    // For point doublings, the formulas have cost 7M+2S (including one
141    // multiplication by the constant 3*b).
142
143    /// The neutral element (point-at-infinity) in the curve.
144    pub const NEUTRAL: Self = Self {
145        X: GFsecp256k1::ZERO,
146        Y: GFsecp256k1::ONE,
147        Z: GFsecp256k1::ZERO,
148    };
149
150    /// The conventional base point in the curve.
151    ///
152    /// Like all non-neutral points in secp256k1, it generates the whole curve.
153    pub const BASE: Self = Self {
154        X: GFsecp256k1::w64be(
155            0x79BE667EF9DCBBAC, 0x55A06295CE870B07,
156            0x029BFCDB2DCE28D9, 0x59F2815B16F81798),
157        Y: GFsecp256k1::w64be(
158            0x483ADA7726A3C465, 0x5DA4FBFC0E1108A8,
159            0xFD17B448A6855419, 0x9C47D08FFB10D4B8),
160        Z: GFsecp256k1::ONE,
161    };
162
163    /// Curve equation parameter b.
164    const B: GFsecp256k1 = GFsecp256k1::w64be(0, 0, 0, 7);
165
166    /// Tries to decode a point.
167    ///
168    /// This function accepts the following encodings and lengths:
169    ///
170    ///  - A single byte of value 0x00: the point-at-infinity.
171    ///
172    ///  - A byte of value 0x02 or 0x03, followed by exactly 32 bytes
173    ///    (unsigned big-endian encoding of the x coordinate): compressed
174    ///    encoding of a non-neutral point.
175    ///
176    ///  - A byte of value 0x04, followed by exactly 64 bytes (unsigned
177    ///    big-endian encodings of x and y): uncompressed encoding of a
178    ///    non-neutral point.
179    ///
180    /// The (very rarely encountered) "hybrid" encoding (like
181    /// uncompressed, but the least significant bit of y is also copied
182    /// into the first byte, which has value 0x06 or 0x07) is not
183    /// supported.
184    ///
185    /// On success, this structure is set to the decoded point, and
186    /// 0xFFFFFFFF is returned. On failure, this structure is set to the
187    /// neutral point, and 0x00000000 is returned. A failure is reported
188    /// if the coordinates can be decoded but do not correspond to a
189    /// point on the curve.
190    ///
191    /// Constant-time behaviour: timing-based side channels may leak
192    /// which encoding type was used (neutral, compressed, uncompressed)
193    /// but not the value of the obtained point, nor whether the encoding
194    /// was for a valid point.
195    pub fn set_decode(&mut self, buf: &[u8]) -> u32 {
196        *self = Self::NEUTRAL;
197
198        if buf.len() == 1 {
199
200            // Single-byte encoding is for the point-at-infinity.
201            // Return 0xFFFFFFFF if and only if the byte has value 0x00.
202            return (((buf[0] as i32) - 1) >> 8) as u32;
203
204        } else if buf.len() == 33 {
205
206            // Compressed encoding.
207            // Check that the first byte is 0x02 or 0x03.
208            let mut r = (((((buf[0] & 0xFE) ^ 0x02) as i32) - 1) >> 8) as u32;
209
210            // Decode x.
211            let (x, rx) = GFsecp256k1::decode32(&bswap32(&buf[1..33]));
212            r &= rx;
213
214            // Compute: y = sqrt(x^3 + b)
215            let (mut y, ry) = (x * x.square() + Self::B).sqrt();
216            r &= ry;
217
218            // Negate y if the sign does not match the bit provided in the
219            // first encoding byte. Note that there is no valid point with
220            // y = 0, thus we do not have to check that the sign is correct
221            // after the conditional negation.
222            let yb = y.encode()[0];
223            let ws = (((yb ^ buf[0]) & 0x01) as u32).wrapping_neg();
224            y.set_cond(&-y, ws);
225
226            // Set the coordinates, adjusting them if the process failed.
227            self.X = GFsecp256k1::select(&GFsecp256k1::ZERO, &x, r);
228            self.Y = GFsecp256k1::select(&GFsecp256k1::ONE, &y, r);
229            self.Z = GFsecp256k1::select(
230                &GFsecp256k1::ZERO, &GFsecp256k1::ONE, r);
231            return r;
232
233        } else if buf.len() == 65 {
234
235            // Uncompressed encoding.
236            // First byte must have value 0x04.
237            let mut r = ((((buf[0] ^ 0x04) as i32) - 1) >> 8) as u32;
238
239            // Decode x and y.
240            let (x, rx) = GFsecp256k1::decode32(&bswap32(&buf[1..33]));
241            let (y, ry) = GFsecp256k1::decode32(&bswap32(&buf[33..65]));
242            r &= rx & ry;
243
244            // Verify that the coordinates match the curve equation.
245            r &= y.square().equals(x * x.square() + Self::B);
246
247            // Set the coordinates, adjusting them if the process failed.
248            self.X = GFsecp256k1::select(&GFsecp256k1::ZERO, &x, r);
249            self.Y = GFsecp256k1::select(&GFsecp256k1::ONE, &y, r);
250            self.Z = GFsecp256k1::select(
251                &GFsecp256k1::ZERO, &GFsecp256k1::ONE, r);
252            return r;
253
254        } else {
255
256            // Invalid encoding length, return 0.
257            return 0;
258
259        }
260    }
261
262    /// Tries to decode a point.
263    ///
264    /// This function accepts the following encodings and lengths:
265    ///
266    ///  - A single byte of value 0x00: the point-at-infinity.
267    ///
268    ///  - A byte of value 0x02 or 0x03, followed by exactly 32 bytes
269    ///    (unsigned big-endian encoding of the x coordinate): compressed
270    ///    encoding of a non-neutral point.
271    ///
272    ///  - A byte of value 0x04, followed by exactly 64 bytes (unsigned
273    ///    big-endian encodings of x and y): uncompressed encoding of a
274    ///    non-neutral point.
275    ///
276    /// The (very rarely encountered) "hybrid" encoding (like
277    /// uncompressed, but the least significant bit of y is also copied
278    /// into the first byte, which has value 0x06 or 0x07) is not
279    /// supported.
280    ///
281    /// On success, the decoded point is returned; on failure, `None` is
282    /// returned. A failure is reported if the coordinates can be decoded
283    /// but do not correspond to a point on the curve.
284    ///
285    /// Constant-time behaviour: timing-based side channels may leak
286    /// which encoding type was used (neutral, compressed, uncompressed)
287    /// but not the value of the obtained point, nor whether the encoding
288    /// was for a valid point.
289    pub fn decode(buf: &[u8]) -> Option<Point> {
290        let mut P = Point::NEUTRAL;
291        if P.set_decode(buf) != 0 {
292            Some(P)
293        } else {
294            None
295        }
296    }
297
298    /// Encodes this point in compressed format (33 bytes).
299    ///
300    /// If the point is the neutral then `[0u8; 33]` is returned, which
301    /// is NOT the standard encoding of the neutral (standard is a single
302    /// byte of of value 0x00); for a non-neutral point, the first byte
303    /// is always equal to 0x02 or 0x03, never to 0x00.
304    pub fn encode_compressed(self) -> [u8; 33] {
305        let r = !self.isneutral();
306        let iZ = GFsecp256k1::ONE / self.Z;  // this is 0 if Z = 0
307        let x = self.X * iZ;  // 0 for the neutral
308        let y = self.Y * iZ;  // 0 for the neutral
309        let mut b = [0u8; 33];
310        b[0] = ((y.encode()[0] & 0x01) | 0x02) & (r as u8);
311        b[1..33].copy_from_slice(&bswap32(&x.encode()));
312        b
313    }
314
315    /// Encodes this point in uncompressed format (65 bytes).
316    ///
317    /// If the point is the neutral then `[0u8; 65]` is returned, which
318    /// is NOT the standard encoding of the neutral (standard is a single
319    /// byte of of value 0x00); for a non-neutral point, the first byte
320    /// is always equal to 0x04, never to 0x00.
321    pub fn encode_uncompressed(self) -> [u8; 65] {
322        let r = !self.isneutral();
323        let iZ = GFsecp256k1::ONE / self.Z;  // this is 0 if Z = 0
324        let x = self.X * iZ;  // 0 for the neutral
325        let y = self.Y * iZ;  // 0 for the neutral
326        let mut b = [0u8; 65];
327        b[0] = 0x04 & (r as u8);
328        b[ 1..33].copy_from_slice(&bswap32(&x.encode()));
329        b[33..65].copy_from_slice(&bswap32(&y.encode()));
330        b
331    }
332
333    /// Gets the affine (x, y) coordinates for this point.
334    ///
335    /// Values (x, y, r) are returned, with x and y being field elements,
336    /// and r a `u32` value that qualifies the outcome:
337    ///
338    ///  - if the point is the neutral, then x = 0, y = 0 and r = 0x00000000;
339    ///
340    ///  - otherwise, x and y are the affine coordinates, and r = 0xFFFFFFFF.
341    ///
342    /// Note that there is no point with x = 0 or with y = 0 on the curve.
343    pub fn to_affine(self) -> (GFsecp256k1, GFsecp256k1, u32) {
344        // Uncompressed format contains both coordinates.
345        let bb = self.encode_uncompressed();
346
347        // First byte is 0x00 for the neutral, 0x04 for other points.
348        let r = (((bb[0] as i32) - 1) >> 8) as u32;
349
350        // The values necessarily decode successfully.
351        let (x, _) = GFsecp256k1::decode32(&bswap32(&bb[1..33]));
352        let (y, _) = GFsecp256k1::decode32(&bswap32(&bb[33..65]));
353        (x, y, r)
354    }
355
356    /// Gets the projective coordinates (X:Y:Z) for this point.
357    ///
358    /// Values (X, Y, Z) are returned, such that:
359    ///
360    ///  - if the point is the neutral (point-at-infinity), then X and Z
361    ///    are 0;
362    ///
363    ///  - otherwise, Z != 0, and the affine point coordinates are
364    ///    x = X/Z and y = Y/Z.
365    ///
366    /// By definition, projective coordinates for a given point are not
367    /// unique; two equal points may have distinct projective coordinates.
368    ///
369    /// The Y coordinate is never 0. The X coordinate may be 0 only for
370    /// the neutral point.
371    pub fn to_projective(self) -> (GFsecp256k1, GFsecp256k1, GFsecp256k1) {
372        (self.X, self.Y, self.Z)
373    }
374
375    /// Sets this instance from the provided affine coordinates.
376    ///
377    /// If the coordinates designate a valid curve point, then the
378    /// function returns 0xFFFFFFFF; otherwise, this instance is set to
379    /// the neutral, and the function returns 0x00000000.
380    pub fn set_affine(&mut self, x: GFsecp256k1, y: GFsecp256k1) -> u32 {
381        *self = Self::NEUTRAL;
382        let y2 = x * x.square() + Self::B;
383        let r = y.square().equals(y2);
384        self.X.set_cond(&x, r);
385        self.Y.set_cond(&y, r);
386        self.Z.set_cond(&GFsecp256k1::ONE, r);
387        r
388    }
389
390    /// Creates an instance from the provided affine coordinates.
391    ///
392    /// The coordinates are verified to comply with the curve equation;
393    /// if they do not, then `None` is returned.
394    ///
395    /// Note: whether the point is on the curve or not may leak through
396    /// side channels; however, the actual value of the point should not
397    /// leak.
398    pub fn from_affine(x: GFsecp256k1, y: GFsecp256k1) -> Option<Self> {
399        let mut P = Self::NEUTRAL;
400        if P.set_affine(x, y) != 0 {
401            Some(P)
402        } else {
403            None
404        }
405    }
406
407    /// Sets this instance from the provided projective coordinates.
408    ///
409    /// If the coordinates designate a valid curve point, then the
410    /// function returns 0xFFFFFFFF; otherwise, this instance is set to
411    /// the neutral, and the function returns 0x00000000.
412    ///
413    /// This function accepts any (X:Y:0) triplet as a representation of
414    /// the point-at-infinity.
415    pub fn set_projective(&mut self, X: GFsecp256k1, Y: GFsecp256k1,
416                          Z: GFsecp256k1) -> u32
417    {
418        *self = Self::NEUTRAL;
419
420        // Detect the point-at-infinity.
421        let zn = Z.iszero();
422
423        // Verify the equation, assuming a non-infinity point.
424        let Y2 = X * X.square() + Self::B * Z * Z.square();
425        let r = (Y.square() * Z).equals(Y2) & !zn;
426
427        // r is 0xFFFFFFFF is the point is non-infinity and the coordinates
428        // are valid.
429
430        // Set the coordinates in the point if the equation is fulfilled
431        // and Z != 0 (which also implies Y != 0, since there is no point
432        // of order 2 on the curve).
433        self.X.set_cond(&X, r);
434        self.Y.set_cond(&Y, r);
435        self.Z.set_cond(&Z, r);
436
437        r | zn
438    }
439
440    /// Creates an instance from the provided projective coordinates.
441    ///
442    /// The coordinates are verified to comply with the curve equation;
443    /// if they do not, then `None` is returned.
444    ///
445    /// This function accepts any (X:Y:0) triplet as a representation of
446    /// the point-at-infinity.
447    ///
448    /// Note: whether the point is on the curve or not may leak through
449    /// side channels; however, the actual value of the point should not
450    /// leak.
451    pub fn from_projective(X: GFsecp256k1, Y: GFsecp256k1, Z: GFsecp256k1) 
452        -> Option<Self>
453    {
454        let mut P = Self::NEUTRAL;
455        if P.set_projective(X, Y, Z) != 0 {
456            Some(P)
457        } else {
458            None
459        }
460    }
461
462    /// Adds point `rhs` to `self`.
463    fn set_add(&mut self, rhs: &Self) {
464        let (X1, Y1, Z1) = (&self.X, &self.Y, &self.Z);
465        let (X2, Y2, Z2) = (&rhs.X, &rhs.Y, &rhs.Z);
466
467        // Formulas from Renes-Costello-Batina 2016:
468        // https://eprint.iacr.org/2015/1060
469        // (algorithm 7, with some renaming and expression compaction)
470        let x1x2 = X1 * X2;
471        let y1y2 = Y1 * Y2;
472        let z1z2 = Z1 * Z2;
473        let C = (X1 + Y1) * (X2 + Y2) - x1x2 - y1y2;  // X1*Y2 + X2*Y1
474        let D = (Y1 + Z1) * (Y2 + Z2) - y1y2 - z1z2;  // Y1*Z2 + Y2*Z1
475        let E = (X1 + Z1) * (X2 + Z2) - x1x2 - z1z2;  // X1*Z2 + X2*Z1
476        let F = x1x2.mul3();
477        let G = z1z2.mul21();
478        let H = y1y2 + G;
479        let I = y1y2 - G;
480        let J = E.mul21();
481        let X3 = C * I - D * J;
482        let Y3 = J * F + I * H;
483        let Z3 = H * D + F * C;
484
485        self.X = X3;
486        self.Y = Y3;
487        self.Z = Z3;
488    }
489
490    /// Adds the affine point `rhs` to `self`.
491    ///
492    /// If the point to add is the neutral, then `rhs.x` and `rhs.y` can
493    /// be arbitrary, and `rz` is 0xFFFFFFFF; otherwise, `rhs.x` and `rhs.y`
494    /// are the affine coordinates of the point to add, and `rz` is
495    /// 0x00000000.
496    fn set_add_affine(&mut self, rhs: &PointAffine, rz: u32) {
497        let (X1, Y1, Z1) = (&self.X, &self.Y, &self.Z);
498        let (X2, Y2) = (&rhs.x, &rhs.y);
499
500        // Same formulas as in set_add(), but modified to account for
501        // Z2 = 1 (implicitly).
502        let x1x2 = X1 * X2;
503        let y1y2 = Y1 * Y2;
504        let C = (X1 + Y1) * (X2 + Y2) - x1x2 - y1y2;  // X1*Y2 + X2*Y1
505        let D = Y2 * Z1 + Y1;                         // Y1*Z2 + Y2*Z1
506        let E = X2 * Z1 + X1;                         // X1*Z2 + X2*Z1
507        let F = x1x2.mul3();
508        let G = Z1.mul21();
509        let H = y1y2 + G;
510        let I = y1y2 - G;
511        let J = E.mul21();
512        let X3 = C * I - D * J;
513        let Y3 = J * F + I * H;
514        let Z3 = H * D + F * C;
515
516        // If rhs is the neutral, then we computed the wrong output and
517        // we must fix it, namely by discarding the computed values in
518        // that case.
519        self.X.set_cond(&X3, !rz);
520        self.Y.set_cond(&Y3, !rz);
521        self.Z.set_cond(&Z3, !rz);
522    }
523
524    /// Subtract the affine point `rhs` from `self`.
525    ///
526    /// If the point to add is the neutral, then `rhs.x` and `rhs.y` can
527    /// be arbitrary, and `rz` is 0xFFFFFFFF; otherwise, `rhs.x` and `rhs.y`
528    /// are the affine coordinates of the point to add, and `rz` is
529    /// 0x00000000.
530    fn set_sub_affine(&mut self, rhs: &PointAffine, rz: u32) {
531        self.set_add_affine(&PointAffine { x: rhs.x, y: -rhs.y }, rz);
532    }
533
534    /// Doubles this point (in place).
535    ///
536    /// This function is somewhat faster than using plain point addition.
537    pub fn set_double(&mut self) {
538        let (X, Y, Z) = (&self.X, &self.Y, &self.Z);
539
540        // Formulas from Renes-Costello-Batina 2016:
541        // https://eprint.iacr.org/2015/1060
542        // (algorithm 9, with some renaming and expression compaction)
543        let yy = Y.square();
544        let yy8 = yy.mul8();
545        let C = Z.square().mul21();
546        let Z3 = Y * Z * yy8;
547        let D = yy - C.mul3();
548        let Y3 = D * (yy + C) + C * yy8;
549        let X3 = (D * X * Y).mul2();
550
551        self.X = X3;
552        self.Y = Y3;
553        self.Z = Z3;
554    }
555
556    /// Doubles this point.
557    ///
558    /// This function is somewhat faster than using plain point addition.
559    #[inline(always)]
560    pub fn double(self) -> Self {
561        let mut r = self;
562        r.set_double();
563        r
564    }
565
566    /// Doubles this point n times (in place).
567    pub fn set_xdouble(&mut self, n: u32) {
568        for _ in 0..n {
569            self.set_double();
570        }
571    }
572
573    /// Doubles this point n times.
574    ///
575    /// When n > 1, this function is faster than calling `double()`
576    /// n times.
577    #[inline(always)]
578    pub fn xdouble(self, n: u32) -> Self {
579        let mut r = self;
580        r.set_xdouble(n);
581        r
582    }
583
584    /// Negates this point (in place).
585    #[inline(always)]
586    pub fn set_neg(&mut self) {
587        self.Y.set_neg();
588    }
589
590    /// Subtracts point `rhs` from `self`.
591    fn set_sub(&mut self, rhs: &Self) {
592        self.set_add(&-rhs);
593    }
594
595    /// Multiplies this point by a small integer.
596    ///
597    /// This operation is constant-time with regard to the source point,
598    /// but NOT with regard to the multiplier; the multiplier `n` MUST
599    /// NOT be secret.
600    pub fn set_mul_small(&mut self, n: u64) {
601        if n == 0 {
602            *self = Self::NEUTRAL;
603            return;
604        }
605        if n == 1 {
606            return;
607        }
608
609        let nlen = 64 - n.leading_zeros();
610        let T = *self;
611        let mut ndbl = 0u32;
612        for i in (0..(nlen - 1)).rev() {
613            ndbl += 1;
614            if ((n >> i) & 1) == 0 {
615                continue;
616            }
617            self.set_xdouble(ndbl);
618            ndbl = 0;
619            self.set_add(&T);
620        }
621        self.set_xdouble(ndbl);
622    }
623
624    /// Compares two points for equality.
625    ///
626    /// Returned value is 0xFFFFFFFF if the two points are equal,
627    /// 0x00000000 otherwise.
628    #[inline]
629    pub fn equals(self, rhs: Self) -> u32 {
630        // If both points are non-neutral, then their Zs are non-zero
631        // and we check that their affine coordinates match.
632        // Since Y != 0 for all points, the test on Y cannot match between
633        // a neutral and a non-neutral point.
634        (self.X * rhs.Z).equals(rhs.X * self.Z)
635        & (self.Y * rhs.Z).equals(rhs.Y * self.Z)
636    }
637
638    /// Tests whether this point is the neutral (point-at-infinity).
639    ///
640    /// Returned value is 0xFFFFFFFF for the neutral, 0x00000000 otherwise.
641    #[inline(always)]
642    pub fn isneutral(self) -> u32 {
643        self.Z.iszero()
644    }
645
646    // Conditionally copies the provided point (`P`) into `self`.
647    //
648    //  - If `ctl` is 0xFFFFFFFF, then the value of `P` is copied into `self`.
649    //
650    //  - if `ctl` is 0x00000000, then the value of `self` is unchanged.
651    //
652    // Value `ctl` MUST be either 0x00000000 or 0xFFFFFFFF.
653    #[inline]
654    pub fn set_cond(&mut self, P: &Self, ctl: u32) {
655        self.X.set_cond(&P.X, ctl);
656        self.Y.set_cond(&P.Y, ctl);
657        self.Z.set_cond(&P.Z, ctl);
658    }
659
660    /// Returns a point equal to `P0` (if `ctl` = 0x00000000) or `P1` (if
661    /// `ctl` = 0xFFFFFFFF).
662    ///
663    /// Value `ctl` MUST be either 0x00000000 or 0xFFFFFFFF.
664    #[inline(always)]
665    pub fn select(P0: &Self, P1: &Self, ctl: u32) -> Self {
666        let mut P = *P0;
667        P.set_cond(P1, ctl);
668        P
669    }
670
671    /// Conditionally negates this point.
672    ///
673    /// This point is negated if `ctl` = 0xFFFFFFFF, but kept unchanged
674    /// if `ctl` = 0x00000000.
675    ///
676    /// Value `ctl` MUST be either 0x00000000 or 0xFFFFFFFF.
677    #[inline]
678    pub fn set_condneg(&mut self, ctl: u32) {
679        self.Y.set_cond(&-self.Y, ctl);
680    }
681
682    // GLV endomorphism
683    // ================
684    //
685    // Let epsilon be a cube root of 1 modulo p. The function
686    // zeta(x, y) = (epsilon*x, y) is an endomorphism over the curve;
687    // moreover, f(P) = theta*P for a value theta which is a cube root of
688    // 1 modulo n (the curve order). We choose (arbitrarily) to use the
689    // lower (as an integer) of the two non-trivial cube roots of 1 for
690    // epsilon, which then imposes a specific theta.
691    //
692    // Using Lagrange's algorithm on the lattice ((theta, 1), (n, 0)), we
693    // can find a size-reduced basis (v1, v2). These two vectors can be
694    // described with two small integers s and t:
695    //   s =  64502973549206556628585045361533709077
696    //   t = 303414439467246543595250775667605759171
697    // Then, v1 = (s, -t) and v2 = (s+t, s). This particular format of v1
698    // and v2 comes from the fact that theta is a cube root of 1 modulo n
699    // (in particular, 1 + theta + theta^2 = 0 mod n). Note that we also
700    // have theta = s/t = -(s+t)/s, and s^2 + t^2 + s*t = n.
701    //
702    // Given a scalar k, interpreted as an integer in the 0..n-1 range, we
703    // can find two small integers k0 and k1 such that k = k0 + k1*theta,
704    // by computing:
705    //   c = round(s*k / n)
706    //   d = round(t*k / n)
707    //   k0 = k - c*s - d*(s + t)
708    //   k1 = c*t - d*s
709    // The GLV paper (https://www.iacr.org/archive/crypto2001/21390189.pdf)
710    // shows that the obtained solution is correct, and that:
711    //   sqrt(k0^2 + k1^2) <= 0.5*sqrt(s^2 + t^2) + 0.5*sqrt((s + t)^2 + s^2)
712    // The right-hand side of this inequality yields an upper bound on
713    // |k0| and |k1| which is slightly _above_ 2^128, which is inconvenient
714    // to us; however, the bound is not tight and we can do better.
715    //
716    // Indeed, we have:
717    //   (k0,k1) = (k,0) - c*(s,-t) - d*(s+t,s)
718    // and:
719    //   (k,0) = (s*k/n)*(s,-t) + (t*k/n)*(s+t,s)
720    // since s^2 + t^2 + s*t = n.
721    // We thus obtain that:
722    //   (k0,k1) = e*(s,-t) + f*(s+t,s)
723    // with e = c - s*k/n and f = d - t*k/n. Given the definitions of c and
724    // d, we necessarily have |e| <= 1/2 and |f| <= 1/2. Writing N(x) the
725    // L2 norm of vector x, the GLV paper then uses the triangular inequality
726    // to state that:
727    //   N(k0,k1) <= |e|*N(v1) + |f|*N(v2) <= 0.5*N(v1) + 0.5*N(v2)
728    // for vectors v1 = (s,-t) and v2 = (s+t,s) in our case. This is true,
729    // but leads to N(k0,k1) <= 2^128.0067. The triangular inequality is a
730    // worst case, in case the vectors v1 and v2 are colinear, but our
731    // specific v1 and v2 are certainly not colinear (in fact, as a
732    // size-reduced lattice basis, they are as orthogonal as can be in that
733    // lattice). We can write:
734    //   N(k0,k1)^2 = <e*v1 + f*v2, e*v1 + f*v2>
735    //              = e^2*N(v1)^2 + f^2*N(v2)^2 + 2*e*f*<v1,v2>
736    //              <= (1/4)*N(v1)^2 + (1/4)*N(v2)^2 + (1/2)*|<v1,v2>|
737    // We know the vectors v1 = (s,-t) and v2 = (s+t,s), so we can compute
738    // the above expression; in particular, <v1,v2> = s*(s+t)-t*s = s^2.
739    // We thus find that N(k0,k1)^2 < 2^255.08, which implies that |k0|
740    // and |k1| are both lower than 2^127.54.
741
742    const EPSILON: GFsecp256k1 = GFsecp256k1::w64be(
743        0x7AE96A2B657C0710, 0x6E64479EAC3434E9,
744        0x9CF0497512F58995, 0xC1396C28719501EE);
745    /* unused
746    const THETA: Scalar = Scalar::w64be(
747        0x5363AD4CC05C30E0, 0xA5261C028812645A,
748        0x122E22EA20816678, 0xDF02967C1B23BD72);
749    */
750
751    /// Endomorphism on the group.
752    fn zeta(self) -> Self {
753        Self {
754            X: self.X * Self::EPSILON,
755            Y: self.Y,
756            Z: self.Z
757        }
758    }
759
760    /// Computes round(e*k/n).
761    ///
762    /// Values are exchanged as arrays of 32-bit limbs, in little-endian
763    /// order (least significant first). n is the curve order. Input k must
764    /// be lower than n; input e is less than 2^128. Output is lower than
765    /// or equal to e.
766    fn mul_divr_rounded(k: &[u32; 8], e: &[u32; 4]) -> [u32; 4] {
767        // We compute round(e*k/n) = floor((e*k + (n-1)/2)/n). Since
768        // k < n < 2^256, we know that e*k + (n-1)/2 < 2^384.
769        // For the division, we apply the Granlund-Montgomery method from:
770        // "Division by Invariant Integers using Multiplication"
771        //    https://dl.acm.org/doi/pdf/10.1145/178243.178249
772        //
773        // Specifically, for the divisor d = curve order, and prec = 384,
774        // the CHOOSE_MULTIPLIER() process (figure 6.2) returns a 382-bit
775        // odd multiplier m, and shift count sh_post = 253. Applying the
776        // optimized algorithm from figure 4.2, we get sh_pre = 0, and the
777        // quotient of a 384-bit integer z by d (rounded low) is obtained as:
778        //   q = floor((m*n)/(2^637))
779
780        // m
781        const M: [u32; 12] = [
782            0x8B79A0F9, 0xBCD2FEBC, 0xB038D378, 0x13ACE39A,
783            0x65F937D8, 0x8805B42E, 0x2A16EBF8, 0x28AA2463,
784            0x00000000, 0x00000000, 0x00000000, 0x20000000,
785        ];
786
787        // (n-1)/2
788        const HN: [u32; 12] = [
789            0x681B20A0, 0xDFE92F46, 0x57A4501D, 0x5D576E73,
790            0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x7FFFFFFF,
791            0x00000000, 0x00000000, 0x00000000, 0x00000000,
792        ];
793
794        // z <- k*e + (n-1)/2
795        let mut z = [0u32; 12];
796        for i in 0..8 {
797            let w = (k[i] as u64) * (e[0] as u64) + (z[i] as u64);
798            z[i] = w as u32;
799            let cc = w >> 32;
800            let w = (k[i] as u64) * (e[1] as u64) + (z[i + 1] as u64) + cc;
801            z[i + 1] = w as u32;
802            let cc = w >> 32;
803            let w = (k[i] as u64) * (e[2] as u64) + (z[i + 2] as u64) + cc;
804            z[i + 2] = w as u32;
805            let cc = w >> 32;
806            let w = (k[i] as u64) * (e[3] as u64) + (z[i + 3] as u64) + cc;
807            z[i + 3] = w as u32;
808            z[i + 4] = (w >> 32) as u32;
809        }
810        let mut cc = 0u32;
811        for i in 0..12 {
812            let w = (z[i] as u64) + (HN[i] as u64) + (cc as u64);
813            z[i] = w as u32;
814            cc = (w >> 32) as u32;
815        }
816
817        // t <- m*z
818        let mut t = [0u32; 24];
819        for i in 0..12 {
820            let mut cc = 0u32;
821            for j in 0..12 {
822                let w = (M[i] as u64) * (z[j] as u64)
823                    + (t[i + j] as u64) + (cc as u64);
824                t[i + j] = w as u32;
825                cc = (w >> 32) as u32;
826            }
827            t[i + 12] = cc;
828        }
829
830        // q = floor(t / 2^637)
831        let q0 = (t[19] >> 29) | (t[20] << 3);
832        let q1 = (t[20] >> 29) | (t[21] << 3);
833        let q2 = (t[21] >> 29) | (t[22] << 3);
834        let q3 = (t[22] >> 29) | (t[23] << 3);
835
836        [ q0, q1, q2, q3 ]
837    }
838
839    /// Splits a scalar k into k0 and k1 (signed) such that
840    /// k = k0 + k1*mu (with mu being a given square root of -1 modulo r).
841    ///
842    /// This function returns |k0|, sgn(k0), |k1| and sgn(k1), with
843    /// sgn(x) = 0xFFFFFFFF for x < 0, 0x00000000 for x >= 0.
844    fn split_theta(k: &Scalar) -> (u128, u32, u128, u32) {
845        // s =  64502973549206556628585045361533709077
846        const S: [u32; 4] = [
847            0x9284EB15, 0xE86C90E4, 0xA7D46BCD, 0x3086D221,
848        ];
849
850        // t = 303414439467246543595250775667605759171
851        const T: [u32; 4] = [
852            0x0ABFE4C3, 0x6F547FA9, 0x010E8828, 0xE4437ED6,
853        ];
854
855        // s+t (mod 2^128)
856        const ST: [u32; 4] = [
857            0x9D44CFD8, 0x57C1108D, 0xA8E2F3F6, 0x14CA50F7,
858        ];
859
860        // Convert k into 32-bit limbs.
861        let kb = k.encode();
862        let mut kw = [0u32; 8];
863        for i in 0..8 {
864            let j = 4 * i;
865            kw[i] = u32::from_le_bytes(*<&[u8; 4]>::try_from(&kb[j..j + 4]).unwrap());
866        }
867
868        // c = round(s*k / n)
869        // d = round(t*k / n)
870        let c = Self::mul_divr_rounded(&kw, &S);
871        let d = Self::mul_divr_rounded(&kw, &T);
872
873        // Since we know that |k0| and |k1| are both less than 2^128, we
874        // can compute the values modulo 2^160.
875
876        // k0 = k - c*s - d*(s + t)
877        let mut kw0 = sub160(
878            &sub160(
879                &[ kw[0], kw[1], kw[2], kw[3], kw[4] ],
880                &mul128_t160(&c, &S)),
881            &mul128_t160(&d, &ST));
882        // Correction: ST contains s + t - 2^128, so we must furthermore
883        // subtract d*2^128 from kw0.
884        kw0[4] = kw0[4].wrapping_sub(d[0]);
885
886        // k1 = c*t - d*s
887        let kw1 = sub160(
888            &mul128_t160(&c, &T),
889            &mul128_t160(&d, &S));
890
891        // Compute abs(k0) and abs(k1); top limb of kw0 (resp. kw1) is
892        // either 0x00000000 (non-negative) or 0xFFFFFFFF (negative).
893        let (k0, sk0) = abs128(&kw0);
894        let (k1, sk1) = abs128(&kw1);
895
896        return (k0, sk0, k1, sk1);
897
898        // =========== helper functions ===========
899
900        // d <- a - b mod 2^160
901        fn sub160(a: &[u32; 5], b: &[u32; 5]) -> [u32; 5] {
902            let w = (a[0] as u64).wrapping_sub(b[0] as u64);
903            let d0 = w as u32;
904            let w = (a[1] as u64).wrapping_sub(b[1] as u64)
905                .wrapping_sub(w >> 63);
906            let d1 = w as u32;
907            let w = (a[2] as u64).wrapping_sub(b[2] as u64)
908                .wrapping_sub(w >> 63);
909            let d2 = w as u32;
910            let w = (a[3] as u64).wrapping_sub(b[3] as u64)
911                .wrapping_sub(w >> 63);
912            let d3 = w as u32;
913            let d4 = a[4].wrapping_sub(b[4]).wrapping_sub((w >> 63) as u32);
914
915            [ d0, d1, d2, d3, d4 ]
916        }
917
918        // d <- (a*b) mod 2^160
919        fn mul128_t160(a: &[u32; 4], b: &[u32; 4]) -> [u32; 5] {
920            let w = (a[0] as u64) * (b[0] as u64);
921            let d0 = w as u32;
922            let w = (a[1] as u64) * (b[0] as u64) + (w >> 32);
923            let d1 = w as u32;
924            let w = (a[2] as u64) * (b[0] as u64) + (w >> 32);
925            let d2 = w as u32;
926            let w = (a[3] as u64) * (b[0] as u64) + (w >> 32);
927            let d3 = w as u32;
928            let d4 = (w >> 32) as u32;
929
930            let w = (a[0] as u64) * (b[1] as u64) + (d1 as u64);
931            let d1 = w as u32;
932            let w = (a[1] as u64) * (b[1] as u64) + (d2 as u64) + (w >> 32);
933            let d2 = w as u32;
934            let w = (a[2] as u64) * (b[1] as u64) + (d3 as u64) + (w >> 32);
935            let d3 = w as u32;
936            let d4 = d4.wrapping_add(a[3].wrapping_mul(b[1]))
937                .wrapping_add((w >> 32) as u32);
938
939            let w = (a[0] as u64) * (b[2] as u64) + (d2 as u64);
940            let d2 = w as u32;
941            let w = (a[1] as u64) * (b[2] as u64) + (d3 as u64) + (w >> 32);
942            let d3 = w as u32;
943            let d4 = d4.wrapping_add(a[2].wrapping_mul(b[2]))
944                .wrapping_add((w >> 32) as u32);
945
946            let w = (a[0] as u64) * (b[3] as u64) + (d3 as u64);
947            let d3 = w as u32;
948            let d4 = d4.wrapping_add(a[1].wrapping_mul(b[3]))
949                .wrapping_add((w >> 32) as u32);
950
951            [ d0, d1, d2, d3, d4 ]
952        }
953
954        // Given g such that |g| < 2^128, return |g| and sgn(g).
955        fn abs128(g: &[u32; 5]) -> (u128, u32) {
956            let gs = g[4];
957            let w = ((g[0] ^ gs) as u64).wrapping_sub(gs as u64);
958            let d0 = w as u32;
959            let w = ((g[1] ^ gs) as u64).wrapping_sub(gs as u64)
960                .wrapping_sub(w >> 63);
961            let d1 = w as u32;
962            let w = ((g[2] ^ gs) as u64).wrapping_sub(gs as u64)
963                .wrapping_sub(w >> 63);
964            let d2 = w as u32;
965            let d3 = (g[3] ^ gs).wrapping_sub(gs)
966                .wrapping_sub((w >> 63) as u32);
967
968            let d = (d0 as u128)
969                | ((d1 as u128) << 32)
970                | ((d2 as u128) << 64)
971                | ((d3 as u128) << 96);
972            (d, gs)
973        }
974    }
975
976    /// Recodes a scalar into 52 signed digits.
977    ///
978    /// Each digit is in -15..+16, top digit is in 0..+2.
979    fn recode_scalar(n: &Scalar) -> [i8; 52] {
980        let mut sd = [0i8; 52];
981        let bb = n.encode();
982        let mut cc: u32 = 0;       // carry from lower digits
983        let mut i: usize = 0;      // index of next source byte
984        let mut acc: u32 = 0;      // buffered bits
985        let mut acc_len: i32 = 0;  // number of buffered bits
986        for j in 0..52 {
987            if acc_len < 5 && j < 51 {
988                acc |= (bb[i] as u32) << acc_len;
989                acc_len += 8;
990                i += 1;
991            }
992            let d = (acc & 0x1F) + cc;
993            acc >>= 5;
994            acc_len -= 5;
995            let m = 16u32.wrapping_sub(d) >> 8;
996            sd[j] = (d.wrapping_sub(m & 32)) as i8;
997            cc = m & 1;
998        }
999        sd
1000    }
1001
1002    /// Recodes a half-width scalar into 26 signed digits.
1003    ///
1004    /// Each digit is in -15..+16, top digit is in 0..+8.
1005    fn recode_u128(n: u128) -> [i8; 26] {
1006        let mut sd = [0i8; 26];
1007        let mut x = n;
1008        let mut cc: u32 = 0;       // carry from lower digits
1009        for j in 0..26 {
1010            let d = ((x as u32) & 0x1F) + cc;
1011            x >>= 5;
1012            let m = 16u32.wrapping_sub(d) >> 8;
1013            sd[j] = (d.wrapping_sub(m & 32)) as i8;
1014            cc = m & 1;
1015        }
1016        sd
1017    }
1018
1019    /// Lookups a point from a window, with sign handling (constant-time).
1020    fn lookup(win: &[Self; 16], k: i8) -> Self {
1021        // Split k into its sign s (0xFFFFFFFF for negative) and
1022        // absolute value (f).
1023        let s = ((k as i32) >> 8) as u32;
1024        let f = ((k as u32) ^ s).wrapping_sub(s);
1025        let mut P = Self::NEUTRAL;
1026        for i in 0..16 {
1027            // win[i] contains (i+1)*P; we want to keep it if (and only if)
1028            // i+1 == f.
1029            // Values a-b and b-a both have their high bit equal to 0 only
1030            // if a == b.
1031            let j = (i as u32) + 1;
1032            let w = !(f.wrapping_sub(j) | j.wrapping_sub(f));
1033            let w = ((w as i32) >> 31) as u32;
1034
1035            P.X.set_cond(&win[i].X, w);
1036            P.Y.set_cond(&win[i].Y, w);
1037            P.Z.set_cond(&win[i].Z, w);
1038        }
1039
1040        // Negate the returned value if needed.
1041        P.Y.set_cond(&-P.Y, s);
1042
1043        P
1044    }
1045
1046    /// Multiplies this point by a scalar (in place).
1047    ///
1048    /// This operation is constant-time with regard to both the points
1049    /// and the scalar value.
1050    pub fn set_mul(&mut self, n: &Scalar) {
1051        // Split the scalar with the endomorphism.
1052        let (n0, s0, n1, s1) = Self::split_theta(n);
1053
1054        // Compute the 5-bit windows:
1055        //   win0[i] = (i+1)*sgn(n0)*P
1056        //   win1[i] = (i+1)*sgn(n1)*zeta(P)
1057        // with zeta(x, y) = (x*epsilon, y) for epsilon^3 = 1 (this is an
1058        // endomorphism on the group).
1059        let mut win0 = [Self::NEUTRAL; 16];
1060        win0[0] = *self;
1061        win0[0].set_condneg(s0);
1062        for i in 1..8 {
1063            let j = 2 * i;
1064            win0[j - 1] = win0[i - 1].double();
1065            win0[j] = win0[j - 1] + win0[0];
1066        }
1067        win0[15] = win0[7].double();
1068        let mut win1 = [Self::NEUTRAL; 16];
1069        for i in 0..16 {
1070            win1[i] = win0[i].zeta();
1071            win1[i].set_condneg(s0 ^ s1);
1072        }
1073
1074        // Recode the two half-width scalars into 26 digits each.
1075        let sd0 = Self::recode_u128(n0);
1076        let sd1 = Self::recode_u128(n1);
1077
1078        // Process the two digit sequences in high-to-low order.
1079        *self = Self::lookup(&win0, sd0[25]);
1080        self.set_add(&Self::lookup(&win1, sd1[25]));
1081        for i in (0..25).rev() {
1082            self.set_xdouble(5);
1083            self.set_add(&Self::lookup(&win0, sd0[i]));
1084            self.set_add(&Self::lookup(&win1, sd1[i]));
1085        }
1086    }
1087
1088    /// Lookups a point from a window in affine coordinates, with sign
1089    /// handling (constant-time).
1090    ///
1091    /// The returned point is in affine coordinates, and an extra "output
1092    /// is neutral" flag is also returned (since the neutral point does
1093    /// not have defined affine coordinates).
1094    fn lookup_affine(win: &[PointAffine; 16], k: i8) -> (PointAffine, u32) {
1095        // Split k into its sign s (0xFFFFFFFF for negative) and
1096        // absolute value (f).
1097        let s = ((k as i32) >> 8) as u32;
1098        let f = ((k as u32) ^ s).wrapping_sub(s);
1099        let mut P = PointAffine { x: GFsecp256k1::ZERO, y: GFsecp256k1::ONE };
1100        for i in 0..16 {
1101            // win[i] contains (i+1)*P; we want to keep it if (and only if)
1102            // i+1 == f.
1103            // Values a-b and b-a both have their high bit equal to 0 only
1104            // if a == b.
1105            let j = (i as u32) + 1;
1106            let w = !(f.wrapping_sub(j) | j.wrapping_sub(f));
1107            let w = ((w as i32) >> 31) as u32;
1108
1109            P.x.set_cond(&win[i].x, w);
1110            P.y.set_cond(&win[i].y, w);
1111        }
1112
1113        // Negate the returned value if needed.
1114        P.y.set_cond(&-P.y, s);
1115        let fz = (((f as i32) - 1) >> 8) as u32;
1116
1117        (P, fz)
1118    }
1119
1120    /// Lookups a point from a window in affine coordinates, with sign
1121    /// handling (constant-time).
1122    ///
1123    /// The returned point is projective coordinates (which can represent
1124    /// the neutral).
1125    #[inline]
1126    fn lookup_affine_proj(win: &[PointAffine; 16], k: i8) -> Self {
1127        let (P, rz) = Self::lookup_affine(win, k);
1128        Self {
1129            X: P.x,
1130            Y: P.y,
1131            Z: GFsecp256k1::select(&GFsecp256k1::ONE, &GFsecp256k1::ZERO, rz),
1132        }
1133    }
1134
1135    /// Lookups a point from a window in affine coordinates, with sign
1136    /// handling (constant-time), and adds it to the current point.
1137    #[inline]
1138    fn set_lookup_affine_add(&mut self, win: &[PointAffine; 16], k: i8) {
1139        let (P, rz) = Self::lookup_affine(win, k);
1140        self.set_add_affine(&P, rz);
1141    }
1142
1143    /// Sets this point by multiplying the conventional generator by the
1144    /// provided scalar.
1145    ///
1146    /// This operation is constant-time. It is faster than using the
1147    /// generic multiplication on `Self::BASE`.
1148    pub fn set_mulgen(&mut self, n: &Scalar) {
1149        // TODO: use the endomorphism to speed up this computation
1150        // (see jq255.rs and gls254.rs for examples)
1151
1152        // Recode the scalar into 52 signed digits.
1153        let sd = Self::recode_scalar(n);
1154
1155        // We process four chunks in parallel. Each chunk is 13 digits.
1156        *self = Self::lookup_affine_proj(&PRECOMP_G, sd[12]);
1157        self.set_lookup_affine_add(&PRECOMP_G65, sd[25]);
1158        self.set_lookup_affine_add(&PRECOMP_G130, sd[38]);
1159        self.set_lookup_affine_add(&PRECOMP_G195, sd[51]);
1160
1161        // Process the digits in high-to-low order.
1162        for i in (0..12).rev() {
1163            self.set_xdouble(5);
1164            self.set_lookup_affine_add(&PRECOMP_G, sd[i]);
1165            self.set_lookup_affine_add(&PRECOMP_G65, sd[i + 13]);
1166            self.set_lookup_affine_add(&PRECOMP_G130, sd[i + 26]);
1167            self.set_lookup_affine_add(&PRECOMP_G195, sd[i + 39]);
1168        }
1169    }
1170
1171    /// Creates a point by multiplying the conventional generator by the
1172    /// provided scalar.
1173    ///
1174    /// This operation is constant-time. It is faster than using the
1175    /// generic multiplication on `Self::BASE`.
1176    #[inline]
1177    pub fn mulgen(n: &Scalar) -> Self {
1178        let mut P = Self::NEUTRAL;
1179        P.set_mulgen(n);
1180        P
1181    }
1182
1183    /// 5-bit wNAF recoding of a scalar; output is a sequence of 257
1184    /// digits.
1185    ///
1186    /// Non-zero digits have an odd value, between -15 and +15
1187    /// (inclusive). (The recoding is constant-time, but use of wNAF is
1188    /// inherently non-constant-time.)
1189    fn recode_scalar_NAF(n: &Scalar) -> [i8; 257] {
1190        // We use a branchless algorithm to avoid misprediction
1191        // penalties.
1192        //
1193        // Let x be the current (complete) integer:
1194        //  - If x is even, then the next digit is 0.
1195        //  - Otherwise, we produce a digit from the low five bits of
1196        //    x. If these low bits have value v (odd, 1..31 range):
1197        //     - If v <= 15, then the next digit is v.
1198        //     - Otherwise, the next digit is v - 32, and we add 32 to x.
1199        //    When then subtract v from x (i.e. we clear the low five bits).
1200        // Once the digit has been produced, we divide x by 2 and loop.
1201        //
1202        // Since a scalar fits on 256 bits, at most 257 digits are needed.
1203
1204        let mut sd = [0i8; 257];
1205        let bb = n.encode();
1206        let mut x = bb[0] as u32;
1207        for i in 0..257 {
1208            if (i & 7) == 4 && i < 252 {
1209                x += (bb[(i + 4) >> 3] as u32) << 4;
1210            }
1211            let m = (x & 1).wrapping_neg();  // -1 if x is odd, 0 otherwise
1212            let v = x & m & 31;              // low 5 bits if x odd, or 0
1213            let c = (v & 16) << 1;           // carry (0 or 32)
1214            let d = v.wrapping_sub(c);       // next digit
1215            sd[i] = d as i8;
1216            x = x.wrapping_sub(d) >> 1;
1217        }
1218        sd
1219    }
1220
1221    /// 5-bit wNAF recoding of a nonnegative integer.
1222    ///
1223    /// 129 digits are produced (array has size 130, extra value is 0).
1224    /// Non-zero digits have an odd value, between -15 and +15
1225    /// (inclusive). (The recoding is constant-time, but use of wNAF is
1226    /// inherently non-constant-time.)
1227    fn recode_u128_NAF(n: u128) -> [i8; 130] {
1228        // See recode_scalar_NAF() for details.
1229        let mut sd = [0i8; 130];
1230        let mut y = n;
1231        for i in 0..129 {
1232            let x = y as u32;
1233            let m = (x & 1).wrapping_neg();  // -1 if x is odd, 0 otherwise
1234            let v = x & m & 31;              // low 5 bits if x odd, or 0
1235            let c = (v & 16) << 1;           // carry (0 or 32)
1236            sd[i] = v.wrapping_sub(c) as i8;
1237            y = y.wrapping_sub(v as u128).wrapping_add(c as u128) >> 1;
1238        }
1239        sd
1240    }
1241
1242    /// Given scalars `u` and `v`, sets this point to `u*self + v*G`
1243    /// (with `G` being the conventional generator point, aka
1244    /// `Self::BASE`).
1245    ///
1246    /// This function can be used to support ECDSA signature
1247    /// verification.
1248    ///
1249    /// THIS FUNCTION IS NOT CONSTANT-TIME; it shall be used only with
1250    /// public data.
1251    pub fn set_mul_add_mulgen_vartime(&mut self, u: &Scalar, v: &Scalar) {
1252        // Split the first scalar with the endomorphism.
1253        let (u0, s0, u1, s1) = Self::split_theta(u);
1254
1255        // Compute the window for the current point:
1256        //   win[i] = (2*i+1)*self    (i = 0 to 7)
1257        let mut win = [Self::NEUTRAL; 8];
1258        let Q = self.double();
1259        win[0] = *self;
1260        for i in 1..8 {
1261            win[i] = win[i - 1] + Q;
1262        }
1263
1264        // Compute the 5-bit windows for the first scalar:
1265        //   win0[i] = (2*i+1)*sgn(k0)*self         (i = 0 to 7)
1266        //   win1[i] = (2*i+1)*sgn(k1)*zeta(self)   (i = 0 to 7)
1267        // with zeta(x, y) = (x*epsilon, y) for epsilon^3 = 1 (this is an
1268        // endomorphism on the group).
1269        let mut win0 = [Self::NEUTRAL; 8];
1270        win0[0] = *self;
1271        win0[0].set_condneg(s0);
1272        let Q = win0[0].double();
1273        for i in 1..8 {
1274            win0[i] = win0[i - 1] + Q;
1275        }
1276        let mut win1 = [Self::NEUTRAL; 8];
1277        for i in 0..8 {
1278            win1[i] = win0[i].zeta();
1279            win1[i].set_condneg(s0 ^ s1);
1280        }
1281
1282        // Recode the two half-width scalars u0 and u1, and the
1283        // full-width scalar v, into 5-bit wNAF.
1284        let sd0 = Self::recode_u128_NAF(u0);
1285        let sd1 = Self::recode_u128_NAF(u1);
1286        let sd2 = Self::recode_scalar_NAF(v);
1287
1288        let mut zz = true;
1289        let mut ndbl = 0u32;
1290        for i in (0..130).rev() {
1291            // We have one more doubling to perform.
1292            ndbl += 1;
1293
1294            // Get next digits. If they are all zeros, then we can loop
1295            // immediately.
1296            let e0 = sd0[i];
1297            let e1 = sd1[i];
1298            let e2 = sd2[i];
1299            let e3 = if i < 127 { sd2[i + 130] } else { 0 };
1300            if ((e0 as u32) | (e1 as u32) | (e2 as u32) | (e3 as u32)) == 0 {
1301                continue;
1302            }
1303
1304            // Apply accumulated doubles.
1305            if zz {
1306                *self = Self::NEUTRAL;
1307                zz = false;
1308            } else {
1309                self.set_xdouble(ndbl);
1310            }
1311            ndbl = 0u32;
1312
1313            // Process digits.
1314            if e0 != 0 {
1315                if e0 > 0 {
1316                    self.set_add(&win0[e0 as usize >> 1]);
1317                } else {
1318                    self.set_sub(&win0[(-e0) as usize >> 1]);
1319                }
1320            }
1321            if e1 != 0 {
1322                if e1 > 0 {
1323                    self.set_add(&win1[e1 as usize >> 1]);
1324                } else {
1325                    self.set_sub(&win1[(-e1) as usize >> 1]);
1326                }
1327            }
1328            if e2 != 0 {
1329                if e2 > 0 {
1330                    self.set_add_affine(&PRECOMP_G[e2 as usize - 1], 0);
1331                } else {
1332                    self.set_sub_affine(&PRECOMP_G[(-e2) as usize - 1], 0);
1333                }
1334            }
1335            if e3 != 0 {
1336                if e3 > 0 {
1337                    self.set_add_affine(&PRECOMP_G130[e3 as usize - 1], 0);
1338                } else {
1339                    self.set_sub_affine(&PRECOMP_G130[(-e3) as usize - 1], 0);
1340                }
1341            }
1342        }
1343
1344        if zz {
1345            *self = Self::NEUTRAL;
1346        } else {
1347            if ndbl > 0 {
1348                self.set_xdouble(ndbl);
1349            }
1350        }
1351    }
1352
1353    /// Given scalars `u` and `v`, returns point `u*self + v*G`
1354    /// (with `G` being the conventional generator point, aka
1355    /// `Self::BASE`).
1356    ///
1357    /// This function can be used to support ECDSA signature
1358    /// verification.
1359    ///
1360    /// THIS FUNCTION IS NOT CONSTANT-TIME; it shall be used only with
1361    /// public data.
1362    #[inline(always)]
1363    pub fn mul_add_mulgen_vartime(self, u: &Scalar, v: &Scalar) -> Self {
1364        let mut R = self;
1365        R.set_mul_add_mulgen_vartime(u, v);
1366        R
1367    }
1368
1369    /// Check whether `s*G = R + k*Q`, for the provided scalars `s`
1370    /// and `k`, provided points `Q` (`self`) and `R`, and conventional
1371    /// generator `G`.
1372    ///
1373    /// Returned value is true on match, false otherwise. This function
1374    /// is meant to support Schnorr signature verification (e.g. as defined
1375    /// in FROST).
1376    ///
1377    /// THIS FUNCTION IS NOT CONSTANT-TIME; it shall be used only with
1378    /// public data.
1379    pub fn verify_helper_vartime(self,
1380        R: &Point, s: &Scalar, k: &Scalar) -> bool
1381    {
1382        // We use mul_add_mulgen_vartime(), which leverages the fast
1383        // endomorphism on the curve.
1384        let T = self.mul_add_mulgen_vartime(&(-k), s);
1385        T.equals(*R) != 0
1386    }
1387}
1388
1389impl Add<Point> for Point {
1390    type Output = Point;
1391
1392    #[inline(always)]
1393    fn add(self, other: Point) -> Point {
1394        let mut r = self;
1395        r.set_add(&other);
1396        r
1397    }
1398}
1399
1400impl Add<&Point> for Point {
1401    type Output = Point;
1402
1403    #[inline(always)]
1404    fn add(self, other: &Point) -> Point {
1405        let mut r = self;
1406        r.set_add(other);
1407        r
1408    }
1409}
1410
1411impl Add<Point> for &Point {
1412    type Output = Point;
1413
1414    #[inline(always)]
1415    fn add(self, other: Point) -> Point {
1416        let mut r = *self;
1417        r.set_add(&other);
1418        r
1419    }
1420}
1421
1422impl Add<&Point> for &Point {
1423    type Output = Point;
1424
1425    #[inline(always)]
1426    fn add(self, other: &Point) -> Point {
1427        let mut r = *self;
1428        r.set_add(other);
1429        r
1430    }
1431}
1432
1433impl AddAssign<Point> for Point {
1434    #[inline(always)]
1435    fn add_assign(&mut self, other: Point) {
1436        self.set_add(&other);
1437    }
1438}
1439
1440impl AddAssign<&Point> for Point {
1441    #[inline(always)]
1442    fn add_assign(&mut self, other: &Point) {
1443        self.set_add(other);
1444    }
1445}
1446
1447impl Mul<Scalar> for Point {
1448    type Output = Point;
1449
1450    #[inline(always)]
1451    fn mul(self, other: Scalar) -> Point {
1452        let mut r = self;
1453        r.set_mul(&other);
1454        r
1455    }
1456}
1457
1458impl Mul<&Scalar> for Point {
1459    type Output = Point;
1460
1461    #[inline(always)]
1462    fn mul(self, other: &Scalar) -> Point {
1463        let mut r = self;
1464        r.set_mul(other);
1465        r
1466    }
1467}
1468
1469impl Mul<Scalar> for &Point {
1470    type Output = Point;
1471
1472    #[inline(always)]
1473    fn mul(self, other: Scalar) -> Point {
1474        let mut r = *self;
1475        r.set_mul(&other);
1476        r
1477    }
1478}
1479
1480impl Mul<&Scalar> for &Point {
1481    type Output = Point;
1482
1483    #[inline(always)]
1484    fn mul(self, other: &Scalar) -> Point {
1485        let mut r = *self;
1486        r.set_mul(other);
1487        r
1488    }
1489}
1490
1491impl MulAssign<Scalar> for Point {
1492    #[inline(always)]
1493    fn mul_assign(&mut self, other: Scalar) {
1494        self.set_mul(&other);
1495    }
1496}
1497
1498impl MulAssign<&Scalar> for Point {
1499    #[inline(always)]
1500    fn mul_assign(&mut self, other: &Scalar) {
1501        self.set_mul(other);
1502    }
1503}
1504
1505impl Mul<Point> for Scalar {
1506    type Output = Point;
1507
1508    #[inline(always)]
1509    fn mul(self, other: Point) -> Point {
1510        let mut r = other;
1511        r.set_mul(&self);
1512        r
1513    }
1514}
1515
1516impl Mul<&Point> for Scalar {
1517    type Output = Point;
1518
1519    #[inline(always)]
1520    fn mul(self, other: &Point) -> Point {
1521        let mut r = *other;
1522        r.set_mul(&self);
1523        r
1524    }
1525}
1526
1527impl Mul<Point> for &Scalar {
1528    type Output = Point;
1529
1530    #[inline(always)]
1531    fn mul(self, other: Point) -> Point {
1532        let mut r = other;
1533        r.set_mul(self);
1534        r
1535    }
1536}
1537
1538impl Mul<&Point> for &Scalar {
1539    type Output = Point;
1540
1541    #[inline(always)]
1542    fn mul(self, other: &Point) -> Point {
1543        let mut r = *other;
1544        r.set_mul(self);
1545        r
1546    }
1547}
1548
1549impl Mul<u64> for Point {
1550    type Output = Point;
1551
1552    #[inline(always)]
1553    fn mul(self, other: u64) -> Point {
1554        let mut r = self;
1555        r.set_mul_small(other);
1556        r
1557    }
1558}
1559
1560impl Mul<u64> for &Point {
1561    type Output = Point;
1562
1563    #[inline(always)]
1564    fn mul(self, other: u64) -> Point {
1565        let mut r = *self;
1566        r.set_mul_small(other);
1567        r
1568    }
1569}
1570
1571impl MulAssign<u64> for Point {
1572    #[inline(always)]
1573    fn mul_assign(&mut self, other: u64) {
1574        self.set_mul_small(other);
1575    }
1576}
1577
1578impl Mul<Point> for u64 {
1579    type Output = Point;
1580
1581    #[inline(always)]
1582    fn mul(self, other: Point) -> Point {
1583        let mut r = other;
1584        r.set_mul_small(self);
1585        r
1586    }
1587}
1588
1589impl Mul<&Point> for u64 {
1590    type Output = Point;
1591
1592    #[inline(always)]
1593    fn mul(self, other: &Point) -> Point {
1594        let mut r = *other;
1595        r.set_mul_small(self);
1596        r
1597    }
1598}
1599
1600impl Neg for Point {
1601    type Output = Point;
1602
1603    #[inline(always)]
1604    fn neg(self) -> Point {
1605        let mut r = self;
1606        r.set_neg();
1607        r
1608    }
1609}
1610
1611impl Neg for &Point {
1612    type Output = Point;
1613
1614    #[inline(always)]
1615    fn neg(self) -> Point {
1616        let mut r = *self;
1617        r.set_neg();
1618        r
1619    }
1620}
1621
1622impl Sub<Point> for Point {
1623    type Output = Point;
1624
1625    #[inline(always)]
1626    fn sub(self, other: Point) -> Point {
1627        let mut r = self;
1628        r.set_sub(&other);
1629        r
1630    }
1631}
1632
1633impl Sub<&Point> for Point {
1634    type Output = Point;
1635
1636    #[inline(always)]
1637    fn sub(self, other: &Point) -> Point {
1638        let mut r = self;
1639        r.set_sub(other);
1640        r
1641    }
1642}
1643
1644impl Sub<Point> for &Point {
1645    type Output = Point;
1646
1647    #[inline(always)]
1648    fn sub(self, other: Point) -> Point {
1649        let mut r = *self;
1650        r.set_sub(&other);
1651        r
1652    }
1653}
1654
1655impl Sub<&Point> for &Point {
1656    type Output = Point;
1657
1658    #[inline(always)]
1659    fn sub(self, other: &Point) -> Point {
1660        let mut r = *self;
1661        r.set_sub(other);
1662        r
1663    }
1664}
1665
1666impl SubAssign<Point> for Point {
1667    #[inline(always)]
1668    fn sub_assign(&mut self, other: Point) {
1669        self.set_sub(&other);
1670    }
1671}
1672
1673impl SubAssign<&Point> for Point {
1674    #[inline(always)]
1675    fn sub_assign(&mut self, other: &Point) {
1676        self.set_sub(other);
1677    }
1678}
1679
1680// ========================================================================
1681
1682/// A secp256k1 private key simply wraps around a scalar.
1683#[derive(Clone, Copy, Debug)]
1684pub struct PrivateKey {
1685    x: Scalar,   // secret scalar
1686}
1687
1688/// A secp256k1 public key simply wraps around a curve point.
1689#[derive(Clone, Copy, Debug)]
1690pub struct PublicKey {
1691    pub point: Point,
1692}
1693
1694impl PrivateKey {
1695
1696    /// Generates a new private key from a cryptographically secure RNG.
1697    pub fn generate<T: CryptoRng + RngCore>(rng: &mut T) -> Self {
1698        let mut seed = [0u8; 32];
1699        rng.fill_bytes(&mut seed);
1700        Self::from_seed(&seed)
1701    }
1702
1703    /// Instantiates a private key by decoding the provided 32-byte
1704    /// array.
1705    ///
1706    /// The 32 bytes contain the unsigned **big-endian** encoding of the
1707    /// secret scalar (as per SEC1 and RFC 5915). The decoding may fail
1708    /// in the following cases:
1709    ///
1710    ///  - The source slice does not have length exactly 32 bytes.
1711    ///
1712    ///  - The scalar value is zero.
1713    ///
1714    ///  - The scalar value is not lower than the curve order.
1715    ///
1716    /// Decoding is constant-time; side-channels may leak whether the
1717    /// value was valid or not, but not the value itself (nor why it was
1718    /// deemed invalid, if decoding failed).
1719    pub fn decode(buf: &[u8]) -> Option<Self> {
1720        if buf.len() != 32 {
1721            return None;
1722        }
1723        let (x, r) = Scalar::decode32(&bswap32(buf));
1724        if (r & !x.iszero()) != 0  {
1725            Some(Self { x })
1726        } else {
1727            None
1728        }
1729    }
1730
1731    /// Encodes this private key into exactly 32 bytes.
1732    ///
1733    /// Encoding uses the unsigned big-endian convention, as per SEC1 and
1734    /// RFC 5915.
1735    pub fn encode(self) -> [u8; 32] {
1736        let buf = self.x.encode();
1737        bswap32(&buf)
1738    }
1739
1740    /// Instantiates a private key from a random seed.
1741    ///
1742    /// The seed MUST have been generated from a cryptographically secure
1743    /// random source that ensured an entropy of at least 128 bits (which
1744    /// implies that the seed cannot logically have length less than 16
1745    /// bytes). The transform from the seed to the private key is not
1746    /// described by any standard; therefore, for key storage, the
1747    /// private key itself should be stored, not the seed.
1748    ///
1749    /// This process guarantees that the output key is valid (i.e. it is
1750    /// in the proper range, and it is non-zero).
1751    pub fn from_seed(seed: &[u8]) -> Self {
1752        // We use SHA-512 over the input seed to get a pseudo-random
1753        // 512-bit value, which is then reduced modulo the curve order.
1754        // A custom prefix ("crrl scep256k1" in ASCII) is used to avoid
1755        // collisions.
1756        let mut sh = Sha512::new();
1757        sh.update(&[ 0x63, 0x72, 0x72, 0x6c, 0x20, 0x73, 0x65,
1758                     0x63, 0x70, 0x32, 0x35, 0x36, 0x6b, 0x31 ]);
1759        sh.update(seed);
1760        let mut x = Scalar::decode_reduce(&sh.finalize()[..]);
1761
1762        // We make sure we do not get zero by replacing the value with 1
1763        // in that case. The probability that such a thing happens is
1764        // negligible.
1765        x.set_cond(&Scalar::ONE, x.iszero());
1766        Self { x }
1767    }
1768
1769    /// Gets the public key corresponding to that private key.
1770    pub fn to_public_key(self) -> PublicKey {
1771        PublicKey { point: Point::mulgen(&self.x) }
1772    }
1773
1774    /// Signs a hash value with ECDSA.
1775    ///
1776    /// The hash value may have an arbitrary length, but in general
1777    /// should be a SHA-256 output. The provided hash value (`hv`) MUST
1778    /// be a real hash value, not a raw unhashed message (in particular,
1779    /// if `hv` is longer than 256 bits, it is internally truncated).
1780    ///
1781    /// An ECDSA signature is a pair of integers (r, s), both being taken
1782    /// modulo the curve order n. This function encodes r and s over 32
1783    /// bytes each (unsigned big-endian notation), and returns their
1784    /// concatenation.
1785    ///
1786    /// Additional randomness can be provided as the `extra_rand` slice.
1787    /// It is not necessary for security that the extra randomness is
1788    /// cryptographically secure. If `extra_rand` has length 0, then the
1789    /// signature generation process is deterministic (but still safe!).
1790    /// Note: this does not follow the exact process of RFC 6979, but the
1791    /// same principle is applied.
1792    pub fn sign_hash(self, hv: &[u8], extra_rand: &[u8]) -> [u8; 64] {
1793
1794        // Convert the input hash value into an integer modulo n:
1795        //  - If hv.len() > 32, keep only the leftmost 32 bytes.
1796        //  - Interpret the value as big-endian.
1797        //  - Reduce the integer modulo n.
1798        // The result is h.
1799        let mut tmp = [0u8; 32];
1800        if hv.len() >= 32 {
1801            tmp[..].copy_from_slice(&hv[..32]);
1802        } else {
1803            tmp[(32 - hv.len())..32].copy_from_slice(hv);
1804        }
1805        let h = Scalar::decode_reduce(&bswap32(&tmp));
1806
1807        // Compute k by reducing the SHA-512 hash value of the concatenation
1808        // of the private key (over 32 bytes, little-endian), the h scalar
1809        // (32 bytes, little-endian), and the extra randomness (if provided).
1810        // If 0 is obtained (this has negligible probability), then 1 is
1811        // used instead.
1812        let mut sh = Sha512::new();
1813        sh.update(&self.x.encode());
1814        sh.update(&h.encode());
1815        if extra_rand.len() > 0 {
1816            sh.update(&extra_rand);
1817        }
1818        let mut k = Scalar::decode_reduce(&sh.finalize());
1819        k.set_cond(&Scalar::ONE, k.iszero());
1820
1821        loop {
1822            // R = k*G; then encode x(R), and decode-reduce as a scalar
1823            let R = Point::mulgen(&k);
1824            let xR_le = bswap32(&R.encode_compressed()[1..33]);
1825            let r = Scalar::decode_reduce(&xR_le);
1826
1827            // Compute s.
1828            let s = (h + self.x * r) / k;
1829
1830            // If s and r are both non-zero, then we have our signature.
1831            if (r.iszero() | s.iszero()) == 0 {
1832                let mut sig = [0u8; 64];
1833                sig[..32].copy_from_slice(&bswap32(&r.encode()));
1834                sig[32..].copy_from_slice(&bswap32(&s.encode()));
1835                return sig;
1836            }
1837
1838            // It is extremely improbable that either r or s is zero, and
1839            // nobody knows an input that would yield such a result.
1840            // Just in case, though, we increment k in that case, and
1841            // try again.
1842            k += Scalar::ONE;
1843            k.set_cond(&Scalar::ONE, k.iszero());
1844        }
1845    }
1846}
1847
1848impl PublicKey {
1849
1850    /// Decodes a public key from bytes.
1851    ///
1852    /// This function accepts both compressed (33 bytes) and uncompressed
1853    /// (65 bytes) formats. The point is always verified to be a valid
1854    /// curve point. Note that the neutral point (the
1855    /// "point-at-infinity") is explicitly rejected.
1856    pub fn decode(buf: &[u8]) -> Option<Self> {
1857        let point = Point::decode(buf)?;
1858        if point.isneutral() != 0 {
1859            return None;
1860        }
1861        Some(Self { point })
1862    }
1863
1864    /// Encodes this public key into the compressed format (33 bytes).
1865    ///
1866    /// The first byte of the encoding always has value 0x02 or 0x03.
1867    pub fn encode_compressed(self) -> [u8; 33] {
1868        self.point.encode_compressed()
1869    }
1870
1871    /// Encodes this public key into the compressed format (65 bytes).
1872    ///
1873    /// The first byte of the encoding always has value 0x04.
1874    pub fn encode_uncompressed(self) -> [u8; 65] {
1875        self.point.encode_uncompressed()
1876    }
1877
1878    /// Verifies a signature on a given hashed message.
1879    ///
1880    /// The signature (`sig`) MUST have an even length; the first half of
1881    /// the signature is interpreted as the "r" integer, while the second
1882    /// half is "s" (both use unsigned big-endian convention).
1883    /// Out-of-range values are rejected. The hashed message is provided
1884    /// as `hv`; it is nominally the output of a suitable hash function
1885    /// (often SHA-256) computed over the actual message. This function
1886    /// can tolerate arbitrary hash output lengths; however, for proper
1887    /// security, the hash output must not be too short, and it must be
1888    /// an actual hash function output, not raw structured data.
1889    ///
1890    /// Note: this function is not constant-time; it assumes that the
1891    /// public key and signature value are public data.
1892    pub fn verify_hash(self, sig: &[u8], hv: &[u8]) -> bool {
1893        // Recover r and s as scalars. We truncate/pad them to 32 bytes
1894        // (verifying that the removed bytes are all zeros), then decode
1895        // them as scalars. Zeros and out-of-range values are rejected.
1896        let sig_len = sig.len();
1897        if (sig_len & 1) != 0 {
1898            return false;
1899        }
1900        let rlen = sig_len >> 1;
1901        let mut rb = [0u8; 32];
1902        let mut sb = [0u8; 32];
1903        if rlen > 32 {
1904            for i in 0..(rlen - 32) {
1905                if sig[i] != 0 || sig[rlen + i] != 0 {
1906                    return false;
1907                }
1908            }
1909            rb[..].copy_from_slice(&sig[(rlen - 32)..rlen]);
1910            sb[..].copy_from_slice(&sig[(sig_len - 32)..sig_len]);
1911        } else {
1912            rb[(32 - rlen)..].copy_from_slice(&sig[..rlen]);
1913            sb[(32 - rlen)..].copy_from_slice(&sig[rlen..]);
1914        }
1915        let (r, cr) = Scalar::decode32(&bswap32(&rb));
1916        if cr == 0 || r.iszero() != 0 {
1917            return false;
1918        }
1919        let (s, cs) = Scalar::decode32(&bswap32(&sb));
1920        if cs == 0 || s.iszero() != 0 {
1921            return false;
1922        }
1923
1924        // Convert the input hash value into an integer modulo n.
1925        let mut tmp = [0u8; 32];
1926        if hv.len() >= 32 {
1927            tmp[..].copy_from_slice(&hv[..32]);
1928        } else {
1929            tmp[32 - hv.len() .. 32].copy_from_slice(hv);
1930        }
1931        let h = Scalar::decode_reduce(&bswap32(&tmp));
1932
1933        // Verification algorithm.
1934        let w = Scalar::ONE / s;
1935        let R = self.point.mul_add_mulgen_vartime(&(r * w), &(h * w));
1936        let xR_le = bswap32(&R.encode_compressed()[1..33]);
1937        let rr = Scalar::decode_reduce(&xR_le);
1938
1939        // Signature is valid if the rebuilt r value (in rr) matches
1940        // the one that was received.
1941        return r.equals(rr) != 0;
1942    }
1943}
1944
1945// ========================================================================
1946
1947// We hardcode known multiples of the points G, (2^65)*G, (2^130)*G
1948// and (2^195)*G, with G being the conventional base point. These are
1949// used to speed mulgen() operations up. The points are stored in affine
1950// coordinates, i.e. their Z coordinate is implicitly equal to 1.
1951
1952/// A curve point (non-infinity) in affine coordinates.
1953#[derive(Clone, Copy, Debug)]
1954struct PointAffine {
1955    x: GFsecp256k1,
1956    y: GFsecp256k1,
1957}
1958
1959// Points i*G for i = 1 to 16, in affine coordinates.
1960static PRECOMP_G: [PointAffine; 16] = [
1961    // G * 1
1962    PointAffine { x: GFsecp256k1::w64be(0x79BE667EF9DCBBAC, 0x55A06295CE870B07,
1963                                        0x029BFCDB2DCE28D9, 0x59F2815B16F81798),
1964                  y: GFsecp256k1::w64be(0x483ADA7726A3C465, 0x5DA4FBFC0E1108A8,
1965                                        0xFD17B448A6855419, 0x9C47D08FFB10D4B8) },
1966    // G * 2
1967    PointAffine { x: GFsecp256k1::w64be(0xC6047F9441ED7D6D, 0x3045406E95C07CD8,
1968                                        0x5C778E4B8CEF3CA7, 0xABAC09B95C709EE5),
1969                  y: GFsecp256k1::w64be(0x1AE168FEA63DC339, 0xA3C58419466CEAEE,
1970                                        0xF7F632653266D0E1, 0x236431A950CFE52A) },
1971    // G * 3
1972    PointAffine { x: GFsecp256k1::w64be(0xF9308A019258C310, 0x49344F85F89D5229,
1973                                        0xB531C845836F99B0, 0x8601F113BCE036F9),
1974                  y: GFsecp256k1::w64be(0x388F7B0F632DE814, 0x0FE337E62A37F356,
1975                                        0x6500A99934C2231B, 0x6CB9FD7584B8E672) },
1976    // G * 4
1977    PointAffine { x: GFsecp256k1::w64be(0xE493DBF1C10D80F3, 0x581E4904930B1404,
1978                                        0xCC6C13900EE07584, 0x74FA94ABE8C4CD13),
1979                  y: GFsecp256k1::w64be(0x51ED993EA0D455B7, 0x5642E2098EA51448,
1980                                        0xD967AE33BFBDFE40, 0xCFE97BDC47739922) },
1981    // G * 5
1982    PointAffine { x: GFsecp256k1::w64be(0x2F8BDE4D1A072093, 0x55B4A7250A5C5128,
1983                                        0xE88B84BDDC619AB7, 0xCBA8D569B240EFE4),
1984                  y: GFsecp256k1::w64be(0xD8AC222636E5E3D6, 0xD4DBA9DDA6C9C426,
1985                                        0xF788271BAB0D6840, 0xDCA87D3AA6AC62D6) },
1986    // G * 6
1987    PointAffine { x: GFsecp256k1::w64be(0xFFF97BD5755EEEA4, 0x20453A14355235D3,
1988                                        0x82F6472F8568A18B, 0x2F057A1460297556),
1989                  y: GFsecp256k1::w64be(0xAE12777AACFBB620, 0xF3BE96017F45C560,
1990                                        0xDE80F0F6518FE4A0, 0x3C870C36B075F297) },
1991    // G * 7
1992    PointAffine { x: GFsecp256k1::w64be(0x5CBDF0646E5DB4EA, 0xA398F365F2EA7A0E,
1993                                        0x3D419B7E0330E39C, 0xE92BDDEDCAC4F9BC),
1994                  y: GFsecp256k1::w64be(0x6AEBCA40BA255960, 0xA3178D6D861A54DB,
1995                                        0xA813D0B813FDE7B5, 0xA5082628087264DA) },
1996    // G * 8
1997    PointAffine { x: GFsecp256k1::w64be(0x2F01E5E15CCA351D, 0xAFF3843FB70F3C2F,
1998                                        0x0A1BDD05E5AF888A, 0x67784EF3E10A2A01),
1999                  y: GFsecp256k1::w64be(0x5C4DA8A741539949, 0x293D082A132D13B4,
2000                                        0xC2E213D6BA5B7617, 0xB5DA2CB76CBDE904) },
2001    // G * 9
2002    PointAffine { x: GFsecp256k1::w64be(0xACD484E2F0C7F653, 0x09AD178A9F559ABD,
2003                                        0xE09796974C57E714, 0xC35F110DFC27CCBE),
2004                  y: GFsecp256k1::w64be(0xCC338921B0A7D9FD, 0x64380971763B61E9,
2005                                        0xADD888A4375F8E0F, 0x05CC262AC64F9C37) },
2006    // G * 10
2007    PointAffine { x: GFsecp256k1::w64be(0xA0434D9E47F3C862, 0x35477C7B1AE6AE5D,
2008                                        0x3442D49B1943C2B7, 0x52A68E2A47E247C7),
2009                  y: GFsecp256k1::w64be(0x893ABA425419BC27, 0xA3B6C7E693A24C69,
2010                                        0x6F794C2ED877A159, 0x3CBEE53B037368D7) },
2011    // G * 11
2012    PointAffine { x: GFsecp256k1::w64be(0x774AE7F858A9411E, 0x5EF4246B70C65AAC,
2013                                        0x5649980BE5C17891, 0xBBEC17895DA008CB),
2014                  y: GFsecp256k1::w64be(0xD984A032EB6B5E19, 0x0243DD56D7B7B365,
2015                                        0x372DB1E2DFF9D6A8, 0x301D74C9C953C61B) },
2016    // G * 12
2017    PointAffine { x: GFsecp256k1::w64be(0xD01115D548E7561B, 0x15C38F004D734633,
2018                                        0x687CF4419620095B, 0xC5B0F47070AFE85A),
2019                  y: GFsecp256k1::w64be(0xA9F34FFDC815E0D7, 0xA8B64537E17BD815,
2020                                        0x79238C5DD9A86D52, 0x6B051B13F4062327) },
2021    // G * 13
2022    PointAffine { x: GFsecp256k1::w64be(0xF28773C2D975288B, 0xC7D1D205C3748651,
2023                                        0xB075FBC6610E58CD, 0xDEEDDF8F19405AA8),
2024                  y: GFsecp256k1::w64be(0x0AB0902E8D880A89, 0x758212EB65CDAF47,
2025                                        0x3A1A06DA521FA91F, 0x29B5CB52DB03ED81) },
2026    // G * 14
2027    PointAffine { x: GFsecp256k1::w64be(0x499FDF9E895E719C, 0xFD64E67F07D38E32,
2028                                        0x26AA7B63678949E6, 0xE49B241A60E823E4),
2029                  y: GFsecp256k1::w64be(0xCAC2F6C4B54E8551, 0x90F044E4A7B3D464,
2030                                        0x464279C27A3F95BC, 0xC65F40D403A13F5B) },
2031    // G * 15
2032    PointAffine { x: GFsecp256k1::w64be(0xD7924D4F7D43EA96, 0x5A465AE3095FF411,
2033                                        0x31E5946F3C85F79E, 0x44ADBCF8E27E080E),
2034                  y: GFsecp256k1::w64be(0x581E2872A86C72A6, 0x83842EC228CC6DEF,
2035                                        0xEA40AF2BD896D3A5, 0xC504DC9FF6A26B58) },
2036    // G * 16
2037    PointAffine { x: GFsecp256k1::w64be(0xE60FCE93B59E9EC5, 0x3011AABC21C23E97,
2038                                        0xB2A31369B87A5AE9, 0xC44EE89E2A6DEC0A),
2039                  y: GFsecp256k1::w64be(0xF7E3507399E59592, 0x9DB99F34F5793710,
2040                                        0x1296891E44D23F0B, 0xE1F32CCE69616821) },
2041];
2042
2043// Points i*(2^65)*G for i = 1 to 16, in affine coordinates.
2044static PRECOMP_G65: [PointAffine; 16] = [
2045    // (2^65)*G * 1
2046    PointAffine { x: GFsecp256k1::w64be(0x8D26200250CEBDAE, 0x120EF31B04C80CD5,
2047                                        0x0D4CDDC8EADBCF29, 0xFC696D32C0ADE462),
2048                  y: GFsecp256k1::w64be(0xEBED3BB4715BF437, 0xD31F6F2DC3EE36BA,
2049                                        0x1D4AFB4E72678B3A, 0xD8E0A8B90F26470C) },
2050    // (2^65)*G * 2
2051    PointAffine { x: GFsecp256k1::w64be(0x1238C0766EAEBEA9, 0xCE4068A1F594D03B,
2052                                        0x8ED4930D072D9C8B, 0x9164643E1516E633),
2053                  y: GFsecp256k1::w64be(0x8A9DB02DBB271359, 0xD6C979E2D1C3DC17,
2054                                        0x0946252DCC740228, 0x05CDB728C77B7805) },
2055    // (2^65)*G * 3
2056    PointAffine { x: GFsecp256k1::w64be(0x17C072D56BDD1382, 0xA782481B8AA4D223,
2057                                        0x2DB794385870BCAD, 0xC3063330A5CD5379),
2058                  y: GFsecp256k1::w64be(0xD901BDF4283DA064, 0xE77C1247AF1D034F,
2059                                        0x8959AC76265BAD0D, 0xF7CAE051B108CD25) },
2060    // (2^65)*G * 4
2061    PointAffine { x: GFsecp256k1::w64be(0x271D5B0770CB9C15, 0xE7B2EA758A6A11B9,
2062                                        0xCDDCD7282B0EC216, 0x19B01552788E7A66),
2063                  y: GFsecp256k1::w64be(0x5D3AA45834E7F491, 0xE457D09949AC877F,
2064                                        0xE2A065E3508A824E, 0x7A8D7258E03C9727) },
2065    // (2^65)*G * 5
2066    PointAffine { x: GFsecp256k1::w64be(0xAC2ACB9B21999A70, 0x540708AB68338266,
2067                                        0xAEF650EED81C5B30, 0xDA1E87D8A8A923B7),
2068                  y: GFsecp256k1::w64be(0x7684428511C1724D, 0x1C9AFA0DF13D9EB3,
2069                                        0x60B0D0BF12D27A4F, 0xA2DC124AD7CD20A6) },
2070    // (2^65)*G * 6
2071    PointAffine { x: GFsecp256k1::w64be(0x88271C02621192F9, 0xBA6B25EF9CB2256E,
2072                                        0xAC32A5F91FD25EA9, 0x5793C018CA2D8DAE),
2073                  y: GFsecp256k1::w64be(0xD719DD53507176AA, 0x401C8B3AE5ABF5AC,
2074                                        0xC300876DC717D099, 0xFB426C0F3E1E77D9) },
2075    // (2^65)*G * 7
2076    PointAffine { x: GFsecp256k1::w64be(0x15B8390D652D7338, 0xE18EE09197E0E176,
2077                                        0x74F8C4BAFA2E7B85, 0x8F5BADC99C89240F),
2078                  y: GFsecp256k1::w64be(0x786CF20C8EFE8D08, 0x3ABDD7CCC7A59F99,
2079                                        0xB30367AB5C1A3335, 0x2E2F9EF8E326F04A) },
2080    // (2^65)*G * 8
2081    PointAffine { x: GFsecp256k1::w64be(0x85672C7D2DE0B7DA, 0x2BD1770D89665868,
2082                                        0x741B3F9AF7643397, 0x721D74D28134AB83),
2083                  y: GFsecp256k1::w64be(0x7C481B9B5B43B2EB, 0x6374049BFA62C2E5,
2084                                        0xE77F17FCC5298F44, 0xC8E3094F790313A6) },
2085    // (2^65)*G * 9
2086    PointAffine { x: GFsecp256k1::w64be(0xED621F7798ADD722, 0xB0DC5E529C6FEC6B,
2087                                        0xDFF60827B0B12C85, 0x18D798DC761F1075),
2088                  y: GFsecp256k1::w64be(0x5768C18656350E03, 0x1CE9AEBA20F74824,
2089                                        0x948E785AD74ED8ED, 0x939D44A1B0F3B558) },
2090    // (2^65)*G * 10
2091    PointAffine { x: GFsecp256k1::w64be(0xEAD4FA2F0A1516E0, 0xD92A75CB7AF3930E,
2092                                        0x6A25734CC87BCC49, 0x5F29B66EB89447A0),
2093                  y: GFsecp256k1::w64be(0xB45174E03831FF21, 0xCE27BB0B2B6F2CB9,
2094                                        0xF5D2A845D92EDA06, 0x5A6036BC79163281) },
2095    // (2^65)*G * 11
2096    PointAffine { x: GFsecp256k1::w64be(0x5F950F20B610C06B, 0x76949DAB52FC6149,
2097                                        0x97D254BE0A1330A0, 0x493F1EA21D608864),
2098                  y: GFsecp256k1::w64be(0x26F67B7E7DC4C006, 0x2E3F482F4316F7A9,
2099                                        0xE794BA1390DF25D9, 0x64EA7D7B75B36550) },
2100    // (2^65)*G * 12
2101    PointAffine { x: GFsecp256k1::w64be(0xCEB67E812E3E4A29, 0xAA6A8311986EC5AB,
2102                                        0x431E8524F124E1FB, 0xA950FAFD1EE503A6),
2103                  y: GFsecp256k1::w64be(0x5E6A8545AC390613, 0xB823DF78109CD86B,
2104                                        0x4B896D95EE69E2F3, 0x1FFD40D94E98C4D1) },
2105    // (2^65)*G * 13
2106    PointAffine { x: GFsecp256k1::w64be(0xA9AAF56B5016DB58, 0x5B8116DDCBAD1169,
2107                                        0x4B16DE8D9DB5EA5A, 0x279CCF4D091B1D7A),
2108                  y: GFsecp256k1::w64be(0xDE7012BEC765B543, 0xBB04D57C8FE914AF,
2109                                        0x663BF17944BE6D9A, 0x80A88EB0E6B5A32F) },
2110    // (2^65)*G * 14
2111    PointAffine { x: GFsecp256k1::w64be(0x07758C6DE814678E, 0xEAFE2E753F2C0693,
2112                                        0x84AD1C823F952889, 0xCADB1BE5796C687A),
2113                  y: GFsecp256k1::w64be(0x6B6039EA9CDC8488, 0xAA540ADD077202B0,
2114                                        0x949F9331AA048403, 0xD9D1005ED089DDA2) },
2115    // (2^65)*G * 15
2116    PointAffine { x: GFsecp256k1::w64be(0x9F46479A69411D57, 0xC3C7EA6ADFA833F9,
2117                                        0x1FB2109AFD30C790, 0x2CE323AE4B14BE0C),
2118                  y: GFsecp256k1::w64be(0x9329281F7B6B346A, 0x61983DA7E41BD909,
2119                                        0xB111BAEB7C16565E, 0xD874F8C18A7B746C) },
2120    // (2^65)*G * 16
2121    PointAffine { x: GFsecp256k1::w64be(0x534CCF6B740F9EC0, 0x36C1861215C8A61F,
2122                                        0x3B89EA46DF2E6D96, 0x998B90BC1F17FC25),
2123                  y: GFsecp256k1::w64be(0xD5715CB09C8B2DDB, 0x462AE3DD32D54355,
2124                                        0x0AE3D277BFDD28DD, 0xD71C7F6ECFE86E76) },
2125];
2126
2127// Points i*(2^130)*G for i = 1 to 16, in affine coordinates.
2128static PRECOMP_G130: [PointAffine; 16] = [
2129    // (2^130)*G * 1
2130    PointAffine { x: GFsecp256k1::w64be(0x7564539E85D56F85, 0x37D6619E1F5C5AA7,
2131                                        0x8D2A3DE0889D1D4E, 0xE8DBCB5729B62026),
2132                  y: GFsecp256k1::w64be(0xC1D685413749B3C6, 0x5231DF524A722925,
2133                                        0x684AACD954B79F33, 0x4172C8FADACE0CF3) },
2134    // (2^130)*G * 2
2135    PointAffine { x: GFsecp256k1::w64be(0x210A917AD9DF2779, 0x6746FF301AD9CCC8,
2136                                        0x78F61A5F1FF4082B, 0x5364DACD57B4A278),
2137                  y: GFsecp256k1::w64be(0x670E1B5450B5E57B, 0x7A39BE81F8D6737D,
2138                                        0x3789E61AAFF20BFC, 0x7F2713FD0C7B2231) },
2139    // (2^130)*G * 3
2140    PointAffine { x: GFsecp256k1::w64be(0x5568DAC679F74A32, 0xEBB5FAD219547AD1,
2141                                        0x66F440ABC1C017B4, 0x70F702D505ED815E),
2142                  y: GFsecp256k1::w64be(0x7A85F8742788BA64, 0x580D6FE01D073F2B,
2143                                        0xEB05F7EEE2582151, 0xD9BBF64C00602DF0) },
2144    // (2^130)*G * 4
2145    PointAffine { x: GFsecp256k1::w64be(0xE4F3FB0176AF85D6, 0x5FF99FF9198C3609,
2146                                        0x1F48E86503681E3E, 0x6686FD5053231E11),
2147                  y: GFsecp256k1::w64be(0x1E63633AD0EF4F1C, 0x1661A6D0EA02B728,
2148                                        0x6CC7E74EC951D1C9, 0x822C38576FEB73BC) },
2149    // (2^130)*G * 5
2150    PointAffine { x: GFsecp256k1::w64be(0x9AA9A7FF54DEBAA0, 0xD30DC06917144F0B,
2151                                        0x1DF5E7985B188A46, 0x56D823710F6AEB45),
2152                  y: GFsecp256k1::w64be(0x5336F7FC662565B2, 0x6A39B258D8C74CF7,
2153                                        0x578DD3874035A888, 0x6AB18C2A27479FAB) },
2154    // (2^130)*G * 6
2155    PointAffine { x: GFsecp256k1::w64be(0x87195A80DC83BE4E, 0xCFC9D4B829725CBE,
2156                                        0x11101C26013C98F2, 0x641753AF1EE840F8),
2157                  y: GFsecp256k1::w64be(0x06031DCC996CE3AE, 0xB15F6DDB4A9A2138,
2158                                        0xDD89C27090A8DFA8, 0x0228269067EED395) },
2159    // (2^130)*G * 7
2160    PointAffine { x: GFsecp256k1::w64be(0x2D492168934B4CE5, 0xBE6F8E222161DE2C,
2161                                        0x80ECCA1E6812AB39, 0xD33B1534E53DADAC),
2162                  y: GFsecp256k1::w64be(0x6B3A38C9BB39F399, 0x8884199D07AC87F8,
2163                                        0xEDCDD04FDBA090C8, 0xE3D18704585E8EB4) },
2164    // (2^130)*G * 8
2165    PointAffine { x: GFsecp256k1::w64be(0x4B30CBB7686773E0, 0x1EC64110ABDB362F,
2166                                        0x88531A825BA17295, 0x3BFEE2233BCDAF2F),
2167                  y: GFsecp256k1::w64be(0x74C6350265BB629B, 0x6F9E2C5777C3C4A9,
2168                                        0x1FDF3C81E4348575, 0x68033D463D26B5B7) },
2169    // (2^130)*G * 9
2170    PointAffine { x: GFsecp256k1::w64be(0x84A517B7E05290EA, 0xD10A1B5E4DCE4564,
2171                                        0xF7B6EAACD75F9C4B, 0x3E6AE00FD4077638),
2172                  y: GFsecp256k1::w64be(0x7B9F0BF5B60EC494, 0x8886EA84D4BC2D84,
2173                                        0x1972106C6C41DCC0, 0x1F86D469AC415EB7) },
2174    // (2^130)*G * 10
2175    PointAffine { x: GFsecp256k1::w64be(0xA4D2802411F577C1, 0xC5D08FBC457A46BD,
2176                                        0x428F4D2AB29475EA, 0xEF622876593E49F0),
2177                  y: GFsecp256k1::w64be(0x1B7AAB6E53FCBD4E, 0x237FB43D851DC788,
2178                                        0x7D1150DDAD78B5FF, 0xB2B1F2984F84B8E0) },
2179    // (2^130)*G * 11
2180    PointAffine { x: GFsecp256k1::w64be(0x5DA4E742B7CB76F4, 0xB6F4FEAABDF4DD5A,
2181                                        0xC8C08D998634A645, 0x2BAAC486B31F9A77),
2182                  y: GFsecp256k1::w64be(0xEE8ECA8A1BDC1F8C, 0x09DDF91432C74CD6,
2183                                        0x3C40261FDE2016A4, 0x3722B1E48FD36174) },
2184    // (2^130)*G * 12
2185    PointAffine { x: GFsecp256k1::w64be(0x900C3241BEE44FE9, 0x0832F51FEB470DEC,
2186                                        0xA2F56E03212A9946, 0x5399F04E6BF05BD6),
2187                  y: GFsecp256k1::w64be(0x6C31F9E8E8B1F0F5, 0xF95C7204570B2439,
2188                                        0xD69853583C4EFB15, 0xDE52AD3BF00D358B) },
2189    // (2^130)*G * 13
2190    PointAffine { x: GFsecp256k1::w64be(0x94B995F51E4B0976, 0x694BEB6BC0698E28,
2191                                        0x0B71CBF2AB17753A, 0xA6D22DACAB359D6C),
2192                  y: GFsecp256k1::w64be(0xCC2C70F0E8B49742, 0xB57CF18D760E7059,
2193                                        0xCE7B03B2E136412B, 0x5BFF9A4C52C9F14C) },
2194    // (2^130)*G * 14
2195    PointAffine { x: GFsecp256k1::w64be(0xF79781E7A4137AC4, 0x7A9A9D009D239B37,
2196                                        0x6CD0FA3CB9F5DE46, 0x8CBA5A110FFCDD69),
2197                  y: GFsecp256k1::w64be(0xF2EF45877691F792, 0xFA1DABBBE9A18626,
2198                                        0xF84C2B7AE5BB71FC, 0xD9276F93D0D887D4) },
2199    // (2^130)*G * 15
2200    PointAffine { x: GFsecp256k1::w64be(0xFDD2FCE57C54C676, 0x553205C63EE71C28,
2201                                        0xC3A2597AC35C0E7D, 0xC14197C5E08ADAEA),
2202                  y: GFsecp256k1::w64be(0x5D5C412719B293AB, 0x8F1AF2F983763114,
2203                                        0x148359BB0D4BFF4D, 0x251A5A6FBED748D1) },
2204    // (2^130)*G * 16
2205    PointAffine { x: GFsecp256k1::w64be(0xCBB434AA7AE1700D, 0xCD15B20B17464817,
2206                                        0xEC11715050E0FA19, 0x2FFE9C29A673059F),
2207                  y: GFsecp256k1::w64be(0x4A1A200AB4DABD17, 0x562D492338B5DFAD,
2208                                        0x41D45E4F0AD5F845, 0xB7DA9642227C070C) },
2209];
2210
2211// Points i*(2^195)*G for i = 1 to 16, in affine coordinates.
2212static PRECOMP_G195: [PointAffine; 16] = [
2213    // (2^195)*G * 1
2214    PointAffine { x: GFsecp256k1::w64be(0x60144494C8F69448, 0x5B85ECB6AEE10956,
2215                                        0xC756267D12894711, 0x922243D5E855B8DA),
2216                  y: GFsecp256k1::w64be(0x8BB5D669F681E646, 0x9E8BE1FD9132E65B,
2217                                        0x543955C27E3F2A4B, 0xAD500590F34E4BBD) },
2218    // (2^195)*G * 2
2219    PointAffine { x: GFsecp256k1::w64be(0xE4A42D43C5CF169D, 0x9391DF6DECF42EE5,
2220                                        0x41B6D8F0C9A13740, 0x1E23632DDA34D24F),
2221                  y: GFsecp256k1::w64be(0x4D9F92E716D1C735, 0x26FC99CCFB8AD34C,
2222                                        0xE886EEDFA8D8E4F1, 0x3A7F7131DEBA9414) },
2223    // (2^195)*G * 3
2224    PointAffine { x: GFsecp256k1::w64be(0x1EB7CB4D971E5316, 0xA209BD338FF36ED9,
2225                                        0xCF4F0DA811F362CD, 0x4A95838EB84DA233),
2226                  y: GFsecp256k1::w64be(0xD984328AE47C84FF, 0x826F3BCD0BDED0AB,
2227                                        0xA336C99981CF0AE9, 0xCB8EA55317C43F18) },
2228    // (2^195)*G * 4
2229    PointAffine { x: GFsecp256k1::w64be(0xFD6451FB84CFB18D, 0x3EF0ACF856C4EF4D,
2230                                        0x0553C562F7AE4D2A, 0x303F2EA33E8F62BB),
2231                  y: GFsecp256k1::w64be(0xE745CEB2B1871578, 0xB6FE7A5C1BC344CC,
2232                                        0xFA2AB492D200E83F, 0xD0AD9086132C0911) },
2233    // (2^195)*G * 5
2234    PointAffine { x: GFsecp256k1::w64be(0xAAA48545E0E226E6, 0x7FBE4AC6C9040AFF,
2235                                        0xB3D427C61FF6C3B8, 0xC3208D14B5BF37FF),
2236                  y: GFsecp256k1::w64be(0xA6BC6AA6CD2927B1, 0x2FFD61B7491637D7,
2237                                        0xBE7E72A29E8F5CD8, 0x72E2CD7501F263F0) },
2238    // (2^195)*G * 6
2239    PointAffine { x: GFsecp256k1::w64be(0x3E419634E156A3A2, 0x4949BC8E8D396FAF,
2240                                        0x09430123677B392B, 0x5C8410AF3BEA0C68),
2241                  y: GFsecp256k1::w64be(0x0123C59D924B21F7, 0xF373CBFE37069306,
2242                                        0x2FA11946303CDA1A, 0xBCBB6FF71A45EDB6) },
2243    // (2^195)*G * 7
2244    PointAffine { x: GFsecp256k1::w64be(0xC7E511DC9DABD507, 0x72576532EFD7DBAE,
2245                                        0xE18BC312477E1DD4, 0x8BEACBB385152AA8),
2246                  y: GFsecp256k1::w64be(0xE9BF1F86DFFE772E, 0xCD7B66963E4F7FA0,
2247                                        0xB3B581714DFD63B1, 0xDA805AA7A782AA01) },
2248    // (2^195)*G * 8
2249    PointAffine { x: GFsecp256k1::w64be(0x1EEE207CB24086BC, 0x716E81A06F9EDBBB,
2250                                        0x0042E2D5DCF3C7A1, 0xFA1D1FB9D5FE696B),
2251                  y: GFsecp256k1::w64be(0x652CBD19AEF6269C, 0xD2B196D12461C95F,
2252                                        0x7A02062E0AFD694E, 0xBB45670E7429337B) },
2253    // (2^195)*G * 9
2254    PointAffine { x: GFsecp256k1::w64be(0x0CFFD9693EB29213, 0x750CC57B7FABCE74,
2255                                        0xD43E6BAB95215B83, 0x6FE50CE90FEF8C18),
2256                  y: GFsecp256k1::w64be(0x831163EB4A1FEB00, 0xD59A834A392A66A2,
2257                                        0xDAFD902840D1AF47, 0x8B41CCDDB1E0280E) },
2258    // (2^195)*G * 10
2259    PointAffine { x: GFsecp256k1::w64be(0x8D9438F5455D7508, 0xEED4A3E62F7F0B57,
2260                                        0x6EB7B64C351C9897, 0xAF75D23C939824D7),
2261                  y: GFsecp256k1::w64be(0x3261E0734FEE6C2A, 0x2CA60BD31AB6EF6F,
2262                                        0x8FB9E2B8326B063D, 0x8A004F489366489F) },
2263    // (2^195)*G * 11
2264    PointAffine { x: GFsecp256k1::w64be(0xCEDC08639C64CD25, 0x38608DB2FD6574FF,
2265                                        0x200255A33F3B48CE, 0x2907F6D12C317482),
2266                  y: GFsecp256k1::w64be(0x413ED3F381BF024F, 0xB8C73D2D1570DE86,
2267                                        0x7FACF5881D6CDFA8, 0x99F2332FE064E123) },
2268    // (2^195)*G * 12
2269    PointAffine { x: GFsecp256k1::w64be(0xF13A99E58DC72FCB, 0x0C62A492D2850704,
2270                                        0x621DDF48F1F433E6, 0x9A9814C417D4B84A),
2271                  y: GFsecp256k1::w64be(0x33C2C8CD0F0BE995, 0xAA6B91CD1E3FE06E,
2272                                        0xB6E37D4710F2D962, 0x85990FC553FD1C81) },
2273    // (2^195)*G * 13
2274    PointAffine { x: GFsecp256k1::w64be(0x5FFAA262A47FAD9E, 0xF51FBF6C76DCFCC2,
2275                                        0xDDE8172EED32DEC4, 0x031D668832363481),
2276                  y: GFsecp256k1::w64be(0x545A43ADE0D50DAE, 0xE362A4FADB98225C,
2277                                        0xD276A0F973BEF10D, 0x45C2A243C3C014F7) },
2278    // (2^195)*G * 14
2279    PointAffine { x: GFsecp256k1::w64be(0xB72524C558EE5442, 0x0D4A912A2FE54543,
2280                                        0x9360C2FB7428E620, 0x8E48071A98D713DE),
2281                  y: GFsecp256k1::w64be(0x4C51B39A8A283E45, 0x1042D182E9D69415,
2282                                        0x0482D26FE44A5FCB, 0x76FFE5259B8350E9) },
2283    // (2^195)*G * 15
2284    PointAffine { x: GFsecp256k1::w64be(0x1E5635B05FA1850B, 0xC7ADF807F79D2294,
2285                                        0xC74DCC1F17092700, 0xD2A125AA698BC489),
2286                  y: GFsecp256k1::w64be(0x09A0088FE337E6DE, 0x8A61A9873FBF3BBA,
2287                                        0x961A9FBDB9B5A056, 0x3BAC9BB85E183204) },
2288    // (2^195)*G * 16
2289    PointAffine { x: GFsecp256k1::w64be(0xCC0EA33EA8A9EB14, 0xD465AB2C346E2111,
2290                                        0xE1C0FC017C572579, 0x08D40F19EF94C0D5),
2291                  y: GFsecp256k1::w64be(0xF9907A3B711C8A2F, 0xB23DD203B5FBE663,
2292                                        0xF6074F266113F543, 0xDEABE597AF452FE6) },
2293];
2294
2295// ========================================================================
2296
2297#[cfg(test)]
2298mod tests {
2299
2300    use super::{Point, Scalar, PrivateKey, PublicKey};
2301    use sha2::{Sha256, Digest};
2302
2303    /* unused
2304    fn print_gf(name: &str, x: GFsecp256k1) {
2305        print!("{} = 0x", name);
2306        let bb = x.encode();
2307        for i in (0..32).rev() {
2308            print!("{:02X}", bb[i]);
2309        }
2310        println!();
2311    }
2312
2313    fn print(name: &str, P: Point) {
2314        println!("{}:", name);
2315        print_gf("  X", P.X);
2316        print_gf("  Y", P.Y);
2317        print_gf("  Z", P.Z);
2318    }
2319
2320    fn print_sc(name: &str, x: Scalar) {
2321        print!("{} = 0x", name);
2322        let bb = x.encode();
2323        for i in (0..32).rev() {
2324            print!("{:02X}", bb[i]);
2325        }
2326        println!();
2327    }
2328    */
2329
2330    #[test]
2331    fn base_arith() {
2332        // Encoding of neutral.
2333        const EP0: [u8; 1] = [ 0 ];
2334
2335        // For a point P (randomly generated on the curve with Sage),
2336        // points i*P for i = 0 to 6, encoded (compressed).
2337        // (Point 0*P is here represented as 33 bytes of value 0x00.)
2338        const EPC: [[u8; 33]; 7] = [
2339            [
2340                0x00,
2341                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2342                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2343                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2344                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2345            ],
2346            [
2347                0x02,
2348                0x85, 0xFC, 0x56, 0xC5, 0xD6, 0xCC, 0xD9, 0x8A,
2349                0x3D, 0x61, 0x14, 0xAB, 0x0C, 0x8B, 0x09, 0xCD,
2350                0x5E, 0x8F, 0xD9, 0x0D, 0x6C, 0x96, 0x6E, 0xD9,
2351                0xF9, 0xE1, 0x92, 0xB2, 0xF7, 0x39, 0x42, 0x88
2352            ],
2353            [
2354                0x02,
2355                0x1E, 0x15, 0x0E, 0x10, 0x08, 0x66, 0x3C, 0xAA,
2356                0xB3, 0x54, 0xD9, 0x24, 0x55, 0x31, 0x0A, 0xCF,
2357                0x5A, 0x51, 0xD1, 0x4C, 0xCA, 0xEB, 0x1B, 0xEC,
2358                0xB1, 0x48, 0xD7, 0xDD, 0x79, 0x7E, 0xA5, 0x5A
2359            ],
2360            [
2361                0x02,
2362                0x60, 0x0C, 0x54, 0xB9, 0x68, 0x05, 0xC8, 0xAD,
2363                0xF7, 0x11, 0xEC, 0xF0, 0x35, 0xEF, 0xFB, 0x42,
2364                0x60, 0x9F, 0x4C, 0xE5, 0x80, 0x12, 0xBE, 0xF1,
2365                0xA6, 0x8C, 0xE6, 0x43, 0x22, 0x5B, 0x6D, 0xBF
2366            ],
2367            [
2368                0x02,
2369                0xCA, 0xA2, 0x44, 0xDD, 0xBF, 0x5E, 0xD5, 0xCB,
2370                0x13, 0x84, 0xA4, 0x68, 0x9E, 0xEC, 0xCA, 0xAA,
2371                0x08, 0x40, 0x80, 0xAA, 0x53, 0xCC, 0xA3, 0x4B,
2372                0xC5, 0x2F, 0xBC, 0x90, 0xA5, 0x3E, 0xB1, 0xE1
2373            ],
2374            [
2375                0x03,
2376                0x6B, 0xD1, 0x67, 0x5D, 0x24, 0x45, 0xC1, 0x84,
2377                0xE0, 0xCD, 0x49, 0xED, 0x12, 0x5E, 0x98, 0x89,
2378                0x6B, 0xB6, 0xF0, 0xBB, 0xD0, 0x1F, 0x3F, 0x49,
2379                0xDF, 0x67, 0xC8, 0xBA, 0x58, 0xD5, 0xE6, 0x16
2380            ],
2381            [
2382                0x03,
2383                0x56, 0xFF, 0xC1, 0x9E, 0xAE, 0xD6, 0xD4, 0x6B,
2384                0xD7, 0x3A, 0x0E, 0x3F, 0xB4, 0x77, 0x59, 0xC9,
2385                0xFA, 0x58, 0xFF, 0x10, 0xA6, 0x37, 0xF4, 0xBF,
2386                0x5E, 0x1E, 0x96, 0xE2, 0x08, 0xAD, 0x42, 0x66
2387            ],
2388        ];
2389
2390        // Same points, but with uncompressed encoding.
2391        // (Point 0*P is here represented as 65 bytes of value 0x00.)
2392        const EPU: [[u8; 65]; 7] = [
2393            [
2394                0x00,
2395                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2396                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2397                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2398                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2399                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2400                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2401                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2402                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
2403            ],
2404            [
2405                0x04,
2406                0x85, 0xFC, 0x56, 0xC5, 0xD6, 0xCC, 0xD9, 0x8A,
2407                0x3D, 0x61, 0x14, 0xAB, 0x0C, 0x8B, 0x09, 0xCD,
2408                0x5E, 0x8F, 0xD9, 0x0D, 0x6C, 0x96, 0x6E, 0xD9,
2409                0xF9, 0xE1, 0x92, 0xB2, 0xF7, 0x39, 0x42, 0x88,
2410                0x9B, 0x59, 0x87, 0xFF, 0x8B, 0x5B, 0x16, 0x12,
2411                0x86, 0x43, 0xB8, 0x3D, 0xF2, 0x6F, 0xF7, 0x66,
2412                0x24, 0x45, 0x62, 0x70, 0xE8, 0x6B, 0x4F, 0xE4,
2413                0x92, 0x13, 0x0F, 0x61, 0x3B, 0x95, 0x04, 0x72
2414            ],
2415            [
2416                0x04,
2417                0x1E, 0x15, 0x0E, 0x10, 0x08, 0x66, 0x3C, 0xAA,
2418                0xB3, 0x54, 0xD9, 0x24, 0x55, 0x31, 0x0A, 0xCF,
2419                0x5A, 0x51, 0xD1, 0x4C, 0xCA, 0xEB, 0x1B, 0xEC,
2420                0xB1, 0x48, 0xD7, 0xDD, 0x79, 0x7E, 0xA5, 0x5A,
2421                0x23, 0x3A, 0xF4, 0x50, 0xE5, 0x46, 0x3A, 0x91,
2422                0x3A, 0x53, 0xE3, 0xCC, 0xFC, 0x92, 0x77, 0x94,
2423                0xB8, 0x6C, 0x43, 0x9D, 0x43, 0xAD, 0x31, 0x52,
2424                0xD1, 0xB1, 0x05, 0x3C, 0x16, 0x26, 0x9B, 0x32
2425            ],
2426            [
2427                0x04,
2428                0x60, 0x0C, 0x54, 0xB9, 0x68, 0x05, 0xC8, 0xAD,
2429                0xF7, 0x11, 0xEC, 0xF0, 0x35, 0xEF, 0xFB, 0x42,
2430                0x60, 0x9F, 0x4C, 0xE5, 0x80, 0x12, 0xBE, 0xF1,
2431                0xA6, 0x8C, 0xE6, 0x43, 0x22, 0x5B, 0x6D, 0xBF,
2432                0xC8, 0x45, 0x8C, 0xCB, 0xA6, 0x41, 0xB7, 0x18,
2433                0x0D, 0x47, 0xE9, 0xC0, 0x64, 0xCB, 0x6C, 0xF4,
2434                0x9E, 0xD6, 0x26, 0x7D, 0xBC, 0x4C, 0xA4, 0xA0,
2435                0xB6, 0xB5, 0x9C, 0xDD, 0xF3, 0x07, 0xC1, 0xF6
2436            ],
2437            [
2438                0x04,
2439                0xCA, 0xA2, 0x44, 0xDD, 0xBF, 0x5E, 0xD5, 0xCB,
2440                0x13, 0x84, 0xA4, 0x68, 0x9E, 0xEC, 0xCA, 0xAA,
2441                0x08, 0x40, 0x80, 0xAA, 0x53, 0xCC, 0xA3, 0x4B,
2442                0xC5, 0x2F, 0xBC, 0x90, 0xA5, 0x3E, 0xB1, 0xE1,
2443                0x19, 0xD0, 0x27, 0x56, 0x2B, 0x06, 0x31, 0xE9,
2444                0x77, 0x35, 0xB7, 0x71, 0x88, 0x90, 0xAF, 0x11,
2445                0x18, 0x19, 0x97, 0x12, 0xD4, 0x73, 0x63, 0x2C,
2446                0x59, 0x4A, 0x56, 0x64, 0x8E, 0x89, 0xD0, 0x44
2447            ],
2448            [
2449                0x04,
2450                0x6B, 0xD1, 0x67, 0x5D, 0x24, 0x45, 0xC1, 0x84,
2451                0xE0, 0xCD, 0x49, 0xED, 0x12, 0x5E, 0x98, 0x89,
2452                0x6B, 0xB6, 0xF0, 0xBB, 0xD0, 0x1F, 0x3F, 0x49,
2453                0xDF, 0x67, 0xC8, 0xBA, 0x58, 0xD5, 0xE6, 0x16,
2454                0xA0, 0x10, 0x2A, 0xDB, 0xEE, 0x27, 0x3B, 0x6B,
2455                0xA3, 0x02, 0x66, 0xC3, 0x36, 0xEC, 0x5C, 0xC2,
2456                0xBA, 0x3D, 0x3B, 0x25, 0xCB, 0xD6, 0x93, 0xAA,
2457                0xD4, 0x72, 0x0F, 0x72, 0x9E, 0x6B, 0x5F, 0x81
2458            ],
2459            [
2460                0x04,
2461                0x56, 0xFF, 0xC1, 0x9E, 0xAE, 0xD6, 0xD4, 0x6B,
2462                0xD7, 0x3A, 0x0E, 0x3F, 0xB4, 0x77, 0x59, 0xC9,
2463                0xFA, 0x58, 0xFF, 0x10, 0xA6, 0x37, 0xF4, 0xBF,
2464                0x5E, 0x1E, 0x96, 0xE2, 0x08, 0xAD, 0x42, 0x66,
2465                0x42, 0xDA, 0xDD, 0x63, 0xF7, 0xCB, 0x8B, 0x3B,
2466                0x0F, 0x77, 0x34, 0x5D, 0x98, 0xEA, 0xDF, 0x4B,
2467                0xBC, 0x71, 0xE0, 0x6B, 0x6C, 0x51, 0x86, 0xEE,
2468                0xAA, 0x55, 0x29, 0x1F, 0x13, 0x28, 0xDB, 0x0F
2469            ],
2470        ];
2471
2472        let P0 = Point::decode(&EP0).unwrap();
2473        assert!(P0.isneutral() == 0xFFFFFFFF);
2474
2475        let mut PP = [P0; 7];
2476        for i in 1..7 {
2477            let P = Point::decode(&EPC[i]).unwrap();
2478            let Q = Point::decode(&EPU[i]).unwrap();
2479            assert!(P.isneutral() == 0);
2480            assert!(Q.isneutral() == 0);
2481            assert!(P.equals(Q) == 0xFFFFFFFF);
2482            assert!(P.encode_compressed() == EPC[i]);
2483            assert!(P.encode_uncompressed() == EPU[i]);
2484            PP[i] = P;
2485        }
2486
2487        let P0 = PP[0];
2488        let P1 = PP[1];
2489        let P2 = PP[2];
2490        let P3 = PP[3];
2491        let P4 = PP[4];
2492        let P5 = PP[5];
2493        let P6 = PP[6];
2494
2495        for i in 1..7 {
2496            assert!(PP[i].equals(PP[i - 1]) == 0);
2497            let Q = PP[i - 1] + PP[1];
2498            assert!(PP[i].equals(Q) == 0xFFFFFFFF);
2499            assert!((Q + Point::NEUTRAL).equals(Q) == 0xFFFFFFFF);
2500            let R = Q + P0;
2501            assert!(PP[i].equals(R) == 0xFFFFFFFF);
2502        }
2503
2504        let Q2 = P1 + P1;
2505        assert!(Q2.encode_compressed() == EPC[2]);
2506        assert!(Q2.equals(P2) == 0xFFFFFFFF);
2507        let R2 = P1.double();
2508        assert!(R2.encode_compressed() == EPC[2]);
2509        assert!(R2.equals(P2) == 0xFFFFFFFF);
2510        assert!(R2.equals(Q2) == 0xFFFFFFFF);
2511
2512        let Q3 = P2 + P1;
2513        assert!(Q3.encode_compressed() == EPC[3]);
2514        assert!(Q3.equals(P3) == 0xFFFFFFFF);
2515        let R3 = Q2 + P1;
2516        assert!(R3.encode_compressed() == EPC[3]);
2517        assert!(R3.equals(P3) == 0xFFFFFFFF);
2518        assert!(R3.equals(Q3) == 0xFFFFFFFF);
2519
2520        let Q4 = Q2.double();
2521        assert!(Q4.encode_compressed() == EPC[4]);
2522        assert!(Q4.equals(P4) == 0xFFFFFFFF);
2523        let R4 = P1.xdouble(2);
2524        assert!(R4.encode_compressed() == EPC[4]);
2525        assert!(R4.equals(P4) == 0xFFFFFFFF);
2526        assert!(R4.equals(Q4) == 0xFFFFFFFF);
2527        let R4 = P1 + Q3;
2528        assert!(R4.encode_compressed() == EPC[4]);
2529        assert!(R4.equals(P4) == 0xFFFFFFFF);
2530        assert!(R4.equals(Q4) == 0xFFFFFFFF);
2531
2532        let Q5 = Q3 + R2;
2533        assert!(Q5.encode_compressed() == EPC[5]);
2534        assert!(Q5.equals(P5) == 0xFFFFFFFF);
2535        let R5 = R3 + Q2;
2536        assert!(R5.encode_compressed() == EPC[5]);
2537        assert!(R5.equals(P5) == 0xFFFFFFFF);
2538        assert!(R5.equals(Q5) == 0xFFFFFFFF);
2539
2540        assert!((R5 - Q3).equals(Q2) == 0xFFFFFFFF);
2541
2542        let Q6 = Q3.double();
2543        assert!(Q6.encode_compressed() == EPC[6]);
2544        assert!(Q6.equals(P6) == 0xFFFFFFFF);
2545        let R6 = Q2 + Q4;
2546        assert!(R6.encode_compressed() == EPC[6]);
2547        assert!(R6.equals(P6) == 0xFFFFFFFF);
2548        assert!(R6.equals(Q6) == 0xFFFFFFFF);
2549
2550        let mut P = Q6;
2551        let mut Q = R6;
2552        for _ in 0..8 {
2553            P += P;
2554        }
2555        Q.set_xdouble(8);
2556        assert!(P.equals(Q) == 0xFFFFFFFF);
2557
2558        let P = P1 + P0.double();
2559        assert!(P.equals(P1) == 0xFFFFFFFF);
2560        assert!(P.equals(P2) == 0x00000000);
2561    }
2562
2563    #[test]
2564    fn split_theta() {
2565        const THETA: Scalar = Scalar::w64be(
2566            0x5363AD4CC05C30E0, 0xA5261C028812645A,
2567            0x122E22EA20816678, 0xDF02967C1B23BD72);
2568
2569        let mut sh = Sha256::new();
2570        for i in 0..100 {
2571            sh.update(&(i as u64).to_le_bytes());
2572            let k: Scalar = Scalar::decode_reduce(&sh.finalize_reset());
2573            let (k0, sk0, k1, sk1) = Point::split_theta(&k);
2574            let mut t0 = Scalar::from_u128(k0);
2575            if sk0 != 0 {
2576                t0 = -t0;
2577            }
2578            let mut t1 = Scalar::from_u128(k1);
2579            if sk1 != 0 {
2580                t1 = -t1;
2581            }
2582            let t = t0 + t1 * THETA;
2583            assert!(t.equals(k) == 0xFFFFFFFF);
2584        }
2585    }
2586
2587    #[test]
2588    fn mulgen() {
2589        // Test vector generated randomly with Sage.
2590        let s = Scalar::w64be(0xF0FCA55C06488D1C, 0x6CA454ED29573B6C,
2591                              0x89D4F76592F96F10, 0x98BD4A5F08DF863E);
2592        let enc: [u8; 33] = [
2593            0x02,
2594            0x08, 0x28, 0x9C, 0x90, 0x62, 0x82, 0x49, 0x71,
2595            0x94, 0x38, 0x9E, 0xA3, 0x2B, 0xD6, 0x35, 0x18,
2596            0xAD, 0xEA, 0xE8, 0x4C, 0x17, 0x9F, 0xEA, 0x6F,
2597            0xD2, 0x53, 0x1A, 0x71, 0x14, 0x4C, 0x94, 0xFA
2598        ];
2599
2600        let R = Point::decode(&enc).unwrap();
2601        let P = Point::BASE * s;
2602        assert!(P.equals(R) == 0xFFFFFFFF);
2603        assert!(P.encode_compressed() == enc);
2604        let Q = Point::mulgen(&s);
2605        assert!(Q.equals(R) == 0xFFFFFFFF);
2606        assert!(Q.encode_compressed() == enc);
2607    }
2608
2609    #[test]
2610    fn mul() {
2611        let mut sh = Sha256::new();
2612        for i in 0..20 {
2613            // Build pseudorandom s1 and s2
2614            sh.update(((2 * i + 0) as u64).to_le_bytes());
2615            let v1 = sh.finalize_reset();
2616            sh.update(((2 * i + 1) as u64).to_le_bytes());
2617            let v2 = sh.finalize_reset();
2618
2619            let s1 = Scalar::decode_reduce(&v1);
2620            let s2 = Scalar::decode_reduce(&v2);
2621            let s3 = s1 * s2;
2622            let P1 = Point::mulgen(&s1);
2623            let Q1 = s1 * Point::BASE;
2624            assert!(P1.equals(Q1) == 0xFFFFFFFF);
2625            let P2 = Point::mulgen(&s3);
2626            let Q2 = s2 * Q1;
2627            assert!(P2.equals(Q2) == 0xFFFFFFFF);
2628        }
2629    }
2630
2631    #[test]
2632    fn mul_add_mulgen() {
2633        let mut sh = Sha256::new();
2634        for i in 0..20 {
2635            // Build pseudorandom A, u and v
2636            sh.update(((3 * i + 0) as u64).to_le_bytes());
2637            let v1 = sh.finalize_reset();
2638            sh.update(((3 * i + 1) as u64).to_le_bytes());
2639            let v2 = sh.finalize_reset();
2640            sh.update(((3 * i + 2) as u64).to_le_bytes());
2641            let v3 = sh.finalize_reset();
2642            let A = Point::mulgen(&Scalar::decode_reduce(&v1));
2643            let u = Scalar::decode_reduce(&v2);
2644            let v = Scalar::decode_reduce(&v3);
2645
2646            // Compute u*A + v*B in two different ways; check that they
2647            // match.
2648            let R1 = u * A + Point::mulgen(&v);
2649            let R2 = A.mul_add_mulgen_vartime(&u, &v);
2650            assert!(R1.equals(R2) == 0xFFFFFFFF);
2651        }
2652    }
2653
2654    #[test]
2655    fn verify_helper() {
2656        let mut sh = Sha256::new();
2657        for i in 0..20 {
2658            // Build pseudorandom Q, s and k.
2659            // Compute R = s*G - k*Q
2660            sh.update(((3 * i + 0) as u64).to_le_bytes());
2661            let v1 = sh.finalize_reset();
2662            sh.update(((3 * i + 1) as u64).to_le_bytes());
2663            let v2 = sh.finalize_reset();
2664            sh.update(((3 * i + 2) as u64).to_le_bytes());
2665            let v3 = sh.finalize_reset();
2666            let Q = Point::mulgen(&Scalar::decode_reduce(&v1));
2667            let s = Scalar::decode_reduce(&v2);
2668            let k = Scalar::decode_reduce(&v3);
2669            let R = Point::mulgen(&s) - k * Q;
2670
2671            // verify_helper_vartime() must return true, but this
2672            // must change to false if we change a scalar or a point.
2673            assert!(Q.verify_helper_vartime(&R, &s, &k));
2674            assert!(!Q.verify_helper_vartime(&R, &(s + Scalar::ONE), &k));
2675            assert!(!Q.verify_helper_vartime(&R, &s, &(k + Scalar::ONE)));
2676            assert!(!Q.verify_helper_vartime(&(R + Point::BASE), &s, &k));
2677            assert!(!(Q + Point::BASE).verify_helper_vartime(&R, &s, &k));
2678        }
2679    }
2680
2681    #[test]
2682    fn signatures() {
2683        // Test vector from project Wycheproof
2684        // (ecdsa_secp256k1_sha256_p1363_test.json)
2685        let pub_enc: [u8; 65] = [
2686            0x04,
2687            0xB8, 0x38, 0xFF, 0x44, 0xE5, 0xBC, 0x17, 0x7B,
2688            0xF2, 0x11, 0x89, 0xD0, 0x76, 0x60, 0x82, 0xFC,
2689            0x9D, 0x84, 0x32, 0x26, 0x88, 0x7F, 0xC9, 0x76,
2690            0x03, 0x71, 0x10, 0x0B, 0x7E, 0xE2, 0x0A, 0x6F,
2691            0xF0, 0xC9, 0xD7, 0x5B, 0xFB, 0xA7, 0xB3, 0x1A,
2692            0x6B, 0xCA, 0x19, 0x74, 0x49, 0x6E, 0xEB, 0x56,
2693            0xDE, 0x35, 0x70, 0x71, 0x95, 0x5D, 0x83, 0xC4,
2694            0xB1, 0xBA, 0xDA, 0xA0, 0xB2, 0x18, 0x32, 0xE9,
2695        ];
2696        let msg = b"123400";
2697        let sig: [u8; 64] = [
2698            0x81, 0x3E, 0xF7, 0x9C, 0xCE, 0xFA, 0x9A, 0x56,
2699            0xF7, 0xBA, 0x80, 0x5F, 0x0E, 0x47, 0x85, 0x84,
2700            0xFE, 0x5F, 0x0D, 0xD5, 0xF5, 0x67, 0xBC, 0x09,
2701            0xB5, 0x12, 0x3C, 0xCB, 0xC9, 0x83, 0x23, 0x65,
2702            0x90, 0x0E, 0x75, 0xAD, 0x23, 0x3F, 0xCC, 0x90,
2703            0x85, 0x09, 0xDB, 0xFF, 0x59, 0x22, 0x64, 0x7D,
2704            0xB3, 0x7C, 0x21, 0xF4, 0xAF, 0xD3, 0x20, 0x3A,
2705            0xE8, 0xDC, 0x4A, 0xE7, 0x79, 0x4B, 0x0F, 0x87,
2706        ];
2707
2708        let pkey = PublicKey::decode(&pub_enc).unwrap();
2709        let mut sh = Sha256::new();
2710        sh.update(&msg);
2711        let hv1: [u8; 32] = sh.finalize_reset().into();
2712        sh.update(&msg);
2713        sh.update(&[0u8]);
2714        let hv2: [u8; 32] = sh.finalize_reset().into();
2715        assert!(pkey.verify_hash(&sig, &hv1));
2716        assert!(!pkey.verify_hash(&sig, &hv2));
2717
2718        for i in 0..20 {
2719            sh.update((i as u64).to_le_bytes());
2720            let seed: [u8; 32] = sh.finalize_reset().into();
2721            let sk = PrivateKey::from_seed(&seed);
2722            let pk = sk.to_public_key();
2723            let sig1 = sk.sign_hash(&hv1, &[]);
2724            let sig2 = sk.sign_hash(&hv2, &[]);
2725            assert!(pk.verify_hash(&sig1, &hv1));
2726            assert!(pk.verify_hash(&sig2, &hv2));
2727            assert!(!pk.verify_hash(&sig1, &hv2));
2728            assert!(!pk.verify_hash(&sig2, &hv1));
2729            assert!(!pkey.verify_hash(&sig1, &hv1));
2730            assert!(!pkey.verify_hash(&sig2, &hv2));
2731        }
2732    }
2733}