/
client.go
1620 lines (1424 loc) · 42.2 KB
/
client.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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 Coinbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ethereum
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"math/big"
"net/http"
"strconv"
"time"
RosettaTypes "github.com/coinbase/rosetta-sdk-go/types"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/core/types"
EthTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth/tracers"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc"
"golang.org/x/sync/semaphore"
)
const (
gethHTTPTimeout = 120 * time.Second
maxTraceConcurrency = int64(16) // nolint:gomnd
semaphoreTraceWeight = int64(1) // nolint:gomnd
// eip1559TxType is the EthTypes.Transaction.Type() value that indicates this transaction
// follows EIP-1559.
eip1559TxType = 2
)
// Client allows for querying a set of specific Ethereum endpoints in an
// idempotent manner. Client relies on the eth_*, debug_*, admin_*, and txpool_*
// methods and on the graphql endpoint.
//
// Client borrows HEAVILY from https://github.com/ethereum/go-ethereum/tree/master/ethclient.
type Client struct {
p *params.ChainConfig
tc *tracers.TraceConfig
c JSONRPC
g GraphQL
traceSemaphore *semaphore.Weighted
skipAdminCalls bool
}
// NewClient creates a Client that from the provided url and params.
func NewClient(url string, params *params.ChainConfig, skipAdminCalls bool) (*Client, error) {
c, err := rpc.DialHTTPWithClient(url, &http.Client{
Timeout: gethHTTPTimeout,
})
if err != nil {
return nil, fmt.Errorf("%w: unable to dial node", err)
}
tc, err := loadTraceConfig()
if err != nil {
return nil, fmt.Errorf("%w: unable to load trace config", err)
}
g, err := newGraphQLClient(url)
if err != nil {
return nil, fmt.Errorf("%w: unable to create GraphQL client", err)
}
return &Client{params, tc, c, g, semaphore.NewWeighted(maxTraceConcurrency), skipAdminCalls}, nil
}
// Close shuts down the RPC client connection.
func (ec *Client) Close() {
ec.c.Close()
}
// Status returns geth status information
// for determining node healthiness.
func (ec *Client) Status(ctx context.Context) (
*RosettaTypes.BlockIdentifier,
int64,
*RosettaTypes.SyncStatus,
[]*RosettaTypes.Peer,
error,
) {
header, err := ec.blockHeaderByNumber(ctx, nil)
if err != nil {
return nil, -1, nil, nil, err
}
progress, err := ec.syncProgress(ctx)
if err != nil {
return nil, -1, nil, nil, err
}
var syncStatus *RosettaTypes.SyncStatus
if progress != nil {
currentIndex := int64(progress.CurrentBlock)
targetIndex := int64(progress.HighestBlock)
syncStatus = &RosettaTypes.SyncStatus{
CurrentIndex: ¤tIndex,
TargetIndex: &targetIndex,
}
}
peers, err := ec.peers(ctx)
if err != nil {
return nil, -1, nil, nil, err
}
return &RosettaTypes.BlockIdentifier{
Hash: header.Hash().Hex(),
Index: header.Number.Int64(),
},
convertTime(header.Time),
syncStatus,
peers,
nil
}
// PendingNonceAt returns the account nonce of the given account in the pending state.
// This is the nonce that should be used for the next transaction.
func (ec *Client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
var result hexutil.Uint64
err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, "pending")
return uint64(result), err
}
// SuggestGasPrice retrieves the currently suggested gas price to allow a timely
// execution of a transaction.
func (ec *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
var hex hexutil.Big
if err := ec.c.CallContext(ctx, &hex, "eth_gasPrice"); err != nil {
return nil, err
}
return (*big.Int)(&hex), nil
}
// Peers retrieves all peers of the node.
func (ec *Client) peers(ctx context.Context) ([]*RosettaTypes.Peer, error) {
var info []*p2p.PeerInfo
if ec.skipAdminCalls {
return []*RosettaTypes.Peer{}, nil
}
if err := ec.c.CallContext(ctx, &info, "admin_peers"); err != nil {
return nil, err
}
peers := make([]*RosettaTypes.Peer, len(info))
for i, peerInfo := range info {
peers[i] = &RosettaTypes.Peer{
PeerID: peerInfo.ID,
Metadata: map[string]interface{}{
"name": peerInfo.Name,
"enode": peerInfo.Enode,
"caps": peerInfo.Caps,
"enr": peerInfo.ENR,
"protocols": peerInfo.Protocols,
},
}
}
return peers, nil
}
// SendTransaction injects a signed transaction into the pending pool for execution.
//
// If the transaction was a contract creation use the TransactionReceipt method to get the
// contract address after the transaction has been mined.
func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error {
data, err := rlp.EncodeToBytes(tx)
if err != nil {
return err
}
return ec.c.CallContext(ctx, nil, "eth_sendRawTransaction", hexutil.Encode(data))
}
func toBlockNumArg(number *big.Int) string {
if number == nil {
return "latest"
}
pending := big.NewInt(-1)
if number.Cmp(pending) == 0 {
return "pending"
}
return hexutil.EncodeBig(number)
}
// Transaction returns the transaction response of the Transaction identified
// by *RosettaTypes.TransactionIdentifier hash
func (ec *Client) Transaction(
ctx context.Context,
blockIdentifier *RosettaTypes.BlockIdentifier,
transactionIdentifier *RosettaTypes.TransactionIdentifier,
) (*RosettaTypes.Transaction, error) {
if transactionIdentifier.Hash == "" {
return nil, errors.New("transaction hash is required")
}
var raw json.RawMessage
err := ec.c.CallContext(ctx, &raw, "eth_getTransactionByHash", transactionIdentifier.Hash)
if err != nil {
return nil, fmt.Errorf("%w: transaction fetch failed", err)
} else if len(raw) == 0 {
return nil, ethereum.NotFound
}
// Decode transaction
var body rpcTransaction
if err := json.Unmarshal(raw, &body); err != nil {
return nil, err
}
var header *types.Header
if blockIdentifier.Hash != "" {
header, err = ec.blockHeaderByHash(ctx, blockIdentifier.Hash)
} else {
header, err = ec.blockHeaderByNumber(ctx, big.NewInt(blockIdentifier.Index))
}
if err != nil {
return nil, fmt.Errorf("%w: could not get block header for %x", err, blockIdentifier.Hash)
}
receipt, err := ec.transactionReceipt(ctx, body.tx.Hash())
if receipt.BlockHash != *body.BlockHash {
return nil, fmt.Errorf(
"%w: expected block hash %s for transaction but got %s",
ErrBlockOrphaned,
body.BlockHash.Hex(),
receipt.BlockHash.Hex(),
)
}
if err != nil {
return nil, fmt.Errorf("%w: could not get receipt for %x", err, body.tx.Hash())
}
var traces *Call
var rawTraces json.RawMessage
var addTraces bool
if header.Number.Int64() != GenesisBlockIndex { // not possible to get traces at genesis
addTraces = true
traces, rawTraces, err = ec.getTransactionTraces(ctx, body.tx.Hash())
if err != nil {
return nil, fmt.Errorf("%w: could not get traces for %x", err, body.tx.Hash())
}
}
loadedTx := body.LoadedTransaction()
loadedTx.Transaction = body.tx
feeAmount, feeBurned, err := calculateGas(body.tx, receipt, *header)
if err != nil {
return nil, err
}
loadedTx.FeeAmount = feeAmount
loadedTx.FeeBurned = feeBurned
loadedTx.Miner = MustChecksum(header.Coinbase.Hex())
loadedTx.Receipt = receipt
if addTraces {
loadedTx.Trace = traces
loadedTx.RawTrace = rawTraces
}
tx, err := ec.populateTransaction(loadedTx)
if err != nil {
return nil, fmt.Errorf("%w: cannot parse %s", err, loadedTx.Transaction.Hash().Hex())
}
return tx, nil
}
// Block returns a populated block at the *RosettaTypes.PartialBlockIdentifier.
// If neither the hash or index is populated in the *RosettaTypes.PartialBlockIdentifier,
// the current block is returned.
func (ec *Client) Block(
ctx context.Context,
blockIdentifier *RosettaTypes.PartialBlockIdentifier,
) (*RosettaTypes.Block, error) {
if blockIdentifier != nil {
if blockIdentifier.Hash != nil {
return ec.getParsedBlock(ctx, "eth_getBlockByHash", *blockIdentifier.Hash, true)
}
if blockIdentifier.Index != nil {
return ec.getParsedBlock(
ctx,
"eth_getBlockByNumber",
toBlockNumArg(big.NewInt(*blockIdentifier.Index)),
true,
)
}
}
return ec.getParsedBlock(ctx, "eth_getBlockByNumber", toBlockNumArg(nil), true)
}
// Header returns a block header from the current canonical chain. If number is
// nil, the latest known header is returned.
func (ec *Client) blockHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
var head *types.Header
err := ec.c.CallContext(ctx, &head, "eth_getBlockByNumber", toBlockNumArg(number), false)
if err == nil && head == nil {
return nil, ethereum.NotFound
}
return head, err
}
// Header returns a block header from the current canonical chain. If hash is empty
// it returns error.
func (ec *Client) blockHeaderByHash(ctx context.Context, hash string) (*types.Header, error) {
var head *types.Header
if hash == "" {
return nil, errors.New("hash is empty")
}
err := ec.c.CallContext(ctx, &head, "eth_getBlockByHash", hash, false)
if err == nil && head == nil {
return nil, ethereum.NotFound
}
return head, err
}
type rpcBlock struct {
Hash common.Hash `json:"hash"`
Transactions []rpcTransaction `json:"transactions"`
UncleHashes []common.Hash `json:"uncles"`
}
func (ec *Client) getUncles(
ctx context.Context,
head *types.Header,
body *rpcBlock,
) ([]*types.Header, error) {
// Quick-verify transaction and uncle lists. This mostly helps with debugging the server.
if head.UncleHash == types.EmptyUncleHash && len(body.UncleHashes) > 0 {
return nil, fmt.Errorf(
"server returned non-empty uncle list but block header indicates no uncles",
)
}
if head.UncleHash != types.EmptyUncleHash && len(body.UncleHashes) == 0 {
return nil, fmt.Errorf(
"server returned empty uncle list but block header indicates uncles",
)
}
if head.TxHash == types.EmptyRootHash && len(body.Transactions) > 0 {
return nil, fmt.Errorf(
"server returned non-empty transaction list but block header indicates no transactions",
)
}
if head.TxHash != types.EmptyRootHash && len(body.Transactions) == 0 {
return nil, fmt.Errorf(
"server returned empty transaction list but block header indicates transactions",
)
}
// Load uncles because they are not included in the block response.
var uncles []*types.Header
if len(body.UncleHashes) > 0 {
uncles = make([]*types.Header, len(body.UncleHashes))
reqs := make([]rpc.BatchElem, len(body.UncleHashes))
for i := range reqs {
reqs[i] = rpc.BatchElem{
Method: "eth_getUncleByBlockHashAndIndex",
Args: []interface{}{body.Hash, hexutil.EncodeUint64(uint64(i))},
Result: &uncles[i],
}
}
if err := ec.c.BatchCallContext(ctx, reqs); err != nil {
return nil, err
}
for i := range reqs {
if reqs[i].Error != nil {
return nil, reqs[i].Error
}
if uncles[i] == nil {
return nil, fmt.Errorf(
"got null header for uncle %d of block %x",
i,
body.Hash[:],
)
}
}
}
return uncles, nil
}
func (ec *Client) getBlock(
ctx context.Context,
blockMethod string,
args ...interface{},
) (
*types.Block,
[]*loadedTransaction,
error,
) {
var raw json.RawMessage
err := ec.c.CallContext(ctx, &raw, blockMethod, args...)
if err != nil {
return nil, nil, fmt.Errorf("%w: block fetch failed", err)
} else if len(raw) == 0 {
return nil, nil, ethereum.NotFound
}
// Decode header and transactions
var head types.Header
var body rpcBlock
if err := json.Unmarshal(raw, &head); err != nil {
return nil, nil, err
}
if err := json.Unmarshal(raw, &body); err != nil {
return nil, nil, err
}
uncles, err := ec.getUncles(ctx, &head, &body)
if err != nil {
return nil, nil, fmt.Errorf("%w: unable to get uncles", err)
}
// Get all transaction receipts
receipts, err := ec.getBlockReceipts(ctx, body.Hash, body.Transactions)
if err != nil {
return nil, nil, fmt.Errorf("%w: could not get receipts for %x", err, body.Hash[:])
}
// Get block traces (not possible to make idempotent block transaction trace requests)
//
// We fetch traces last because we want to avoid limiting the number of other
// block-related data fetches we perform concurrently (we limit the number of
// concurrent traces that are computed to 16 to avoid overwhelming geth).
var traces []*rpcCall
var rawTraces []*rpcRawCall
var addTraces bool
if head.Number.Int64() != GenesisBlockIndex { // not possible to get traces at genesis
addTraces = true
traces, rawTraces, err = ec.getBlockTraces(ctx, body.Hash)
if err != nil {
return nil, nil, fmt.Errorf("%w: could not get traces for %x", err, body.Hash[:])
}
}
// Convert all txs to loaded txs
txs := make([]*types.Transaction, len(body.Transactions))
loadedTxs := make([]*loadedTransaction, len(body.Transactions))
for i, tx := range body.Transactions {
txs[i] = tx.tx
receipt := receipts[i]
if err != nil {
return nil, nil, fmt.Errorf("%w: failure getting effective gas price", err)
}
loadedTxs[i] = tx.LoadedTransaction()
loadedTxs[i].Transaction = txs[i]
feeAmount, feeBurned, err := calculateGas(txs[i], receipt, head)
if err != nil {
return nil, nil, err
}
loadedTxs[i].FeeAmount = feeAmount
loadedTxs[i].FeeBurned = feeBurned
loadedTxs[i].Miner = MustChecksum(head.Coinbase.Hex())
loadedTxs[i].Receipt = receipt
// Continue if calls does not exist (occurs at genesis)
if !addTraces {
continue
}
loadedTxs[i].Trace = traces[i].Result
loadedTxs[i].RawTrace = rawTraces[i].Result
}
return types.NewBlockWithHeader(&head).WithBody(txs, uncles), loadedTxs, nil
}
func calculateGas(
tx *types.Transaction,
txReceipt *types.Receipt,
head types.Header,
) (
*big.Int, *big.Int, error,
) {
gasUsed := new(big.Int).SetUint64(txReceipt.GasUsed)
gasPrice, err := effectiveGasPrice(tx, head.BaseFee)
if err != nil {
return nil, nil, fmt.Errorf("%w: failure getting effective gas price", err)
}
feeAmount := new(big.Int).Mul(gasUsed, gasPrice)
var feeBurned *big.Int
if head.BaseFee != nil { // EIP-1559
feeBurned = new(big.Int).Mul(gasUsed, head.BaseFee)
}
return feeAmount, feeBurned, nil
}
// effectiveGasPrice returns the price of gas charged to this transaction to be included in the
// block.
func effectiveGasPrice(tx *EthTypes.Transaction, baseFee *big.Int) (*big.Int, error) {
if tx.Type() != eip1559TxType {
return tx.GasPrice(), nil
}
// For EIP-1559 the gas price is determined by the base fee & miner tip instead
// of the tx-specified gas price.
tip, err := tx.EffectiveGasTip(baseFee)
if err != nil {
return nil, err
}
return new(big.Int).Add(tip, baseFee), nil
}
func (ec *Client) getTransactionTraces(
ctx context.Context,
transactionHash common.Hash,
) (*Call, json.RawMessage, error) {
if err := ec.traceSemaphore.Acquire(ctx, semaphoreTraceWeight); err != nil {
return nil, nil, err
}
defer ec.traceSemaphore.Release(semaphoreTraceWeight)
var call *Call
var raw json.RawMessage
err := ec.c.CallContext(ctx, &raw, "debug_traceTransaction", transactionHash, ec.tc)
if err != nil {
return nil, nil, err
}
// Decode *Call
if err := json.Unmarshal(raw, &call); err != nil {
return nil, nil, err
}
return call, raw, nil
}
func (ec *Client) getBlockTraces(
ctx context.Context,
blockHash common.Hash,
) ([]*rpcCall, []*rpcRawCall, error) {
if err := ec.traceSemaphore.Acquire(ctx, semaphoreTraceWeight); err != nil {
return nil, nil, err
}
defer ec.traceSemaphore.Release(semaphoreTraceWeight)
var calls []*rpcCall
var rawCalls []*rpcRawCall
var raw json.RawMessage
err := ec.c.CallContext(ctx, &raw, "debug_traceBlockByHash", blockHash, ec.tc)
if err != nil {
return nil, nil, err
}
// Decode []*rpcCall
if err := json.Unmarshal(raw, &calls); err != nil {
return nil, nil, err
}
// Decode []*rpcRawCall
if err := json.Unmarshal(raw, &rawCalls); err != nil {
return nil, nil, err
}
return calls, rawCalls, nil
}
func (ec *Client) getBlockReceipts(
ctx context.Context,
blockHash common.Hash,
txs []rpcTransaction,
) ([]*types.Receipt, error) {
receipts := make([]*types.Receipt, len(txs))
if len(txs) == 0 {
return receipts, nil
}
reqs := make([]rpc.BatchElem, len(txs))
for i := range reqs {
reqs[i] = rpc.BatchElem{
Method: "eth_getTransactionReceipt",
Args: []interface{}{txs[i].tx.Hash().Hex()},
Result: &receipts[i],
}
}
if err := ec.c.BatchCallContext(ctx, reqs); err != nil {
return nil, err
}
for i := range reqs {
if reqs[i].Error != nil {
return nil, reqs[i].Error
}
if receipts[i] == nil {
return nil, fmt.Errorf("got empty receipt for %x", txs[i].tx.Hash().Hex())
}
if receipts[i].BlockHash != blockHash {
return nil, fmt.Errorf(
"%w: expected block hash %s for transaction but got %s",
ErrBlockOrphaned,
blockHash.Hex(),
receipts[i].BlockHash.Hex(),
)
}
}
return receipts, nil
}
type rpcCall struct {
Result *Call `json:"result"`
}
type rpcRawCall struct {
Result json.RawMessage `json:"result"`
}
// Call is an Ethereum debug trace.
type Call struct {
Type string `json:"type"`
From common.Address `json:"from"`
To common.Address `json:"to"`
Value *big.Int `json:"value"`
GasUsed *big.Int `json:"gasUsed"`
Revert bool
ErrorMessage string `json:"error"`
Calls []*Call `json:"calls"`
}
type flatCall struct {
Type string `json:"type"`
From common.Address `json:"from"`
To common.Address `json:"to"`
Value *big.Int `json:"value"`
GasUsed *big.Int `json:"gasUsed"`
Revert bool
ErrorMessage string `json:"error"`
}
func (t *Call) flatten() *flatCall {
return &flatCall{
Type: t.Type,
From: t.From,
To: t.To,
Value: t.Value,
GasUsed: t.GasUsed,
Revert: t.Revert,
ErrorMessage: t.ErrorMessage,
}
}
// UnmarshalJSON is a custom unmarshaler for Call.
func (t *Call) UnmarshalJSON(input []byte) error {
type CustomTrace struct {
Type string `json:"type"`
From common.Address `json:"from"`
To common.Address `json:"to"`
Value *hexutil.Big `json:"value"`
GasUsed *hexutil.Big `json:"gasUsed"`
Revert bool
ErrorMessage string `json:"error"`
Calls []*Call `json:"calls"`
}
var dec CustomTrace
if err := json.Unmarshal(input, &dec); err != nil {
return err
}
t.Type = dec.Type
t.From = dec.From
t.To = dec.To
if dec.Value != nil {
t.Value = (*big.Int)(dec.Value)
} else {
t.Value = new(big.Int)
}
if dec.GasUsed != nil {
t.GasUsed = (*big.Int)(dec.GasUsed)
} else {
t.GasUsed = new(big.Int)
}
if dec.ErrorMessage != "" {
// Any error surfaced by the decoder means that the transaction
// has reverted.
t.Revert = true
}
t.ErrorMessage = dec.ErrorMessage
t.Calls = dec.Calls
return nil
}
// flattenTraces recursively flattens all traces.
func flattenTraces(data *Call, flattened []*flatCall) []*flatCall {
results := append(flattened, data.flatten())
for _, child := range data.Calls {
// Ensure all children of a reverted call
// are also reverted!
if data.Revert {
child.Revert = true
// Copy error message from parent
// if child does not have one
if len(child.ErrorMessage) == 0 {
child.ErrorMessage = data.ErrorMessage
}
}
children := flattenTraces(child, flattened)
results = append(results, children...)
}
return results
}
// traceOps returns all *RosettaTypes.Operation for a given
// array of flattened traces.
func traceOps(calls []*flatCall, startIndex int) []*RosettaTypes.Operation { // nolint: gocognit
var ops []*RosettaTypes.Operation
if len(calls) == 0 {
return ops
}
destroyedAccounts := map[string]*big.Int{}
for _, trace := range calls {
// Handle partial transaction success
metadata := map[string]interface{}{}
opStatus := SuccessStatus
if trace.Revert {
opStatus = FailureStatus
metadata["error"] = trace.ErrorMessage
}
var zeroValue bool
if trace.Value.Sign() == 0 {
zeroValue = true
}
// Skip all 0 value CallType operations (TODO: make optional to include)
//
// We can't continue here because we may need to adjust our destroyed
// accounts map if a CallTYpe operation resurrects an account.
shouldAdd := true
if zeroValue && CallType(trace.Type) {
shouldAdd = false
}
// Checksum addresses
from := MustChecksum(trace.From.String())
to := MustChecksum(trace.To.String())
if shouldAdd {
fromOp := &RosettaTypes.Operation{
OperationIdentifier: &RosettaTypes.OperationIdentifier{
Index: int64(len(ops) + startIndex),
},
Type: trace.Type,
Status: RosettaTypes.String(opStatus),
Account: &RosettaTypes.AccountIdentifier{
Address: from,
},
Amount: &RosettaTypes.Amount{
Value: new(big.Int).Neg(trace.Value).String(),
Currency: Currency,
},
Metadata: metadata,
}
if zeroValue {
fromOp.Amount = nil
} else {
_, destroyed := destroyedAccounts[from]
if destroyed && opStatus == SuccessStatus {
destroyedAccounts[from] = new(big.Int).Sub(destroyedAccounts[from], trace.Value)
}
}
ops = append(ops, fromOp)
}
// Add to destroyed accounts if SELFDESTRUCT
// and overwrite existing balance.
if trace.Type == SelfDestructOpType {
destroyedAccounts[from] = new(big.Int)
// If destination of of SELFDESTRUCT is self,
// we should skip. In the EVM, the balance is reset
// after the balance is increased on the destination
// so this is a no-op.
if from == to {
continue
}
}
// Skip empty to addresses (this may not
// actually occur but leaving it as a
// sanity check)
if len(trace.To.String()) == 0 {
continue
}
// If the account is resurrected, we remove it from
// the destroyed accounts map.
if CreateType(trace.Type) {
delete(destroyedAccounts, to)
}
if shouldAdd {
lastOpIndex := ops[len(ops)-1].OperationIdentifier.Index
toOp := &RosettaTypes.Operation{
OperationIdentifier: &RosettaTypes.OperationIdentifier{
Index: lastOpIndex + 1,
},
RelatedOperations: []*RosettaTypes.OperationIdentifier{
{
Index: lastOpIndex,
},
},
Type: trace.Type,
Status: RosettaTypes.String(opStatus),
Account: &RosettaTypes.AccountIdentifier{
Address: to,
},
Amount: &RosettaTypes.Amount{
Value: trace.Value.String(),
Currency: Currency,
},
Metadata: metadata,
}
if zeroValue {
toOp.Amount = nil
} else {
_, destroyed := destroyedAccounts[to]
if destroyed && opStatus == SuccessStatus {
destroyedAccounts[to] = new(big.Int).Add(destroyedAccounts[to], trace.Value)
}
}
ops = append(ops, toOp)
}
}
// Zero-out all destroyed accounts that are removed
// during transaction finalization.
for acct, val := range destroyedAccounts {
if val.Sign() == 0 {
continue
}
if val.Sign() < 0 {
log.Fatalf("negative balance for suicided account %s: %s\n", acct, val.String())
}
ops = append(ops, &RosettaTypes.Operation{
OperationIdentifier: &RosettaTypes.OperationIdentifier{
Index: ops[len(ops)-1].OperationIdentifier.Index + 1,
},
Type: DestructOpType,
Status: RosettaTypes.String(SuccessStatus),
Account: &RosettaTypes.AccountIdentifier{
Address: acct,
},
Amount: &RosettaTypes.Amount{
Value: new(big.Int).Neg(val).String(),
Currency: Currency,
},
})
}
return ops
}
type txExtraInfo struct {
BlockNumber *string `json:"blockNumber,omitempty"`
BlockHash *common.Hash `json:"blockHash,omitempty"`
From *common.Address `json:"from,omitempty"`
}
type rpcTransaction struct {
tx *types.Transaction
txExtraInfo
}
func (tx *rpcTransaction) UnmarshalJSON(msg []byte) error {
if err := json.Unmarshal(msg, &tx.tx); err != nil {
return err
}
return json.Unmarshal(msg, &tx.txExtraInfo)
}
func (tx *rpcTransaction) LoadedTransaction() *loadedTransaction {
ethTx := &loadedTransaction{
Transaction: tx.tx,
From: tx.txExtraInfo.From,
BlockNumber: tx.txExtraInfo.BlockNumber,
BlockHash: tx.txExtraInfo.BlockHash,
}
return ethTx
}
type loadedTransaction struct {
Transaction *types.Transaction
From *common.Address
BlockNumber *string
BlockHash *common.Hash
FeeAmount *big.Int
FeeBurned *big.Int // nil if no fees were burned
Miner string
Status bool
Trace *Call
RawTrace json.RawMessage
Receipt *types.Receipt
}
func feeOps(tx *loadedTransaction) []*RosettaTypes.Operation {
var minerEarnedAmount *big.Int
if tx.FeeBurned == nil {
minerEarnedAmount = tx.FeeAmount
} else {
minerEarnedAmount = new(big.Int).Sub(tx.FeeAmount, tx.FeeBurned)
}
ops := []*RosettaTypes.Operation{
{
OperationIdentifier: &RosettaTypes.OperationIdentifier{
Index: 0,
},
Type: FeeOpType,
Status: RosettaTypes.String(SuccessStatus),
Account: &RosettaTypes.AccountIdentifier{
Address: MustChecksum(tx.From.String()),
},
Amount: &RosettaTypes.Amount{
Value: new(big.Int).Neg(minerEarnedAmount).String(),
Currency: Currency,
},
},
{
OperationIdentifier: &RosettaTypes.OperationIdentifier{
Index: 1,
},
RelatedOperations: []*RosettaTypes.OperationIdentifier{
{
Index: 0,
},
},
Type: FeeOpType,
Status: RosettaTypes.String(SuccessStatus),
Account: &RosettaTypes.AccountIdentifier{
Address: MustChecksum(tx.Miner),
},
Amount: &RosettaTypes.Amount{
Value: minerEarnedAmount.String(),
Currency: Currency,
},
},
}
if tx.FeeBurned == nil {
return ops
}
burntOp := &RosettaTypes.Operation{
OperationIdentifier: &RosettaTypes.OperationIdentifier{
Index: 2, // nolint:gomnd
},
Type: FeeOpType,
Status: RosettaTypes.String(SuccessStatus),
Account: &RosettaTypes.AccountIdentifier{
Address: MustChecksum(tx.From.String()),
},
Amount: &RosettaTypes.Amount{
Value: new(big.Int).Neg(tx.FeeBurned).String(),
Currency: Currency,
},
}
return append(ops, burntOp)
}
// transactionReceipt returns the receipt of a transaction by transaction hash.
// Note that the receipt is not available for pending transactions.
func (ec *Client) transactionReceipt(