secp256k1: Add test gen for random mod n scalars.

This adds a new test helper for generating random mod n scalars without
also generating a companion big integer and updates the tests to make
use of it.  It also marks the combined version as a test helper while
here.

The new helper will be useful for future tests.
This commit is contained in:
Dave Collins 2022-02-27 02:41:43 -06:00
parent b2f6fd7bc8
commit 53a9ec0897
No known key found for this signature in database
GPG Key ID: B8904D9D9C93D1F2
2 changed files with 23 additions and 5 deletions

View File

@ -1,6 +1,6 @@
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2015-2020 The Decred developers
// Copyright (c) 2013-2020 Dave Collins
// Copyright (c) 2015-2022 The Decred developers
// Copyright (c) 2013-2022 Dave Collins
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
@ -43,7 +43,7 @@ func randFieldVal(t *testing.T, rng *rand.Rand) *FieldVal {
t.Fatalf("failed to read random: %v", err)
}
// Create and return both a big integer and a field value.
// Create and return a field value.
var fv FieldVal
fv.SetBytes(&buf)
return &fv

View File

@ -1,4 +1,4 @@
// Copyright (c) 2020 The Decred developers
// Copyright (c) 2020-2022 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
@ -32,9 +32,27 @@ func (s *ModNScalar) SetHex(hexString string) *ModNScalar {
return s
}
// randModNScalar returns a mod N scalar created from a random value generated
// by the passed rng.
func randModNScalar(t *testing.T, rng *rand.Rand) *ModNScalar {
t.Helper()
var buf [32]byte
if _, err := rng.Read(buf[:]); err != nil {
t.Fatalf("failed to read random: %v", err)
}
// Create and return a mod N scalar.
var modNVal ModNScalar
modNVal.SetBytes(&buf)
return &modNVal
}
// randIntAndModNScalar returns a big integer and mod N scalar both created from
// the same random value generated by the passed rng.
func randIntAndModNScalar(t *testing.T, rng *rand.Rand) (*big.Int, *ModNScalar) {
t.Helper()
var buf [32]byte
if _, err := rng.Read(buf[:]); err != nil {
t.Fatalf("failed to read random: %v", err)
@ -473,7 +491,7 @@ func TestModNScalarEqualsRandom(t *testing.T) {
for i := 0; i < 100; i++ {
// Ensure a randomly-generated scalar equals itself.
_, s := randIntAndModNScalar(t, rng)
s := randModNScalar(t, rng)
if !s.Equals(s) {
t.Fatalf("failed equality check\nscalar in: %v", s)
}