Skip to content

Commit 9b0af51

Browse files
fjlobscuren
authored andcommitted
crypto: add btcec fallback for sign/recover without cgo (bnb-chain#3680)
* vendor: add github.com/btcsuite/btcd/btcec * crypto: add btcec fallback for sign/recover without cgo This commit adds a non-cgo fallback implementation of secp256k1 operations. * crypto, core/vm: remove wrappers for sha256, ripemd160
1 parent bf21549 commit 9b0af51

32 files changed

Lines changed: 3929 additions & 224 deletions

‎accounts/keystore/key.go‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ import (
3232
"github.com/ethereum/go-ethereum/accounts"
3333
"github.com/ethereum/go-ethereum/common"
3434
"github.com/ethereum/go-ethereum/crypto"
35-
"github.com/ethereum/go-ethereum/crypto/secp256k1"
3635
"github.com/pborman/uuid"
3736
)
3837

@@ -157,7 +156,7 @@ func NewKeyForDirectICAP(rand io.Reader) *Key {
157156
panic("key generation: could not read from random source: " + err.Error())
158157
}
159158
reader := bytes.NewReader(randBytes)
160-
privateKeyECDSA, err := ecdsa.GenerateKey(secp256k1.S256(), reader)
159+
privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), reader)
161160
if err != nil {
162161
panic("key generation: ecdsa.GenerateKey failed: " + err.Error())
163162
}
@@ -169,7 +168,7 @@ func NewKeyForDirectICAP(rand io.Reader) *Key {
169168
}
170169

171170
func newKey(rand io.Reader) (*Key, error) {
172-
privateKeyECDSA, err := ecdsa.GenerateKey(secp256k1.S256(), rand)
171+
privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), rand)
173172
if err != nil {
174173
return nil, err
175174
}

‎core/vm/contracts.go‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,14 @@
1717
package vm
1818

1919
import (
20+
"crypto/sha256"
21+
2022
"github.com/ethereum/go-ethereum/common"
2123
"github.com/ethereum/go-ethereum/crypto"
2224
"github.com/ethereum/go-ethereum/logger"
2325
"github.com/ethereum/go-ethereum/logger/glog"
2426
"github.com/ethereum/go-ethereum/params"
27+
"golang.org/x/crypto/ripemd160"
2528
)
2629

2730
// Precompiled contract is the basic interface for native Go contracts. The implementation
@@ -35,8 +38,8 @@ type PrecompiledContract interface {
3538
// Precompiled contains the default set of ethereum contracts
3639
var PrecompiledContracts = map[common.Address]PrecompiledContract{
3740
common.BytesToAddress([]byte{1}): &ecrecover{},
38-
common.BytesToAddress([]byte{2}): &sha256{},
39-
common.BytesToAddress([]byte{3}): &ripemd160{},
41+
common.BytesToAddress([]byte{2}): &sha256hash{},
42+
common.BytesToAddress([]byte{3}): &ripemd160hash{},
4043
common.BytesToAddress([]byte{4}): &dataCopy{},
4144
}
4245

@@ -88,31 +91,34 @@ func (c *ecrecover) Run(in []byte) []byte {
8891
}
8992

9093
// SHA256 implemented as a native contract
91-
type sha256 struct{}
94+
type sha256hash struct{}
9295

9396
// RequiredGas returns the gas required to execute the pre-compiled contract.
9497
//
9598
// This method does not require any overflow checking as the input size gas costs
9699
// required for anything significant is so high it's impossible to pay for.
97-
func (c *sha256) RequiredGas(inputSize int) uint64 {
100+
func (c *sha256hash) RequiredGas(inputSize int) uint64 {
98101
return uint64(inputSize+31)/32*params.Sha256WordGas + params.Sha256Gas
99102
}
100-
func (c *sha256) Run(in []byte) []byte {
101-
return crypto.Sha256(in)
103+
func (c *sha256hash) Run(in []byte) []byte {
104+
h := sha256.Sum256(in)
105+
return h[:]
102106
}
103107

104108
// RIPMED160 implemented as a native contract
105-
type ripemd160 struct{}
109+
type ripemd160hash struct{}
106110

107111
// RequiredGas returns the gas required to execute the pre-compiled contract.
108112
//
109113
// This method does not require any overflow checking as the input size gas costs
110114
// required for anything significant is so high it's impossible to pay for.
111-
func (c *ripemd160) RequiredGas(inputSize int) uint64 {
115+
func (c *ripemd160hash) RequiredGas(inputSize int) uint64 {
112116
return uint64(inputSize+31)/32*params.Ripemd160WordGas + params.Ripemd160Gas
113117
}
114-
func (c *ripemd160) Run(in []byte) []byte {
115-
return common.LeftPadBytes(crypto.Ripemd160(in), 32)
118+
func (c *ripemd160hash) Run(in []byte) []byte {
119+
ripemd := ripemd160.New()
120+
ripemd.Write(in)
121+
return common.LeftPadBytes(ripemd.Sum(nil), 32)
116122
}
117123

118124
// data copy implemented as a native contract

‎crypto/crypto.go‎

Lines changed: 16 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -20,22 +20,21 @@ import (
2020
"crypto/ecdsa"
2121
"crypto/elliptic"
2222
"crypto/rand"
23-
"crypto/sha256"
24-
"fmt"
23+
"encoding/hex"
24+
"errors"
2525
"io"
2626
"io/ioutil"
2727
"math/big"
2828
"os"
2929

30-
"encoding/hex"
31-
"errors"
32-
3330
"github.com/ethereum/go-ethereum/common"
34-
"github.com/ethereum/go-ethereum/crypto/ecies"
35-
"github.com/ethereum/go-ethereum/crypto/secp256k1"
3631
"github.com/ethereum/go-ethereum/crypto/sha3"
3732
"github.com/ethereum/go-ethereum/rlp"
38-
"golang.org/x/crypto/ripemd160"
33+
)
34+
35+
var (
36+
secp256k1_N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
37+
secp256k1_halfN = new(big.Int).Div(secp256k1_N, big.NewInt(2))
3938
)
4039

4140
func Keccak256(data ...[]byte) []byte {
@@ -56,7 +55,6 @@ func Keccak256Hash(data ...[]byte) (h common.Hash) {
5655
}
5756

5857
// Deprecated: For backward compatibility as other packages depend on these
59-
func Sha3(data ...[]byte) []byte { return Keccak256(data...) }
6058
func Sha3Hash(data ...[]byte) common.Hash { return Keccak256Hash(data...) }
6159

6260
// Creates an ethereum address given the bytes and the nonce
@@ -65,39 +63,16 @@ func CreateAddress(b common.Address, nonce uint64) common.Address {
6563
return common.BytesToAddress(Keccak256(data)[12:])
6664
}
6765

68-
func Sha256(data []byte) []byte {
69-
hash := sha256.Sum256(data)
70-
71-
return hash[:]
72-
}
73-
74-
func Ripemd160(data []byte) []byte {
75-
ripemd := ripemd160.New()
76-
ripemd.Write(data)
77-
78-
return ripemd.Sum(nil)
79-
}
80-
81-
// Ecrecover returns the public key for the private key that was used to
82-
// calculate the signature.
83-
//
84-
// Note: secp256k1 expects the recover id to be either 0, 1. Ethereum
85-
// signatures have a recover id with an offset of 27. Callers must take
86-
// this into account and if "recovering" from an Ethereum signature adjust.
87-
func Ecrecover(hash, sig []byte) ([]byte, error) {
88-
return secp256k1.RecoverPubkey(hash, sig)
89-
}
90-
91-
// New methods using proper ecdsa keys from the stdlib
66+
// ToECDSA creates a private key with the given D value.
9267
func ToECDSA(prv []byte) *ecdsa.PrivateKey {
9368
if len(prv) == 0 {
9469
return nil
9570
}
9671

9772
priv := new(ecdsa.PrivateKey)
98-
priv.PublicKey.Curve = secp256k1.S256()
73+
priv.PublicKey.Curve = S256()
9974
priv.D = common.BigD(prv)
100-
priv.PublicKey.X, priv.PublicKey.Y = secp256k1.S256().ScalarBaseMult(prv)
75+
priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(prv)
10176
return priv
10277
}
10378

@@ -112,15 +87,15 @@ func ToECDSAPub(pub []byte) *ecdsa.PublicKey {
11287
if len(pub) == 0 {
11388
return nil
11489
}
115-
x, y := elliptic.Unmarshal(secp256k1.S256(), pub)
116-
return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}
90+
x, y := elliptic.Unmarshal(S256(), pub)
91+
return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}
11792
}
11893

11994
func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
12095
if pub == nil || pub.X == nil || pub.Y == nil {
12196
return nil
12297
}
123-
return elliptic.Marshal(secp256k1.S256(), pub.X, pub.Y)
98+
return elliptic.Marshal(S256(), pub.X, pub.Y)
12499
}
125100

126101
// HexToECDSA parses a secp256k1 private key.
@@ -164,7 +139,7 @@ func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
164139
}
165140

166141
func GenerateKey() (*ecdsa.PrivateKey, error) {
167-
return ecdsa.GenerateKey(secp256k1.S256(), rand.Reader)
142+
return ecdsa.GenerateKey(S256(), rand.Reader)
168143
}
169144

170145
// ValidateSignatureValues verifies whether the signature values are valid with
@@ -175,49 +150,11 @@ func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
175150
}
176151
// reject upper range of s values (ECDSA malleability)
177152
// see discussion in secp256k1/libsecp256k1/include/secp256k1.h
178-
if homestead && s.Cmp(secp256k1.HalfN) > 0 {
153+
if homestead && s.Cmp(secp256k1_halfN) > 0 {
179154
return false
180155
}
181156
// Frontier: allow s to be in full N range
182-
return r.Cmp(secp256k1.N) < 0 && s.Cmp(secp256k1.N) < 0 && (v == 0 || v == 1)
183-
}
184-
185-
func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
186-
s, err := Ecrecover(hash, sig)
187-
if err != nil {
188-
return nil, err
189-
}
190-
191-
x, y := elliptic.Unmarshal(secp256k1.S256(), s)
192-
return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}, nil
193-
}
194-
195-
// Sign calculates an ECDSA signature.
196-
//
197-
// This function is susceptible to chosen plaintext attacks that can leak
198-
// information about the private key that is used for signing. Callers must
199-
// be aware that the given hash cannot be chosen by an adversery. Common
200-
// solution is to hash any input before calculating the signature.
201-
//
202-
// The produced signature is in the [R || S || V] format where V is 0 or 1.
203-
func Sign(data []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
204-
if len(data) != 32 {
205-
return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(data))
206-
}
207-
208-
seckey := common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8)
209-
defer zeroBytes(seckey)
210-
sig, err = secp256k1.Sign(data, seckey)
211-
return
212-
}
213-
214-
func Encrypt(pub *ecdsa.PublicKey, message []byte) ([]byte, error) {
215-
return ecies.Encrypt(rand.Reader, ecies.ImportECDSAPublic(pub), message, nil, nil)
216-
}
217-
218-
func Decrypt(prv *ecdsa.PrivateKey, ct []byte) ([]byte, error) {
219-
key := ecies.ImportECDSA(prv)
220-
return key.Decrypt(rand.Reader, ct, nil, nil)
157+
return r.Cmp(secp256k1_N) < 0 && s.Cmp(secp256k1_N) < 0 && (v == 0 || v == 1)
221158
}
222159

223160
func PubkeyToAddress(p ecdsa.PublicKey) common.Address {

‎crypto/crypto_test.go‎

Lines changed: 8 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ import (
2828
"time"
2929

3030
"github.com/ethereum/go-ethereum/common"
31-
"github.com/ethereum/go-ethereum/crypto/secp256k1"
3231
)
3332

3433
var testAddrHex = "970e8128ab834e8eac17ab8e3812f010678cf791"
@@ -37,30 +36,12 @@ var testPrivHex = "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232
3736
// These tests are sanity checks.
3837
// They should ensure that we don't e.g. use Sha3-224 instead of Sha3-256
3938
// and that the sha3 library uses keccak-f permutation.
40-
func TestSha3(t *testing.T) {
41-
msg := []byte("abc")
42-
exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
43-
checkhash(t, "Sha3-256", func(in []byte) []byte { return Keccak256(in) }, msg, exp)
44-
}
45-
4639
func TestSha3Hash(t *testing.T) {
4740
msg := []byte("abc")
4841
exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
4942
checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := Keccak256Hash(in); return h[:] }, msg, exp)
5043
}
5144

52-
func TestSha256(t *testing.T) {
53-
msg := []byte("abc")
54-
exp, _ := hex.DecodeString("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
55-
checkhash(t, "Sha256", Sha256, msg, exp)
56-
}
57-
58-
func TestRipemd160(t *testing.T) {
59-
msg := []byte("abc")
60-
exp, _ := hex.DecodeString("8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")
61-
checkhash(t, "Ripemd160", Ripemd160, msg, exp)
62-
}
63-
6445
func BenchmarkSha3(b *testing.B) {
6546
a := []byte("hello world")
6647
amount := 1000000
@@ -170,7 +151,7 @@ func TestValidateSignatureValues(t *testing.T) {
170151
minusOne := big.NewInt(-1)
171152
one := common.Big1
172153
zero := common.Big0
173-
secp256k1nMinus1 := new(big.Int).Sub(secp256k1.N, common.Big1)
154+
secp256k1nMinus1 := new(big.Int).Sub(secp256k1_N, common.Big1)
174155

175156
// correct v,r,s
176157
check(true, 0, one, one)
@@ -197,9 +178,9 @@ func TestValidateSignatureValues(t *testing.T) {
197178
// correct sig with max r,s
198179
check(true, 0, secp256k1nMinus1, secp256k1nMinus1)
199180
// correct v, combinations of incorrect r,s at upper limit
200-
check(false, 0, secp256k1.N, secp256k1nMinus1)
201-
check(false, 0, secp256k1nMinus1, secp256k1.N)
202-
check(false, 0, secp256k1.N, secp256k1.N)
181+
check(false, 0, secp256k1_N, secp256k1nMinus1)
182+
check(false, 0, secp256k1nMinus1, secp256k1_N)
183+
check(false, 0, secp256k1_N, secp256k1_N)
203184

204185
// current callers ensures r,s cannot be negative, but let's test for that too
205186
// as crypto package could be used stand-alone
@@ -225,14 +206,13 @@ func checkAddr(t *testing.T, addr0, addr1 common.Address) {
225206
func TestPythonIntegration(t *testing.T) {
226207
kh := "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
227208
k0, _ := HexToECDSA(kh)
228-
k1 := FromECDSA(k0)
229209

230210
msg0 := Keccak256([]byte("foo"))
231-
sig0, _ := secp256k1.Sign(msg0, k1)
211+
sig0, _ := Sign(msg0, k0)
232212

233213
msg1 := common.FromHex("00000000000000000000000000000000")
234-
sig1, _ := secp256k1.Sign(msg0, k1)
214+
sig1, _ := Sign(msg0, k0)
235215

236-
fmt.Printf("msg: %x, privkey: %x sig: %x\n", msg0, k1, sig0)
237-
fmt.Printf("msg: %x, privkey: %x sig: %x\n", msg1, k1, sig1)
216+
t.Logf("msg: %x, privkey: %s sig: %x\n", msg0, kh, sig0)
217+
t.Logf("msg: %x, privkey: %s sig: %x\n", msg1, kh, sig1)
238218
}

‎crypto/ecies/asn1.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ import (
4242
"hash"
4343
"math/big"
4444

45-
"github.com/ethereum/go-ethereum/crypto/secp256k1"
45+
ethcrypto "github.com/ethereum/go-ethereum/crypto"
4646
)
4747

4848
var (
@@ -120,7 +120,7 @@ func (curve secgNamedCurve) Equal(curve2 secgNamedCurve) bool {
120120
func namedCurveFromOID(curve secgNamedCurve) elliptic.Curve {
121121
switch {
122122
case curve.Equal(secgNamedCurveS256):
123-
return secp256k1.S256()
123+
return ethcrypto.S256()
124124
case curve.Equal(secgNamedCurveP256):
125125
return elliptic.P256()
126126
case curve.Equal(secgNamedCurveP384):
@@ -139,7 +139,7 @@ func oidFromNamedCurve(curve elliptic.Curve) (secgNamedCurve, bool) {
139139
return secgNamedCurveP384, true
140140
case elliptic.P521():
141141
return secgNamedCurveP521, true
142-
case secp256k1.S256():
142+
case ethcrypto.S256():
143143
return secgNamedCurveS256, true
144144
}
145145

0 commit comments

Comments
 (0)