github.com/ethereum/go-ethereum@v1.16.1/crypto/secp256k1/libsecp256k1/src/tests_exhaustive.c (about)

     1  /***********************************************************************
     2   * Copyright (c) 2016 Andrew Poelstra                                  *
     3   * Distributed under the MIT software license, see the accompanying    *
     4   * file COPYING or https://www.opensource.org/licenses/mit-license.php.*
     5   ***********************************************************************/
     6  
     7  #include <stdio.h>
     8  #include <stdlib.h>
     9  #include <time.h>
    10  
    11  #ifndef EXHAUSTIVE_TEST_ORDER
    12  /* see group_impl.h for allowable values */
    13  #define EXHAUSTIVE_TEST_ORDER 13
    14  #endif
    15  
    16  /* These values of B are all values in [1, 8] that result in a curve with even order. */
    17  #define EXHAUSTIVE_TEST_CURVE_HAS_EVEN_ORDER (SECP256K1_B == 1 || SECP256K1_B == 6 || SECP256K1_B == 8)
    18  
    19  #ifdef USE_EXTERNAL_DEFAULT_CALLBACKS
    20      #pragma message("Ignoring USE_EXTERNAL_CALLBACKS in exhaustive_tests.")
    21      #undef USE_EXTERNAL_DEFAULT_CALLBACKS
    22  #endif
    23  #include "secp256k1.c"
    24  
    25  #include "../include/secp256k1.h"
    26  #include "assumptions.h"
    27  #include "group.h"
    28  #include "testrand_impl.h"
    29  #include "ecmult_compute_table_impl.h"
    30  #include "ecmult_gen_compute_table_impl.h"
    31  #include "testutil.h"
    32  #include "util.h"
    33  
    34  static int count = 2;
    35  
    36  static uint32_t num_cores = 1;
    37  static uint32_t this_core = 0;
    38  
    39  SECP256K1_INLINE static int skip_section(uint64_t* iter) {
    40      if (num_cores == 1) return 0;
    41      *iter += 0xe7037ed1a0b428dbULL;
    42      return ((((uint32_t)*iter ^ (*iter >> 32)) * num_cores) >> 32) != this_core;
    43  }
    44  
    45  static int secp256k1_nonce_function_smallint(unsigned char *nonce32, const unsigned char *msg32,
    46                                        const unsigned char *key32, const unsigned char *algo16,
    47                                        void *data, unsigned int attempt) {
    48      secp256k1_scalar s;
    49      int *idata = data;
    50      (void)msg32;
    51      (void)key32;
    52      (void)algo16;
    53      /* Some nonces cannot be used because they'd cause s and/or r to be zero.
    54       * The signing function has retry logic here that just re-calls the nonce
    55       * function with an increased `attempt`. So if attempt > 0 this means we
    56       * need to change the nonce to avoid an infinite loop. */
    57      if (attempt > 0) {
    58          *idata = (*idata + 1) % EXHAUSTIVE_TEST_ORDER;
    59      }
    60      secp256k1_scalar_set_int(&s, *idata);
    61      secp256k1_scalar_get_b32(nonce32, &s);
    62      return 1;
    63  }
    64  
    65  static void test_exhaustive_endomorphism(const secp256k1_ge *group) {
    66      int i;
    67      for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) {
    68          secp256k1_ge res;
    69          secp256k1_ge_mul_lambda(&res, &group[i]);
    70          CHECK(secp256k1_ge_eq_var(&group[i * EXHAUSTIVE_TEST_LAMBDA % EXHAUSTIVE_TEST_ORDER], &res));
    71      }
    72  }
    73  
    74  static void test_exhaustive_addition(const secp256k1_ge *group, const secp256k1_gej *groupj) {
    75      int i, j;
    76      uint64_t iter = 0;
    77  
    78      /* Sanity-check (and check infinity functions) */
    79      CHECK(secp256k1_ge_is_infinity(&group[0]));
    80      CHECK(secp256k1_gej_is_infinity(&groupj[0]));
    81      for (i = 1; i < EXHAUSTIVE_TEST_ORDER; i++) {
    82          CHECK(!secp256k1_ge_is_infinity(&group[i]));
    83          CHECK(!secp256k1_gej_is_infinity(&groupj[i]));
    84      }
    85  
    86      /* Check all addition formulae */
    87      for (j = 0; j < EXHAUSTIVE_TEST_ORDER; j++) {
    88          secp256k1_fe fe_inv;
    89          if (skip_section(&iter)) continue;
    90          secp256k1_fe_inv(&fe_inv, &groupj[j].z);
    91          for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) {
    92              secp256k1_ge zless_gej;
    93              secp256k1_gej tmp;
    94              /* add_var */
    95              secp256k1_gej_add_var(&tmp, &groupj[i], &groupj[j], NULL);
    96              CHECK(secp256k1_gej_eq_ge_var(&tmp, &group[(i + j) % EXHAUSTIVE_TEST_ORDER]));
    97              /* add_ge */
    98              if (j > 0) {
    99                  secp256k1_gej_add_ge(&tmp, &groupj[i], &group[j]);
   100                  CHECK(secp256k1_gej_eq_ge_var(&tmp, &group[(i + j) % EXHAUSTIVE_TEST_ORDER]));
   101              }
   102              /* add_ge_var */
   103              secp256k1_gej_add_ge_var(&tmp, &groupj[i], &group[j], NULL);
   104              CHECK(secp256k1_gej_eq_ge_var(&tmp, &group[(i + j) % EXHAUSTIVE_TEST_ORDER]));
   105              /* add_zinv_var */
   106              zless_gej.infinity = groupj[j].infinity;
   107              zless_gej.x = groupj[j].x;
   108              zless_gej.y = groupj[j].y;
   109              secp256k1_gej_add_zinv_var(&tmp, &groupj[i], &zless_gej, &fe_inv);
   110              CHECK(secp256k1_gej_eq_ge_var(&tmp, &group[(i + j) % EXHAUSTIVE_TEST_ORDER]));
   111          }
   112      }
   113  
   114      /* Check doubling */
   115      for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) {
   116          secp256k1_gej tmp;
   117          secp256k1_gej_double(&tmp, &groupj[i]);
   118          CHECK(secp256k1_gej_eq_ge_var(&tmp, &group[(2 * i) % EXHAUSTIVE_TEST_ORDER]));
   119          secp256k1_gej_double_var(&tmp, &groupj[i], NULL);
   120          CHECK(secp256k1_gej_eq_ge_var(&tmp, &group[(2 * i) % EXHAUSTIVE_TEST_ORDER]));
   121      }
   122  
   123      /* Check negation */
   124      for (i = 1; i < EXHAUSTIVE_TEST_ORDER; i++) {
   125          secp256k1_ge tmp;
   126          secp256k1_gej tmpj;
   127          secp256k1_ge_neg(&tmp, &group[i]);
   128          CHECK(secp256k1_ge_eq_var(&tmp, &group[EXHAUSTIVE_TEST_ORDER - i]));
   129          secp256k1_gej_neg(&tmpj, &groupj[i]);
   130          CHECK(secp256k1_gej_eq_ge_var(&tmpj, &group[EXHAUSTIVE_TEST_ORDER - i]));
   131      }
   132  }
   133  
   134  static void test_exhaustive_ecmult(const secp256k1_ge *group, const secp256k1_gej *groupj) {
   135      int i, j, r_log;
   136      uint64_t iter = 0;
   137      for (r_log = 1; r_log < EXHAUSTIVE_TEST_ORDER; r_log++) {
   138          for (j = 0; j < EXHAUSTIVE_TEST_ORDER; j++) {
   139              if (skip_section(&iter)) continue;
   140              for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) {
   141                  secp256k1_gej tmp;
   142                  secp256k1_scalar na, ng;
   143                  secp256k1_scalar_set_int(&na, i);
   144                  secp256k1_scalar_set_int(&ng, j);
   145  
   146                  secp256k1_ecmult(&tmp, &groupj[r_log], &na, &ng);
   147                  CHECK(secp256k1_gej_eq_ge_var(&tmp, &group[(i * r_log + j) % EXHAUSTIVE_TEST_ORDER]));
   148              }
   149          }
   150      }
   151  
   152      for (j = 0; j < EXHAUSTIVE_TEST_ORDER; j++) {
   153          for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) {
   154              int ret;
   155              secp256k1_gej tmp;
   156              secp256k1_fe xn, xd, tmpf;
   157              secp256k1_scalar ng;
   158  
   159              if (skip_section(&iter)) continue;
   160  
   161              secp256k1_scalar_set_int(&ng, j);
   162  
   163              /* Test secp256k1_ecmult_const. */
   164              secp256k1_ecmult_const(&tmp, &group[i], &ng);
   165              CHECK(secp256k1_gej_eq_ge_var(&tmp, &group[(i * j) % EXHAUSTIVE_TEST_ORDER]));
   166  
   167              if (i != 0 && j != 0) {
   168                  /* Test secp256k1_ecmult_const_xonly with all curve X coordinates, and xd=NULL. */
   169                  ret = secp256k1_ecmult_const_xonly(&tmpf, &group[i].x, NULL, &ng, 0);
   170                  CHECK(ret);
   171                  CHECK(secp256k1_fe_equal(&tmpf, &group[(i * j) % EXHAUSTIVE_TEST_ORDER].x));
   172  
   173                  /* Test secp256k1_ecmult_const_xonly with all curve X coordinates, with random xd. */
   174                  testutil_random_fe_non_zero(&xd);
   175                  secp256k1_fe_mul(&xn, &xd, &group[i].x);
   176                  ret = secp256k1_ecmult_const_xonly(&tmpf, &xn, &xd, &ng, 0);
   177                  CHECK(ret);
   178                  CHECK(secp256k1_fe_equal(&tmpf, &group[(i * j) % EXHAUSTIVE_TEST_ORDER].x));
   179              }
   180          }
   181      }
   182  }
   183  
   184  typedef struct {
   185      secp256k1_scalar sc[2];
   186      secp256k1_ge pt[2];
   187  } ecmult_multi_data;
   188  
   189  static int ecmult_multi_callback(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *cbdata) {
   190      ecmult_multi_data *data = (ecmult_multi_data*) cbdata;
   191      *sc = data->sc[idx];
   192      *pt = data->pt[idx];
   193      return 1;
   194  }
   195  
   196  static void test_exhaustive_ecmult_multi(const secp256k1_context *ctx, const secp256k1_ge *group) {
   197      int i, j, k, x, y;
   198      uint64_t iter = 0;
   199      secp256k1_scratch *scratch = secp256k1_scratch_create(&ctx->error_callback, 4096);
   200      for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) {
   201          for (j = 0; j < EXHAUSTIVE_TEST_ORDER; j++) {
   202              for (k = 0; k < EXHAUSTIVE_TEST_ORDER; k++) {
   203                  for (x = 0; x < EXHAUSTIVE_TEST_ORDER; x++) {
   204                      if (skip_section(&iter)) continue;
   205                      for (y = 0; y < EXHAUSTIVE_TEST_ORDER; y++) {
   206                          secp256k1_gej tmp;
   207                          secp256k1_scalar g_sc;
   208                          ecmult_multi_data data;
   209  
   210                          secp256k1_scalar_set_int(&data.sc[0], i);
   211                          secp256k1_scalar_set_int(&data.sc[1], j);
   212                          secp256k1_scalar_set_int(&g_sc, k);
   213                          data.pt[0] = group[x];
   214                          data.pt[1] = group[y];
   215  
   216                          secp256k1_ecmult_multi_var(&ctx->error_callback, scratch, &tmp, &g_sc, ecmult_multi_callback, &data, 2);
   217                          CHECK(secp256k1_gej_eq_ge_var(&tmp, &group[(i * x + j * y + k) % EXHAUSTIVE_TEST_ORDER]));
   218                      }
   219                  }
   220              }
   221          }
   222      }
   223      secp256k1_scratch_destroy(&ctx->error_callback, scratch);
   224  }
   225  
   226  static void r_from_k(secp256k1_scalar *r, const secp256k1_ge *group, int k, int* overflow) {
   227      secp256k1_fe x;
   228      unsigned char x_bin[32];
   229      k %= EXHAUSTIVE_TEST_ORDER;
   230      x = group[k].x;
   231      secp256k1_fe_normalize(&x);
   232      secp256k1_fe_get_b32(x_bin, &x);
   233      secp256k1_scalar_set_b32(r, x_bin, overflow);
   234  }
   235  
   236  static void test_exhaustive_verify(const secp256k1_context *ctx, const secp256k1_ge *group) {
   237      int s, r, msg, key;
   238      uint64_t iter = 0;
   239      for (s = 1; s < EXHAUSTIVE_TEST_ORDER; s++) {
   240          for (r = 1; r < EXHAUSTIVE_TEST_ORDER; r++) {
   241              for (msg = 1; msg < EXHAUSTIVE_TEST_ORDER; msg++) {
   242                  for (key = 1; key < EXHAUSTIVE_TEST_ORDER; key++) {
   243                      secp256k1_ge nonconst_ge;
   244                      secp256k1_ecdsa_signature sig;
   245                      secp256k1_pubkey pk;
   246                      secp256k1_scalar sk_s, msg_s, r_s, s_s;
   247                      secp256k1_scalar s_times_k_s, msg_plus_r_times_sk_s;
   248                      int k, should_verify;
   249                      unsigned char msg32[32];
   250  
   251                      if (skip_section(&iter)) continue;
   252  
   253                      secp256k1_scalar_set_int(&s_s, s);
   254                      secp256k1_scalar_set_int(&r_s, r);
   255                      secp256k1_scalar_set_int(&msg_s, msg);
   256                      secp256k1_scalar_set_int(&sk_s, key);
   257  
   258                      /* Verify by hand */
   259                      /* Run through every k value that gives us this r and check that *one* works.
   260                       * Note there could be none, there could be multiple, ECDSA is weird. */
   261                      should_verify = 0;
   262                      for (k = 0; k < EXHAUSTIVE_TEST_ORDER; k++) {
   263                          secp256k1_scalar check_x_s;
   264                          r_from_k(&check_x_s, group, k, NULL);
   265                          if (r_s == check_x_s) {
   266                              secp256k1_scalar_set_int(&s_times_k_s, k);
   267                              secp256k1_scalar_mul(&s_times_k_s, &s_times_k_s, &s_s);
   268                              secp256k1_scalar_mul(&msg_plus_r_times_sk_s, &r_s, &sk_s);
   269                              secp256k1_scalar_add(&msg_plus_r_times_sk_s, &msg_plus_r_times_sk_s, &msg_s);
   270                              should_verify |= secp256k1_scalar_eq(&s_times_k_s, &msg_plus_r_times_sk_s);
   271                          }
   272                      }
   273                      /* nb we have a "high s" rule */
   274                      should_verify &= !secp256k1_scalar_is_high(&s_s);
   275  
   276                      /* Verify by calling verify */
   277                      secp256k1_ecdsa_signature_save(&sig, &r_s, &s_s);
   278                      memcpy(&nonconst_ge, &group[sk_s], sizeof(nonconst_ge));
   279                      secp256k1_pubkey_save(&pk, &nonconst_ge);
   280                      secp256k1_scalar_get_b32(msg32, &msg_s);
   281                      CHECK(should_verify ==
   282                            secp256k1_ecdsa_verify(ctx, &sig, msg32, &pk));
   283                  }
   284              }
   285          }
   286      }
   287  }
   288  
   289  static void test_exhaustive_sign(const secp256k1_context *ctx, const secp256k1_ge *group) {
   290      int i, j, k;
   291      uint64_t iter = 0;
   292  
   293      /* Loop */
   294      for (i = 1; i < EXHAUSTIVE_TEST_ORDER; i++) {  /* message */
   295          for (j = 1; j < EXHAUSTIVE_TEST_ORDER; j++) {  /* key */
   296              if (skip_section(&iter)) continue;
   297              for (k = 1; k < EXHAUSTIVE_TEST_ORDER; k++) {  /* nonce */
   298                  const int starting_k = k;
   299                  int ret;
   300                  secp256k1_ecdsa_signature sig;
   301                  secp256k1_scalar sk, msg, r, s, expected_r;
   302                  unsigned char sk32[32], msg32[32];
   303                  secp256k1_scalar_set_int(&msg, i);
   304                  secp256k1_scalar_set_int(&sk, j);
   305                  secp256k1_scalar_get_b32(sk32, &sk);
   306                  secp256k1_scalar_get_b32(msg32, &msg);
   307  
   308                  ret = secp256k1_ecdsa_sign(ctx, &sig, msg32, sk32, secp256k1_nonce_function_smallint, &k);
   309                  CHECK(ret == 1);
   310  
   311                  secp256k1_ecdsa_signature_load(ctx, &r, &s, &sig);
   312                  /* Note that we compute expected_r *after* signing -- this is important
   313                   * because our nonce-computing function function might change k during
   314                   * signing. */
   315                  r_from_k(&expected_r, group, k, NULL);
   316                  CHECK(r == expected_r);
   317                  CHECK((k * s) % EXHAUSTIVE_TEST_ORDER == (i + r * j) % EXHAUSTIVE_TEST_ORDER ||
   318                        (k * (EXHAUSTIVE_TEST_ORDER - s)) % EXHAUSTIVE_TEST_ORDER == (i + r * j) % EXHAUSTIVE_TEST_ORDER);
   319  
   320                  /* Overflow means we've tried every possible nonce */
   321                  if (k < starting_k) {
   322                      break;
   323                  }
   324              }
   325          }
   326      }
   327  
   328      /* We would like to verify zero-knowledge here by counting how often every
   329       * possible (s, r) tuple appears, but because the group order is larger
   330       * than the field order, when coercing the x-values to scalar values, some
   331       * appear more often than others, so we are actually not zero-knowledge.
   332       * (This effect also appears in the real code, but the difference is on the
   333       * order of 1/2^128th the field order, so the deviation is not useful to a
   334       * computationally bounded attacker.)
   335       */
   336  }
   337  
   338  #ifdef ENABLE_MODULE_RECOVERY
   339  #include "modules/recovery/tests_exhaustive_impl.h"
   340  #endif
   341  
   342  #ifdef ENABLE_MODULE_EXTRAKEYS
   343  #include "modules/extrakeys/tests_exhaustive_impl.h"
   344  #endif
   345  
   346  #ifdef ENABLE_MODULE_SCHNORRSIG
   347  #include "modules/schnorrsig/tests_exhaustive_impl.h"
   348  #endif
   349  
   350  #ifdef ENABLE_MODULE_ELLSWIFT
   351  #include "modules/ellswift/tests_exhaustive_impl.h"
   352  #endif
   353  
   354  int main(int argc, char** argv) {
   355      int i;
   356      secp256k1_gej groupj[EXHAUSTIVE_TEST_ORDER];
   357      secp256k1_ge group[EXHAUSTIVE_TEST_ORDER];
   358      unsigned char rand32[32];
   359      secp256k1_context *ctx;
   360  
   361      /* Disable buffering for stdout to improve reliability of getting
   362       * diagnostic information. Happens right at the start of main because
   363       * setbuf must be used before any other operation on the stream. */
   364      setbuf(stdout, NULL);
   365      /* Also disable buffering for stderr because it's not guaranteed that it's
   366       * unbuffered on all systems. */
   367      setbuf(stderr, NULL);
   368  
   369      printf("Exhaustive tests for order %lu\n", (unsigned long)EXHAUSTIVE_TEST_ORDER);
   370  
   371      /* find iteration count */
   372      if (argc > 1) {
   373          count = strtol(argv[1], NULL, 0);
   374      }
   375      printf("test count = %i\n", count);
   376  
   377      /* find random seed */
   378      testrand_init(argc > 2 ? argv[2] : NULL);
   379  
   380      /* set up split processing */
   381      if (argc > 4) {
   382          num_cores = strtol(argv[3], NULL, 0);
   383          this_core = strtol(argv[4], NULL, 0);
   384          if (num_cores < 1 || this_core >= num_cores) {
   385              fprintf(stderr, "Usage: %s [count] [seed] [numcores] [thiscore]\n", argv[0]);
   386              return EXIT_FAILURE;
   387          }
   388          printf("running tests for core %lu (out of [0..%lu])\n", (unsigned long)this_core, (unsigned long)num_cores - 1);
   389      }
   390  
   391      /* Recreate the ecmult{,_gen} tables using the right generator (as selected via EXHAUSTIVE_TEST_ORDER) */
   392      secp256k1_ecmult_gen_compute_table(&secp256k1_ecmult_gen_prec_table[0][0], &secp256k1_ge_const_g, COMB_BLOCKS, COMB_TEETH, COMB_SPACING);
   393      secp256k1_ecmult_compute_two_tables(secp256k1_pre_g, secp256k1_pre_g_128, WINDOW_G, &secp256k1_ge_const_g);
   394  
   395      while (count--) {
   396          /* Build context */
   397          ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
   398          testrand256(rand32);
   399          CHECK(secp256k1_context_randomize(ctx, rand32));
   400  
   401          /* Generate the entire group */
   402          secp256k1_gej_set_infinity(&groupj[0]);
   403          secp256k1_ge_set_gej(&group[0], &groupj[0]);
   404          for (i = 1; i < EXHAUSTIVE_TEST_ORDER; i++) {
   405              secp256k1_gej_add_ge(&groupj[i], &groupj[i - 1], &secp256k1_ge_const_g);
   406              secp256k1_ge_set_gej(&group[i], &groupj[i]);
   407              if (count != 0) {
   408                  /* Set a different random z-value for each Jacobian point, except z=1
   409                     is used in the last iteration. */
   410                  secp256k1_fe z;
   411                  testutil_random_fe(&z);
   412                  secp256k1_gej_rescale(&groupj[i], &z);
   413              }
   414  
   415              /* Verify against ecmult_gen */
   416              {
   417                  secp256k1_scalar scalar_i;
   418                  secp256k1_gej generatedj;
   419                  secp256k1_ge generated;
   420  
   421                  secp256k1_scalar_set_int(&scalar_i, i);
   422                  secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &generatedj, &scalar_i);
   423                  secp256k1_ge_set_gej(&generated, &generatedj);
   424  
   425                  CHECK(group[i].infinity == 0);
   426                  CHECK(generated.infinity == 0);
   427                  CHECK(secp256k1_fe_equal(&generated.x, &group[i].x));
   428                  CHECK(secp256k1_fe_equal(&generated.y, &group[i].y));
   429              }
   430          }
   431  
   432          /* Run the tests */
   433          test_exhaustive_endomorphism(group);
   434          test_exhaustive_addition(group, groupj);
   435          test_exhaustive_ecmult(group, groupj);
   436          test_exhaustive_ecmult_multi(ctx, group);
   437          test_exhaustive_sign(ctx, group);
   438          test_exhaustive_verify(ctx, group);
   439  
   440  #ifdef ENABLE_MODULE_RECOVERY
   441          test_exhaustive_recovery(ctx, group);
   442  #endif
   443  #ifdef ENABLE_MODULE_EXTRAKEYS
   444          test_exhaustive_extrakeys(ctx, group);
   445  #endif
   446  #ifdef ENABLE_MODULE_SCHNORRSIG
   447          test_exhaustive_schnorrsig(ctx);
   448  #endif
   449  #ifdef ENABLE_MODULE_ELLSWIFT
   450      /* The ellswift algorithm does have additional edge cases when operating on
   451       * curves of even order, which are not included in the code as secp256k1 is
   452       * of odd order. Skip the ellswift tests if the used exhaustive tests curve
   453       * is even-ordered accordingly. */
   454      #if !EXHAUSTIVE_TEST_CURVE_HAS_EVEN_ORDER
   455          test_exhaustive_ellswift(ctx, group);
   456      #endif
   457  #endif
   458  
   459          secp256k1_context_destroy(ctx);
   460      }
   461  
   462      testrand_finish();
   463  
   464      printf("no problems found\n");
   465      return EXIT_SUCCESS;
   466  }