-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevmtx.go
More file actions
524 lines (496 loc) · 14 KB
/
evmtx.go
File metadata and controls
524 lines (496 loc) · 14 KB
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
package outscript
import (
"crypto"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"strconv"
"github.com/BottleFmt/gobottle"
"github.com/KarpelesLab/typutil"
"github.com/ModChain/rlp"
"github.com/ModChain/secp256k1"
"golang.org/x/crypto/sha3"
)
// LegacyTx
// DynamicFeeTx represents an EIP-1559 transaction
// AccessListTx is the data of EIP-2930 access list transactions
//
// Legacy = rlp([nonce, gasPrice, gasLimit, to, value, data, v, r, s])
// EIP-2930 = 0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, signatureYParity, signatureR, signatureS])
// EIP-1559 = 0x02 || rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, amount, data, access_list, signature_y_parity, signature_r, signature_s])
// EIP-4844 = 0x03 || [chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, to, value, data, access_list, max_fee_per_blob_gas, blob_versioned_hashes, y_parity, r, s]
// however, EIP-2930 is so rare we can probably forget about it
// EvmTxType represents the type of EVM transaction encoding.
type EvmTxType int
const (
EvmTxLegacy EvmTxType = iota // Legacy (pre-EIP-2718) transaction
EvmTxEIP2930 // EIP-2930 access list transaction
EvmTxEIP1559 // EIP-1559 dynamic fee transaction
EvmTxEIP4844 // EIP-4844 blob transaction
)
// EvmTx represents an Ethereum Virtual Machine transaction. It supports legacy,
// EIP-2930, EIP-1559, and EIP-4844 transaction types, and can be signed, serialized,
// parsed, and converted to/from JSON.
type EvmTx struct {
Nonce uint64
GasTipCap *big.Int // a.k.a. maxPriorityFeePerGas
GasFeeCap *big.Int // a.k.a. maxFeePerGas, correspond to GasFee if tx type is legacy or eip2930
Gas uint64 // gas of tx, can be obtained with eth_estimateGas, 21000 if Data is empty
To string
Value *big.Int
Data []byte
ChainId uint64 // in legacy tx, chainId is encoded in v before signature
Type EvmTxType // type of transaction: legacy, eip2930 or eip1559
AccessList []any // TODO
Signed bool
Y, R, S *big.Int
}
// evmTxJson is used when encoding/decoding evmTx into json
type evmTxJson struct {
From string `json:"from,omitempty"` // not used when reading but useful for debug
Gas string `json:"gas"`
GasPrice string `json:"gasPrice,omitempty"`
GasTipCap string `json:"maxPriorityFeePerGas,omitempty"`
GasFeeCap string `json:"maxFeePerGas,omitempty"`
Hash string `json:"hash,omitempty"`
Input string `json:"input"`
Nonce string `json:"nonce"`
To string `json:"to,omitempty"`
Value string `json:"value"`
ChainId string `json:"chainId"`
V string `json:"v"`
R string `json:"r"`
S string `json:"s"`
}
// RlpFields returns the Rlp fields for the given transaction, less the signature fields
func (tx *EvmTx) RlpFields() []any {
switch tx.Type {
case EvmTxLegacy:
return []any{
tx.Nonce,
tx.GasFeeCap,
tx.Gas,
tx.To,
tx.Value,
tx.Data,
}
case EvmTxEIP2930:
return []any{
tx.ChainId,
tx.Nonce,
tx.GasFeeCap,
tx.Gas,
tx.To,
tx.Value,
tx.Data,
[]any{},
}
case EvmTxEIP1559:
return []any{
tx.ChainId,
tx.Nonce,
tx.GasTipCap,
tx.GasFeeCap,
tx.Gas,
tx.To,
tx.Value,
tx.Data,
[]any{},
}
default:
return nil
}
}
func (tx *EvmTx) typeValue() byte {
switch tx.Type {
case EvmTxLegacy:
return 0
case EvmTxEIP2930:
return 1
case EvmTxEIP1559:
return 2
case EvmTxEIP4844:
return 3
default:
return 0xff // :(
}
}
// MarshalBinary transforms the transaction into its binary representation
func (tx *EvmTx) MarshalBinary() ([]byte, error) {
if !tx.Signed {
return tx.SignBytes()
}
switch tx.Type {
case EvmTxLegacy:
f := tx.RlpFields()
f = append(f, tx.Y, tx.R, tx.S)
return rlp.EncodeValue(f)
default:
f := tx.RlpFields()
f = append(f, tx.Y, tx.R, tx.S)
buf, err := rlp.EncodeValue(f)
if err != nil {
return nil, err
}
return append([]byte{tx.typeValue()}, buf...), nil
}
}
// SignBytes returns the bytes used to sign the transaction
func (tx *EvmTx) SignBytes() ([]byte, error) {
switch tx.Type {
case EvmTxLegacy:
f := tx.RlpFields()
if tx.ChainId != 0 {
// if ChainId == 0, we assume no EIP-155
f = append(f, tx.ChainId, 0, 0)
}
return rlp.EncodeValue(f)
default:
buf, err := rlp.EncodeValue(tx.RlpFields())
if err != nil {
return nil, err
}
return append([]byte{tx.typeValue()}, buf...), nil
}
}
// UnmarshalBinary implements encoding.BinaryUnmarshaler
func (tx *EvmTx) UnmarshalBinary(buf []byte) error {
return tx.ParseTransaction(buf)
}
// ParseTransaction will parse an incoming transaction and return an error in case of failure.
// In case of error, the state of tx is undefined.
func (tx *EvmTx) ParseTransaction(buf []byte) error {
if len(buf) < 1 {
return io.ErrUnexpectedEOF
}
if buf[0] >= 0x80 {
// legacy transaction as per https://eips.ethereum.org/EIPS/eip-2718
dec, err := rlp.Decode(buf)
if err != nil {
return err
}
if len(dec) != 1 {
return errors.New("invalid rlp data for legacy transaction")
}
txData, err := typutil.As[[][]byte](dec[0])
if err != nil {
return fmt.Errorf("failed to decode rlp data: %w", err)
}
ln := len(txData)
if ln != 6 && ln != 9 {
return fmt.Errorf("lgacy transaction must have 6 or 9 fields, got %d", ln)
}
tx.Type = EvmTxLegacy
tx.Nonce = rlp.DecodeUint64(txData[0])
tx.GasFeeCap = new(big.Int).SetBytes(txData[1])
tx.Gas = rlp.DecodeUint64(txData[2])
tx.To = "0x" + hex.EncodeToString(txData[3])
tx.Value = new(big.Int).SetBytes(txData[4])
tx.Data = txData[5]
if ln == 9 {
// signed
tx.Signed = true
tx.Y = new(big.Int).SetBytes(txData[6]) // 27|28, or ChainId * 2 + 35 + (v & 1) if EIP-155
tx.R = new(big.Int).SetBytes(txData[7])
tx.S = new(big.Int).SetBytes(txData[8])
} else {
tx.Signed = false
}
return nil
}
switch buf[0] {
case 1: // EvmTxEIP2930
dec, err := rlp.Decode(buf[1:])
if err != nil {
return err
}
if len(dec) != 1 {
return errors.New("invalid rlp data for legacy transaction")
}
txData := dec[0].([]any)
ln := len(txData)
if ln != 8 && ln != 11 {
return fmt.Errorf("EIP-2930 transaction must have 8 or 11 fields, got %d", ln)
}
tx.Type = EvmTxEIP2930
tx.ChainId = rlp.DecodeUint64(txData[0].([]byte))
tx.Nonce = rlp.DecodeUint64(txData[1].([]byte))
tx.GasFeeCap = new(big.Int).SetBytes(txData[2].([]byte))
tx.Gas = rlp.DecodeUint64(txData[3].([]byte))
tx.To = "0x" + hex.EncodeToString(txData[4].([]byte))
tx.Value = new(big.Int).SetBytes(txData[5].([]byte))
tx.Data = txData[6].([]byte)
tx.AccessList = txData[7].([]any) // TODO
if ln == 11 {
tx.Signed = true
tx.Y = new(big.Int).SetBytes(txData[8].([]byte))
tx.R = new(big.Int).SetBytes(txData[9].([]byte))
tx.S = new(big.Int).SetBytes(txData[10].([]byte))
} else {
tx.Signed = false
}
return nil
case 2: // EvmTxEIP1559
dec, err := rlp.Decode(buf[1:])
if err != nil {
return err
}
if len(dec) != 1 {
return errors.New("invalid rlp data for legacy transaction")
}
txData := dec[0].([]any)
ln := len(txData)
if ln != 9 && ln != 12 {
return fmt.Errorf("EIP-1559 transaction must have 9 or 12 fields, got %d", ln)
}
tx.Type = EvmTxEIP1559
tx.ChainId = rlp.DecodeUint64(txData[0].([]byte))
tx.Nonce = rlp.DecodeUint64(txData[1].([]byte))
tx.GasTipCap = new(big.Int).SetBytes(txData[2].([]byte))
tx.GasFeeCap = new(big.Int).SetBytes(txData[3].([]byte))
tx.Gas = rlp.DecodeUint64(txData[4].([]byte))
tx.To = "0x" + hex.EncodeToString(txData[5].([]byte))
tx.Value = new(big.Int).SetBytes(txData[6].([]byte))
tx.Data = txData[7].([]byte)
tx.AccessList = txData[8].([]any) // TODO
if ln == 12 {
tx.Signed = true
tx.Y = new(big.Int).SetBytes(txData[9].([]byte))
tx.R = new(big.Int).SetBytes(txData[10].([]byte))
tx.S = new(big.Int).SetBytes(txData[11].([]byte))
} else {
tx.Signed = false
}
return nil
}
return errors.New("not supported")
}
// Signature returns the parsed secp256k1 signature from the signed transaction.
func (tx *EvmTx) Signature() (*secp256k1.Signature, error) {
if !tx.Signed {
return nil, errors.New("cannot obtain signature of an unsigned transaction")
}
r := new(secp256k1.ModNScalar)
if overflow := r.SetByteSlice(tx.R.Bytes()); overflow {
return nil, errors.New("cannot read signature: invalid value for R >= group order")
}
s := new(secp256k1.ModNScalar)
if overflow := s.SetByteSlice(tx.S.Bytes()); overflow {
return nil, errors.New("cannot read signature: invalid value for S >= group order")
}
v := tx.Y.Uint64()
if tx.Type == EvmTxLegacy {
if v >= 35 {
// EIP-155: v = ChainId * 2 + 35 + (v & 1)
bit := 1 - (v & 1)
v -= 35 + bit
tx.ChainId = v / 2
v = bit
} else {
tx.ChainId = 0
}
}
return secp256k1.NewSignatureWithRecoveryCode(r, s, byte(v)), nil
}
// SenderPubkey recovers the sender's public key from the transaction signature.
func (tx *EvmTx) SenderPubkey() (*secp256k1.PublicKey, error) {
if !tx.Signed {
return nil, errors.New("cannot obtain signature of an unsigned transaction")
}
sig, err := tx.Signature()
if err != nil {
return nil, err
}
// RecoverCompact expects a signature inform V,R,S
buf, err := tx.SignBytes()
if err != nil {
return nil, err
}
pub, err := sig.RecoverPublicKey(gobottle.Hash(buf, sha3.NewLegacyKeccak256))
if err != nil {
return nil, err
}
return pub, nil
}
// SenderAddress recovers and returns the EIP-55 checksummed sender address from the transaction signature.
func (tx *EvmTx) SenderAddress() (string, error) {
pubkey, err := tx.SenderPubkey()
if err != nil {
return "", err
}
addr, err := New(pubkey).Generate("eth")
if err != nil {
return "", err
}
return eip55(addr), nil
}
// Sign signs the transaction using the given key with default signer options.
func (tx *EvmTx) Sign(key crypto.Signer) error {
return tx.SignWithOptions(key, crypto.Hash(0))
}
// SignWithOptions signs the transaction using the given key and signer options.
func (tx *EvmTx) SignWithOptions(key crypto.Signer, opts crypto.SignerOpts) error {
buf, err := tx.SignBytes()
if err != nil {
return err
}
h := gobottle.Hash(buf, sha3.NewLegacyKeccak256)
sig, err := key.Sign(rand.Reader, h, opts)
if err != nil {
return err
}
// expect sig to be in DER format
sigO, err := secp256k1.ParseDERSignature(sig)
if err != nil {
return err
}
// find recovery bit
sigO.BruteforceRecoveryCode(h, key.Public().(*secp256k1.PublicKey))
// apply signature
tx.Signed = true
var v byte
tx.R, tx.S, v = sigO.Export()
if tx.Type == EvmTxLegacy {
if tx.ChainId == 0 {
// super-legacy
tx.Y = big.NewInt(27 + int64(v))
} else {
// EIP-155: v = ChainId * 2 + 35 + (v & 1)
tx.Y = big.NewInt(int64(tx.ChainId)*2 + 35 + int64(v))
}
} else {
tx.Y = big.NewInt(int64(v))
}
return nil
}
// Hash returns the Keccak-256 hash of the signed transaction's binary encoding.
func (tx *EvmTx) Hash() ([]byte, error) {
data, err := tx.MarshalBinary()
if err != nil {
return nil, err
}
return gobottle.Hash(data, sha3.NewLegacyKeccak256), nil
}
// MarshalJSON encodes the transaction as a JSON object with hex-encoded numeric fields.
func (tx *EvmTx) MarshalJSON() ([]byte, error) {
obj := &evmTxJson{
Gas: "0x" + strconv.FormatUint(tx.Gas, 16),
Input: "0x" + hex.EncodeToString(tx.Data),
Nonce: "0x" + strconv.FormatUint(tx.Nonce, 16),
To: tx.To,
Value: "0x" + tx.Value.Text(16),
ChainId: "0x" + strconv.FormatUint(tx.ChainId, 16),
}
if tx.Type == EvmTxLegacy {
obj.GasPrice = "0x" + tx.GasFeeCap.Text(16)
} else {
obj.GasFeeCap = "0x" + tx.GasFeeCap.Text(16)
obj.GasTipCap = "0x" + tx.GasTipCap.Text(16)
}
if tx.Signed {
obj.From, _ = tx.SenderAddress()
obj.V = "0x" + tx.Y.Text(16)
obj.R = "0x" + tx.R.Text(16)
obj.S = "0x" + tx.S.Text(16)
//obj.Hash = gobottle.Hash(tx.????, sha3.NewLegacyKeccak256)
}
return json.Marshal(obj)
}
// UnmarshalJSON decodes a JSON representation into an EvmTx.
func (tx *EvmTx) UnmarshalJSON(b []byte) error {
var obj *evmTxJson
var ok bool
err := json.Unmarshal(b, &obj)
if err != nil {
return err
}
if obj.Gas != "" {
tx.Gas, err = strconv.ParseUint(obj.Gas, 0, 64)
if err != nil {
return err
}
}
if obj.GasFeeCap != "" && obj.GasTipCap != "" {
// EIP-1559
tx.GasFeeCap, ok = new(big.Int).SetString(obj.GasFeeCap, 0)
if !ok {
return errors.New("invalid value in gasPrice")
}
tx.GasTipCap, ok = new(big.Int).SetString(obj.GasTipCap, 0)
if !ok {
return errors.New("invalid value in gasPrice")
}
tx.Type = EvmTxEIP1559
} else if obj.GasPrice != "" {
tx.GasFeeCap, ok = new(big.Int).SetString(obj.GasPrice, 0)
if !ok {
return errors.New("invalid value in gasPrice")
}
}
if obj.Input != "" {
tx.Data, err = parseEthBufferHex(obj.Input)
if err != nil {
return err
}
}
if obj.Nonce != "" {
tx.Nonce, err = strconv.ParseUint(obj.Nonce, 0, 64)
if err != nil {
return err
}
}
if obj.To != "" {
tx.To = obj.To
}
if obj.Value != "" {
tx.Value, ok = new(big.Int).SetString(obj.Value, 0)
if !ok {
return errors.New("invalid value in value")
}
}
if obj.ChainId != "" {
tx.ChainId, err = strconv.ParseUint(obj.ChainId, 0, 64)
if err != nil {
return err
}
}
if obj.V != "" {
tx.Y, ok = new(big.Int).SetString(obj.V, 0)
if !ok {
return errors.New("invalid value in v")
}
}
if obj.R != "" {
tx.R, ok = new(big.Int).SetString(obj.R, 0)
if !ok {
return errors.New("invalid value in r")
}
}
if obj.S != "" {
tx.S, ok = new(big.Int).SetString(obj.S, 0)
if !ok {
return errors.New("invalid value in s")
}
}
return nil
}
func parseEthBufferHex(buf string) ([]byte, error) {
if len(buf) < 2 {
return nil, errors.New("eth buffer must start with 0x")
}
return hex.DecodeString(buf[2:])
}
// Call sets the transaction's Data field to the ABI-encoded method call for the given
// method signature and parameters.
func (tx *EvmTx) Call(method string, params ...any) error {
res, err := EvmCall(method, params...)
if err != nil {
return err
}
tx.Data = res
return nil
}