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.

74 lines
1.9 KiB

  1. package secp256k1
  2. import (
  3. "bytes"
  4. "math/big"
  5. "testing"
  6. "github.com/stretchr/testify/require"
  7. secp256k1 "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", secp256k1.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(secp256k1.S256().N) < 0)
  37. require.True(t, fe.Sign() > 0)
  38. })
  39. }
  40. }
  41. // Ensure that signature verification works, and that
  42. // non-canonical signatures fail.
  43. // Note: run with CGO_ENABLED=0 or go test -tags !cgo.
  44. func TestSignatureVerificationAndRejectUpperS(t *testing.T) {
  45. msg := []byte("We have lingered long enough on the shores of the cosmic ocean.")
  46. for i := 0; i < 500; i++ {
  47. priv := GenPrivKey()
  48. sigStr, err := priv.Sign(msg)
  49. require.NoError(t, err)
  50. sig := signatureFromBytes(sigStr)
  51. require.False(t, sig.S.Cmp(secp256k1halfN) > 0)
  52. pub := priv.PubKey()
  53. require.True(t, pub.VerifySignature(msg, sigStr))
  54. // malleate:
  55. sig.S.Sub(secp256k1.S256().CurveParams.N, sig.S)
  56. require.True(t, sig.S.Cmp(secp256k1halfN) > 0)
  57. malSigStr := serializeSig(sig)
  58. require.False(t, pub.VerifySignature(msg, malSigStr),
  59. "VerifyBytes incorrect with malleated & invalid S. sig=%v, key=%v",
  60. sig,
  61. priv,
  62. )
  63. }
  64. }