Skip to content

Commit 08eea0f

Browse files
karalabefjl
authored andcommitted
accounts, core, crypto, internal: use normalised V during signature handling (bnb-chain#3455)
To address increasing complexity in code that handles signatures, this PR discards all notion of "different" signature types at the library level. Both the crypto and accounts package is reduced to only be able to produce plain canonical secp256k1 signatures. This makes the crpyto APIs much cleaner, simpler and harder to abuse.
1 parent 0fac8cb commit 08eea0f

10 files changed

Lines changed: 91 additions & 201 deletions

File tree

‎accounts/abi/bind/auth.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
5252
if address != keyAddr {
5353
return nil, errors.New("not authorized to sign this account")
5454
}
55-
signature, err := crypto.SignEthereum(signer.Hash(tx).Bytes(), key)
55+
signature, err := crypto.Sign(signer.Hash(tx).Bytes(), key)
5656
if err != nil {
5757
return nil, err
5858
}

‎accounts/account_manager.go‎

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -136,42 +136,29 @@ func (am *Manager) DeleteAccount(a Account, passphrase string) error {
136136
return err
137137
}
138138

139-
// Sign calculates a ECDSA signature for the given hash.
140-
// Note, Ethereum signatures have a particular format as described in the
141-
// yellow paper. Use the SignEthereum function to calculate a signature
142-
// in Ethereum format.
139+
// Sign calculates a ECDSA signature for the given hash. The produced signature
140+
// is in the [R || S || V] format where V is 0 or 1.
143141
func (am *Manager) Sign(addr common.Address, hash []byte) ([]byte, error) {
144142
am.mu.RLock()
145143
defer am.mu.RUnlock()
146-
unlockedKey, found := am.unlocked[addr]
147-
if !found {
148-
return nil, ErrLocked
149-
}
150-
return crypto.Sign(hash, unlockedKey.PrivateKey)
151-
}
152144

153-
// SignEthereum calculates a ECDSA signature for the given hash.
154-
// The signature has the format as described in the Ethereum yellow paper.
155-
func (am *Manager) SignEthereum(addr common.Address, hash []byte) ([]byte, error) {
156-
am.mu.RLock()
157-
defer am.mu.RUnlock()
158145
unlockedKey, found := am.unlocked[addr]
159146
if !found {
160147
return nil, ErrLocked
161148
}
162-
return crypto.SignEthereum(hash, unlockedKey.PrivateKey)
149+
return crypto.Sign(hash, unlockedKey.PrivateKey)
163150
}
164151

165-
// SignWithPassphrase signs hash if the private key matching the given
166-
// address can be decrypted with the given passphrase.
152+
// SignWithPassphrase signs hash if the private key matching the given address
153+
// can be decrypted with the given passphrase. The produced signature is in the
154+
// [R || S || V] format where V is 0 or 1.
167155
func (am *Manager) SignWithPassphrase(addr common.Address, passphrase string, hash []byte) (signature []byte, err error) {
168156
_, key, err := am.getDecryptedKey(Account{Address: addr}, passphrase)
169157
if err != nil {
170158
return nil, err
171159
}
172-
173160
defer zeroKey(key.PrivateKey)
174-
return crypto.SignEthereum(hash, key.PrivateKey)
161+
return crypto.Sign(hash, key.PrivateKey)
175162
}
176163

177164
// Unlock unlocks the given account indefinitely.

‎core/types/block_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ func TestBlockEncoding(t *testing.T) {
5353

5454
tx1 := NewTransaction(0, common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"), big.NewInt(10), big.NewInt(50000), big.NewInt(10), nil)
5555

56-
tx1, _ = tx1.WithSignature(HomesteadSigner{}, common.Hex2Bytes("9bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094f8a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b11b"))
56+
tx1, _ = tx1.WithSignature(HomesteadSigner{}, common.Hex2Bytes("9bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094f8a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b100"))
5757
fmt.Println(block.Transactions()[0].Hash())
5858
fmt.Println(tx1.data)
5959
fmt.Println(tx1.Hash())

‎core/types/transaction.go‎

Lines changed: 2 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -199,9 +199,9 @@ func (tx *Transaction) UnmarshalJSON(input []byte) error {
199199

200200
var V byte
201201
if isProtectedV((*big.Int)(dec.V)) {
202-
V = normaliseV(NewEIP155Signer(deriveChainId((*big.Int)(dec.V))), (*big.Int)(dec.V))
202+
V = byte((new(big.Int).Sub((*big.Int)(dec.V), deriveChainId((*big.Int)(dec.V))).Uint64()) - 35)
203203
} else {
204-
V = byte(((*big.Int)(dec.V)).Uint64())
204+
V = byte(((*big.Int)(dec.V)).Uint64() - 27)
205205
}
206206
if !crypto.ValidateSignatureValues(V, (*big.Int)(dec.R), (*big.Int)(dec.S), false) {
207207
return ErrInvalidSig
@@ -272,51 +272,6 @@ func (tx *Transaction) Size() common.StorageSize {
272272
return common.StorageSize(c)
273273
}
274274

275-
/*
276-
// From returns the address derived from the signature (V, R, S) using secp256k1
277-
// elliptic curve and an error if it failed deriving or upon an incorrect
278-
// signature.
279-
//
280-
// From Uses the homestead consensus rules to determine whether the signature is
281-
// valid.
282-
//
283-
// From caches the address, allowing it to be used regardless of
284-
// Frontier / Homestead. however, the first time called it runs
285-
// signature validations, so we need two versions. This makes it
286-
// easier to ensure backwards compatibility of things like package rpc
287-
// where eth_getblockbynumber uses tx.From() and needs to work for
288-
// both txs before and after the first homestead block. Signatures
289-
// valid in homestead are a subset of valid ones in Frontier)
290-
func (tx *Transaction) From() (common.Address, error) {
291-
if tx.signer == nil {
292-
return common.Address{}, errNoSigner
293-
}
294-
295-
if from := tx.from.Load(); from != nil {
296-
return from.(common.Address), nil
297-
}
298-
299-
pubkey, err := tx.signer.PublicKey(tx)
300-
if err != nil {
301-
return common.Address{}, err
302-
}
303-
var addr common.Address
304-
copy(addr[:], crypto.Keccak256(pubkey[1:])[12:])
305-
tx.from.Store(addr)
306-
return addr, nil
307-
}
308-
309-
// SignatureValues returns the ECDSA signature values contained in the transaction.
310-
func (tx *Transaction) SignatureValues() (v byte, r *big.Int, s *big.Int, err error) {
311-
if tx.signer == nil {
312-
return 0, nil, nil,errNoSigner
313-
}
314-
315-
return normaliseV(tx.signer, tx.data.V), new(big.Int).Set(tx.data.R),new(big.Int).Set(tx.data.S), nil
316-
}
317-
318-
*/
319-
320275
// AsMessage returns the transaction as a core.Message.
321276
//
322277
// AsMessage requires a signer to derive the sender.

‎core/types/transaction_signing.go‎

Lines changed: 19 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ func MakeSigner(config *params.ChainConfig, blockNumber *big.Int) Signer {
5353
// SignECDSA signs the transaction using the given signer and private key
5454
func SignECDSA(s Signer, tx *Transaction, prv *ecdsa.PrivateKey) (*Transaction, error) {
5555
h := s.Hash(tx)
56-
sig, err := crypto.SignEthereum(h[:], prv)
56+
sig, err := crypto.Sign(h[:], prv)
5757
if err != nil {
5858
return nil, err
5959
}
@@ -91,11 +91,6 @@ func Sender(signer Signer, tx *Transaction) (common.Address, error) {
9191
return addr, nil
9292
}
9393

94-
// SignatureValues returns the ECDSA signature values contained in the transaction.
95-
func SignatureValues(signer Signer, tx *Transaction) (v byte, r *big.Int, s *big.Int) {
96-
return normaliseV(signer, tx.data.V), new(big.Int).Set(tx.data.R), new(big.Int).Set(tx.data.S)
97-
}
98-
9994
type Signer interface {
10095
// Hash returns the rlp encoded hash for signatures
10196
Hash(tx *Transaction) common.Hash
@@ -143,17 +138,16 @@ func (s EIP155Signer) PublicKey(tx *Transaction) ([]byte, error) {
143138
return nil, ErrInvalidChainId
144139
}
145140

146-
V := normaliseV(s, tx.data.V)
141+
V := byte(new(big.Int).Sub(tx.data.V, s.chainIdMul).Uint64() - 35)
147142
if !crypto.ValidateSignatureValues(V, tx.data.R, tx.data.S, true) {
148143
return nil, ErrInvalidSig
149144
}
150-
151145
// encode the signature in uncompressed format
152146
R, S := tx.data.R.Bytes(), tx.data.S.Bytes()
153147
sig := make([]byte, 65)
154148
copy(sig[32-len(R):32], R)
155149
copy(sig[64-len(S):64], S)
156-
sig[64] = V - 27
150+
sig[64] = V
157151

158152
// recover the public key from the signature
159153
hash := s.Hash(tx)
@@ -167,8 +161,8 @@ func (s EIP155Signer) PublicKey(tx *Transaction) ([]byte, error) {
167161
return pub, nil
168162
}
169163

170-
// WithSignature returns a new transaction with the given signature.
171-
// This signature needs to be formatted as described in the yellow paper (v+27).
164+
// WithSignature returns a new transaction with the given signature. This signature
165+
// needs to be in the [R || S || V] format where V is 0 or 1.
172166
func (s EIP155Signer) WithSignature(tx *Transaction, sig []byte) (*Transaction, error) {
173167
if len(sig) != 65 {
174168
panic(fmt.Sprintf("wrong size for snature: got %d, want 65", len(sig)))
@@ -179,7 +173,7 @@ func (s EIP155Signer) WithSignature(tx *Transaction, sig []byte) (*Transaction,
179173
cpy.data.S = new(big.Int).SetBytes(sig[32:64])
180174
cpy.data.V = new(big.Int).SetBytes([]byte{sig[64]})
181175
if s.chainId.BitLen() > 0 {
182-
cpy.data.V = big.NewInt(int64(sig[64] - 27 + 35))
176+
cpy.data.V = big.NewInt(int64(sig[64] + 35))
183177
cpy.data.V.Add(cpy.data.V, s.chainIdMul)
184178
}
185179
return cpy, nil
@@ -201,7 +195,7 @@ func (s EIP155Signer) Hash(tx *Transaction) common.Hash {
201195

202196
func (s EIP155Signer) SigECDSA(tx *Transaction, prv *ecdsa.PrivateKey) (*Transaction, error) {
203197
h := s.Hash(tx)
204-
sig, err := crypto.SignEthereum(h[:], prv)
198+
sig, err := crypto.Sign(h[:], prv)
205199
if err != nil {
206200
return nil, err
207201
}
@@ -217,22 +211,22 @@ func (s HomesteadSigner) Equal(s2 Signer) bool {
217211
return ok
218212
}
219213

220-
// WithSignature returns a new transaction with the given snature.
221-
// This snature needs to be formatted as described in the yellow paper (v+27).
214+
// WithSignature returns a new transaction with the given signature. This signature
215+
// needs to be in the [R || S || V] format where V is 0 or 1.
222216
func (hs HomesteadSigner) WithSignature(tx *Transaction, sig []byte) (*Transaction, error) {
223217
if len(sig) != 65 {
224218
panic(fmt.Sprintf("wrong size for snature: got %d, want 65", len(sig)))
225219
}
226220
cpy := &Transaction{data: tx.data}
227221
cpy.data.R = new(big.Int).SetBytes(sig[:32])
228222
cpy.data.S = new(big.Int).SetBytes(sig[32:64])
229-
cpy.data.V = new(big.Int).SetBytes([]byte{sig[64]})
223+
cpy.data.V = new(big.Int).SetBytes([]byte{sig[64] + 27})
230224
return cpy, nil
231225
}
232226

233227
func (hs HomesteadSigner) SignECDSA(tx *Transaction, prv *ecdsa.PrivateKey) (*Transaction, error) {
234228
h := hs.Hash(tx)
235-
sig, err := crypto.SignEthereum(h[:], prv)
229+
sig, err := crypto.Sign(h[:], prv)
236230
if err != nil {
237231
return nil, err
238232
}
@@ -243,7 +237,7 @@ func (hs HomesteadSigner) PublicKey(tx *Transaction) ([]byte, error) {
243237
if tx.data.V.BitLen() > 8 {
244238
return nil, ErrInvalidSig
245239
}
246-
V := byte(tx.data.V.Uint64())
240+
V := byte(tx.data.V.Uint64() - 27)
247241
if !crypto.ValidateSignatureValues(V, tx.data.R, tx.data.S, true) {
248242
return nil, ErrInvalidSig
249243
}
@@ -252,7 +246,7 @@ func (hs HomesteadSigner) PublicKey(tx *Transaction) ([]byte, error) {
252246
sig := make([]byte, 65)
253247
copy(sig[32-len(r):32], r)
254248
copy(sig[64-len(s):64], s)
255-
sig[64] = V - 27
249+
sig[64] = V
256250

257251
// recover the public key from the snature
258252
hash := hs.Hash(tx)
@@ -273,22 +267,22 @@ func (s FrontierSigner) Equal(s2 Signer) bool {
273267
return ok
274268
}
275269

276-
// WithSignature returns a new transaction with the given snature.
277-
// This snature needs to be formatted as described in the yellow paper (v+27).
270+
// WithSignature returns a new transaction with the given signature. This signature
271+
// needs to be in the [R || S || V] format where V is 0 or 1.
278272
func (fs FrontierSigner) WithSignature(tx *Transaction, sig []byte) (*Transaction, error) {
279273
if len(sig) != 65 {
280274
panic(fmt.Sprintf("wrong size for snature: got %d, want 65", len(sig)))
281275
}
282276
cpy := &Transaction{data: tx.data}
283277
cpy.data.R = new(big.Int).SetBytes(sig[:32])
284278
cpy.data.S = new(big.Int).SetBytes(sig[32:64])
285-
cpy.data.V = new(big.Int).SetBytes([]byte{sig[64]})
279+
cpy.data.V = new(big.Int).SetBytes([]byte{sig[64] + 27})
286280
return cpy, nil
287281
}
288282

289283
func (fs FrontierSigner) SignECDSA(tx *Transaction, prv *ecdsa.PrivateKey) (*Transaction, error) {
290284
h := fs.Hash(tx)
291-
sig, err := crypto.SignEthereum(h[:], prv)
285+
sig, err := crypto.Sign(h[:], prv)
292286
if err != nil {
293287
return nil, err
294288
}
@@ -313,7 +307,7 @@ func (fs FrontierSigner) PublicKey(tx *Transaction) ([]byte, error) {
313307
return nil, ErrInvalidSig
314308
}
315309

316-
V := byte(tx.data.V.Uint64())
310+
V := byte(tx.data.V.Uint64() - 27)
317311
if !crypto.ValidateSignatureValues(V, tx.data.R, tx.data.S, false) {
318312
return nil, ErrInvalidSig
319313
}
@@ -322,7 +316,7 @@ func (fs FrontierSigner) PublicKey(tx *Transaction) ([]byte, error) {
322316
sig := make([]byte, 65)
323317
copy(sig[32-len(r):32], r)
324318
copy(sig[64-len(s):64], s)
325-
sig[64] = V - 27
319+
sig[64] = V
326320

327321
// recover the public key from the snature
328322
hash := fs.Hash(tx)
@@ -336,18 +330,6 @@ func (fs FrontierSigner) PublicKey(tx *Transaction) ([]byte, error) {
336330
return pub, nil
337331
}
338332

339-
// normaliseV returns the Ethereum version of the V parameter
340-
func normaliseV(s Signer, v *big.Int) byte {
341-
if s, ok := s.(EIP155Signer); ok {
342-
stdV := v.BitLen() <= 8 && (v.Uint64() == 27 || v.Uint64() == 28)
343-
if s.chainId.BitLen() > 0 && !stdV {
344-
nv := byte((new(big.Int).Sub(v, s.chainIdMul).Uint64()) - 35 + 27)
345-
return nv
346-
}
347-
}
348-
return byte(v.Uint64())
349-
}
350-
351333
// deriveChainId derives the chain id from the given v parameter
352334
func deriveChainId(v *big.Int) *big.Int {
353335
if v.BitLen() <= 64 {

‎core/types/transaction_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ var (
4747
common.FromHex("5544"),
4848
).WithSignature(
4949
HomesteadSigner{},
50-
common.Hex2Bytes("98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a31c"),
50+
common.Hex2Bytes("98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a301"),
5151
)
5252
)
5353

‎core/vm/contracts.go‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -89,21 +89,15 @@ func ecrecoverFunc(in []byte) []byte {
8989

9090
r := common.BytesToBig(in[64:96])
9191
s := common.BytesToBig(in[96:128])
92-
// Treat V as a 256bit integer
93-
vbig := common.Bytes2Big(in[32:64])
94-
v := byte(vbig.Uint64())
92+
v := in[63] - 27
9593

9694
// tighter sig s values in homestead only apply to tx sigs
97-
if !crypto.ValidateSignatureValues(v, r, s, false) {
95+
if common.Bytes2Big(in[32:63]).BitLen() > 0 || !crypto.ValidateSignatureValues(v, r, s, false) {
9896
glog.V(logger.Detail).Infof("ECRECOVER error: v, r or s value invalid")
9997
return nil
10098
}
101-
102-
// v needs to be at the end and normalized for libsecp256k1
103-
vbignormal := new(big.Int).Sub(vbig, big.NewInt(27))
104-
vnormal := byte(vbignormal.Uint64())
105-
rsv := append(in[64:128], vnormal)
106-
pubKey, err := crypto.Ecrecover(in[:32], rsv)
99+
// v needs to be at the end for libsecp256k1
100+
pubKey, err := crypto.Ecrecover(in[:32], append(in[64:128], v))
107101
// make sure the public key is a valid one
108102
if err != nil {
109103
glog.V(logger.Detail).Infoln("ECRECOVER error: ", err)

0 commit comments

Comments
 (0)