github.com/Team-Kujira/tendermint@v0.34.24-indexer/crypto/secp256k1/secp256k1_internal_test.go (about) 1 package secp256k1 2 3 import ( 4 "bytes" 5 "math/big" 6 "testing" 7 8 "github.com/stretchr/testify/require" 9 10 secp256k1 "github.com/btcsuite/btcd/btcec" 11 ) 12 13 func Test_genPrivKey(t *testing.T) { 14 15 empty := make([]byte, 32) 16 oneB := big.NewInt(1).Bytes() 17 onePadded := make([]byte, 32) 18 copy(onePadded[32-len(oneB):32], oneB) 19 t.Logf("one padded: %v, len=%v", onePadded, len(onePadded)) 20 21 validOne := append(empty, onePadded...) 22 tests := []struct { 23 name string 24 notSoRand []byte 25 shouldPanic bool 26 }{ 27 {"empty bytes (panics because 1st 32 bytes are zero and 0 is not a valid field element)", empty, true}, 28 {"curve order: N", secp256k1.S256().N.Bytes(), true}, 29 {"valid because 0 < 1 < N", validOne, false}, 30 } 31 for _, tt := range tests { 32 tt := tt 33 t.Run(tt.name, func(t *testing.T) { 34 if tt.shouldPanic { 35 require.Panics(t, func() { 36 genPrivKey(bytes.NewReader(tt.notSoRand)) 37 }) 38 return 39 } 40 got := genPrivKey(bytes.NewReader(tt.notSoRand)) 41 fe := new(big.Int).SetBytes(got[:]) 42 require.True(t, fe.Cmp(secp256k1.S256().N) < 0) 43 require.True(t, fe.Sign() > 0) 44 }) 45 } 46 } 47 48 // Ensure that signature verification works, and that 49 // non-canonical signatures fail. 50 // Note: run with CGO_ENABLED=0 or go test -tags !cgo. 51 func TestSignatureVerificationAndRejectUpperS(t *testing.T) { 52 msg := []byte("We have lingered long enough on the shores of the cosmic ocean.") 53 for i := 0; i < 500; i++ { 54 priv := GenPrivKey() 55 sigStr, err := priv.Sign(msg) 56 require.NoError(t, err) 57 sig := signatureFromBytes(sigStr) 58 require.False(t, sig.S.Cmp(secp256k1halfN) > 0) 59 60 pub := priv.PubKey() 61 require.True(t, pub.VerifySignature(msg, sigStr)) 62 63 // malleate: 64 sig.S.Sub(secp256k1.S256().CurveParams.N, sig.S) 65 require.True(t, sig.S.Cmp(secp256k1halfN) > 0) 66 malSigStr := serializeSig(sig) 67 68 require.False(t, pub.VerifySignature(msg, malSigStr), 69 "VerifyBytes incorrect with malleated & invalid S. sig=%v, key=%v", 70 sig, 71 priv, 72 ) 73 } 74 }