crypto, crypto/secp256k1: add CompressPubkey (#15626)
This adds the inverse to DecompressPubkey and improves a few minor details in crypto/secp256k1.
This commit is contained in:
@ -18,10 +18,13 @@ package crypto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdsa"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/ethereum/go-ethereum/common/math"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -65,6 +68,11 @@ func TestVerifySignature(t *testing.T) {
|
||||
if VerifySignature(testpubkey, testmsg, sig[:len(sig)-2]) {
|
||||
t.Errorf("signature valid even though it's incomplete")
|
||||
}
|
||||
wrongkey := common.CopyBytes(testpubkey)
|
||||
wrongkey[10]++
|
||||
if VerifySignature(wrongkey, testmsg, sig) {
|
||||
t.Errorf("signature valid with with wrong public key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecompressPubkey(t *testing.T) {
|
||||
@ -86,6 +94,36 @@ func TestDecompressPubkey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompressPubkey(t *testing.T) {
|
||||
key := &ecdsa.PublicKey{
|
||||
Curve: S256(),
|
||||
X: math.MustParseBig256("0xe32df42865e97135acfb65f3bae71bdc86f4d49150ad6a440b6f15878109880a"),
|
||||
Y: math.MustParseBig256("0x0a2b2667f7e725ceea70c673093bf67663e0312623c8e091b13cf2c0f11ef652"),
|
||||
}
|
||||
compressed := CompressPubkey(key)
|
||||
if !bytes.Equal(compressed, testpubkeyc) {
|
||||
t.Errorf("wrong public key result: got %x, want %x", compressed, testpubkeyc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPubkeyRandom(t *testing.T) {
|
||||
const runs = 200
|
||||
|
||||
for i := 0; i < runs; i++ {
|
||||
key, err := GenerateKey()
|
||||
if err != nil {
|
||||
t.Fatalf("iteration %d: %v", i, err)
|
||||
}
|
||||
pubkey2, err := DecompressPubkey(CompressPubkey(&key.PublicKey))
|
||||
if err != nil {
|
||||
t.Fatalf("iteration %d: %v", i, err)
|
||||
}
|
||||
if !reflect.DeepEqual(key.PublicKey, *pubkey2) {
|
||||
t.Fatalf("iteration %d: keys not equal", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkEcrecoverSignature(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
if _, err := Ecrecover(testmsg, testsig); err != nil {
|
||||
|
Reference in New Issue
Block a user