github.com/Finschia/finschia-sdk@v0.48.1/crypto/keys/secp256k1/secp256k1_internal_test.go (about)

     1  package secp256k1
     2  
     3  import (
     4  	"bytes"
     5  	"math/big"
     6  	"testing"
     7  
     8  	btcSecp256k1 "github.com/btcsuite/btcd/btcec"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func Test_genPrivKey(t *testing.T) {
    13  	empty := make([]byte, 32)
    14  	oneB := big.NewInt(1).Bytes()
    15  	onePadded := make([]byte, 32)
    16  	copy(onePadded[32-len(oneB):32], oneB)
    17  	t.Logf("one padded: %v, len=%v", onePadded, len(onePadded))
    18  
    19  	validOne := append(empty, onePadded...)
    20  	tests := []struct {
    21  		name        string
    22  		notSoRand   []byte
    23  		shouldPanic bool
    24  	}{
    25  		{"empty bytes (panics because 1st 32 bytes are zero and 0 is not a valid field element)", empty, true},
    26  		{"curve order: N", btcSecp256k1.S256().N.Bytes(), true},
    27  		{"valid because 0 < 1 < N", validOne, false},
    28  	}
    29  	for _, tt := range tests {
    30  		tt := tt
    31  		t.Run(tt.name, func(t *testing.T) {
    32  			if tt.shouldPanic {
    33  				require.Panics(t, func() {
    34  					genPrivKey(bytes.NewReader(tt.notSoRand))
    35  				})
    36  				return
    37  			}
    38  			got := genPrivKey(bytes.NewReader(tt.notSoRand))
    39  			fe := new(big.Int).SetBytes(got[:])
    40  			require.True(t, fe.Cmp(btcSecp256k1.S256().N) < 0)
    41  			require.True(t, fe.Sign() > 0)
    42  		})
    43  	}
    44  }