Skip to content

Commit

Permalink
Add scalar_set_b32_seckey which does the same as scalar_set_b32 and a…
Browse files Browse the repository at this point in the history
…lso returns whether it's a valid secret key
  • Loading branch information
jonasnick committed Mar 30, 2020
1 parent 4f27e34 commit 9ab2cbe
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/scalar.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, uns
*/
static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *bin, int *overflow);

/** Set a scalar from a big endian byte array and returns 1 if it is a valid
* seckey and 0 otherwise. */
static int secp256k1_scalar_set_b32_seckey(secp256k1_scalar *r, const unsigned char *bin);

/** Set a scalar to an unsigned integer. */
static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v);

Expand Down
6 changes: 6 additions & 0 deletions src/scalar_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ static void secp256k1_scalar_order_get_num(secp256k1_num *r) {
}
#endif

static int secp256k1_scalar_set_b32_seckey(secp256k1_scalar *r, const unsigned char *bin) {
int overflow;
secp256k1_scalar_set_b32(r, bin, &overflow);
return (!overflow) & (!secp256k1_scalar_is_zero(r));
}

static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *x) {
#if defined(EXHAUSTIVE_TEST_ORDER)
int i;
Expand Down
26 changes: 26 additions & 0 deletions src/tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ void random_scalar_order(secp256k1_scalar *num) {
} while(1);
}

void random_scalar_order_b32(unsigned char *b32) {
secp256k1_scalar num;
random_scalar_order(&num);
secp256k1_scalar_get_b32(b32, &num);
}

void run_context_tests(int use_prealloc) {
secp256k1_pubkey pubkey;
secp256k1_pubkey zero_pubkey;
Expand Down Expand Up @@ -1077,11 +1083,31 @@ void scalar_test(void) {

}

void run_scalar_set_b32_seckey_tests(void) {
unsigned char b32[32];
secp256k1_scalar s1;
secp256k1_scalar s2;

/* Usually set_b32 and set_b32_seckey give the same result */
random_scalar_order_b32(b32);
secp256k1_scalar_set_b32(&s1, b32, NULL);
CHECK(secp256k1_scalar_set_b32_seckey(&s2, b32) == 1);
CHECK(secp256k1_scalar_eq(&s1, &s2) == 1);

memset(b32, 0, sizeof(b32));
CHECK(secp256k1_scalar_set_b32_seckey(&s2, b32) == 0);
memset(b32, 0xFF, sizeof(b32));
CHECK(secp256k1_scalar_set_b32_seckey(&s2, b32) == 0);
}

void run_scalar_tests(void) {
int i;
for (i = 0; i < 128 * count; i++) {
scalar_test();
}
for (i = 0; i < count; i++) {
run_scalar_set_b32_seckey_tests();
}

{
/* (-1)+1 should be zero. */
Expand Down

0 comments on commit 9ab2cbe

Please sign in to comment.