-
Notifications
You must be signed in to change notification settings - Fork 0
/
ethTx.go
583 lines (482 loc) · 14.3 KB
/
ethTx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
package types
import (
"crypto/ecdsa"
"errors"
"fmt"
sdk "github.com/ci123chain/ci123chain/pkg/abci/types"
ethcmn "github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rlp"
"golang.org/x/crypto/sha3"
"io"
"math/big"
"sync/atomic"
)
const (
RouterKey = "vm"
TypeMsgEthereumTx = "MsgEthereumTx"
)
var _ sdk.Tx = (*MsgEthereumTx)(nil)
var ModuleCdc = GetCodec()
var big8 = big.NewInt(8)
// MsgEthereumTx encapsulates an Ethereum transaction as an SDK message.
type MsgEthereumTx struct {
Data TxData
// caches
size atomic.Value
from atomic.Value
}
// sigCache is used to cache the derived sender and contains the signer used
// to derive it.
type sigCache struct {
signer ethtypes.Signer
from ethcmn.Address
}
// NewMsgEthereumTx returns a reference to a new Ethereum transaction message.
func NewMsgEthereumTx(
nonce uint64, to *ethcmn.Address, amount *big.Int,
gasLimit uint64, gasPrice *big.Int, payload []byte,
) MsgEthereumTx {
return newMsgEthereumTx(nonce, to, amount, gasLimit, gasPrice, payload)
}
// NewMsgEthereumTxContract returns a reference to a new Ethereum transaction
// message designated for contract creation.
func NewMsgEthereumTxContract(
nonce uint64, amount *big.Int, gasLimit uint64, gasPrice *big.Int, payload []byte,
) MsgEthereumTx {
return newMsgEthereumTx(nonce, nil, amount, gasLimit, gasPrice, payload)
}
func newMsgEthereumTx(
nonce uint64, to *ethcmn.Address, amount *big.Int,
gasLimit uint64, gasPrice *big.Int, payload []byte,
) MsgEthereumTx {
if len(payload) > 0 {
payload = ethcmn.CopyBytes(payload)
}
txData := TxData{
AccountNonce: nonce,
Recipient: to,
Payload: payload,
GasLimit: gasLimit,
Amount: new(big.Int),
Price: new(big.Int),
V: new(big.Int),
R: new(big.Int),
S: new(big.Int),
}
if amount != nil {
txData.Amount.Set(amount)
}
if gasPrice != nil {
txData.Price.Set(gasPrice)
}
return MsgEthereumTx{Data: txData}
}
func (msg MsgEthereumTx) String() string {
return msg.Data.String()
}
// Route returns the route value of an MsgEthereumTx.
func (msg MsgEthereumTx) Route() string { return RouterKey }
// Type returns the types value of an MsgEthereumTx.
func (msg MsgEthereumTx) MsgType() string { return TypeMsgEthereumTx }
// ValidateBasic implements the sdk.Msg interface. It performs basic validation
// checks of a Transaction. If returns an error if validation fails.
func (msg MsgEthereumTx) ValidateBasic() error {
if msg.Data.Price.Cmp(big.NewInt(0)) == 0 {
return ErrInvalidParam("gas price cannot be 0")
}
if msg.Data.Price.Sign() == -1 {
return ErrInvalidParam(fmt.Sprintf("gas price cannot be negative %s", msg.Data.Price))
}
// Amount can be 0
if msg.Data.Amount.Sign() == -1 {
return ErrInvalidParam(fmt.Sprintf("amount cannot be negative %s", msg.Data.Amount))
}
return nil
}
// To returns the recipient address of the transaction. It returns nil if the
// transaction is a contract creation.
func (msg MsgEthereumTx) To() *ethcmn.Address {
return msg.Data.Recipient
}
// GetMsgs returns a single MsgEthereumTx as an sdk.Msg.
func (msg MsgEthereumTx) GetMsgs() []sdk.Msg {
return []sdk.Msg{msg}
}
func (msg MsgEthereumTx) GetNonce() uint64 {
return msg.Data.AccountNonce
}
func (msg MsgEthereumTx) SetPubKey([]byte) {
return
}
func (msg MsgEthereumTx) GetFromAddress() sdk.AccAddress {
return msg.From()
}
func (msg MsgEthereumTx) Bytes() []byte {
bytes, err := ModuleCdc.MarshalBinaryBare(msg)
if err != nil {
panic(err)
}
return bytes
}
// GetSigners returns the expected signers for an Ethereum transaction message.
// For such a message, there should exist only a single 'signer'.
//
// NOTE: This method panics if 'VerifySig' hasn't been called first.
func (msg MsgEthereumTx) GetSigners() []sdk.AccAddress {
sender := msg.From()
if sender.Empty() {
panic("must use 'VerifySig' with a chain ID to get the signer")
}
return []sdk.AccAddress{sender}
}
// GetSignBytes returns the Amino bytes of an Ethereum transaction message used
// for signing.
//
// NOTE: This method cannot be used as a chain ID is needed to create valid bytes
// to sign over. Use 'RLPSignBytes' instead.
func (msg MsgEthereumTx) GetSignBytes() []byte {
panic("must use 'RLPSignBytes' with a chain ID to get the valid bytes to sign")
}
func (msg MsgEthereumTx) GetSignature() []byte {
panic("must use 'RLPSignBytes' with a chain ID to get the valid bytes to sign")
}
func (msg MsgEthereumTx) SetSignature([]byte) {
panic("must use 'RLPSignBytes' with a chain ID to get the valid bytes to sign")
}
// RLPSignBytes returns the RLP hash of an Ethereum transaction message with a
// given chainID used for signing.
func (msg MsgEthereumTx) RLPSignBytes(chainID *big.Int) ethcmn.Hash {
return rlpHash([]interface{}{
msg.Data.AccountNonce,
msg.Data.Price,
msg.Data.GasLimit,
msg.Data.Recipient,
msg.Data.Amount,
msg.Data.Payload,
chainID, uint(0), uint(0),
})
}
// EncodeRLP implements the rlp.Encoder interface.
func (msg *MsgEthereumTx) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, &msg.Data)
}
// DecodeRLP implements the rlp.Decoder interface.
func (msg *MsgEthereumTx) DecodeRLP(s *rlp.Stream) error {
_, size, err := s.Kind()
if err != nil {
// return error if stream is too large
return err
}
if err := s.Decode(&msg.Data); err != nil {
return err
}
msg.size.Store(ethcmn.StorageSize(rlp.ListSize(size)))
return nil
}
// Sign calculates a secp256k1 ECDSA signature and signs the transaction. It
// takes a private key and chainID to sign an Ethereum transaction according to
// EIP155 standard. It mutates the transaction as it populates the V, R, S
// fields of the Transaction's Signature.
func (msg *MsgEthereumTx) Sign(chainID *big.Int, priv *ecdsa.PrivateKey) error {
txHash := msg.RLPSignBytes(chainID)
sig, err := ethcrypto.Sign(txHash[:], priv)
if err != nil {
return err
}
if len(sig) != 65 {
return fmt.Errorf("wrong size for signature: got %d, want 65", len(sig))
}
r := new(big.Int).SetBytes(sig[:32])
s := new(big.Int).SetBytes(sig[32:64])
var v *big.Int
if chainID.Sign() == 0 {
v = new(big.Int).SetBytes([]byte{sig[64] + 27})
} else {
v = big.NewInt(int64(sig[64] + 35))
chainIDMul := new(big.Int).Mul(chainID, big.NewInt(2))
v.Add(v, chainIDMul)
}
msg.Data.V = v
msg.Data.R = r
msg.Data.S = s
return nil
}
// VerifySig attempts to verify a Transaction's signature for a given chainID.
// A derived address is returned upon success or an error if recovery fails.
func (msg *MsgEthereumTx) VerifySig(chainID *big.Int) (ethcmn.Address, error) {
signer := ethtypes.NewEIP155Signer(chainID)
if sc := msg.from.Load(); sc != nil {
sigCache := sc.(sigCache)
// If the signer used to derive from in a previous call is not the same as
// used current, invalidate the cache.
if sigCache.signer.Equal(signer) {
return sigCache.from, nil
}
}
// do not allow recovery for transactions with an unprotected chainID
if chainID.Sign() == 0 {
return ethcmn.Address{}, errors.New("chainID cannot be zero")
}
chainIDMul := new(big.Int).Mul(chainID, big.NewInt(2))
V := new(big.Int).Sub(msg.Data.V, chainIDMul)
V.Sub(V, big8)
sigHash := msg.RLPSignBytes(chainID)
sender, err := recoverEthSig(msg.Data.R, msg.Data.S, V, sigHash)
if err != nil {
return ethcmn.Address{}, err
}
msg.from.Store(sigCache{signer: signer, from: sender})
return sender, nil
}
// GetGas implements the GasTx interface. It returns the GasLimit of the transaction.
func (msg MsgEthereumTx) GetGas() uint64 {
return msg.Data.GasLimit
}
// Fee returns gasprice * gaslimit.
func (msg MsgEthereumTx) Fee() *big.Int {
return new(big.Int).Mul(msg.Data.Price, new(big.Int).SetUint64(msg.Data.GasLimit))
}
// ChainID returns which chain id this transaction was signed for (if at all)
func (msg *MsgEthereumTx) ChainID() *big.Int {
return deriveChainID(msg.Data.V)
}
// Cost returns amount + gasprice * gaslimit.
func (msg MsgEthereumTx) Cost() *big.Int {
total := msg.Fee()
total.Add(total, msg.Data.Amount)
return total
}
// RawSignatureValues returns the V, R, S signature values of the transaction.
// The return values should not be modified by the caller.
func (msg MsgEthereumTx) RawSignatureValues() (v, r, s *big.Int) {
return msg.Data.V, msg.Data.R, msg.Data.S
}
// From loads the ethereum sender address from the sigcache and returns an
// sdk.AccAddress from its bytes
func (msg *MsgEthereumTx) From() sdk.AccAddress {
sc := msg.from.Load()
if sc == nil {
return sdk.AccAddress{}
}
sigCache := sc.(sigCache)
if len(sigCache.from.Bytes()) == 0 {
return sdk.AccAddress{}
}
return sdk.AccAddress{sigCache.from}
}
// deriveChainID derives the chain id from the given v parameter
func deriveChainID(v *big.Int) *big.Int {
if v.BitLen() <= 64 {
v := v.Uint64()
if v == 27 || v == 28 {
return new(big.Int)
}
return new(big.Int).SetUint64((v - 35) / 2)
}
v = new(big.Int).Sub(v, big.NewInt(35))
return v.Div(v, big.NewInt(2))
}
// TxData implements the Ethereum transaction data structure. It is used
// solely as intended in Ethereum abiding by the protocol.
type TxData struct {
AccountNonce uint64 `json:"nonce"`
Price *big.Int `json:"gasPrice"`
GasLimit uint64 `json:"gas"`
Recipient *ethcmn.Address `json:"to" rlp:"nil"` // nil means contract creation
Amount *big.Int `json:"value"`
Payload []byte `json:"input"`
// signature values
V *big.Int `json:"v"`
R *big.Int `json:"r"`
S *big.Int `json:"s"`
// hash is only used when marshaling to JSON
Hash *ethcmn.Hash `json:"hash" rlp:"-"`
}
// encodableTxData implements the Ethereum transaction data structure. It is used
// solely as intended in Ethereum abiding by the protocol.
type encodableTxData struct {
AccountNonce uint64 `json:"nonce"`
Price string `json:"gasPrice"`
GasLimit uint64 `json:"gas"`
Recipient *ethcmn.Address `json:"to" rlp:"nil"` // nil means contract creation
Amount string `json:"value"`
Payload []byte `json:"input"`
// signature values
V string `json:"v"`
R string `json:"r"`
S string `json:"s"`
// hash is only used when marshaling to JSON
Hash *ethcmn.Hash `json:"hash" rlp:"-"`
}
func (td TxData) String() string {
if td.Recipient != nil {
return fmt.Sprintf("nonce=%d price=%s gasLimit=%d recipient=%s amount=%s data=0x%x v=%s r=%s s=%s",
td.AccountNonce, td.Price, td.GasLimit, td.Recipient.Hex(), td.Amount, td.Payload, td.V, td.R, td.S)
}
return fmt.Sprintf("nonce=%d price=%s gasLimit=%d recipient=nil amount=%s data=0x%x v=%s r=%s s=%s",
td.AccountNonce, td.Price, td.GasLimit, td.Amount, td.Payload, td.V, td.R, td.S)
}
// MarshalAmino defines custom encoding scheme for TxData
func (td TxData) MarshalAmino() ([]byte, error) {
gasPrice, err := MarshalBigInt(td.Price)
if err != nil {
return nil, err
}
amount, err := MarshalBigInt(td.Amount)
if err != nil {
return nil, err
}
v, err := MarshalBigInt(td.V)
if err != nil {
return nil, err
}
r, err := MarshalBigInt(td.R)
if err != nil {
return nil, err
}
s, err := MarshalBigInt(td.S)
if err != nil {
return nil, err
}
e := encodableTxData{
AccountNonce: td.AccountNonce,
Price: gasPrice,
GasLimit: td.GasLimit,
Recipient: td.Recipient,
Amount: amount,
Payload: td.Payload,
V: v,
R: r,
S: s,
Hash: td.Hash,
}
return ModuleCdc.MarshalBinaryBare(e)
}
// UnmarshalAmino defines custom decoding scheme for TxData
func (td *TxData) UnmarshalAmino(data []byte) error {
var e encodableTxData
err := ModuleCdc.UnmarshalBinaryBare(data, &e)
if err != nil {
return err
}
td.AccountNonce = e.AccountNonce
td.GasLimit = e.GasLimit
td.Recipient = e.Recipient
td.Payload = e.Payload
td.Hash = e.Hash
price, err := UnmarshalBigInt(e.Price)
if err != nil {
return err
}
if td.Price != nil {
td.Price.Set(price)
} else {
td.Price = price
}
amt, err := UnmarshalBigInt(e.Amount)
if err != nil {
return err
}
if td.Amount != nil {
td.Amount.Set(amt)
} else {
td.Amount = amt
}
v, err := UnmarshalBigInt(e.V)
if err != nil {
return err
}
if td.V != nil {
td.V.Set(v)
} else {
td.V = v
}
r, err := UnmarshalBigInt(e.R)
if err != nil {
return err
}
if td.R != nil {
td.R.Set(r)
} else {
td.R = r
}
s, err := UnmarshalBigInt(e.S)
if err != nil {
return err
}
if td.S != nil {
td.S.Set(s)
} else {
td.S = s
}
return nil
}
// MarshalBigInt marshalls big int into text string for consistent encoding
func MarshalBigInt(i *big.Int) (string, error) {
bz, err := i.MarshalText()
if err != nil {
return "", err
}
return string(bz), nil
}
// MustMarshalBigInt marshalls big int into text string for consistent encoding.
// It panics if an error is encountered.
func MustMarshalBigInt(i *big.Int) string {
str, err := MarshalBigInt(i)
if err != nil {
panic(err)
}
return str
}
// UnmarshalBigInt unmarshalls string from *big.Int
func UnmarshalBigInt(s string) (*big.Int, error) {
ret := new(big.Int)
err := ret.UnmarshalText([]byte(s))
if err != nil {
return nil, err
}
return ret, nil
}
// MustUnmarshalBigInt unmarshalls string from *big.Int.
// It panics if an error is encountered.
func MustUnmarshalBigInt(s string) *big.Int {
ret, err := UnmarshalBigInt(s)
if err != nil {
panic(err)
}
return ret
}
func rlpHash(x interface{}) (hash ethcmn.Hash) {
hasher := sha3.NewLegacyKeccak256()
_ = rlp.Encode(hasher, x)
_ = hasher.Sum(hash[:0])
return hash
}
func recoverEthSig(R, S, Vb *big.Int, sigHash ethcmn.Hash) (ethcmn.Address, error) {
if Vb.BitLen() > 8 {
return ethcmn.Address{}, errors.New("invalid signature")
}
V := byte(Vb.Uint64() - 27)
if !ethcrypto.ValidateSignatureValues(V, R, S, true) {
return ethcmn.Address{}, errors.New("invalid signature")
}
// encode the signature in uncompressed format
r, s := R.Bytes(), S.Bytes()
sig := make([]byte, 65)
copy(sig[32-len(r):32], r)
copy(sig[64-len(s):64], s)
sig[64] = V
// recover the public key from the signature
pub, err := ethcrypto.Ecrecover(sigHash[:], sig)
if err != nil {
return ethcmn.Address{}, err
}
if len(pub) == 0 || pub[0] != 4 {
return ethcmn.Address{}, errors.New("invalid public key")
}
var addr ethcmn.Address
copy(addr[:], ethcrypto.Keccak256(pub[1:])[12:])
return addr, nil
}