1 /**********************************************************************
2  * Copyright (c) 2013-2015 Pieter Wuille                              *
3  * Distributed under the MIT software license, see the accompanying   *
4  * file COPYING or http://www.opensource.org/licenses/mit-license.php.*
5  **********************************************************************/
6 
7 #include "include/secp256k1.h"
8 #include "include/secp256k1_preallocated.h"
9 
10 #include "assumptions.h"
11 #include "util.h"
12 #include "num_impl.h"
13 #include "field_impl.h"
14 #include "scalar_impl.h"
15 #include "group_impl.h"
16 #include "ecmult_impl.h"
17 #include "ecmult_const_impl.h"
18 #include "ecmult_gen_impl.h"
19 #include "ecdsa_impl.h"
20 #include "eckey_impl.h"
21 #include "hash_impl.h"
22 #include "scratch_impl.h"
23 #include "selftest.h"
24 
25 #if defined(VALGRIND)
26 # include <valgrind/memcheck.h>
27 #endif
28 
29 #define ARG_CHECK(cond) do { \
30     if (EXPECT(!(cond), 0)) { \
31         secp256k1_callback_call(&ctx->illegal_callback, #cond); \
32         return 0; \
33     } \
34 } while(0)
35 
36 #define ARG_CHECK_NO_RETURN(cond) do { \
37     if (EXPECT(!(cond), 0)) { \
38         secp256k1_callback_call(&ctx->illegal_callback, #cond); \
39     } \
40 } while(0)
41 
42 #ifndef USE_EXTERNAL_DEFAULT_CALLBACKS
43 #include <stdlib.h>
44 #include <stdio.h>
secp256k1_default_illegal_callback_fn(const char * str,void * data)45 static void secp256k1_default_illegal_callback_fn(const char* str, void* data) {
46     (void)data;
47     fprintf(stderr, "[libsecp256k1] illegal argument: %s\n", str);
48     abort();
49 }
secp256k1_default_error_callback_fn(const char * str,void * data)50 static void secp256k1_default_error_callback_fn(const char* str, void* data) {
51     (void)data;
52     fprintf(stderr, "[libsecp256k1] internal consistency check failed: %s\n", str);
53     abort();
54 }
55 #else
56 void secp256k1_default_illegal_callback_fn(const char* str, void* data);
57 void secp256k1_default_error_callback_fn(const char* str, void* data);
58 #endif
59 
60 static const secp256k1_callback default_illegal_callback = {
61     secp256k1_default_illegal_callback_fn,
62     NULL
63 };
64 
65 static const secp256k1_callback default_error_callback = {
66     secp256k1_default_error_callback_fn,
67     NULL
68 };
69 
70 struct secp256k1_context_struct {
71     secp256k1_ecmult_context ecmult_ctx;
72     secp256k1_ecmult_gen_context ecmult_gen_ctx;
73     secp256k1_callback illegal_callback;
74     secp256k1_callback error_callback;
75     int declassify;
76 };
77 
78 static const secp256k1_context secp256k1_context_no_precomp_ = {
79     { 0 },
80     { 0 },
81     { secp256k1_default_illegal_callback_fn, 0 },
82     { secp256k1_default_error_callback_fn, 0 },
83     0
84 };
85 const secp256k1_context *secp256k1_context_no_precomp = &secp256k1_context_no_precomp_;
86 
secp256k1_context_preallocated_size(unsigned int flags)87 size_t secp256k1_context_preallocated_size(unsigned int flags) {
88     size_t ret = ROUND_TO_ALIGN(sizeof(secp256k1_context));
89 
90     if (EXPECT((flags & SECP256K1_FLAGS_TYPE_MASK) != SECP256K1_FLAGS_TYPE_CONTEXT, 0)) {
91             secp256k1_callback_call(&default_illegal_callback,
92                                     "Invalid flags");
93             return 0;
94     }
95 
96     if (flags & SECP256K1_FLAGS_BIT_CONTEXT_SIGN) {
97         ret += SECP256K1_ECMULT_GEN_CONTEXT_PREALLOCATED_SIZE;
98     }
99     if (flags & SECP256K1_FLAGS_BIT_CONTEXT_VERIFY) {
100         ret += SECP256K1_ECMULT_CONTEXT_PREALLOCATED_SIZE;
101     }
102     return ret;
103 }
104 
secp256k1_context_preallocated_clone_size(const secp256k1_context * ctx)105 size_t secp256k1_context_preallocated_clone_size(const secp256k1_context* ctx) {
106     size_t ret = ROUND_TO_ALIGN(sizeof(secp256k1_context));
107     VERIFY_CHECK(ctx != NULL);
108     if (secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)) {
109         ret += SECP256K1_ECMULT_GEN_CONTEXT_PREALLOCATED_SIZE;
110     }
111     if (secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)) {
112         ret += SECP256K1_ECMULT_CONTEXT_PREALLOCATED_SIZE;
113     }
114     return ret;
115 }
116 
secp256k1_context_preallocated_create(void * prealloc,unsigned int flags)117 secp256k1_context* secp256k1_context_preallocated_create(void* prealloc, unsigned int flags) {
118     void* const base = prealloc;
119     size_t prealloc_size;
120     secp256k1_context* ret;
121 
122     if (!secp256k1_selftest()) {
123         secp256k1_callback_call(&default_error_callback, "self test failed");
124     }
125     VERIFY_CHECK(prealloc != NULL);
126     prealloc_size = secp256k1_context_preallocated_size(flags);
127     ret = (secp256k1_context*)manual_alloc(&prealloc, sizeof(secp256k1_context), base, prealloc_size);
128     ret->illegal_callback = default_illegal_callback;
129     ret->error_callback = default_error_callback;
130 
131     if (EXPECT((flags & SECP256K1_FLAGS_TYPE_MASK) != SECP256K1_FLAGS_TYPE_CONTEXT, 0)) {
132             secp256k1_callback_call(&ret->illegal_callback,
133                                     "Invalid flags");
134             return NULL;
135     }
136 
137     secp256k1_ecmult_context_init(&ret->ecmult_ctx);
138     secp256k1_ecmult_gen_context_init(&ret->ecmult_gen_ctx);
139 
140     if (flags & SECP256K1_FLAGS_BIT_CONTEXT_SIGN) {
141         secp256k1_ecmult_gen_context_build(&ret->ecmult_gen_ctx, &prealloc);
142     }
143     if (flags & SECP256K1_FLAGS_BIT_CONTEXT_VERIFY) {
144         secp256k1_ecmult_context_build(&ret->ecmult_ctx, &prealloc);
145     }
146     ret->declassify = !!(flags & SECP256K1_FLAGS_BIT_CONTEXT_DECLASSIFY);
147 
148     return (secp256k1_context*) ret;
149 }
150 
secp256k1_context_create(unsigned int flags)151 secp256k1_context* secp256k1_context_create(unsigned int flags) {
152     size_t const prealloc_size = secp256k1_context_preallocated_size(flags);
153     secp256k1_context* ctx = (secp256k1_context*)checked_malloc(&default_error_callback, prealloc_size);
154     if (EXPECT(secp256k1_context_preallocated_create(ctx, flags) == NULL, 0)) {
155         free(ctx);
156         return NULL;
157     }
158 
159     return ctx;
160 }
161 
secp256k1_context_preallocated_clone(const secp256k1_context * ctx,void * prealloc)162 secp256k1_context* secp256k1_context_preallocated_clone(const secp256k1_context* ctx, void* prealloc) {
163     size_t prealloc_size;
164     secp256k1_context* ret;
165     VERIFY_CHECK(ctx != NULL);
166     ARG_CHECK(prealloc != NULL);
167 
168     prealloc_size = secp256k1_context_preallocated_clone_size(ctx);
169     ret = (secp256k1_context*)prealloc;
170     memcpy(ret, ctx, prealloc_size);
171     secp256k1_ecmult_gen_context_finalize_memcpy(&ret->ecmult_gen_ctx, &ctx->ecmult_gen_ctx);
172     secp256k1_ecmult_context_finalize_memcpy(&ret->ecmult_ctx, &ctx->ecmult_ctx);
173     return ret;
174 }
175 
secp256k1_context_clone(const secp256k1_context * ctx)176 secp256k1_context* secp256k1_context_clone(const secp256k1_context* ctx) {
177     secp256k1_context* ret;
178     size_t prealloc_size;
179 
180     VERIFY_CHECK(ctx != NULL);
181     prealloc_size = secp256k1_context_preallocated_clone_size(ctx);
182     ret = (secp256k1_context*)checked_malloc(&ctx->error_callback, prealloc_size);
183     ret = secp256k1_context_preallocated_clone(ctx, ret);
184     return ret;
185 }
186 
secp256k1_context_preallocated_destroy(secp256k1_context * ctx)187 void secp256k1_context_preallocated_destroy(secp256k1_context* ctx) {
188     ARG_CHECK_NO_RETURN(ctx != secp256k1_context_no_precomp);
189     if (ctx != NULL) {
190         secp256k1_ecmult_context_clear(&ctx->ecmult_ctx);
191         secp256k1_ecmult_gen_context_clear(&ctx->ecmult_gen_ctx);
192     }
193 }
194 
secp256k1_context_destroy(secp256k1_context * ctx)195 void secp256k1_context_destroy(secp256k1_context* ctx) {
196     if (ctx != NULL) {
197         secp256k1_context_preallocated_destroy(ctx);
198         free(ctx);
199     }
200 }
201 
secp256k1_context_set_illegal_callback(secp256k1_context * ctx,void (* fun)(const char * message,void * data),const void * data)202 void secp256k1_context_set_illegal_callback(secp256k1_context* ctx, void (*fun)(const char* message, void* data), const void* data) {
203     ARG_CHECK_NO_RETURN(ctx != secp256k1_context_no_precomp);
204     if (fun == NULL) {
205         fun = secp256k1_default_illegal_callback_fn;
206     }
207     ctx->illegal_callback.fn = fun;
208     ctx->illegal_callback.data = data;
209 }
210 
secp256k1_context_set_error_callback(secp256k1_context * ctx,void (* fun)(const char * message,void * data),const void * data)211 void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(const char* message, void* data), const void* data) {
212     ARG_CHECK_NO_RETURN(ctx != secp256k1_context_no_precomp);
213     if (fun == NULL) {
214         fun = secp256k1_default_error_callback_fn;
215     }
216     ctx->error_callback.fn = fun;
217     ctx->error_callback.data = data;
218 }
219 
secp256k1_scratch_space_create(const secp256k1_context * ctx,size_t max_size)220 secp256k1_scratch_space* secp256k1_scratch_space_create(const secp256k1_context* ctx, size_t max_size) {
221     VERIFY_CHECK(ctx != NULL);
222     return secp256k1_scratch_create(&ctx->error_callback, max_size);
223 }
224 
secp256k1_scratch_space_destroy(const secp256k1_context * ctx,secp256k1_scratch_space * scratch)225 void secp256k1_scratch_space_destroy(const secp256k1_context *ctx, secp256k1_scratch_space* scratch) {
226     VERIFY_CHECK(ctx != NULL);
227     secp256k1_scratch_destroy(&ctx->error_callback, scratch);
228 }
229 
230 /* Mark memory as no-longer-secret for the purpose of analysing constant-time behaviour
231  *  of the software. This is setup for use with valgrind but could be substituted with
232  *  the appropriate instrumentation for other analysis tools.
233  */
secp256k1_declassify(const secp256k1_context * ctx,const void * p,size_t len)234 static SECP256K1_INLINE void secp256k1_declassify(const secp256k1_context* ctx, const void *p, size_t len) {
235 #if defined(VALGRIND)
236     if (EXPECT(ctx->declassify,0)) VALGRIND_MAKE_MEM_DEFINED(p, len);
237 #else
238     (void)ctx;
239     (void)p;
240     (void)len;
241 #endif
242 }
243 
secp256k1_pubkey_load(const secp256k1_context * ctx,secp256k1_ge * ge,const secp256k1_pubkey * pubkey)244 static int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) {
245     if (sizeof(secp256k1_ge_storage) == 64) {
246         /* When the secp256k1_ge_storage type is exactly 64 byte, use its
247          * representation inside secp256k1_pubkey, as conversion is very fast.
248          * Note that secp256k1_pubkey_save must use the same representation. */
249         secp256k1_ge_storage s;
250         memcpy(&s, &pubkey->data[0], sizeof(s));
251         secp256k1_ge_from_storage(ge, &s);
252     } else {
253         /* Otherwise, fall back to 32-byte big endian for X and Y. */
254         secp256k1_fe x, y;
255         secp256k1_fe_set_b32(&x, pubkey->data);
256         secp256k1_fe_set_b32(&y, pubkey->data + 32);
257         secp256k1_ge_set_xy(ge, &x, &y);
258     }
259     ARG_CHECK(!secp256k1_fe_is_zero(&ge->x));
260     return 1;
261 }
262 
secp256k1_pubkey_save(secp256k1_pubkey * pubkey,secp256k1_ge * ge)263 static void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge) {
264     if (sizeof(secp256k1_ge_storage) == 64) {
265         secp256k1_ge_storage s;
266         secp256k1_ge_to_storage(&s, ge);
267         memcpy(&pubkey->data[0], &s, sizeof(s));
268     } else {
269         VERIFY_CHECK(!secp256k1_ge_is_infinity(ge));
270         secp256k1_fe_normalize_var(&ge->x);
271         secp256k1_fe_normalize_var(&ge->y);
272         secp256k1_fe_get_b32(pubkey->data, &ge->x);
273         secp256k1_fe_get_b32(pubkey->data + 32, &ge->y);
274     }
275 }
276 
secp256k1_ec_pubkey_parse(const secp256k1_context * ctx,secp256k1_pubkey * pubkey,const unsigned char * input,size_t inputlen)277 int secp256k1_ec_pubkey_parse(const secp256k1_context* ctx, secp256k1_pubkey* pubkey, const unsigned char *input, size_t inputlen) {
278     secp256k1_ge Q;
279 
280     VERIFY_CHECK(ctx != NULL);
281     ARG_CHECK(pubkey != NULL);
282     memset(pubkey, 0, sizeof(*pubkey));
283     ARG_CHECK(input != NULL);
284     if (!secp256k1_eckey_pubkey_parse(&Q, input, inputlen)) {
285         return 0;
286     }
287     if (!secp256k1_ge_is_in_correct_subgroup(&Q)) {
288         return 0;
289     }
290     secp256k1_pubkey_save(pubkey, &Q);
291     secp256k1_ge_clear(&Q);
292     return 1;
293 }
294 
secp256k1_ec_pubkey_serialize(const secp256k1_context * ctx,unsigned char * output,size_t * outputlen,const secp256k1_pubkey * pubkey,unsigned int flags)295 int secp256k1_ec_pubkey_serialize(const secp256k1_context* ctx, unsigned char *output, size_t *outputlen, const secp256k1_pubkey* pubkey, unsigned int flags) {
296     secp256k1_ge Q;
297     size_t len;
298     int ret = 0;
299 
300     VERIFY_CHECK(ctx != NULL);
301     ARG_CHECK(outputlen != NULL);
302     ARG_CHECK(*outputlen >= ((flags & SECP256K1_FLAGS_BIT_COMPRESSION) ? 33u : 65u));
303     len = *outputlen;
304     *outputlen = 0;
305     ARG_CHECK(output != NULL);
306     memset(output, 0, len);
307     ARG_CHECK(pubkey != NULL);
308     ARG_CHECK((flags & SECP256K1_FLAGS_TYPE_MASK) == SECP256K1_FLAGS_TYPE_COMPRESSION);
309     if (secp256k1_pubkey_load(ctx, &Q, pubkey)) {
310         ret = secp256k1_eckey_pubkey_serialize(&Q, output, &len, flags & SECP256K1_FLAGS_BIT_COMPRESSION);
311         if (ret) {
312             *outputlen = len;
313         }
314     }
315     return ret;
316 }
317 
secp256k1_ecdsa_signature_load(const secp256k1_context * ctx,secp256k1_scalar * r,secp256k1_scalar * s,const secp256k1_ecdsa_signature * sig)318 static void secp256k1_ecdsa_signature_load(const secp256k1_context* ctx, secp256k1_scalar* r, secp256k1_scalar* s, const secp256k1_ecdsa_signature* sig) {
319     (void)ctx;
320     if (sizeof(secp256k1_scalar) == 32) {
321         /* When the secp256k1_scalar type is exactly 32 byte, use its
322          * representation inside secp256k1_ecdsa_signature, as conversion is very fast.
323          * Note that secp256k1_ecdsa_signature_save must use the same representation. */
324         memcpy(r, &sig->data[0], 32);
325         memcpy(s, &sig->data[32], 32);
326     } else {
327         secp256k1_scalar_set_b32(r, &sig->data[0], NULL);
328         secp256k1_scalar_set_b32(s, &sig->data[32], NULL);
329     }
330 }
331 
secp256k1_ecdsa_signature_save(secp256k1_ecdsa_signature * sig,const secp256k1_scalar * r,const secp256k1_scalar * s)332 static void secp256k1_ecdsa_signature_save(secp256k1_ecdsa_signature* sig, const secp256k1_scalar* r, const secp256k1_scalar* s) {
333     if (sizeof(secp256k1_scalar) == 32) {
334         memcpy(&sig->data[0], r, 32);
335         memcpy(&sig->data[32], s, 32);
336     } else {
337         secp256k1_scalar_get_b32(&sig->data[0], r);
338         secp256k1_scalar_get_b32(&sig->data[32], s);
339     }
340 }
341 
secp256k1_ecdsa_signature_parse_der(const secp256k1_context * ctx,secp256k1_ecdsa_signature * sig,const unsigned char * input,size_t inputlen)342 int secp256k1_ecdsa_signature_parse_der(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const unsigned char *input, size_t inputlen) {
343     secp256k1_scalar r, s;
344 
345     VERIFY_CHECK(ctx != NULL);
346     ARG_CHECK(sig != NULL);
347     ARG_CHECK(input != NULL);
348 
349     if (secp256k1_ecdsa_sig_parse(&r, &s, input, inputlen)) {
350         secp256k1_ecdsa_signature_save(sig, &r, &s);
351         return 1;
352     } else {
353         memset(sig, 0, sizeof(*sig));
354         return 0;
355     }
356 }
357 
secp256k1_ecdsa_signature_parse_compact(const secp256k1_context * ctx,secp256k1_ecdsa_signature * sig,const unsigned char * input64)358 int secp256k1_ecdsa_signature_parse_compact(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const unsigned char *input64) {
359     secp256k1_scalar r, s;
360     int ret = 1;
361     int overflow = 0;
362 
363     VERIFY_CHECK(ctx != NULL);
364     ARG_CHECK(sig != NULL);
365     ARG_CHECK(input64 != NULL);
366 
367     secp256k1_scalar_set_b32(&r, &input64[0], &overflow);
368     ret &= !overflow;
369     secp256k1_scalar_set_b32(&s, &input64[32], &overflow);
370     ret &= !overflow;
371     if (ret) {
372         secp256k1_ecdsa_signature_save(sig, &r, &s);
373     } else {
374         memset(sig, 0, sizeof(*sig));
375     }
376     return ret;
377 }
378 
secp256k1_ecdsa_signature_serialize_der(const secp256k1_context * ctx,unsigned char * output,size_t * outputlen,const secp256k1_ecdsa_signature * sig)379 int secp256k1_ecdsa_signature_serialize_der(const secp256k1_context* ctx, unsigned char *output, size_t *outputlen, const secp256k1_ecdsa_signature* sig) {
380     secp256k1_scalar r, s;
381 
382     VERIFY_CHECK(ctx != NULL);
383     ARG_CHECK(output != NULL);
384     ARG_CHECK(outputlen != NULL);
385     ARG_CHECK(sig != NULL);
386 
387     secp256k1_ecdsa_signature_load(ctx, &r, &s, sig);
388     return secp256k1_ecdsa_sig_serialize(output, outputlen, &r, &s);
389 }
390 
secp256k1_ecdsa_signature_serialize_compact(const secp256k1_context * ctx,unsigned char * output64,const secp256k1_ecdsa_signature * sig)391 int secp256k1_ecdsa_signature_serialize_compact(const secp256k1_context* ctx, unsigned char *output64, const secp256k1_ecdsa_signature* sig) {
392     secp256k1_scalar r, s;
393 
394     VERIFY_CHECK(ctx != NULL);
395     ARG_CHECK(output64 != NULL);
396     ARG_CHECK(sig != NULL);
397 
398     secp256k1_ecdsa_signature_load(ctx, &r, &s, sig);
399     secp256k1_scalar_get_b32(&output64[0], &r);
400     secp256k1_scalar_get_b32(&output64[32], &s);
401     return 1;
402 }
403 
secp256k1_ecdsa_signature_normalize(const secp256k1_context * ctx,secp256k1_ecdsa_signature * sigout,const secp256k1_ecdsa_signature * sigin)404 int secp256k1_ecdsa_signature_normalize(const secp256k1_context* ctx, secp256k1_ecdsa_signature *sigout, const secp256k1_ecdsa_signature *sigin) {
405     secp256k1_scalar r, s;
406     int ret = 0;
407 
408     VERIFY_CHECK(ctx != NULL);
409     ARG_CHECK(sigin != NULL);
410 
411     secp256k1_ecdsa_signature_load(ctx, &r, &s, sigin);
412     ret = secp256k1_scalar_is_high(&s);
413     if (sigout != NULL) {
414         if (ret) {
415             secp256k1_scalar_negate(&s, &s);
416         }
417         secp256k1_ecdsa_signature_save(sigout, &r, &s);
418     }
419 
420     return ret;
421 }
422 
secp256k1_ecdsa_verify(const secp256k1_context * ctx,const secp256k1_ecdsa_signature * sig,const unsigned char * msg32,const secp256k1_pubkey * pubkey)423 int secp256k1_ecdsa_verify(const secp256k1_context* ctx, const secp256k1_ecdsa_signature *sig, const unsigned char *msg32, const secp256k1_pubkey *pubkey) {
424     secp256k1_ge q;
425     secp256k1_scalar r, s;
426     secp256k1_scalar m;
427     VERIFY_CHECK(ctx != NULL);
428     ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx));
429     ARG_CHECK(msg32 != NULL);
430     ARG_CHECK(sig != NULL);
431     ARG_CHECK(pubkey != NULL);
432 
433     secp256k1_scalar_set_b32(&m, msg32, NULL);
434     secp256k1_ecdsa_signature_load(ctx, &r, &s, sig);
435     return (!secp256k1_scalar_is_high(&s) &&
436             secp256k1_pubkey_load(ctx, &q, pubkey) &&
437             secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &r, &s, &q, &m));
438 }
439 
buffer_append(unsigned char * buf,unsigned int * offset,const void * data,unsigned int len)440 static SECP256K1_INLINE void buffer_append(unsigned char *buf, unsigned int *offset, const void *data, unsigned int len) {
441     memcpy(buf + *offset, data, len);
442     *offset += len;
443 }
444 
nonce_function_rfc6979(unsigned char * nonce32,const unsigned char * msg32,const unsigned char * key32,const unsigned char * algo16,void * data,unsigned int counter)445 static int nonce_function_rfc6979(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) {
446    unsigned char keydata[112];
447    unsigned int offset = 0;
448    secp256k1_rfc6979_hmac_sha256 rng;
449    unsigned int i;
450    /* We feed a byte array to the PRNG as input, consisting of:
451     * - the private key (32 bytes) and message (32 bytes), see RFC 6979 3.2d.
452     * - optionally 32 extra bytes of data, see RFC 6979 3.6 Additional Data.
453     * - optionally 16 extra bytes with the algorithm name.
454     * Because the arguments have distinct fixed lengths it is not possible for
455     *  different argument mixtures to emulate each other and result in the same
456     *  nonces.
457     */
458    buffer_append(keydata, &offset, key32, 32);
459    buffer_append(keydata, &offset, msg32, 32);
460    if (data != NULL) {
461        buffer_append(keydata, &offset, data, 32);
462    }
463    if (algo16 != NULL) {
464        buffer_append(keydata, &offset, algo16, 16);
465    }
466    secp256k1_rfc6979_hmac_sha256_initialize(&rng, keydata, offset);
467    memset(keydata, 0, sizeof(keydata));
468    for (i = 0; i <= counter; i++) {
469        secp256k1_rfc6979_hmac_sha256_generate(&rng, nonce32, 32);
470    }
471    secp256k1_rfc6979_hmac_sha256_finalize(&rng);
472    return 1;
473 }
474 
475 const secp256k1_nonce_function secp256k1_nonce_function_rfc6979 = nonce_function_rfc6979;
476 const secp256k1_nonce_function secp256k1_nonce_function_default = nonce_function_rfc6979;
477 
secp256k1_ecdsa_sign_inner(const secp256k1_context * ctx,secp256k1_scalar * r,secp256k1_scalar * s,int * recid,const unsigned char * msg32,const unsigned char * seckey,secp256k1_nonce_function noncefp,const void * noncedata)478 static int secp256k1_ecdsa_sign_inner(const secp256k1_context* ctx, secp256k1_scalar* r, secp256k1_scalar* s, int* recid, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, const void* noncedata) {
479     secp256k1_scalar sec, non, msg;
480     int ret = 0;
481     int is_sec_valid;
482     unsigned char nonce32[32];
483     unsigned int count = 0;
484     /* Default initialization here is important so we won't pass uninit values to the cmov in the end */
485     *r = secp256k1_scalar_zero;
486     *s = secp256k1_scalar_zero;
487     if (recid) {
488         *recid = 0;
489     }
490     if (noncefp == NULL) {
491         noncefp = secp256k1_nonce_function_default;
492     }
493 
494     /* Fail if the secret key is invalid. */
495     is_sec_valid = secp256k1_scalar_set_b32_seckey(&sec, seckey);
496     secp256k1_scalar_cmov(&sec, &secp256k1_scalar_one, !is_sec_valid);
497     secp256k1_scalar_set_b32(&msg, msg32, NULL);
498     while (1) {
499         int is_nonce_valid;
500         ret = !!noncefp(nonce32, msg32, seckey, NULL, (void*)noncedata, count);
501         if (!ret) {
502             break;
503         }
504         is_nonce_valid = secp256k1_scalar_set_b32_seckey(&non, nonce32);
505         /* The nonce is still secret here, but it being invalid is is less likely than 1:2^255. */
506         secp256k1_declassify(ctx, &is_nonce_valid, sizeof(is_nonce_valid));
507         if (is_nonce_valid) {
508             ret = secp256k1_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, r, s, &sec, &msg, &non, recid);
509             /* The final signature is no longer a secret, nor is the fact that we were successful or not. */
510             secp256k1_declassify(ctx, &ret, sizeof(ret));
511             if (ret) {
512                 break;
513             }
514         }
515         count++;
516     }
517     /* We don't want to declassify is_sec_valid and therefore the range of
518      * seckey. As a result is_sec_valid is included in ret only after ret was
519      * used as a branching variable. */
520     ret &= is_sec_valid;
521     memset(nonce32, 0, 32);
522     secp256k1_scalar_clear(&msg);
523     secp256k1_scalar_clear(&non);
524     secp256k1_scalar_clear(&sec);
525     secp256k1_scalar_cmov(r, &secp256k1_scalar_zero, !ret);
526     secp256k1_scalar_cmov(s, &secp256k1_scalar_zero, !ret);
527     if (recid) {
528         const int zero = 0;
529         secp256k1_int_cmov(recid, &zero, !ret);
530     }
531     return ret;
532 }
533 
secp256k1_ecdsa_sign(const secp256k1_context * ctx,secp256k1_ecdsa_signature * signature,const unsigned char * msg32,const unsigned char * seckey,secp256k1_nonce_function noncefp,const void * noncedata)534 int secp256k1_ecdsa_sign(const secp256k1_context* ctx, secp256k1_ecdsa_signature *signature, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, const void* noncedata) {
535     secp256k1_scalar r, s;
536     int ret;
537     VERIFY_CHECK(ctx != NULL);
538     ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx));
539     ARG_CHECK(msg32 != NULL);
540     ARG_CHECK(signature != NULL);
541     ARG_CHECK(seckey != NULL);
542 
543     ret = secp256k1_ecdsa_sign_inner(ctx, &r, &s, NULL, msg32, seckey, noncefp, noncedata);
544     secp256k1_ecdsa_signature_save(signature, &r, &s);
545     return ret;
546 }
547 
secp256k1_ec_seckey_verify(const secp256k1_context * ctx,const unsigned char * seckey)548 int secp256k1_ec_seckey_verify(const secp256k1_context* ctx, const unsigned char *seckey) {
549     secp256k1_scalar sec;
550     int ret;
551     VERIFY_CHECK(ctx != NULL);
552     ARG_CHECK(seckey != NULL);
553 
554     ret = secp256k1_scalar_set_b32_seckey(&sec, seckey);
555     secp256k1_scalar_clear(&sec);
556     return ret;
557 }
558 
secp256k1_ec_pubkey_create_helper(const secp256k1_ecmult_gen_context * ecmult_gen_ctx,secp256k1_scalar * seckey_scalar,secp256k1_ge * p,const unsigned char * seckey)559 static int secp256k1_ec_pubkey_create_helper(const secp256k1_ecmult_gen_context *ecmult_gen_ctx, secp256k1_scalar *seckey_scalar, secp256k1_ge *p, const unsigned char *seckey) {
560     secp256k1_gej pj;
561     int ret;
562 
563     ret = secp256k1_scalar_set_b32_seckey(seckey_scalar, seckey);
564     secp256k1_scalar_cmov(seckey_scalar, &secp256k1_scalar_one, !ret);
565 
566     secp256k1_ecmult_gen(ecmult_gen_ctx, &pj, seckey_scalar);
567     secp256k1_ge_set_gej(p, &pj);
568     return ret;
569 }
570 
secp256k1_ec_pubkey_create(const secp256k1_context * ctx,secp256k1_pubkey * pubkey,const unsigned char * seckey)571 int secp256k1_ec_pubkey_create(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const unsigned char *seckey) {
572     secp256k1_ge p;
573     secp256k1_scalar seckey_scalar;
574     int ret = 0;
575     VERIFY_CHECK(ctx != NULL);
576     ARG_CHECK(pubkey != NULL);
577     memset(pubkey, 0, sizeof(*pubkey));
578     ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx));
579     ARG_CHECK(seckey != NULL);
580 
581     ret = secp256k1_ec_pubkey_create_helper(&ctx->ecmult_gen_ctx, &seckey_scalar, &p, seckey);
582     secp256k1_pubkey_save(pubkey, &p);
583     memczero(pubkey, sizeof(*pubkey), !ret);
584 
585     secp256k1_scalar_clear(&seckey_scalar);
586     return ret;
587 }
588 
secp256k1_ec_seckey_negate(const secp256k1_context * ctx,unsigned char * seckey)589 int secp256k1_ec_seckey_negate(const secp256k1_context* ctx, unsigned char *seckey) {
590     secp256k1_scalar sec;
591     int ret = 0;
592     VERIFY_CHECK(ctx != NULL);
593     ARG_CHECK(seckey != NULL);
594 
595     ret = secp256k1_scalar_set_b32_seckey(&sec, seckey);
596     secp256k1_scalar_cmov(&sec, &secp256k1_scalar_zero, !ret);
597     secp256k1_scalar_negate(&sec, &sec);
598     secp256k1_scalar_get_b32(seckey, &sec);
599 
600     secp256k1_scalar_clear(&sec);
601     return ret;
602 }
603 
secp256k1_ec_privkey_negate(const secp256k1_context * ctx,unsigned char * seckey)604 int secp256k1_ec_privkey_negate(const secp256k1_context* ctx, unsigned char *seckey) {
605     return secp256k1_ec_seckey_negate(ctx, seckey);
606 }
607 
secp256k1_ec_pubkey_negate(const secp256k1_context * ctx,secp256k1_pubkey * pubkey)608 int secp256k1_ec_pubkey_negate(const secp256k1_context* ctx, secp256k1_pubkey *pubkey) {
609     int ret = 0;
610     secp256k1_ge p;
611     VERIFY_CHECK(ctx != NULL);
612     ARG_CHECK(pubkey != NULL);
613 
614     ret = secp256k1_pubkey_load(ctx, &p, pubkey);
615     memset(pubkey, 0, sizeof(*pubkey));
616     if (ret) {
617         secp256k1_ge_neg(&p, &p);
618         secp256k1_pubkey_save(pubkey, &p);
619     }
620     return ret;
621 }
622 
623 
secp256k1_ec_seckey_tweak_add_helper(secp256k1_scalar * sec,const unsigned char * tweak)624 static int secp256k1_ec_seckey_tweak_add_helper(secp256k1_scalar *sec, const unsigned char *tweak) {
625     secp256k1_scalar term;
626     int overflow = 0;
627     int ret = 0;
628 
629     secp256k1_scalar_set_b32(&term, tweak, &overflow);
630     ret = (!overflow) & secp256k1_eckey_privkey_tweak_add(sec, &term);
631     secp256k1_scalar_clear(&term);
632     return ret;
633 }
634 
secp256k1_ec_seckey_tweak_add(const secp256k1_context * ctx,unsigned char * seckey,const unsigned char * tweak)635 int secp256k1_ec_seckey_tweak_add(const secp256k1_context* ctx, unsigned char *seckey, const unsigned char *tweak) {
636     secp256k1_scalar sec;
637     int ret = 0;
638     VERIFY_CHECK(ctx != NULL);
639     ARG_CHECK(seckey != NULL);
640     ARG_CHECK(tweak != NULL);
641 
642     ret = secp256k1_scalar_set_b32_seckey(&sec, seckey);
643     ret &= secp256k1_ec_seckey_tweak_add_helper(&sec, tweak);
644     secp256k1_scalar_cmov(&sec, &secp256k1_scalar_zero, !ret);
645     secp256k1_scalar_get_b32(seckey, &sec);
646 
647     secp256k1_scalar_clear(&sec);
648     return ret;
649 }
650 
secp256k1_ec_privkey_tweak_add(const secp256k1_context * ctx,unsigned char * seckey,const unsigned char * tweak)651 int secp256k1_ec_privkey_tweak_add(const secp256k1_context* ctx, unsigned char *seckey, const unsigned char *tweak) {
652     return secp256k1_ec_seckey_tweak_add(ctx, seckey, tweak);
653 }
654 
secp256k1_ec_pubkey_tweak_add_helper(const secp256k1_ecmult_context * ecmult_ctx,secp256k1_ge * p,const unsigned char * tweak)655 static int secp256k1_ec_pubkey_tweak_add_helper(const secp256k1_ecmult_context* ecmult_ctx, secp256k1_ge *p, const unsigned char *tweak) {
656     secp256k1_scalar term;
657     int overflow = 0;
658     secp256k1_scalar_set_b32(&term, tweak, &overflow);
659     return !overflow && secp256k1_eckey_pubkey_tweak_add(ecmult_ctx, p, &term);
660 }
661 
secp256k1_ec_pubkey_tweak_add(const secp256k1_context * ctx,secp256k1_pubkey * pubkey,const unsigned char * tweak)662 int secp256k1_ec_pubkey_tweak_add(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const unsigned char *tweak) {
663     secp256k1_ge p;
664     int ret = 0;
665     VERIFY_CHECK(ctx != NULL);
666     ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx));
667     ARG_CHECK(pubkey != NULL);
668     ARG_CHECK(tweak != NULL);
669 
670     ret = secp256k1_pubkey_load(ctx, &p, pubkey);
671     memset(pubkey, 0, sizeof(*pubkey));
672     ret = ret && secp256k1_ec_pubkey_tweak_add_helper(&ctx->ecmult_ctx, &p, tweak);
673     if (ret) {
674         secp256k1_pubkey_save(pubkey, &p);
675     }
676 
677     return ret;
678 }
679 
secp256k1_ec_seckey_tweak_mul(const secp256k1_context * ctx,unsigned char * seckey,const unsigned char * tweak)680 int secp256k1_ec_seckey_tweak_mul(const secp256k1_context* ctx, unsigned char *seckey, const unsigned char *tweak) {
681     secp256k1_scalar factor;
682     secp256k1_scalar sec;
683     int ret = 0;
684     int overflow = 0;
685     VERIFY_CHECK(ctx != NULL);
686     ARG_CHECK(seckey != NULL);
687     ARG_CHECK(tweak != NULL);
688 
689     secp256k1_scalar_set_b32(&factor, tweak, &overflow);
690     ret = secp256k1_scalar_set_b32_seckey(&sec, seckey);
691     ret &= (!overflow) & secp256k1_eckey_privkey_tweak_mul(&sec, &factor);
692     secp256k1_scalar_cmov(&sec, &secp256k1_scalar_zero, !ret);
693     secp256k1_scalar_get_b32(seckey, &sec);
694 
695     secp256k1_scalar_clear(&sec);
696     secp256k1_scalar_clear(&factor);
697     return ret;
698 }
699 
secp256k1_ec_privkey_tweak_mul(const secp256k1_context * ctx,unsigned char * seckey,const unsigned char * tweak)700 int secp256k1_ec_privkey_tweak_mul(const secp256k1_context* ctx, unsigned char *seckey, const unsigned char *tweak) {
701     return secp256k1_ec_seckey_tweak_mul(ctx, seckey, tweak);
702 }
703 
secp256k1_ec_pubkey_tweak_mul(const secp256k1_context * ctx,secp256k1_pubkey * pubkey,const unsigned char * tweak)704 int secp256k1_ec_pubkey_tweak_mul(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const unsigned char *tweak) {
705     secp256k1_ge p;
706     secp256k1_scalar factor;
707     int ret = 0;
708     int overflow = 0;
709     VERIFY_CHECK(ctx != NULL);
710     ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx));
711     ARG_CHECK(pubkey != NULL);
712     ARG_CHECK(tweak != NULL);
713 
714     secp256k1_scalar_set_b32(&factor, tweak, &overflow);
715     ret = !overflow && secp256k1_pubkey_load(ctx, &p, pubkey);
716     memset(pubkey, 0, sizeof(*pubkey));
717     if (ret) {
718         if (secp256k1_eckey_pubkey_tweak_mul(&ctx->ecmult_ctx, &p, &factor)) {
719             secp256k1_pubkey_save(pubkey, &p);
720         } else {
721             ret = 0;
722         }
723     }
724 
725     return ret;
726 }
727 
secp256k1_context_randomize(secp256k1_context * ctx,const unsigned char * seed32)728 int secp256k1_context_randomize(secp256k1_context* ctx, const unsigned char *seed32) {
729     VERIFY_CHECK(ctx != NULL);
730     if (secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)) {
731         secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, seed32);
732     }
733     return 1;
734 }
735 
secp256k1_ec_pubkey_combine(const secp256k1_context * ctx,secp256k1_pubkey * pubnonce,const secp256k1_pubkey * const * pubnonces,size_t n)736 int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey *pubnonce, const secp256k1_pubkey * const *pubnonces, size_t n) {
737     size_t i;
738     secp256k1_gej Qj;
739     secp256k1_ge Q;
740 
741     ARG_CHECK(pubnonce != NULL);
742     memset(pubnonce, 0, sizeof(*pubnonce));
743     ARG_CHECK(n >= 1);
744     ARG_CHECK(pubnonces != NULL);
745 
746     secp256k1_gej_set_infinity(&Qj);
747 
748     for (i = 0; i < n; i++) {
749         secp256k1_pubkey_load(ctx, &Q, pubnonces[i]);
750         secp256k1_gej_add_ge(&Qj, &Qj, &Q);
751     }
752     if (secp256k1_gej_is_infinity(&Qj)) {
753         return 0;
754     }
755     secp256k1_ge_set_gej(&Q, &Qj);
756     secp256k1_pubkey_save(pubnonce, &Q);
757     return 1;
758 }
759 
760 #ifdef ENABLE_MODULE_ECDH
761 # include "modules/ecdh/main_impl.h"
762 #endif
763 
764 #ifdef ENABLE_MODULE_RECOVERY
765 # include "modules/recovery/main_impl.h"
766 #endif
767 
768 #ifdef ENABLE_MODULE_EXTRAKEYS
769 # include "modules/extrakeys/main_impl.h"
770 #endif
771 
772 #ifdef ENABLE_MODULE_SCHNORRSIG
773 # include "modules/schnorrsig/main_impl.h"
774 #endif
775