You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.1 KiB

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