Skip to content

Commit e85b68e

Browse files
authored
crypto: add DecompressPubkey, VerifySignature (#15615)
We need those operations for p2p/enr. Also upgrade github.com/btcsuite/btcd/btcec to the latest version and improve BenchmarkSha3. The benchmark printed extra output that confused tools like benchstat and ignored N.
1 parent 6e613cf commit e85b68e

14 files changed

Lines changed: 327 additions & 230 deletions

File tree

‎crypto/crypto_test.go‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,10 @@ import (
2020
"bytes"
2121
"crypto/ecdsa"
2222
"encoding/hex"
23-
"fmt"
2423
"io/ioutil"
2524
"math/big"
2625
"os"
2726
"testing"
28-
"time"
2927

3028
"github.com/ethereum/go-ethereum/common"
3129
)
@@ -44,13 +42,9 @@ func TestKeccak256Hash(t *testing.T) {
4442

4543
func BenchmarkSha3(b *testing.B) {
4644
a := []byte("hello world")
47-
amount := 1000000
48-
start := time.Now()
49-
for i := 0; i < amount; i++ {
45+
for i := 0; i < b.N; i++ {
5046
Keccak256(a)
5147
}
52-
53-
fmt.Println(amount, ":", time.Since(start))
5448
}
5549

5650
func TestSign(t *testing.T) {

‎crypto/secp256k1/ext.h‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,55 @@ static int secp256k1_ecdsa_recover_pubkey(
4646
return secp256k1_ec_pubkey_serialize(ctx, pubkey_out, &outputlen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
4747
}
4848

49+
// secp256k1_ecdsa_verify_enc verifies an encoded compact signature.
50+
//
51+
// Returns: 1: signature is valid
52+
// 0: signature is invalid
53+
// Args: ctx: pointer to a context object (cannot be NULL)
54+
// In: sigdata: pointer to a 64-byte signature (cannot be NULL)
55+
// msgdata: pointer to a 32-byte message (cannot be NULL)
56+
// pubkeydata: pointer to public key data (cannot be NULL)
57+
// pubkeylen: length of pubkeydata
58+
static int secp256k1_ecdsa_verify_enc(
59+
const secp256k1_context* ctx,
60+
const unsigned char *sigdata,
61+
const unsigned char *msgdata,
62+
const unsigned char *pubkeydata,
63+
size_t pubkeylen
64+
) {
65+
secp256k1_ecdsa_signature sig;
66+
secp256k1_pubkey pubkey;
67+
68+
if (!secp256k1_ecdsa_signature_parse_compact(ctx, &sig, sigdata)) {
69+
return 0;
70+
}
71+
if (!secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeydata, pubkeylen)) {
72+
return 0;
73+
}
74+
return secp256k1_ecdsa_verify(ctx, &sig, msgdata, &pubkey);
75+
}
76+
77+
// secp256k1_decompress_pubkey decompresses a public key.
78+
//
79+
// Returns: 1: public key is valid
80+
// 0: public key is invalid
81+
// Args: ctx: pointer to a context object (cannot be NULL)
82+
// Out: pubkey_out: the serialized 65-byte public key (cannot be NULL)
83+
// In: pubkeydata: pointer to 33 bytes of compressed public key data (cannot be NULL)
84+
static int secp256k1_decompress_pubkey(
85+
const secp256k1_context* ctx,
86+
unsigned char *pubkey_out,
87+
const unsigned char *pubkeydata
88+
) {
89+
secp256k1_pubkey pubkey;
90+
91+
if (!secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeydata, 33)) {
92+
return 0;
93+
}
94+
size_t outputlen = 65;
95+
return secp256k1_ec_pubkey_serialize(ctx, pubkey_out, &outputlen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
96+
}
97+
4998
// secp256k1_pubkey_scalar_mul multiplies a point by a scalar in constant time.
5099
//
51100
// Returns: 1: multiplication was successful

‎crypto/secp256k1/secp256.go‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import "C"
3838

3939
import (
4040
"errors"
41+
"math/big"
4142
"unsafe"
4243
)
4344

@@ -55,6 +56,7 @@ var (
5556
ErrInvalidSignatureLen = errors.New("invalid signature length")
5657
ErrInvalidRecoveryID = errors.New("invalid signature recovery id")
5758
ErrInvalidKey = errors.New("invalid private key")
59+
ErrInvalidPubkey = errors.New("invalid public key")
5860
ErrSignFailed = errors.New("signing failed")
5961
ErrRecoverFailed = errors.New("recovery failed")
6062
)
@@ -119,6 +121,33 @@ func RecoverPubkey(msg []byte, sig []byte) ([]byte, error) {
119121
return pubkey, nil
120122
}
121123

124+
// VerifySignature checks that the given pubkey created signature over message.
125+
// The signature should be in [R || S] format.
126+
func VerifySignature(pubkey, msg, signature []byte) bool {
127+
if len(msg) != 32 || len(signature) != 64 || len(pubkey) == 0 {
128+
return false
129+
}
130+
sigdata := (*C.uchar)(unsafe.Pointer(&signature[0]))
131+
msgdata := (*C.uchar)(unsafe.Pointer(&msg[0]))
132+
keydata := (*C.uchar)(unsafe.Pointer(&pubkey[0]))
133+
return C.secp256k1_ecdsa_verify_enc(context, sigdata, msgdata, keydata, C.size_t(len(pubkey))) != 0
134+
}
135+
136+
// DecompressPubkey parses a public key in the 33-byte compressed format.
137+
// It returns non-nil coordinates if the public key is valid.
138+
func DecompressPubkey(pubkey []byte) (X, Y *big.Int) {
139+
if len(pubkey) != 33 {
140+
return nil, nil
141+
}
142+
buf := make([]byte, 65)
143+
bufdata := (*C.uchar)(unsafe.Pointer(&buf[0]))
144+
pubkeydata := (*C.uchar)(unsafe.Pointer(&pubkey[0]))
145+
if C.secp256k1_decompress_pubkey(context, bufdata, pubkeydata) == 0 {
146+
return nil, nil
147+
}
148+
return new(big.Int).SetBytes(buf[1:33]), new(big.Int).SetBytes(buf[33:])
149+
}
150+
122151
func checkSignature(sig []byte) error {
123152
if len(sig) != 65 {
124153
return ErrInvalidSignatureLen

‎crypto/signature_cgo.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,12 @@ import (
2727
"github.com/ethereum/go-ethereum/crypto/secp256k1"
2828
)
2929

30+
// Ecrecover returns the uncompressed public key that created the given signature.
3031
func Ecrecover(hash, sig []byte) ([]byte, error) {
3132
return secp256k1.RecoverPubkey(hash, sig)
3233
}
3334

35+
// SigToPub returns the public key that created the given signature.
3436
func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
3537
s, err := Ecrecover(hash, sig)
3638
if err != nil {
@@ -58,6 +60,22 @@ func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
5860
return secp256k1.Sign(hash, seckey)
5961
}
6062

63+
// VerifySignature checks that the given public key created signature over hash.
64+
// The public key should be in compressed (33 bytes) or uncompressed (65 bytes) format.
65+
// The signature should have the 64 byte [R || S] format.
66+
func VerifySignature(pubkey, hash, signature []byte) bool {
67+
return secp256k1.VerifySignature(pubkey, hash, signature)
68+
}
69+
70+
// DecompressPubkey parses a public key in the 33-byte compressed format.
71+
func DecompressPubkey(pubkey []byte) (*ecdsa.PublicKey, error) {
72+
x, y := secp256k1.DecompressPubkey(pubkey)
73+
if x == nil {
74+
return nil, fmt.Errorf("invalid public key")
75+
}
76+
return &ecdsa.PublicKey{X: x, Y: y, Curve: S256()}, nil
77+
}
78+
6179
// S256 returns an instance of the secp256k1 curve.
6280
func S256() elliptic.Curve {
6381
return secp256k1.S256()

‎crypto/signature_nocgo.go‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,14 @@ package crypto
2121
import (
2222
"crypto/ecdsa"
2323
"crypto/elliptic"
24+
"errors"
2425
"fmt"
26+
"math/big"
2527

2628
"github.com/btcsuite/btcd/btcec"
2729
)
2830

31+
// Ecrecover returns the uncompressed public key that created the given signature.
2932
func Ecrecover(hash, sig []byte) ([]byte, error) {
3033
pub, err := SigToPub(hash, sig)
3134
if err != nil {
@@ -35,6 +38,7 @@ func Ecrecover(hash, sig []byte) ([]byte, error) {
3538
return bytes, err
3639
}
3740

41+
// SigToPub returns the public key that created the given signature.
3842
func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
3943
// Convert to btcec input format with 'recovery id' v at the beginning.
4044
btcsig := make([]byte, 65)
@@ -71,6 +75,33 @@ func Sign(hash []byte, prv *ecdsa.PrivateKey) ([]byte, error) {
7175
return sig, nil
7276
}
7377

78+
// VerifySignature checks that the given public key created signature over hash.
79+
// The public key should be in compressed (33 bytes) or uncompressed (65 bytes) format.
80+
// The signature should have the 64 byte [R || S] format.
81+
func VerifySignature(pubkey, hash, signature []byte) bool {
82+
if len(signature) != 64 {
83+
return false
84+
}
85+
sig := &btcec.Signature{R: new(big.Int).SetBytes(signature[:32]), S: new(big.Int).SetBytes(signature[32:])}
86+
key, err := btcec.ParsePubKey(pubkey, btcec.S256())
87+
if err != nil {
88+
return false
89+
}
90+
return sig.Verify(hash, key)
91+
}
92+
93+
// DecompressPubkey parses a public key in the 33-byte compressed format.
94+
func DecompressPubkey(pubkey []byte) (*ecdsa.PublicKey, error) {
95+
if len(pubkey) != 33 {
96+
return nil, errors.New("invalid compressed public key length")
97+
}
98+
key, err := btcec.ParsePubKey(pubkey, btcec.S256())
99+
if err != nil {
100+
return nil, err
101+
}
102+
return key.ToECDSA(), nil
103+
}
104+
74105
// S256 returns an instance of the secp256k1 curve.
75106
func S256() elliptic.Curve {
76107
return btcec.S256()

‎crypto/signature_test.go‎

Lines changed: 84 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,95 @@ package crypto
1818

1919
import (
2020
"bytes"
21-
"encoding/hex"
2221
"testing"
22+
23+
"github.com/ethereum/go-ethereum/common"
24+
"github.com/ethereum/go-ethereum/common/hexutil"
25+
)
26+
27+
var (
28+
testmsg = hexutil.MustDecode("0xce0677bb30baa8cf067c88db9811f4333d131bf8bcf12fe7065d211dce971008")
29+
testsig = hexutil.MustDecode("0x90f27b8b488db00b00606796d2987f6a5f59ae62ea05effe84fef5b8b0e549984a691139ad57a3f0b906637673aa2f63d1f55cb1a69199d4009eea23ceaddc9301")
30+
testpubkey = hexutil.MustDecode("0x04e32df42865e97135acfb65f3bae71bdc86f4d49150ad6a440b6f15878109880a0a2b2667f7e725ceea70c673093bf67663e0312623c8e091b13cf2c0f11ef652")
31+
testpubkeyc = hexutil.MustDecode("0x02e32df42865e97135acfb65f3bae71bdc86f4d49150ad6a440b6f15878109880a")
2332
)
2433

25-
func TestRecoverSanity(t *testing.T) {
26-
msg, _ := hex.DecodeString("ce0677bb30baa8cf067c88db9811f4333d131bf8bcf12fe7065d211dce971008")
27-
sig, _ := hex.DecodeString("90f27b8b488db00b00606796d2987f6a5f59ae62ea05effe84fef5b8b0e549984a691139ad57a3f0b906637673aa2f63d1f55cb1a69199d4009eea23ceaddc9301")
28-
pubkey1, _ := hex.DecodeString("04e32df42865e97135acfb65f3bae71bdc86f4d49150ad6a440b6f15878109880a0a2b2667f7e725ceea70c673093bf67663e0312623c8e091b13cf2c0f11ef652")
29-
pubkey2, err := Ecrecover(msg, sig)
34+
func TestEcrecover(t *testing.T) {
35+
pubkey, err := Ecrecover(testmsg, testsig)
3036
if err != nil {
3137
t.Fatalf("recover error: %s", err)
3238
}
33-
if !bytes.Equal(pubkey1, pubkey2) {
34-
t.Errorf("pubkey mismatch: want: %x have: %x", pubkey1, pubkey2)
39+
if !bytes.Equal(pubkey, testpubkey) {
40+
t.Errorf("pubkey mismatch: want: %x have: %x", testpubkey, pubkey)
41+
}
42+
}
43+
44+
func TestVerifySignature(t *testing.T) {
45+
sig := testsig[:len(testsig)-1] // remove recovery id
46+
if !VerifySignature(testpubkey, testmsg, sig) {
47+
t.Errorf("can't verify signature with uncompressed key")
48+
}
49+
if !VerifySignature(testpubkeyc, testmsg, sig) {
50+
t.Errorf("can't verify signature with compressed key")
51+
}
52+
53+
if VerifySignature(nil, testmsg, sig) {
54+
t.Errorf("signature valid with no key")
55+
}
56+
if VerifySignature(testpubkey, nil, sig) {
57+
t.Errorf("signature valid with no message")
58+
}
59+
if VerifySignature(testpubkey, testmsg, nil) {
60+
t.Errorf("nil signature valid")
61+
}
62+
if VerifySignature(testpubkey, testmsg, append(common.CopyBytes(sig), 1, 2, 3)) {
63+
t.Errorf("signature valid with extra bytes at the end")
64+
}
65+
if VerifySignature(testpubkey, testmsg, sig[:len(sig)-2]) {
66+
t.Errorf("signature valid even though it's incomplete")
67+
}
68+
}
69+
70+
func TestDecompressPubkey(t *testing.T) {
71+
key, err := DecompressPubkey(testpubkeyc)
72+
if err != nil {
73+
t.Fatal(err)
74+
}
75+
if uncompressed := FromECDSAPub(key); !bytes.Equal(uncompressed, testpubkey) {
76+
t.Errorf("wrong public key result: got %x, want %x", uncompressed, testpubkey)
77+
}
78+
if _, err := DecompressPubkey(nil); err == nil {
79+
t.Errorf("no error for nil pubkey")
80+
}
81+
if _, err := DecompressPubkey(testpubkeyc[:5]); err == nil {
82+
t.Errorf("no error for incomplete pubkey")
83+
}
84+
if _, err := DecompressPubkey(append(common.CopyBytes(testpubkeyc), 1, 2, 3)); err == nil {
85+
t.Errorf("no error for pubkey with extra bytes at the end")
86+
}
87+
}
88+
89+
func BenchmarkEcrecoverSignature(b *testing.B) {
90+
for i := 0; i < b.N; i++ {
91+
if _, err := Ecrecover(testmsg, testsig); err != nil {
92+
b.Fatal("ecrecover error", err)
93+
}
94+
}
95+
}
96+
97+
func BenchmarkVerifySignature(b *testing.B) {
98+
sig := testsig[:len(testsig)-1] // remove recovery id
99+
for i := 0; i < b.N; i++ {
100+
if !VerifySignature(testpubkey, testmsg, sig) {
101+
b.Fatal("verify error")
102+
}
103+
}
104+
}
105+
106+
func BenchmarkDecompressPubkey(b *testing.B) {
107+
for i := 0; i < b.N; i++ {
108+
if _, err := DecompressPubkey(testpubkeyc); err != nil {
109+
b.Fatal(err)
110+
}
35111
}
36112
}

‎vendor/github.com/btcsuite/btcd/btcec/README.md‎

Lines changed: 7 additions & 13 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)