Skip to content

Commit 8f814cd

Browse files
committed
Add test for boundary conditions of scalar_set_b32 with respect to overflows
1 parent 3fec982 commit 8f814cd

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

src/tests.c

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1123,16 +1123,43 @@ void run_scalar_tests(void) {
11231123

11241124
#ifndef USE_NUM_NONE
11251125
{
1126-
/* A scalar with value of the curve order should be 0. */
1126+
/* Test secp256k1_scalar_set_b32 boundary conditions */
11271127
secp256k1_num order;
1128-
secp256k1_scalar zero;
1128+
secp256k1_scalar scalar;
11291129
unsigned char bin[32];
1130+
unsigned char bin_tmp[32];
11301131
int overflow = 0;
1132+
/* 2^256-1 - order */
1133+
static const secp256k1_scalar all_ones_minus_order = SECP256K1_SCALAR_CONST(
1134+
0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00000001UL,
1135+
0x45512319UL, 0x50B75FC4UL, 0x402DA173UL, 0x2FC9BEBEUL
1136+
);
1137+
1138+
/* A scalar set to 0s should be 0. */
1139+
memset(bin, 0, 32);
1140+
secp256k1_scalar_set_b32(&scalar, bin, &overflow);
1141+
CHECK(overflow == 0);
1142+
CHECK(secp256k1_scalar_is_zero(&scalar));
1143+
1144+
/* A scalar with value of the curve order should be 0. */
11311145
secp256k1_scalar_order_get_num(&order);
11321146
secp256k1_num_get_bin(bin, 32, &order);
1133-
secp256k1_scalar_set_b32(&zero, bin, &overflow);
1147+
secp256k1_scalar_set_b32(&scalar, bin, &overflow);
1148+
CHECK(overflow == 1);
1149+
CHECK(secp256k1_scalar_is_zero(&scalar));
1150+
1151+
/* A scalar with value of the curve order minus one should not overflow. */
1152+
bin[31] -= 1;
1153+
secp256k1_scalar_set_b32(&scalar, bin, &overflow);
1154+
CHECK(overflow == 0);
1155+
secp256k1_scalar_get_b32(bin_tmp, &scalar);
1156+
CHECK(memcmp(bin, bin_tmp, 32) == 0);
1157+
1158+
/* A scalar set to all 1s should overflow. */
1159+
memset(bin, 0xFF, 32);
1160+
secp256k1_scalar_set_b32(&scalar, bin, &overflow);
11341161
CHECK(overflow == 1);
1135-
CHECK(secp256k1_scalar_is_zero(&zero));
1162+
CHECK(secp256k1_scalar_eq(&scalar, &all_ones_minus_order));
11361163
}
11371164
#endif
11381165

0 commit comments

Comments
 (0)