-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtypes.go
More file actions
574 lines (507 loc) · 19.2 KB
/
Copy pathtypes.go
File metadata and controls
574 lines (507 loc) · 19.2 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
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
package types
import (
"bytes"
"errors"
"fmt"
"math/big"
"github.com/holiman/uint256"
"github.com/onflow/flow-evm-gateway/models"
errs "github.com/onflow/flow-evm-gateway/models/errors"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto/kzg4844"
)
// TransactionArgs represents the arguments to construct a new transaction
// or a message call.
type TransactionArgs struct {
From *common.Address `json:"from"`
To *common.Address `json:"to"`
Gas *hexutil.Uint64 `json:"gas"`
GasPrice *hexutil.Big `json:"gasPrice"`
MaxFeePerGas *hexutil.Big `json:"maxFeePerGas"`
MaxPriorityFeePerGas *hexutil.Big `json:"maxPriorityFeePerGas"`
Value *hexutil.Big `json:"value"`
Nonce *hexutil.Uint64 `json:"nonce"`
// We accept "data" and "input" for backwards-compatibility reasons.
// "input" is the newer name and should be preferred by clients.
// Issue detail: https://github.com/ethereum/go-ethereum/issues/15628
Data *hexutil.Bytes `json:"data"`
Input *hexutil.Bytes `json:"input"`
// Introduced by AccessListTxType transaction.
AccessList *types.AccessList `json:"accessList,omitempty"`
ChainID *hexutil.Big `json:"chainId,omitempty"`
// For BlobTxType
BlobFeeCap *hexutil.Big `json:"maxFeePerBlobGas"`
BlobHashes []common.Hash `json:"blobVersionedHashes,omitempty"`
// For BlobTxType transactions with blob sidecar
Blobs []kzg4844.Blob `json:"blobs"`
Commitments []kzg4844.Commitment `json:"commitments"`
Proofs []kzg4844.Proof `json:"proofs"`
// For SetCodeTxType
AuthorizationList []types.SetCodeAuthorization `json:"authorizationList"`
}
func (txArgs TransactionArgs) Validate() error {
// Prevent accidental erroneous usage of both 'input' and 'data' (show stopper)
if txArgs.Data != nil && txArgs.Input != nil && !bytes.Equal(*txArgs.Data, *txArgs.Input) {
return errs.NewInvalidTransactionError(
errors.New(`ambiguous request: both "data" and "input" are set and are not identical`),
)
}
// Place data on 'data'
var data []byte
if txArgs.Input != nil {
txArgs.Data = txArgs.Input
}
if txArgs.Data != nil {
data = *txArgs.Data
}
txDataLen := len(data)
// Contract creation doesn't validate call data, handle first
if txArgs.To == nil {
// Contract creation should contain sufficient data to deploy a contract. A
// typical error is omitting sender due to some quirk in the javascript call
// e.g. https://github.com/ethereum/go-ethereum/issues/16106.
if txDataLen == 0 {
// Prevent sending ether into black hole (show stopper)
if txArgs.Value != nil && txArgs.Value.ToInt().Cmp(big.NewInt(0)) > 0 {
return errs.NewInvalidTransactionError(
errors.New("transaction will create a contract with value but empty code"),
)
}
// No value submitted at least, critically Warn, but don't blow up
return errs.NewInvalidTransactionError(errors.New("transaction will create a contract with empty code"))
}
}
// Not a contract creation, validate as a plain transaction
if txArgs.To != nil {
to := *txArgs.To
if bytes.Equal(to.Bytes(), common.Address{}.Bytes()) {
return errs.NewInvalidTransactionError(errors.New("transaction recipient is the zero address"))
}
}
return nil
}
// ToTransaction converts the arguments to a transaction.
func (txArgs TransactionArgs) ToTransaction(
defaultType int,
defaultGas uint64,
) *types.Transaction {
nonce := uint64(0)
if txArgs.Nonce != nil {
nonce = uint64(*txArgs.Nonce)
}
if txArgs.Gas == nil {
gas := hexutil.Uint64(defaultGas)
txArgs.Gas = &gas
}
usedType := types.LegacyTxType
switch {
case txArgs.AuthorizationList != nil || defaultType == types.SetCodeTxType:
usedType = types.SetCodeTxType
case txArgs.BlobHashes != nil || defaultType == types.BlobTxType:
usedType = types.BlobTxType
case txArgs.MaxFeePerGas != nil || defaultType == types.DynamicFeeTxType:
usedType = types.DynamicFeeTxType
case txArgs.AccessList != nil || defaultType == types.AccessListTxType:
usedType = types.AccessListTxType
}
// Make it possible to default to newer tx, but use legacy if gasprice is provided
if txArgs.GasPrice != nil {
usedType = types.LegacyTxType
}
var data types.TxData
switch usedType {
case types.SetCodeTxType:
al := types.AccessList{}
if txArgs.AccessList != nil {
al = *txArgs.AccessList
}
authList := []types.SetCodeAuthorization{}
if txArgs.AuthorizationList != nil {
authList = txArgs.AuthorizationList
}
data = &types.SetCodeTx{
To: *txArgs.To,
ChainID: uint256.MustFromBig(txArgs.ChainID.ToInt()),
Nonce: nonce,
Gas: uint64(*txArgs.Gas),
GasFeeCap: uint256.MustFromBig((*big.Int)(txArgs.MaxFeePerGas)),
GasTipCap: uint256.MustFromBig((*big.Int)(txArgs.MaxPriorityFeePerGas)),
Value: uint256.MustFromBig((*big.Int)(txArgs.Value)),
Data: txArgs.data(),
AccessList: al,
AuthList: authList,
}
case types.BlobTxType:
al := types.AccessList{}
if txArgs.AccessList != nil {
al = *txArgs.AccessList
}
data = &types.BlobTx{
To: *txArgs.To,
ChainID: uint256.MustFromBig((*big.Int)(txArgs.ChainID)),
Nonce: nonce,
Gas: uint64(*txArgs.Gas),
GasFeeCap: uint256.MustFromBig((*big.Int)(txArgs.MaxFeePerGas)),
GasTipCap: uint256.MustFromBig((*big.Int)(txArgs.MaxPriorityFeePerGas)),
Value: uint256.MustFromBig((*big.Int)(txArgs.Value)),
Data: txArgs.data(),
AccessList: al,
BlobHashes: txArgs.BlobHashes,
BlobFeeCap: uint256.MustFromBig((*big.Int)(txArgs.BlobFeeCap)),
}
if txArgs.Blobs != nil {
data.(*types.BlobTx).Sidecar = &types.BlobTxSidecar{
Blobs: txArgs.Blobs,
Commitments: txArgs.Commitments,
Proofs: txArgs.Proofs,
}
}
case types.DynamicFeeTxType:
al := types.AccessList{}
if txArgs.AccessList != nil {
al = *txArgs.AccessList
}
data = &types.DynamicFeeTx{
To: txArgs.To,
ChainID: (*big.Int)(txArgs.ChainID),
Nonce: nonce,
Gas: uint64(*txArgs.Gas),
GasFeeCap: (*big.Int)(txArgs.MaxFeePerGas),
GasTipCap: (*big.Int)(txArgs.MaxPriorityFeePerGas),
Value: (*big.Int)(txArgs.Value),
Data: txArgs.data(),
AccessList: al,
}
case types.AccessListTxType:
al := types.AccessList{}
if txArgs.AccessList != nil {
al = *txArgs.AccessList
}
data = &types.AccessListTx{
To: txArgs.To,
ChainID: (*big.Int)(txArgs.ChainID),
Nonce: nonce,
Gas: uint64(*txArgs.Gas),
GasPrice: (*big.Int)(txArgs.GasPrice),
Value: (*big.Int)(txArgs.Value),
Data: txArgs.data(),
AccessList: al,
}
default:
data = &types.LegacyTx{
To: txArgs.To,
Nonce: nonce,
Gas: uint64(*txArgs.Gas),
GasPrice: (*big.Int)(txArgs.GasPrice),
Value: (*big.Int)(txArgs.Value),
Data: txArgs.data(),
}
}
return types.NewTx(data)
}
// data retrieves the transaction calldata. Input field is preferred.
func (txArgs *TransactionArgs) data() []byte {
if txArgs.Input != nil {
return *txArgs.Input
}
if txArgs.Data != nil {
return *txArgs.Data
}
return nil
}
// AccessListResult returns an optional accesslist
// It's the result of the `debug_createAccessList` RPC call.
// It contains an error if the transaction itself failed.
type AccessListResult struct {
Accesslist *types.AccessList `json:"accessList"`
Error string `json:"error,omitempty"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
}
type FeeHistoryResult struct {
OldestBlock *hexutil.Big `json:"oldestBlock"`
Reward [][]*hexutil.Big `json:"reward,omitempty"`
BaseFee []*hexutil.Big `json:"baseFeePerGas,omitempty"`
GasUsedRatio []float64 `json:"gasUsedRatio"`
}
// AccountResult structs for GetProof
type AccountResult struct {
Address common.Address `json:"address"`
AccountProof []string `json:"accountProof"`
Balance *hexutil.Big `json:"balance"`
CodeHash common.Hash `json:"codeHash"`
Nonce hexutil.Uint64 `json:"nonce"`
StorageHash common.Hash `json:"storageHash"`
StorageProof []StorageResult `json:"storageProof"`
}
type StorageResult struct {
Key string `json:"key"`
Value *hexutil.Big `json:"value"`
Proof []string `json:"proof"`
}
// Transaction represents a transaction that will serialize to the RPC representation of a transaction
type Transaction struct {
BlockHash *common.Hash `json:"blockHash"`
BlockNumber *hexutil.Big `json:"blockNumber"`
From common.Address `json:"from"`
Gas hexutil.Uint64 `json:"gas"`
GasPrice *hexutil.Big `json:"gasPrice"`
GasFeeCap *hexutil.Big `json:"maxFeePerGas,omitempty"`
GasTipCap *hexutil.Big `json:"maxPriorityFeePerGas,omitempty"`
MaxFeePerBlobGas *hexutil.Big `json:"maxFeePerBlobGas,omitempty"`
Hash common.Hash `json:"hash"`
Input hexutil.Bytes `json:"input"`
Nonce hexutil.Uint64 `json:"nonce"`
To *common.Address `json:"to"`
TransactionIndex *hexutil.Uint64 `json:"transactionIndex"`
Value *hexutil.Big `json:"value"`
Type hexutil.Uint64 `json:"type"`
Accesses *types.AccessList `json:"accessList,omitempty"`
ChainID *hexutil.Big `json:"chainId,omitempty"`
BlobVersionedHashes []common.Hash `json:"blobVersionedHashes,omitempty"`
AuthorizationList []types.SetCodeAuthorization `json:"authorizationList,omitempty"`
V *hexutil.Big `json:"v"`
R *hexutil.Big `json:"r"`
S *hexutil.Big `json:"s"`
YParity *hexutil.Uint64 `json:"yParity,omitempty"`
size uint64
}
func (tx *Transaction) Size() uint64 {
return tx.size
}
func NewTransactionResult(
tx models.Transaction,
receipt models.Receipt,
networkID *big.Int,
) (*Transaction, error) {
res, err := NewTransaction(tx, networkID)
if err != nil {
return nil, err
}
index := uint64(receipt.TransactionIndex)
res.TransactionIndex = (*hexutil.Uint64)(&index)
res.BlockHash = &receipt.BlockHash
res.BlockNumber = (*hexutil.Big)(receipt.BlockNumber)
return res, nil
}
func NewTransaction(
tx models.Transaction,
networkID *big.Int,
) (*Transaction, error) {
from, err := tx.From()
if err != nil {
return nil, fmt.Errorf(
"failed to get from address for tx: %s, with: %w",
tx.Hash(),
err,
)
}
v, r, s := tx.RawSignatureValues()
// These are the common fields through all the transaction types
result := &Transaction{
Type: hexutil.Uint64(tx.Type()),
From: from,
Gas: hexutil.Uint64(tx.Gas()),
GasPrice: (*hexutil.Big)(tx.GasPrice()),
Hash: tx.Hash(),
Input: tx.Data(),
Nonce: hexutil.Uint64(tx.Nonce()),
To: tx.To(),
Value: (*hexutil.Big)(tx.Value()),
V: (*hexutil.Big)(v),
R: (*hexutil.Big)(r),
S: (*hexutil.Big)(s),
size: tx.Size(),
}
// if a legacy transaction has an EIP-155 chain id, include it explicitly
if id := tx.ChainId(); id.Sign() != 0 {
result.ChainID = (*hexutil.Big)(id)
}
// After the Pectra hard-fork, the full list of supported tx types is:
// LegacyTxType = 0x00
// AccessListTxType = 0x01
// DynamicFeeTxType = 0x02
// BlobTxType = 0x03
// SetCodeTxType = 0x04
// Each newly-added tx type, is backwards-compatible.
// It supports the fields of previous tx types and it
// introduces its own fields as well. By comparing
// with `if tx.Type() > SomeTxType`, we are
// able to save some duplicated lines of code, and
// incrementally apply the extra fields to their
// respective tx type. For example, when:
// `tx.Type()` is `DynamicFeeTxType`, the
// following conditions are true:
// `tx.Type() > LegacyTxType`
// `tx.Type() > AccessListTxType`
// but the rest are not.
// A `DynamicFeeTxType` supports the fields of
// `LegacyTxType` & `AccessListTxType`, but not
// the fields of `SetCodeTxType`.
if tx.Type() > types.LegacyTxType {
al := tx.AccessList()
yparity := hexutil.Uint64(v.Sign())
result.Accesses = &al
result.YParity = &yparity
result.ChainID = (*hexutil.Big)(tx.ChainId())
}
if tx.Type() > types.AccessListTxType {
result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap())
result.GasTipCap = (*hexutil.Big)(tx.GasTipCap())
// Since BaseFee is `0`, this is the max gas price
// the sender is willing to pay.
result.GasPrice = (*hexutil.Big)(tx.GasFeeCap())
result.ChainID = (*hexutil.Big)(tx.ChainId())
}
if tx.Type() > types.DynamicFeeTxType {
result.MaxFeePerBlobGas = (*hexutil.Big)(tx.BlobGasFeeCap())
result.BlobVersionedHashes = tx.BlobHashes()
result.ChainID = (*hexutil.Big)(tx.ChainId())
}
// The `AuthorizationList` field became available with the introduction
// of https://eip7702.io/#specification, under the `SetCodeTxType`
if tx.Type() > types.BlobTxType {
result.AuthorizationList = tx.SetCodeAuthorizations()
result.ChainID = (*hexutil.Big)(tx.ChainId())
}
return result, nil
}
// SignTransactionResult represents a RLP encoded signed transaction.
type SignTransactionResult struct {
Raw hexutil.Bytes `json:"raw"`
Tx *types.Transaction `json:"tx"`
}
// OverrideAccount indicates the overriding fields of account during the execution
// of a message call.
// Note, state and stateDiff can't be specified at the same time. If state is
// set, message execution will only use the data in the given state. Otherwise
// if stateDiff is set, all diff will be applied first and then execute the call
// message.
type OverrideAccount struct {
Nonce *hexutil.Uint64 `json:"nonce"`
Code *hexutil.Bytes `json:"code"`
Balance *hexutil.Big `json:"balance"`
State map[common.Hash]common.Hash `json:"state"`
StateDiff map[common.Hash]common.Hash `json:"stateDiff"`
MovePrecompileTo *common.Address `json:"movePrecompileToAddress"`
}
// StateOverride is the collection of overridden accounts.
type StateOverride map[common.Address]OverrideAccount
// BlockOverrides is a set of header fields to override.
type BlockOverrides struct {
Number *hexutil.Big
Difficulty *hexutil.Big // No-op if we're simulating post-merge calls.
Time *hexutil.Uint64
GasLimit *hexutil.Uint64
FeeRecipient *common.Address
PrevRandao *common.Hash
BaseFeePerGas *hexutil.Big
BlobBaseFee *hexutil.Big
BeaconRoot *common.Hash
Withdrawals *types.Withdrawals
}
type Block struct {
Number hexutil.Uint64 `json:"number"`
Hash common.Hash `json:"hash"`
ParentHash common.Hash `json:"parentHash"`
Nonce types.BlockNonce `json:"nonce"`
Sha3Uncles common.Hash `json:"sha3Uncles"`
LogsBloom hexutil.Bytes `json:"logsBloom"`
TransactionsRoot common.Hash `json:"transactionsRoot"`
StateRoot common.Hash `json:"stateRoot"`
ReceiptsRoot common.Hash `json:"receiptsRoot"`
Miner common.Address `json:"miner"`
Difficulty hexutil.Uint64 `json:"difficulty"`
ExtraData hexutil.Bytes `json:"extraData"`
Size hexutil.Uint64 `json:"size"`
GasLimit hexutil.Uint64 `json:"gasLimit"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
Timestamp hexutil.Uint64 `json:"timestamp"`
Transactions any `json:"transactions"`
Uncles []common.Hash `json:"uncles"`
MixHash common.Hash `json:"mixHash"`
BaseFeePerGas hexutil.Big `json:"baseFeePerGas"`
// SlotNumber was added by EIP-7843 and is ignored in legacy headers.
SlotNumber *hexutil.Uint64 `json:"slotNumber,omitempty"`
}
type BlockHeader struct {
Number hexutil.Uint64 `json:"number"`
Hash common.Hash `json:"hash"`
ParentHash common.Hash `json:"parentHash"`
Nonce types.BlockNonce `json:"nonce"`
Sha3Uncles common.Hash `json:"sha3Uncles"`
LogsBloom hexutil.Bytes `json:"logsBloom"`
TransactionsRoot common.Hash `json:"transactionsRoot"`
StateRoot common.Hash `json:"stateRoot"`
ReceiptsRoot common.Hash `json:"receiptsRoot"`
Miner common.Address `json:"miner"`
ExtraData hexutil.Bytes `json:"extraData"`
GasLimit hexutil.Uint64 `json:"gasLimit"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
Timestamp hexutil.Uint64 `json:"timestamp"`
Difficulty hexutil.Uint64 `json:"difficulty"`
}
type SyncStatus struct {
StartingBlock hexutil.Uint64 `json:"startingBlock"`
CurrentBlock hexutil.Uint64 `json:"currentBlock"`
HighestBlock hexutil.Uint64 `json:"highestBlock"`
}
// MarshalReceipt takes a receipt and its associated transaction,
// and marshals the receipt to the proper structure needed by
// eth_getTransactionReceipt.
func MarshalReceipt(
receipt *models.Receipt,
tx models.Transaction,
) (map[string]any, error) {
from, err := tx.From()
if err != nil {
return map[string]any{}, err
}
txHash := tx.Hash()
fields := map[string]any{
"blockHash": receipt.BlockHash,
"blockNumber": hexutil.Uint64(receipt.BlockNumber.Uint64()),
"transactionHash": txHash,
"transactionIndex": hexutil.Uint64(receipt.TransactionIndex),
"from": from,
"to": nil,
"gasUsed": hexutil.Uint64(receipt.GasUsed),
"cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
"contractAddress": nil,
"logs": receipt.Logs,
"logsBloom": receipt.Bloom,
"type": hexutil.Uint(tx.Type()),
"effectiveGasPrice": (*hexutil.Big)(receipt.EffectiveGasPrice),
}
// Dynamically fallback to `BaseFeePerGas` when computing `EffectiveGasPrice`
// to fix historical gasPrice = 0 issues.
// This avoids the need to re-index the entire chain for previously stored
// transactions. For any transaction that had a `0` gas price, regardless
// whether they were COA interactions or regular EVM, we
// set the `effectiveGasPrice` to the value of `BaseFeePerGas`,
// which is the minimum amount of gas price required by any
// transaction, in order to comply with EIP-1559.
if receipt.EffectiveGasPrice.Sign() == 0 {
fields["effectiveGasPrice"] = (*hexutil.Big)(models.BaseFeePerGas)
}
if tx.To() != nil {
fields["to"] = tx.To()
}
fields["status"] = hexutil.Uint(receipt.Status)
if receipt.Logs == nil {
fields["logs"] = []*types.Log{}
}
if tx.Type() == types.BlobTxType {
fields["blobGasUsed"] = hexutil.Uint64(receipt.BlobGasUsed)
fields["blobGasPrice"] = (*hexutil.Big)(receipt.BlobGasPrice)
}
// If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
if receipt.ContractAddress != (common.Address{}) {
fields["contractAddress"] = receipt.ContractAddress
}
if len(receipt.RevertReason) > 0 {
fields["revertReason"] = hexutil.Bytes(receipt.RevertReason)
}
return fields, nil
}