Coverage Report

Created: 2024-09-11 06:39

/src/trezor-firmware/crypto/ecdsa.c
Line
Count
Source (jump to first uncovered line)
1
/**
2
 * Copyright (c) 2013-2014 Tomas Dzetkulic
3
 * Copyright (c) 2013-2014 Pavol Rusnak
4
 * Copyright (c)      2015 Jochen Hoenicke
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining
7
 * a copy of this software and associated documentation files (the "Software"),
8
 * to deal in the Software without restriction, including without limitation
9
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10
 * and/or sell copies of the Software, and to permit persons to whom the
11
 * Software is furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included
14
 * in all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
20
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
 * OTHER DEALINGS IN THE SOFTWARE.
23
 */
24
25
#include <assert.h>
26
#include <stdint.h>
27
#include <stdlib.h>
28
#include <string.h>
29
30
#include "address.h"
31
#include "base58.h"
32
#include "bignum.h"
33
#include "ecdsa.h"
34
#include "hmac.h"
35
#include "memzero.h"
36
#include "rand.h"
37
#include "rfc6979.h"
38
#include "secp256k1.h"
39
#ifdef USE_SECP256K1_ZKP_ECDSA
40
#include "zkp_ecdsa.h"
41
#endif
42
43
// Set cp2 = cp1
44
112
void point_copy(const curve_point *cp1, curve_point *cp2) { *cp2 = *cp1; }
45
46
// cp2 = cp1 + cp2
47
void point_add(const ecdsa_curve *curve, const curve_point *cp1,
48
63.4k
               curve_point *cp2) {
49
63.4k
  bignum256 lambda = {0}, inv = {0}, xr = {0}, yr = {0};
50
51
63.4k
  if (point_is_infinity(cp1)) {
52
114
    return;
53
114
  }
54
63.3k
  if (point_is_infinity(cp2)) {
55
112
    point_copy(cp1, cp2);
56
112
    return;
57
112
  }
58
63.2k
  if (point_is_equal(cp1, cp2)) {
59
60
    point_double(curve, cp2);
60
60
    return;
61
60
  }
62
63.1k
  if (point_is_negative_of(cp1, cp2)) {
63
63
    point_set_infinity(cp2);
64
63
    return;
65
63
  }
66
67
  // lambda = (y2 - y1) / (x2 - x1)
68
63.0k
  bn_subtractmod(&(cp2->x), &(cp1->x), &inv, &curve->prime);
69
63.0k
  bn_inverse(&inv, &curve->prime);
70
63.0k
  bn_subtractmod(&(cp2->y), &(cp1->y), &lambda, &curve->prime);
71
63.0k
  bn_multiply(&inv, &lambda, &curve->prime);
72
73
  // xr = lambda^2 - x1 - x2
74
63.0k
  xr = lambda;
75
63.0k
  bn_multiply(&xr, &xr, &curve->prime);
76
63.0k
  yr = cp1->x;
77
63.0k
  bn_addmod(&yr, &(cp2->x), &curve->prime);
78
63.0k
  bn_subtractmod(&xr, &yr, &xr, &curve->prime);
79
63.0k
  bn_fast_mod(&xr, &curve->prime);
80
63.0k
  bn_mod(&xr, &curve->prime);
81
82
  // yr = lambda (x1 - xr) - y1
83
63.0k
  bn_subtractmod(&(cp1->x), &xr, &yr, &curve->prime);
84
63.0k
  bn_multiply(&lambda, &yr, &curve->prime);
85
63.0k
  bn_subtractmod(&yr, &(cp1->y), &yr, &curve->prime);
86
63.0k
  bn_fast_mod(&yr, &curve->prime);
87
63.0k
  bn_mod(&yr, &curve->prime);
88
89
63.0k
  cp2->x = xr;
90
63.0k
  cp2->y = yr;
91
63.0k
}
92
93
// cp = cp + cp
94
9.21k
void point_double(const ecdsa_curve *curve, curve_point *cp) {
95
9.21k
  bignum256 lambda = {0}, xr = {0}, yr = {0};
96
97
9.21k
  if (point_is_infinity(cp)) {
98
19
    return;
99
19
  }
100
9.19k
  if (bn_is_zero(&(cp->y))) {
101
36
    point_set_infinity(cp);
102
36
    return;
103
36
  }
104
105
  // lambda = (3 x^2 + a) / (2 y)
106
9.16k
  lambda = cp->y;
107
9.16k
  bn_mult_k(&lambda, 2, &curve->prime);
108
9.16k
  bn_fast_mod(&lambda, &curve->prime);
109
9.16k
  bn_mod(&lambda, &curve->prime);
110
9.16k
  bn_inverse(&lambda, &curve->prime);
111
112
9.16k
  xr = cp->x;
113
9.16k
  bn_multiply(&xr, &xr, &curve->prime);
114
9.16k
  bn_mult_k(&xr, 3, &curve->prime);
115
9.16k
  bn_subi(&xr, -curve->a, &curve->prime);
116
9.16k
  bn_multiply(&xr, &lambda, &curve->prime);
117
118
  // xr = lambda^2 - 2*x
119
9.16k
  xr = lambda;
120
9.16k
  bn_multiply(&xr, &xr, &curve->prime);
121
9.16k
  yr = cp->x;
122
9.16k
  bn_lshift(&yr);
123
9.16k
  bn_subtractmod(&xr, &yr, &xr, &curve->prime);
124
9.16k
  bn_fast_mod(&xr, &curve->prime);
125
9.16k
  bn_mod(&xr, &curve->prime);
126
127
  // yr = lambda (x - xr) - y
128
9.16k
  bn_subtractmod(&(cp->x), &xr, &yr, &curve->prime);
129
9.16k
  bn_multiply(&lambda, &yr, &curve->prime);
130
9.16k
  bn_subtractmod(&yr, &(cp->y), &yr, &curve->prime);
131
9.16k
  bn_fast_mod(&yr, &curve->prime);
132
9.16k
  bn_mod(&yr, &curve->prime);
133
134
9.16k
  cp->x = xr;
135
9.16k
  cp->y = yr;
136
9.16k
}
137
138
// set point to internal representation of point at infinity
139
157
void point_set_infinity(curve_point *p) {
140
157
  bn_zero(&(p->x));
141
157
  bn_zero(&(p->y));
142
157
}
143
144
// return true iff p represent point at infinity
145
// both coords are zero in internal representation
146
140k
int point_is_infinity(const curve_point *p) {
147
140k
  return bn_is_zero(&(p->x)) && bn_is_zero(&(p->y));
148
140k
}
149
150
// return true iff both points are equal
151
63.2k
int point_is_equal(const curve_point *p, const curve_point *q) {
152
63.2k
  return bn_is_equal(&(p->x), &(q->x)) && bn_is_equal(&(p->y), &(q->y));
153
63.2k
}
154
155
// returns true iff p == -q
156
// expects p and q be valid points on curve other than point at infinity
157
63.1k
int point_is_negative_of(const curve_point *p, const curve_point *q) {
158
  // if P == (x, y), then -P would be (x, -y) on this curve
159
63.1k
  if (!bn_is_equal(&(p->x), &(q->x))) {
160
63.0k
    return 0;
161
63.0k
  }
162
163
  // we shouldn't hit this for a valid point
164
66
  if (bn_is_zero(&(p->y))) {
165
3
    return 0;
166
3
  }
167
168
63
  return !bn_is_equal(&(p->y), &(q->y));
169
66
}
170
171
typedef struct jacobian_curve_point {
172
  bignum256 x, y, z;
173
} jacobian_curve_point;
174
175
// generate random K for signing/side-channel noise
176
9.95k
static void generate_k_random(bignum256 *k, const bignum256 *prime) {
177
10.0k
  do {
178
10.0k
    int i = 0;
179
90.1k
    for (i = 0; i < 8; i++) {
180
80.1k
      k->val[i] = random32() & ((1u << BN_BITS_PER_LIMB) - 1);
181
80.1k
    }
182
10.0k
    k->val[8] = random32() & ((1u << BN_BITS_LAST_LIMB) - 1);
183
    // check that k is in range and not zero.
184
10.0k
  } while (bn_is_zero(k) || !bn_is_less(k, prime));
185
9.95k
}
186
187
void curve_to_jacobian(const curve_point *p, jacobian_curve_point *jp,
188
8.78k
                       const bignum256 *prime) {
189
  // randomize z coordinate
190
8.78k
  generate_k_random(&jp->z, prime);
191
192
8.78k
  jp->x = jp->z;
193
8.78k
  bn_multiply(&jp->z, &jp->x, prime);
194
  // x = z^2
195
8.78k
  jp->y = jp->x;
196
8.78k
  bn_multiply(&jp->z, &jp->y, prime);
197
  // y = z^3
198
199
8.78k
  bn_multiply(&p->x, &jp->x, prime);
200
8.78k
  bn_multiply(&p->y, &jp->y, prime);
201
8.78k
}
202
203
void jacobian_to_curve(const jacobian_curve_point *jp, curve_point *p,
204
8.78k
                       const bignum256 *prime) {
205
8.78k
  p->y = jp->z;
206
8.78k
  bn_inverse(&p->y, prime);
207
  // p->y = z^-1
208
8.78k
  p->x = p->y;
209
8.78k
  bn_multiply(&p->x, &p->x, prime);
210
  // p->x = z^-2
211
8.78k
  bn_multiply(&p->x, &p->y, prime);
212
  // p->y = z^-3
213
8.78k
  bn_multiply(&jp->x, &p->x, prime);
214
  // p->x = jp->x * z^-2
215
8.78k
  bn_multiply(&jp->y, &p->y, prime);
216
  // p->y = jp->y * z^-3
217
8.78k
  bn_mod(&p->x, prime);
218
8.78k
  bn_mod(&p->y, prime);
219
8.78k
}
220
221
void point_jacobian_add(const curve_point *p1, jacobian_curve_point *p2,
222
553k
                        const ecdsa_curve *curve) {
223
553k
  bignum256 r = {0}, h = {0}, r2 = {0};
224
553k
  bignum256 hcby = {0}, hsqx = {0};
225
553k
  bignum256 xz = {0}, yz = {0}, az = {0};
226
553k
  int is_doubling = 0;
227
553k
  const bignum256 *prime = &curve->prime;
228
553k
  int a = curve->a;
229
230
553k
  assert(-3 <= a && a <= 0);
231
232
  /* First we bring p1 to the same denominator:
233
   * x1' := x1 * z2^2
234
   * y1' := y1 * z2^3
235
   */
236
  /*
237
   * lambda  = ((y1' - y2)/z2^3) / ((x1' - x2)/z2^2)
238
   *         = (y1' - y2) / (x1' - x2) z2
239
   * x3/z3^2 = lambda^2 - (x1' + x2)/z2^2
240
   * y3/z3^3 = 1/2 lambda * (2x3/z3^2 - (x1' + x2)/z2^2) + (y1'+y2)/z2^3
241
   *
242
   * For the special case x1=x2, y1=y2 (doubling) we have
243
   * lambda = 3/2 ((x2/z2^2)^2 + a) / (y2/z2^3)
244
   *        = 3/2 (x2^2 + a*z2^4) / y2*z2)
245
   *
246
   * to get rid of fraction we write lambda as
247
   * lambda = r / (h*z2)
248
   * with  r = is_doubling ? 3/2 x2^2 + az2^4 : (y1 - y2)
249
   *       h = is_doubling ?      y1+y2       : (x1 - x2)
250
   *
251
   * With z3 = h*z2  (the denominator of lambda)
252
   * we get x3 = lambda^2*z3^2 - (x1' + x2)/z2^2*z3^2
253
   *           = r^2 - h^2 * (x1' + x2)
254
   *    and y3 = 1/2 r * (2x3 - h^2*(x1' + x2)) + h^3*(y1' + y2)
255
   */
256
257
  /* h = x1 - x2
258
   * r = y1 - y2
259
   * x3 = r^2 - h^3 - 2*h^2*x2
260
   * y3 = r*(h^2*x2 - x3) - h^3*y2
261
   * z3 = h*z2
262
   */
263
264
553k
  xz = p2->z;
265
553k
  bn_multiply(&xz, &xz, prime);  // xz = z2^2
266
553k
  yz = p2->z;
267
553k
  bn_multiply(&xz, &yz, prime);  // yz = z2^3
268
269
553k
  if (a != 0) {
270
0
    az = xz;
271
0
    bn_multiply(&az, &az, prime);  // az = z2^4
272
0
    bn_mult_k(&az, -a, prime);     // az = -az2^4
273
0
  }
274
275
553k
  bn_multiply(&p1->x, &xz, prime);  // xz = x1' = x1*z2^2;
276
553k
  h = xz;
277
553k
  bn_subtractmod(&h, &p2->x, &h, prime);
278
553k
  bn_fast_mod(&h, prime);
279
  // h = x1' - x2;
280
281
553k
  bn_add(&xz, &p2->x);
282
  // xz = x1' + x2
283
284
  // check for h == 0 % prime.  Note that h never normalizes to
285
  // zero, since h = x1' + 2*prime - x2 > 0 and a positive
286
  // multiple of prime is always normalized to prime by
287
  // bn_fast_mod.
288
553k
  is_doubling = bn_is_equal(&h, prime);
289
290
553k
  bn_multiply(&p1->y, &yz, prime);  // yz = y1' = y1*z2^3;
291
553k
  bn_subtractmod(&yz, &p2->y, &r, prime);
292
  // r = y1' - y2;
293
294
553k
  bn_add(&yz, &p2->y);
295
  // yz = y1' + y2
296
297
553k
  r2 = p2->x;
298
553k
  bn_multiply(&r2, &r2, prime);
299
553k
  bn_mult_k(&r2, 3, prime);
300
301
553k
  if (a != 0) {
302
    // subtract -a z2^4, i.e, add a z2^4
303
0
    bn_subtractmod(&r2, &az, &r2, prime);
304
0
  }
305
553k
  bn_cmov(&r, is_doubling, &r2, &r);
306
553k
  bn_cmov(&h, is_doubling, &yz, &h);
307
308
  // hsqx = h^2
309
553k
  hsqx = h;
310
553k
  bn_multiply(&hsqx, &hsqx, prime);
311
312
  // hcby = h^3
313
553k
  hcby = h;
314
553k
  bn_multiply(&hsqx, &hcby, prime);
315
316
  // hsqx = h^2 * (x1 + x2)
317
553k
  bn_multiply(&xz, &hsqx, prime);
318
319
  // hcby = h^3 * (y1 + y2)
320
553k
  bn_multiply(&yz, &hcby, prime);
321
322
  // z3 = h*z2
323
553k
  bn_multiply(&h, &p2->z, prime);
324
325
  // x3 = r^2 - h^2 (x1 + x2)
326
553k
  p2->x = r;
327
553k
  bn_multiply(&p2->x, &p2->x, prime);
328
553k
  bn_subtractmod(&p2->x, &hsqx, &p2->x, prime);
329
553k
  bn_fast_mod(&p2->x, prime);
330
331
  // y3 = 1/2 (r*(h^2 (x1 + x2) - 2x3) - h^3 (y1 + y2))
332
553k
  bn_subtractmod(&hsqx, &p2->x, &p2->y, prime);
333
553k
  bn_subtractmod(&p2->y, &p2->x, &p2->y, prime);
334
553k
  bn_multiply(&r, &p2->y, prime);
335
553k
  bn_subtractmod(&p2->y, &hcby, &p2->y, prime);
336
553k
  bn_mult_half(&p2->y, prime);
337
553k
  bn_fast_mod(&p2->y, prime);
338
553k
}
339
340
2.21M
void point_jacobian_double(jacobian_curve_point *p, const ecdsa_curve *curve) {
341
2.21M
  bignum256 az4 = {0}, m = {0}, msq = {0}, ysq = {0}, xysq = {0};
342
2.21M
  const bignum256 *prime = &curve->prime;
343
344
2.21M
  assert(-3 <= curve->a && curve->a <= 0);
345
  /* usual algorithm:
346
   *
347
   * lambda  = (3((x/z^2)^2 + a) / 2y/z^3) = (3x^2 + az^4)/2yz
348
   * x3/z3^2 = lambda^2 - 2x/z^2
349
   * y3/z3^3 = lambda * (x/z^2 - x3/z3^2) - y/z^3
350
   *
351
   * to get rid of fraction we set
352
   *  m = (3 x^2 + az^4) / 2
353
   * Hence,
354
   *  lambda = m / yz = m / z3
355
   *
356
   * With z3 = yz  (the denominator of lambda)
357
   * we get x3 = lambda^2*z3^2 - 2*x/z^2*z3^2
358
   *           = m^2 - 2*xy^2
359
   *    and y3 = (lambda * (x/z^2 - x3/z3^2) - y/z^3) * z3^3
360
   *           = m * (xy^2 - x3) - y^4
361
   */
362
363
  /* m = (3*x^2 + a z^4) / 2
364
   * x3 = m^2 - 2*xy^2
365
   * y3 = m*(xy^2 - x3) - 8y^4
366
   * z3 = y*z
367
   */
368
369
2.21M
  m = p->x;
370
2.21M
  bn_multiply(&m, &m, prime);
371
2.21M
  bn_mult_k(&m, 3, prime);
372
373
2.21M
  az4 = p->z;
374
2.21M
  bn_multiply(&az4, &az4, prime);
375
2.21M
  bn_multiply(&az4, &az4, prime);
376
2.21M
  bn_mult_k(&az4, -curve->a, prime);
377
2.21M
  bn_subtractmod(&m, &az4, &m, prime);
378
2.21M
  bn_mult_half(&m, prime);
379
380
  // msq = m^2
381
2.21M
  msq = m;
382
2.21M
  bn_multiply(&msq, &msq, prime);
383
  // ysq = y^2
384
2.21M
  ysq = p->y;
385
2.21M
  bn_multiply(&ysq, &ysq, prime);
386
  // xysq = xy^2
387
2.21M
  xysq = p->x;
388
2.21M
  bn_multiply(&ysq, &xysq, prime);
389
390
  // z3 = yz
391
2.21M
  bn_multiply(&p->y, &p->z, prime);
392
393
  // x3 = m^2 - 2*xy^2
394
2.21M
  p->x = xysq;
395
2.21M
  bn_lshift(&p->x);
396
2.21M
  bn_fast_mod(&p->x, prime);
397
2.21M
  bn_subtractmod(&msq, &p->x, &p->x, prime);
398
2.21M
  bn_fast_mod(&p->x, prime);
399
400
  // y3 = m*(xy^2 - x3) - y^4
401
2.21M
  bn_subtractmod(&xysq, &p->x, &p->y, prime);
402
2.21M
  bn_multiply(&m, &p->y, prime);
403
2.21M
  bn_multiply(&ysq, &ysq, prime);
404
2.21M
  bn_subtractmod(&p->y, &ysq, &p->y, prime);
405
2.21M
  bn_fast_mod(&p->y, prime);
406
2.21M
}
407
408
// res = k * p
409
// returns 0 on success
410
int point_multiply(const ecdsa_curve *curve, const bignum256 *k,
411
8.84k
                   const curve_point *p, curve_point *res) {
412
  // this algorithm is loosely based on
413
  //  Katsuyuki Okeya and Tsuyoshi Takagi, The Width-w NAF Method Provides
414
  //  Small Memory and Fast Elliptic Scalar Multiplications Secure against
415
  //  Side Channel Attacks.
416
8.84k
  if (!bn_is_less(k, &curve->order)) {
417
0
    return 1;
418
0
  }
419
420
8.84k
  int i = 0, j = 0;
421
8.84k
  static CONFIDENTIAL bignum256 a;
422
8.84k
  uint32_t *aptr = NULL;
423
8.84k
  uint32_t abits = 0;
424
8.84k
  int ashift = 0;
425
8.84k
  uint32_t is_even = (k->val[0] & 1) - 1;
426
8.84k
  uint32_t bits = {0}, sign = {0}, nsign = {0};
427
8.84k
  static CONFIDENTIAL jacobian_curve_point jres;
428
8.84k
  curve_point pmult[8] = {0};
429
8.84k
  const bignum256 *prime = &curve->prime;
430
431
  // is_even = 0xffffffff if k is even, 0 otherwise.
432
433
  // add 2^256.
434
  // make number odd: subtract curve->order if even
435
8.84k
  uint32_t tmp = 1;
436
8.84k
  uint32_t is_non_zero = 0;
437
79.6k
  for (j = 0; j < 8; j++) {
438
70.7k
    is_non_zero |= k->val[j];
439
70.7k
    tmp += (BN_BASE - 1) + k->val[j] - (curve->order.val[j] & is_even);
440
70.7k
    a.val[j] = tmp & (BN_BASE - 1);
441
70.7k
    tmp >>= BN_BITS_PER_LIMB;
442
70.7k
  }
443
8.84k
  is_non_zero |= k->val[j];
444
8.84k
  a.val[j] = tmp + 0xffffff + k->val[j] - (curve->order.val[j] & is_even);
445
8.84k
  assert((a.val[0] & 1) != 0);
446
447
  // special case 0*p:  just return zero. We don't care about constant time.
448
8.84k
  if (!is_non_zero) {
449
58
    point_set_infinity(res);
450
58
    return 1;
451
58
  }
452
453
  // Now a = k + 2^256 (mod curve->order) and a is odd.
454
  //
455
  // The idea is to bring the new a into the form.
456
  // sum_{i=0..64} a[i] 16^i,  where |a[i]| < 16 and a[i] is odd.
457
  // a[0] is odd, since a is odd.  If a[i] would be even, we can
458
  // add 1 to it and subtract 16 from a[i-1].  Afterwards,
459
  // a[64] = 1, which is the 2^256 that we added before.
460
  //
461
  // Since k = a - 2^256 (mod curve->order), we can compute
462
  //   k*p = sum_{i=0..63} a[i] 16^i * p
463
  //
464
  // We compute |a[i]| * p in advance for all possible
465
  // values of |a[i]| * p.  pmult[i] = (2*i+1) * p
466
  // We compute p, 3*p, ..., 15*p and store it in the table pmult.
467
  // store p^2 temporarily in pmult[7]
468
8.78k
  pmult[7] = *p;
469
8.78k
  point_double(curve, &pmult[7]);
470
  // compute 3*p, etc by repeatedly adding p^2.
471
8.78k
  pmult[0] = *p;
472
70.2k
  for (i = 1; i < 8; i++) {
473
61.5k
    pmult[i] = pmult[7];
474
61.5k
    point_add(curve, &pmult[i - 1], &pmult[i]);
475
61.5k
  }
476
477
  // now compute  res = sum_{i=0..63} a[i] * 16^i * p step by step,
478
  // starting with i = 63.
479
  // initialize jres = |a[63]| * p.
480
  // Note that a[i] = a>>(4*i) & 0xf if (a&0x10) != 0
481
  // and - (16 - (a>>(4*i) & 0xf)) otherwise.   We can compute this as
482
  //   ((a ^ (((a >> 4) & 1) - 1)) & 0xf) >> 1
483
  // since a is odd.
484
8.78k
  aptr = &a.val[8];
485
8.78k
  abits = *aptr;
486
8.78k
  ashift = 256 - (BN_BITS_PER_LIMB * 8) - 4;
487
8.78k
  bits = abits >> ashift;
488
8.78k
  sign = (bits >> 4) - 1;
489
8.78k
  bits ^= sign;
490
8.78k
  bits &= 15;
491
8.78k
  curve_to_jacobian(&pmult[bits >> 1], &jres, prime);
492
562k
  for (i = 62; i >= 0; i--) {
493
    // sign = sign(a[i+1])  (0xffffffff for negative, 0 for positive)
494
    // invariant jres = (-1)^sign sum_{j=i+1..63} (a[j] * 16^{j-i-1} * p)
495
    // abits >> (ashift - 4) = lowbits(a >> (i*4))
496
497
553k
    point_jacobian_double(&jres, curve);
498
553k
    point_jacobian_double(&jres, curve);
499
553k
    point_jacobian_double(&jres, curve);
500
553k
    point_jacobian_double(&jres, curve);
501
502
    // get lowest 5 bits of a >> (i*4).
503
553k
    ashift -= 4;
504
553k
    if (ashift < 0) {
505
      // the condition only depends on the iteration number and
506
      // leaks no private information to a side-channel.
507
70.2k
      bits = abits << (-ashift);
508
70.2k
      abits = *(--aptr);
509
70.2k
      ashift += BN_BITS_PER_LIMB;
510
70.2k
      bits |= abits >> ashift;
511
483k
    } else {
512
483k
      bits = abits >> ashift;
513
483k
    }
514
553k
    bits &= 31;
515
553k
    nsign = (bits >> 4) - 1;
516
553k
    bits ^= nsign;
517
553k
    bits &= 15;
518
519
    // negate last result to make signs of this round and the
520
    // last round equal.
521
553k
    bn_cnegate((sign ^ nsign) & 1, &jres.z, prime);
522
523
    // add odd factor
524
553k
    point_jacobian_add(&pmult[bits >> 1], &jres, curve);
525
553k
    sign = nsign;
526
553k
  }
527
8.78k
  bn_cnegate(sign & 1, &jres.z, prime);
528
8.78k
  jacobian_to_curve(&jres, res, prime);
529
8.78k
  memzero(&a, sizeof(a));
530
8.78k
  memzero(&jres, sizeof(jres));
531
532
8.78k
  return 0;
533
8.84k
}
534
535
#if USE_PRECOMPUTED_CP
536
537
// res = k * G
538
// k must be a normalized number with 0 <= k < curve->order
539
// returns 0 on success
540
int scalar_multiply(const ecdsa_curve *curve, const bignum256 *k,
541
                    curve_point *res) {
542
  if (!bn_is_less(k, &curve->order)) {
543
    return 1;
544
  }
545
546
  int i = {0}, j = {0};
547
  static CONFIDENTIAL bignum256 a;
548
  uint32_t is_even = (k->val[0] & 1) - 1;
549
  uint32_t lowbits = 0;
550
  static CONFIDENTIAL jacobian_curve_point jres;
551
  const bignum256 *prime = &curve->prime;
552
553
  // is_even = 0xffffffff if k is even, 0 otherwise.
554
555
  // add 2^256.
556
  // make number odd: subtract curve->order if even
557
  uint32_t tmp = 1;
558
  uint32_t is_non_zero = 0;
559
  for (j = 0; j < 8; j++) {
560
    is_non_zero |= k->val[j];
561
    tmp += (BN_BASE - 1) + k->val[j] - (curve->order.val[j] & is_even);
562
    a.val[j] = tmp & (BN_BASE - 1);
563
    tmp >>= BN_BITS_PER_LIMB;
564
  }
565
  is_non_zero |= k->val[j];
566
  a.val[j] = tmp + 0xffffff + k->val[j] - (curve->order.val[j] & is_even);
567
  assert((a.val[0] & 1) != 0);
568
569
  // special case 0*G:  just return zero. We don't care about constant time.
570
  if (!is_non_zero) {
571
    point_set_infinity(res);
572
    return 0;
573
  }
574
575
  // Now a = k + 2^256 (mod curve->order) and a is odd.
576
  //
577
  // The idea is to bring the new a into the form.
578
  // sum_{i=0..64} a[i] 16^i,  where |a[i]| < 16 and a[i] is odd.
579
  // a[0] is odd, since a is odd.  If a[i] would be even, we can
580
  // add 1 to it and subtract 16 from a[i-1].  Afterwards,
581
  // a[64] = 1, which is the 2^256 that we added before.
582
  //
583
  // Since k = a - 2^256 (mod curve->order), we can compute
584
  //   k*G = sum_{i=0..63} a[i] 16^i * G
585
  //
586
  // We have a big table curve->cp that stores all possible
587
  // values of |a[i]| 16^i * G.
588
  // curve->cp[i][j] = (2*j+1) * 16^i * G
589
590
  // now compute  res = sum_{i=0..63} a[i] * 16^i * G step by step.
591
  // initial res = |a[0]| * G.  Note that a[0] = a & 0xf if (a&0x10) != 0
592
  // and - (16 - (a & 0xf)) otherwise.   We can compute this as
593
  //   ((a ^ (((a >> 4) & 1) - 1)) & 0xf) >> 1
594
  // since a is odd.
595
  lowbits = a.val[0] & ((1 << 5) - 1);
596
  lowbits ^= (lowbits >> 4) - 1;
597
  lowbits &= 15;
598
  curve_to_jacobian(&curve->cp[0][lowbits >> 1], &jres, prime);
599
  for (i = 1; i < 64; i++) {
600
    // invariant res = sign(a[i-1]) sum_{j=0..i-1} (a[j] * 16^j * G)
601
602
    // shift a by 4 places.
603
    for (j = 0; j < 8; j++) {
604
      a.val[j] =
605
          (a.val[j] >> 4) | ((a.val[j + 1] & 0xf) << (BN_BITS_PER_LIMB - 4));
606
    }
607
    a.val[j] >>= 4;
608
    // a = old(a)>>(4*i)
609
    // a is even iff sign(a[i-1]) = -1
610
611
    lowbits = a.val[0] & ((1 << 5) - 1);
612
    lowbits ^= (lowbits >> 4) - 1;
613
    lowbits &= 15;
614
    // negate last result to make signs of this round and the
615
    // last round equal.
616
    bn_cnegate(~lowbits & 1, &jres.y, prime);
617
618
    // add odd factor
619
    point_jacobian_add(&curve->cp[i][lowbits >> 1], &jres, curve);
620
  }
621
  bn_cnegate(~(a.val[0] >> 4) & 1, &jres.y, prime);
622
  jacobian_to_curve(&jres, res, prime);
623
  memzero(&a, sizeof(a));
624
  memzero(&jres, sizeof(jres));
625
626
  return 0;
627
}
628
629
#else
630
631
int scalar_multiply(const ecdsa_curve *curve, const bignum256 *k,
632
4.90k
                    curve_point *res) {
633
4.90k
  return point_multiply(curve, k, &curve->G, res);
634
4.90k
}
635
636
#endif
637
638
int tc_ecdh_multiply(const ecdsa_curve *curve, const uint8_t *priv_key,
639
581
                     const uint8_t *pub_key, uint8_t *session_key) {
640
581
  curve_point point = {0};
641
581
  if (!ecdsa_read_pubkey(curve, pub_key, &point)) {
642
116
    return 1;
643
116
  }
644
645
465
  bignum256 k = {0};
646
465
  bn_read_be(priv_key, &k);
647
465
  if (bn_is_zero(&k) || !bn_is_less(&k, &curve->order)) {
648
    // Invalid private key.
649
0
    return 2;
650
0
  }
651
652
465
  point_multiply(curve, &k, &point, &point);
653
465
  memzero(&k, sizeof(k));
654
655
465
  session_key[0] = 0x04;
656
465
  bn_write_be(&point.x, session_key + 1);
657
465
  bn_write_be(&point.y, session_key + 33);
658
465
  memzero(&point, sizeof(point));
659
660
465
  return 0;
661
465
}
662
663
// msg is a data to be signed
664
// msg_len is the message length
665
int ecdsa_sign(const ecdsa_curve *curve, HasherType hasher_sign,
666
               const uint8_t *priv_key, const uint8_t *msg, uint32_t msg_len,
667
               uint8_t *sig, uint8_t *pby,
668
884
               int (*is_canonical)(uint8_t by, uint8_t sig[64])) {
669
884
  uint8_t hash[32] = {0};
670
884
  hasher_Raw(hasher_sign, msg, msg_len, hash);
671
884
  int res = ecdsa_sign_digest(curve, priv_key, hash, sig, pby, is_canonical);
672
884
  memzero(hash, sizeof(hash));
673
884
  return res;
674
884
}
675
676
// uses secp256k1 curve
677
// priv_key is a 32 byte big endian stored number
678
// sig is 64 bytes long array for the signature
679
// digest is 32 bytes of digest
680
// is_canonical is an optional function that checks if the signature
681
// conforms to additional coin-specific rules.
682
int tc_ecdsa_sign_digest(const ecdsa_curve *curve, const uint8_t *priv_key,
683
                         const uint8_t *digest, uint8_t *sig, uint8_t *pby,
684
1.21k
                         int (*is_canonical)(uint8_t by, uint8_t sig[64])) {
685
1.21k
  int i = 0;
686
1.21k
  curve_point R = {0};
687
1.21k
  bignum256 k = {0}, z = {0}, randk = {0};
688
1.21k
  bignum256 *s = &R.y;
689
1.21k
  uint8_t by;  // signature recovery byte
690
691
1.21k
#if USE_RFC6979
692
1.21k
  rfc6979_state rng = {0};
693
1.21k
  init_rfc6979(priv_key, digest, curve, &rng);
694
1.21k
#endif
695
696
1.21k
  bn_read_be(digest, &z);
697
1.21k
  if (bn_is_zero(&z)) {
698
    // The probability of the digest being all-zero by chance is infinitesimal,
699
    // so this is most likely an indication of a bug. Furthermore, the signature
700
    // has no value, because in this case it can be easily forged for any public
701
    // key, see ecdsa_verify_digest().
702
9
    return 1;
703
9
  }
704
705
1.20k
  for (i = 0; i < 10000; i++) {
706
1.20k
#if USE_RFC6979
707
    // generate K deterministically
708
1.20k
    generate_k_rfc6979(&k, &rng);
709
    // if k is too big or too small, we don't like it
710
1.20k
    if (bn_is_zero(&k) || !bn_is_less(&k, &curve->order)) {
711
0
      continue;
712
0
    }
713
#else
714
    // generate random number k
715
    generate_k_random(&k, &curve->order);
716
#endif
717
718
    // compute k*G
719
1.20k
    scalar_multiply(curve, &k, &R);
720
1.20k
    by = R.y.val[0] & 1;
721
    // r = (rx mod n)
722
1.20k
    if (!bn_is_less(&R.x, &curve->order)) {
723
0
      bn_subtract(&R.x, &curve->order, &R.x);
724
0
      by |= 2;
725
0
    }
726
    // if r is zero, we retry
727
1.20k
    if (bn_is_zero(&R.x)) {
728
0
      continue;
729
0
    }
730
731
1.20k
    bn_read_be(priv_key, s);
732
1.20k
    if (bn_is_zero(s) || !bn_is_less(s, &curve->order)) {
733
      // Invalid private key.
734
36
      return 2;
735
36
    }
736
737
    // randomize operations to counter side-channel attacks
738
1.16k
    generate_k_random(&randk, &curve->order);
739
1.16k
    bn_multiply(&randk, &k, &curve->order);  // k*rand
740
1.16k
    bn_inverse(&k, &curve->order);           // (k*rand)^-1
741
1.16k
    bn_multiply(&R.x, s, &curve->order);     // R.x*priv
742
1.16k
    bn_add(s, &z);                           // R.x*priv + z
743
1.16k
    bn_multiply(&k, s, &curve->order);       // (k*rand)^-1 (R.x*priv + z)
744
1.16k
    bn_multiply(&randk, s, &curve->order);   // k^-1 (R.x*priv + z)
745
1.16k
    bn_mod(s, &curve->order);
746
    // if s is zero, we retry
747
1.16k
    if (bn_is_zero(s)) {
748
0
      continue;
749
0
    }
750
751
    // if S > order/2 => S = -S
752
1.16k
    if (bn_is_less(&curve->order_half, s)) {
753
591
      bn_subtract(&curve->order, s, s);
754
591
      by ^= 1;
755
591
    }
756
    // we are done, R.x and s is the result signature
757
1.16k
    bn_write_be(&R.x, sig);
758
1.16k
    bn_write_be(s, sig + 32);
759
760
    // check if the signature is acceptable or retry
761
1.16k
    if (is_canonical && !is_canonical(by, sig)) {
762
0
      continue;
763
0
    }
764
765
1.16k
    if (pby) {
766
0
      *pby = by;
767
0
    }
768
769
1.16k
    memzero(&k, sizeof(k));
770
1.16k
    memzero(&randk, sizeof(randk));
771
1.16k
#if USE_RFC6979
772
1.16k
    memzero(&rng, sizeof(rng));
773
1.16k
#endif
774
1.16k
    return 0;
775
1.16k
  }
776
777
  // Too many retries without a valid signature
778
  // -> fail with an error
779
0
  memzero(&k, sizeof(k));
780
0
  memzero(&randk, sizeof(randk));
781
0
#if USE_RFC6979
782
0
  memzero(&rng, sizeof(rng));
783
0
#endif
784
0
  return -1;
785
1.20k
}
786
787
// returns 0 on success
788
int tc_ecdsa_get_public_key33(const ecdsa_curve *curve, const uint8_t *priv_key,
789
0
                              uint8_t *pub_key) {
790
0
  curve_point R = {0};
791
0
  bignum256 k = {0};
792
793
0
  bn_read_be(priv_key, &k);
794
0
  if (bn_is_zero(&k) || !bn_is_less(&k, &curve->order)) {
795
    // Invalid private key.
796
0
    memzero(pub_key, 33);
797
0
    return -1;
798
0
  }
799
800
  // compute k*G
801
0
  if (scalar_multiply(curve, &k, &R) != 0) {
802
0
    memzero(&k, sizeof(k));
803
0
    return 1;
804
0
  }
805
0
  pub_key[0] = 0x02 | (R.y.val[0] & 0x01);
806
0
  bn_write_be(&R.x, pub_key + 1);
807
0
  memzero(&R, sizeof(R));
808
0
  memzero(&k, sizeof(k));
809
0
  return 0;
810
0
}
811
812
// returns 0 on success
813
int tc_ecdsa_get_public_key65(const ecdsa_curve *curve, const uint8_t *priv_key,
814
2.05k
                              uint8_t *pub_key) {
815
2.05k
  curve_point R = {0};
816
2.05k
  bignum256 k = {0};
817
818
2.05k
  bn_read_be(priv_key, &k);
819
2.05k
  if (bn_is_zero(&k) || !bn_is_less(&k, &curve->order)) {
820
    // Invalid private key.
821
0
    memzero(pub_key, 65);
822
0
    return -1;
823
0
  }
824
825
  // compute k*G
826
2.05k
  if (scalar_multiply(curve, &k, &R) != 0) {
827
0
    memzero(&k, sizeof(k));
828
0
    return 1;
829
0
  }
830
2.05k
  pub_key[0] = 0x04;
831
2.05k
  bn_write_be(&R.x, pub_key + 1);
832
2.05k
  bn_write_be(&R.y, pub_key + 33);
833
2.05k
  memzero(&R, sizeof(R));
834
2.05k
  memzero(&k, sizeof(k));
835
2.05k
  return 0;
836
2.05k
}
837
838
int ecdsa_uncompress_pubkey(const ecdsa_curve *curve, const uint8_t *pub_key,
839
0
                            uint8_t *uncompressed) {
840
0
  curve_point pub = {0};
841
842
0
  if (!ecdsa_read_pubkey(curve, pub_key, &pub)) {
843
0
    return 0;
844
0
  }
845
846
0
  uncompressed[0] = 4;
847
0
  bn_write_be(&pub.x, uncompressed + 1);
848
0
  bn_write_be(&pub.y, uncompressed + 33);
849
850
0
  return 1;
851
0
}
852
853
void ecdsa_get_pubkeyhash(const uint8_t *pub_key, HasherType hasher_pubkey,
854
0
                          uint8_t *pubkeyhash) {
855
0
  uint8_t h[HASHER_DIGEST_LENGTH] = {0};
856
0
  if (pub_key[0] == 0x04) {  // uncompressed format
857
0
    hasher_Raw(hasher_pubkey, pub_key, 65, h);
858
0
  } else if (pub_key[0] == 0x00) {  // point at infinity
859
0
    hasher_Raw(hasher_pubkey, pub_key, 1, h);
860
0
  } else {  // expecting compressed format
861
0
    hasher_Raw(hasher_pubkey, pub_key, 33, h);
862
0
  }
863
0
  memcpy(pubkeyhash, h, 20);
864
0
  memzero(h, sizeof(h));
865
0
}
866
867
void ecdsa_get_address_raw(const uint8_t *pub_key, uint32_t version,
868
0
                           HasherType hasher_pubkey, uint8_t *addr_raw) {
869
0
  size_t prefix_len = address_prefix_bytes_len(version);
870
0
  address_write_prefix_bytes(version, addr_raw);
871
0
  ecdsa_get_pubkeyhash(pub_key, hasher_pubkey, addr_raw + prefix_len);
872
0
}
873
874
void ecdsa_get_address(const uint8_t *pub_key, uint32_t version,
875
                       HasherType hasher_pubkey, HasherType hasher_base58,
876
0
                       char *addr, int addrsize) {
877
0
  uint8_t raw[MAX_ADDR_RAW_SIZE] = {0};
878
0
  size_t prefix_len = address_prefix_bytes_len(version);
879
0
  ecdsa_get_address_raw(pub_key, version, hasher_pubkey, raw);
880
0
  base58_encode_check(raw, 20 + prefix_len, hasher_base58, addr, addrsize);
881
  // not as important to clear this one, but we might as well
882
0
  memzero(raw, sizeof(raw));
883
0
}
884
885
void ecdsa_get_address_segwit_p2sh_raw(const uint8_t *pub_key, uint32_t version,
886
                                       HasherType hasher_pubkey,
887
0
                                       uint8_t *addr_raw) {
888
0
  uint8_t buf[32 + 2] = {0};
889
0
  buf[0] = 0;   // version byte
890
0
  buf[1] = 20;  // push 20 bytes
891
0
  ecdsa_get_pubkeyhash(pub_key, hasher_pubkey, buf + 2);
892
0
  size_t prefix_len = address_prefix_bytes_len(version);
893
0
  address_write_prefix_bytes(version, addr_raw);
894
0
  hasher_Raw(hasher_pubkey, buf, 22, addr_raw + prefix_len);
895
0
}
896
897
void ecdsa_get_address_segwit_p2sh(const uint8_t *pub_key, uint32_t version,
898
                                   HasherType hasher_pubkey,
899
                                   HasherType hasher_base58, char *addr,
900
0
                                   int addrsize) {
901
0
  uint8_t raw[MAX_ADDR_RAW_SIZE] = {0};
902
0
  size_t prefix_len = address_prefix_bytes_len(version);
903
0
  ecdsa_get_address_segwit_p2sh_raw(pub_key, version, hasher_pubkey, raw);
904
0
  base58_encode_check(raw, prefix_len + 20, hasher_base58, addr, addrsize);
905
0
  memzero(raw, sizeof(raw));
906
0
}
907
908
void ecdsa_get_wif(const uint8_t *priv_key, uint32_t version,
909
0
                   HasherType hasher_base58, char *wif, int wifsize) {
910
0
  uint8_t wif_raw[MAX_WIF_RAW_SIZE] = {0};
911
0
  size_t prefix_len = address_prefix_bytes_len(version);
912
0
  address_write_prefix_bytes(version, wif_raw);
913
0
  memcpy(wif_raw + prefix_len, priv_key, 32);
914
0
  wif_raw[prefix_len + 32] = 0x01;
915
0
  base58_encode_check(wif_raw, prefix_len + 32 + 1, hasher_base58, wif,
916
0
                      wifsize);
917
  // private keys running around our stack can cause trouble
918
0
  memzero(wif_raw, sizeof(wif_raw));
919
0
}
920
921
int ecdsa_address_decode(const char *addr, uint32_t version,
922
0
                         HasherType hasher_base58, uint8_t *out) {
923
0
  if (!addr) return 0;
924
0
  int prefix_len = address_prefix_bytes_len(version);
925
0
  return base58_decode_check(addr, hasher_base58, out, 20 + prefix_len) ==
926
0
             20 + prefix_len &&
927
0
         address_check_prefix(out, version);
928
0
}
929
930
0
void compress_coords(const curve_point *cp, uint8_t *compressed) {
931
0
  compressed[0] = bn_is_odd(&cp->y) ? 0x03 : 0x02;
932
0
  bn_write_be(&cp->x, compressed + 1);
933
0
}
934
935
void uncompress_coords(const ecdsa_curve *curve, uint8_t odd,
936
186
                       const bignum256 *x, bignum256 *y) {
937
  // y^2 = x^3 + a*x + b
938
186
  memcpy(y, x, sizeof(bignum256));       // y is x
939
186
  bn_multiply(x, y, &curve->prime);      // y is x^2
940
186
  bn_subi(y, -curve->a, &curve->prime);  // y is x^2 + a
941
186
  bn_multiply(x, y, &curve->prime);      // y is x^3 + ax
942
186
  bn_add(y, &curve->b);                  // y is x^3 + ax + b
943
186
  bn_sqrt(y, &curve->prime);             // y = sqrt(y)
944
186
  if ((odd & 0x01) != (y->val[0] & 1)) {
945
97
    bn_subtract(&curve->prime, y, y);  // y = -y
946
97
  }
947
186
}
948
949
int ecdsa_read_pubkey(const ecdsa_curve *curve, const uint8_t *pub_key,
950
2.52k
                      curve_point *pub) {
951
2.52k
  if (!curve) {
952
0
    curve = &secp256k1;
953
0
  }
954
2.52k
  if (pub_key[0] == 0x04) {
955
2.52k
    bn_read_be(pub_key + 1, &(pub->x));
956
2.52k
    bn_read_be(pub_key + 33, &(pub->y));
957
2.52k
    return ecdsa_validate_pubkey(curve, pub);
958
2.52k
  }
959
0
  if (pub_key[0] == 0x02 || pub_key[0] == 0x03) {  // compute missing y coords
960
0
    bn_read_be(pub_key + 1, &(pub->x));
961
0
    uncompress_coords(curve, pub_key[0], &(pub->x), &(pub->y));
962
0
    return ecdsa_validate_pubkey(curve, pub);
963
0
  }
964
  // error
965
0
  return 0;
966
0
}
967
968
// Verifies that:
969
//   - pub is not the point at infinity.
970
//   - pub->x and pub->y are in range [0,p-1].
971
//   - pub is on the curve.
972
// We assume that all curves using this code have cofactor 1, so there is no
973
// need to verify that pub is a scalar multiple of G.
974
2.70k
int ecdsa_validate_pubkey(const ecdsa_curve *curve, const curve_point *pub) {
975
2.70k
  bignum256 y_2 = {0}, x3_ax_b = {0};
976
977
2.70k
  if (point_is_infinity(pub)) {
978
23
    return 0;
979
23
  }
980
981
2.68k
  if (!bn_is_less(&(pub->x), &curve->prime) ||
982
2.68k
      !bn_is_less(&(pub->y), &curve->prime)) {
983
6
    return 0;
984
6
  }
985
986
2.67k
  memcpy(&y_2, &(pub->y), sizeof(bignum256));
987
2.67k
  memcpy(&x3_ax_b, &(pub->x), sizeof(bignum256));
988
989
  // y^2
990
2.67k
  bn_multiply(&(pub->y), &y_2, &curve->prime);
991
2.67k
  bn_mod(&y_2, &curve->prime);
992
993
  // x^3 + ax + b
994
2.67k
  bn_multiply(&(pub->x), &x3_ax_b, &curve->prime);  // x^2
995
2.67k
  bn_subi(&x3_ax_b, -curve->a, &curve->prime);      // x^2 + a
996
2.67k
  bn_multiply(&(pub->x), &x3_ax_b, &curve->prime);  // x^3 + ax
997
2.67k
  bn_addmod(&x3_ax_b, &curve->b, &curve->prime);    // x^3 + ax + b
998
2.67k
  bn_mod(&x3_ax_b, &curve->prime);
999
1000
2.67k
  if (!bn_is_equal(&x3_ax_b, &y_2)) {
1001
487
    return 0;
1002
487
  }
1003
1004
2.19k
  return 1;
1005
2.67k
}
1006
1007
// uses secp256k1 curve
1008
// pub_key - 65 bytes uncompressed key
1009
// signature - 64 bytes signature
1010
// msg is a data that was signed
1011
// msg_len is the message length
1012
1013
int ecdsa_verify(const ecdsa_curve *curve, HasherType hasher_sign,
1014
                 const uint8_t *pub_key, const uint8_t *sig, const uint8_t *msg,
1015
1.04k
                 uint32_t msg_len) {
1016
1.04k
  uint8_t hash[32] = {0};
1017
1.04k
  hasher_Raw(hasher_sign, msg, msg_len, hash);
1018
1.04k
  int res = ecdsa_verify_digest(curve, pub_key, sig, hash);
1019
1.04k
  memzero(hash, sizeof(hash));
1020
1.04k
  return res;
1021
1.04k
}
1022
1023
// Compute public key from signature and recovery id.
1024
// returns 0 if the key is successfully recovered
1025
int tc_ecdsa_recover_pub_from_sig(const ecdsa_curve *curve, uint8_t *pub_key,
1026
                                  const uint8_t *sig, const uint8_t *digest,
1027
226
                                  int recid) {
1028
226
  bignum256 r = {0}, s = {0}, e = {0};
1029
226
  curve_point cp = {0}, cp2 = {0};
1030
1031
  // read r and s
1032
226
  bn_read_be(sig, &r);
1033
226
  bn_read_be(sig + 32, &s);
1034
226
  if (!bn_is_less(&r, &curve->order) || bn_is_zero(&r)) {
1035
5
    return 1;
1036
5
  }
1037
221
  if (!bn_is_less(&s, &curve->order) || bn_is_zero(&s)) {
1038
10
    return 1;
1039
10
  }
1040
  // cp = R = k * G (k is secret nonce when signing)
1041
211
  memcpy(&cp.x, &r, sizeof(bignum256));
1042
211
  if (recid & 2) {
1043
50
    bn_add(&cp.x, &curve->order);
1044
50
    if (!bn_is_less(&cp.x, &curve->prime)) {
1045
25
      return 1;
1046
25
    }
1047
50
  }
1048
  // compute y from x
1049
186
  uncompress_coords(curve, recid & 1, &cp.x, &cp.y);
1050
186
  if (!ecdsa_validate_pubkey(curve, &cp)) {
1051
31
    return 1;
1052
31
  }
1053
  // e = -digest
1054
155
  bn_read_be(digest, &e);
1055
155
  bn_mod(&e, &curve->order);
1056
155
  bn_subtract(&curve->order, &e, &e);
1057
  // r = r^-1
1058
155
  bn_inverse(&r, &curve->order);
1059
  // e = -digest * r^-1
1060
155
  bn_multiply(&r, &e, &curve->order);
1061
155
  bn_mod(&e, &curve->order);
1062
  // s = s * r^-1
1063
155
  bn_multiply(&r, &s, &curve->order);
1064
155
  bn_mod(&s, &curve->order);
1065
  // cp = s * r^-1 * k * G
1066
155
  point_multiply(curve, &s, &cp, &cp);
1067
  // cp2 = -digest * r^-1 * G
1068
155
  scalar_multiply(curve, &e, &cp2);
1069
  // cp = (s * r^-1 * k - digest * r^-1) * G = Pub
1070
155
  point_add(curve, &cp2, &cp);
1071
  // The point at infinity is not considered to be a valid public key.
1072
155
  if (point_is_infinity(&cp)) {
1073
2
    return 1;
1074
2
  }
1075
153
  pub_key[0] = 0x04;
1076
153
  bn_write_be(&cp.x, pub_key + 1);
1077
153
  bn_write_be(&cp.y, pub_key + 33);
1078
153
  return 0;
1079
155
}
1080
1081
// returns 0 if verification succeeded
1082
int tc_ecdsa_verify_digest(const ecdsa_curve *curve, const uint8_t *pub_key,
1083
1.60k
                           const uint8_t *sig, const uint8_t *digest) {
1084
1.60k
  curve_point pub = {0}, res = {0};
1085
1.60k
  bignum256 r = {0}, s = {0}, z = {0};
1086
1.60k
  int result = 0;
1087
1088
1.60k
  if (!ecdsa_read_pubkey(curve, pub_key, &pub)) {
1089
65
    result = 1;
1090
65
  }
1091
1092
1.60k
  if (result == 0) {
1093
1.53k
    bn_read_be(sig, &r);
1094
1.53k
    bn_read_be(sig + 32, &s);
1095
1.53k
    bn_read_be(digest, &z);
1096
1.53k
    if (bn_is_zero(&r) || bn_is_zero(&s) || (!bn_is_less(&r, &curve->order)) ||
1097
1.53k
        (!bn_is_less(&s, &curve->order))) {
1098
25
      result = 2;
1099
25
    }
1100
1.53k
    if (bn_is_zero(&z)) {
1101
      // The digest was all-zero. The probability of this happening by chance is
1102
      // infinitesimal, but it could be induced by a fault injection. In this
1103
      // case the signature (r,s) can be forged by taking r := (t * Q).x mod n
1104
      // and s := r * t^-1 mod n for any t in [1, n-1]. We fail verification,
1105
      // because there is no guarantee that the signature was created by the
1106
      // owner of the private key.
1107
22
      result = 3;
1108
22
    }
1109
1.53k
  }
1110
1111
1.60k
  if (result == 0) {
1112
1.48k
    bn_inverse(&s, &curve->order);       // s = s^-1
1113
1.48k
    bn_multiply(&s, &z, &curve->order);  // z = z * s  [u1 = z * s^-1 mod n]
1114
1.48k
    bn_mod(&z, &curve->order);
1115
1.48k
    bn_multiply(&r, &s, &curve->order);  // s = r * s  [u2 = r * s^-1 mod n]
1116
1.48k
    bn_mod(&s, &curve->order);
1117
1.48k
    scalar_multiply(curve, &z, &res);       // res = z * G    [= u1 * G]
1118
1.48k
    point_multiply(curve, &s, &pub, &pub);  // pub = s * pub  [= u2 * Q]
1119
1.48k
    point_add(curve, &pub, &res);  // res = pub + res  [R = u1 * G + u2 * Q]
1120
1.48k
    if (point_is_infinity(&res)) {
1121
      // R == Infinity
1122
0
      result = 4;
1123
0
    }
1124
1.48k
  }
1125
1126
1.60k
  if (result == 0) {
1127
1.48k
    bn_mod(&(res.x), &curve->order);
1128
1.48k
    if (!bn_is_equal(&res.x, &r)) {
1129
      // R.x != r
1130
      // signature does not match
1131
297
      result = 5;
1132
297
    }
1133
1.48k
  }
1134
1135
1.60k
  memzero(&pub, sizeof(pub));
1136
1.60k
  memzero(&res, sizeof(res));
1137
1.60k
  memzero(&r, sizeof(r));
1138
1.60k
  memzero(&s, sizeof(s));
1139
1.60k
  memzero(&z, sizeof(z));
1140
1141
  // all OK
1142
1.60k
  return result;
1143
1.60k
}
1144
1145
ecdsa_tweak_pubkey_result tc_ecdsa_tweak_pubkey(
1146
    const ecdsa_curve *curve, const uint8_t *public_key_bytes,
1147
0
    const uint8_t *tweak_bytes, uint8_t *tweaked_public_key_bytes) {
1148
0
  int result = ECDSA_TWEAK_PUBKEY_SUCCESS;
1149
0
  curve_point public_key = {0};
1150
0
  bignum256 tweak = {0};
1151
0
  curve_point public_tweak = {0};
1152
1153
0
  if (public_key_bytes[0] != 0x02 && public_key_bytes[0] != 0x03) {
1154
0
    result = ECDSA_TWEAK_PUBKEY_INVALID_PUBKEY_ERR;
1155
0
    goto end;
1156
0
  }
1157
1158
0
  if (!ecdsa_read_pubkey(curve, public_key_bytes, &public_key)) {
1159
0
    result = ECDSA_TWEAK_PUBKEY_INVALID_PUBKEY_ERR;
1160
0
    goto end;
1161
0
  }
1162
1163
0
  bn_read_be(tweak_bytes, &tweak);
1164
0
  if (!bn_is_less(&tweak, &curve->order)) {
1165
0
    result = ECDSA_TWEAK_PUBKEY_INVALID_TWEAK_OR_RESULT_ERR;
1166
0
    goto end;
1167
0
  }
1168
1169
0
  (void)scalar_multiply(curve, &tweak, &public_tweak);
1170
0
  point_add(curve, &public_tweak, &public_key);
1171
1172
0
  if (point_is_infinity(&public_key)) {
1173
0
    result = ECDSA_TWEAK_PUBKEY_INVALID_TWEAK_OR_RESULT_ERR;
1174
0
    goto end;
1175
0
  }
1176
1177
0
  tweaked_public_key_bytes[0] = 0x02 | (public_key.y.val[0] & 0x01);
1178
0
  bn_write_be(&public_key.x, tweaked_public_key_bytes + 1);
1179
1180
0
end:
1181
0
  memzero(&public_key, sizeof(public_key));
1182
0
  memzero(&tweak, sizeof(tweak));
1183
0
  memzero(&public_tweak, sizeof(public_tweak));
1184
1185
0
  return result;
1186
0
}
1187
1188
0
int ecdsa_sig_to_der(const uint8_t *sig, uint8_t *der) {
1189
0
  int i = 0;
1190
0
  uint8_t *p = der, *len = NULL, *len1 = NULL, *len2 = NULL;
1191
0
  *p = 0x30;
1192
0
  p++;  // sequence
1193
0
  *p = 0x00;
1194
0
  len = p;
1195
0
  p++;  // len(sequence)
1196
1197
0
  *p = 0x02;
1198
0
  p++;  // integer
1199
0
  *p = 0x00;
1200
0
  len1 = p;
1201
0
  p++;  // len(integer)
1202
1203
  // process R
1204
0
  i = 0;
1205
0
  while (i < 31 && sig[i] == 0) {
1206
0
    i++;
1207
0
  }                      // skip leading zeroes
1208
0
  if (sig[i] >= 0x80) {  // put zero in output if MSB set
1209
0
    *p = 0x00;
1210
0
    p++;
1211
0
    *len1 = *len1 + 1;
1212
0
  }
1213
0
  while (i < 32) {  // copy bytes to output
1214
0
    *p = sig[i];
1215
0
    p++;
1216
0
    *len1 = *len1 + 1;
1217
0
    i++;
1218
0
  }
1219
1220
0
  *p = 0x02;
1221
0
  p++;  // integer
1222
0
  *p = 0x00;
1223
0
  len2 = p;
1224
0
  p++;  // len(integer)
1225
1226
  // process S
1227
0
  i = 32;
1228
0
  while (i < 63 && sig[i] == 0) {
1229
0
    i++;
1230
0
  }                      // skip leading zeroes
1231
0
  if (sig[i] >= 0x80) {  // put zero in output if MSB set
1232
0
    *p = 0x00;
1233
0
    p++;
1234
0
    *len2 = *len2 + 1;
1235
0
  }
1236
0
  while (i < 64) {  // copy bytes to output
1237
0
    *p = sig[i];
1238
0
    p++;
1239
0
    *len2 = *len2 + 1;
1240
0
    i++;
1241
0
  }
1242
1243
0
  *len = *len1 + *len2 + 4;
1244
0
  return *len + 2;
1245
0
}
1246
1247
// Parse a DER-encoded signature. We check whether the encoded integers satisfy
1248
// DER requirements regarding leading zeros.
1249
0
int ecdsa_sig_from_der(const uint8_t *der, size_t der_len, uint8_t sig[64]) {
1250
0
  memzero(sig, 64);
1251
1252
  // Check sequence header.
1253
0
  if (der_len < 2 || der_len > 72 || der[0] != 0x30 || der[1] != der_len - 2) {
1254
0
    return 1;
1255
0
  }
1256
1257
  // Read two DER-encoded integers.
1258
0
  size_t pos = 2;
1259
0
  for (int i = 0; i < 2; ++i) {
1260
    // Check integer header.
1261
0
    if (der_len < pos + 2 || der[pos] != 0x02) {
1262
0
      return 1;
1263
0
    }
1264
1265
    // Locate the integer.
1266
0
    size_t int_len = der[pos + 1];
1267
0
    pos += 2;
1268
0
    if (pos + int_len > der_len) {
1269
0
      return 1;
1270
0
    }
1271
1272
    // Positive integers must not start with an octet that has bit 8 set to 1.
1273
0
    if (int_len == 0 || der[pos] > 0x7f) {
1274
0
      return 1;
1275
0
    }
1276
1277
    // Skip a possible leading null octet.
1278
0
    if (int_len > 1 && der[pos] == 0x00) {
1279
0
      int_len--;
1280
0
      pos++;
1281
1282
      // Check that integer uses the shortest possible encoding.
1283
0
      if (der[pos] < 0x80) {
1284
0
        return 1;
1285
0
      }
1286
0
    }
1287
1288
    // Copy the integer to the output, making sure it fits.
1289
0
    if (int_len > 32) {
1290
0
      return 1;
1291
0
    }
1292
0
    memcpy(sig + 32 * (i + 1) - int_len, der + pos, int_len);
1293
1294
    // Move on to the next one.
1295
0
    pos += int_len;
1296
0
  }
1297
1298
  // Check that there are no trailing elements in the sequence.
1299
0
  if (pos != der_len) {
1300
0
    return 1;
1301
0
  }
1302
1303
0
  return 0;
1304
0
}
1305
1306
int ecdsa_get_public_key33(const ecdsa_curve *curve, const uint8_t *priv_key,
1307
0
                           uint8_t *pub_key) {
1308
#ifdef USE_SECP256K1_ZKP_ECDSA
1309
  if (curve == &secp256k1) {
1310
    return zkp_ecdsa_get_public_key33(curve, priv_key, pub_key);
1311
  }
1312
#endif
1313
0
  return tc_ecdsa_get_public_key33(curve, priv_key, pub_key);
1314
0
}
1315
1316
int ecdsa_get_public_key65(const ecdsa_curve *curve, const uint8_t *priv_key,
1317
2.05k
                           uint8_t *pub_key) {
1318
#ifdef USE_SECP256K1_ZKP_ECDSA
1319
  if (curve == &secp256k1) {
1320
    return zkp_ecdsa_get_public_key65(curve, priv_key, pub_key);
1321
  }
1322
#endif
1323
2.05k
  return tc_ecdsa_get_public_key65(curve, priv_key, pub_key);
1324
2.05k
}
1325
1326
int ecdsa_sign_digest(const ecdsa_curve *curve, const uint8_t *priv_key,
1327
                      const uint8_t *digest, uint8_t *sig, uint8_t *pby,
1328
1.21k
                      int (*is_canonical)(uint8_t by, uint8_t sig[64])) {
1329
#ifdef USE_SECP256K1_ZKP_ECDSA
1330
  if (curve == &secp256k1) {
1331
    return zkp_ecdsa_sign_digest(curve, priv_key, digest, sig, pby,
1332
                                 is_canonical);
1333
  }
1334
#endif
1335
1.21k
  return tc_ecdsa_sign_digest(curve, priv_key, digest, sig, pby, is_canonical);
1336
1.21k
}
1337
1338
int ecdsa_verify_digest(const ecdsa_curve *curve, const uint8_t *pub_key,
1339
1.60k
                        const uint8_t *sig, const uint8_t *digest) {
1340
#ifdef USE_SECP256K1_ZKP_ECDSA
1341
  if (curve == &secp256k1) {
1342
    return zkp_ecdsa_verify_digest(curve, pub_key, sig, digest);
1343
  }
1344
#endif
1345
1.60k
  return tc_ecdsa_verify_digest(curve, pub_key, sig, digest);
1346
1.60k
}
1347
1348
int ecdsa_recover_pub_from_sig(const ecdsa_curve *curve, uint8_t *pub_key,
1349
                               const uint8_t *sig, const uint8_t *digest,
1350
226
                               int recid) {
1351
#ifdef USE_SECP256K1_ZKP_ECDSA
1352
  if (curve == &secp256k1) {
1353
    return zkp_ecdsa_recover_pub_from_sig(curve, pub_key, sig, digest, recid);
1354
  }
1355
#endif
1356
226
  return tc_ecdsa_recover_pub_from_sig(curve, pub_key, sig, digest, recid);
1357
226
}
1358
1359
int ecdh_multiply(const ecdsa_curve *curve, const uint8_t *priv_key,
1360
581
                  const uint8_t *pub_key, uint8_t *session_key) {
1361
#ifdef USE_SECP256K1_ZKP_ECDSA
1362
  if (curve == &secp256k1) {
1363
    return zkp_ecdh_multiply(curve, priv_key, pub_key, session_key);
1364
  }
1365
#endif
1366
581
  return tc_ecdh_multiply(curve, priv_key, pub_key, session_key);
1367
581
}
1368
1369
ecdsa_tweak_pubkey_result ecdsa_tweak_pubkey(const ecdsa_curve *curve,
1370
                                             const uint8_t *pub_key,
1371
                                             const uint8_t *tweak,
1372
0
                                             uint8_t *tweaked_pub_key) {
1373
#ifdef USE_SECP256K1_ZKP_ECDSA
1374
  if (curve == &secp256k1) {
1375
    return zkp_ecdsa_tweak_pubkey(curve, pub_key, tweak, tweaked_pub_key);
1376
  }
1377
#endif
1378
0
  return tc_ecdsa_tweak_pubkey(curve, pub_key, tweak, tweaked_pub_key);
1379
0
}