-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
trace_filtering.go
809 lines (741 loc) · 22.2 KB
/
trace_filtering.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
package jsonrpc
import (
"context"
"errors"
"fmt"
jsoniter "github.com/json-iterator/go"
"github.com/ledgerwatch/erigon-lib/chain"
"github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/hexutil"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/erigon-lib/kv/iter"
"github.com/ledgerwatch/erigon-lib/kv/order"
"github.com/ledgerwatch/erigon-lib/kv/rawdbv3"
"github.com/ledgerwatch/erigon-lib/log/v3"
"github.com/ledgerwatch/erigon/eth/consensuschain"
"github.com/ledgerwatch/erigon/consensus"
"github.com/ledgerwatch/erigon/consensus/ethash"
"github.com/ledgerwatch/erigon/core"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/state"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/core/vm"
"github.com/ledgerwatch/erigon/core/vm/evmtypes"
"github.com/ledgerwatch/erigon/ethdb"
bortypes "github.com/ledgerwatch/erigon/polygon/bor/types"
"github.com/ledgerwatch/erigon/rpc"
"github.com/ledgerwatch/erigon/turbo/rpchelper"
"github.com/ledgerwatch/erigon/turbo/transactions"
)
// Transaction implements trace_transaction
func (api *TraceAPIImpl) Transaction(ctx context.Context, txHash common.Hash, gasBailOut *bool) (ParityTraces, error) {
if gasBailOut == nil {
gasBailOut = new(bool) // false by default
}
tx, err := api.kv.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
chainConfig, err := api.chainConfig(ctx, tx)
if err != nil {
return nil, err
}
var isBorStateSyncTxn bool
blockNumber, ok, err := api.txnLookup(ctx, tx, txHash)
if err != nil {
return nil, err
}
if !ok {
if chainConfig.Bor == nil {
return nil, nil
}
// otherwise this may be a bor state sync transaction - check
blockNumber, ok, err = api._blockReader.EventLookup(ctx, tx, txHash)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
isBorStateSyncTxn = true
}
block, err := api.blockByNumberWithSenders(ctx, tx, blockNumber)
if err != nil {
return nil, err
}
if block == nil {
return nil, nil
}
var txIndex int
if isBorStateSyncTxn {
txIndex = block.Transactions().Len()
} else {
var found bool
for idx := 0; idx < block.Transactions().Len(); idx++ {
txn := block.Transactions()[idx]
if txn.Hash() == txHash {
txIndex = idx
found = true
break
}
}
if !found {
return nil, fmt.Errorf("txn with hash %x belongs to currentely non-canonical block %d. only canonical blocks can be traced", txHash, block.NumberU64())
}
}
bn := hexutil.Uint64(blockNumber)
hash := block.Hash()
signer := types.MakeSigner(chainConfig, blockNumber, block.Time())
// Returns an array of trace arrays, one trace array for each transaction
traces, _, err := api.callManyTransactions(ctx, tx, block, []string{TraceTypeTrace}, txIndex, *gasBailOut, signer, chainConfig)
if err != nil {
return nil, err
}
out := make([]ParityTrace, 0, len(traces))
blockno := uint64(bn)
for txno, trace := range traces {
// We're only looking for a specific transaction
if txno == txIndex {
for _, pt := range trace.Trace {
pt.BlockHash = &hash
pt.BlockNumber = &blockno
pt.TransactionHash = trace.TransactionHash
txpos := uint64(txno)
pt.TransactionPosition = &txpos
out = append(out, *pt)
}
}
}
return out, err
}
// Get implements trace_get
func (api *TraceAPIImpl) Get(ctx context.Context, txHash common.Hash, indicies []hexutil.Uint64, gasBailOut *bool) (*ParityTrace, error) {
// Parity fails if it gets more than a single index. It returns nothing in this case. Must we?
if len(indicies) > 1 {
return nil, nil
}
traces, err := api.Transaction(ctx, txHash, gasBailOut)
if err != nil {
return nil, err
}
// 'trace_get' index starts at one (oddly)
firstIndex := int(indicies[0]) + 1
for i, trace := range traces {
if i == firstIndex {
return &trace, nil
}
}
return nil, err
}
func rewardKindToString(kind consensus.RewardKind) string {
switch kind {
case consensus.RewardAuthor:
return "block"
case consensus.RewardEmptyStep:
return "emptyStep"
case consensus.RewardExternal:
return "external"
case consensus.RewardUncle:
return "uncle"
default:
return "unknown"
}
}
// Block implements trace_block
func (api *TraceAPIImpl) Block(ctx context.Context, blockNr rpc.BlockNumber, gasBailOut *bool) (ParityTraces, error) {
if gasBailOut == nil {
gasBailOut = new(bool) // false by default
}
tx, err := api.kv.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
blockNum, hash, _, err := rpchelper.GetBlockNumber(rpc.BlockNumberOrHashWithNumber(blockNr), tx, api.filters)
if err != nil {
return nil, err
}
if blockNum == 0 {
return []ParityTrace{}, nil
}
bn := hexutil.Uint64(blockNum)
// Extract transactions from block
block, bErr := api.blockWithSenders(ctx, tx, hash, blockNum)
if bErr != nil {
return nil, bErr
}
if block == nil {
return nil, fmt.Errorf("could not find block %d", uint64(bn))
}
cfg, err := api.chainConfig(ctx, tx)
if err != nil {
return nil, err
}
signer := types.MakeSigner(cfg, blockNum, block.Time())
traces, syscall, err := api.callManyTransactions(ctx, tx, block, []string{TraceTypeTrace}, -1 /* all tx indices */, *gasBailOut /* gasBailOut */, signer, cfg)
if err != nil {
return nil, err
}
out := make([]ParityTrace, 0, len(traces))
for txno, trace := range traces {
txpos := uint64(txno)
for _, pt := range trace.Trace {
pt.BlockHash = &hash
pt.BlockNumber = &blockNum
pt.TransactionHash = trace.TransactionHash
pt.TransactionPosition = &txpos
out = append(out, *pt)
}
}
rewards, err := api.engine().CalculateRewards(cfg, block.Header(), block.Uncles(), syscall)
if err != nil {
return nil, err
}
for _, r := range rewards {
var tr ParityTrace
rewardAction := &RewardTraceAction{}
rewardAction.Author = r.Beneficiary
rewardAction.RewardType = rewardKindToString(r.Kind)
rewardAction.Value.ToInt().Set(r.Amount.ToBig())
tr.Action = rewardAction
tr.BlockHash = &common.Hash{}
copy(tr.BlockHash[:], block.Hash().Bytes())
tr.BlockNumber = new(uint64)
*tr.BlockNumber = block.NumberU64()
tr.Type = "reward" // nolint: goconst
tr.TraceAddress = []int{}
out = append(out, tr)
}
return out, err
}
func traceFilterBitmapsV3(tx kv.TemporalTx, req TraceFilterRequest, from, to uint64) (fromAddresses, toAddresses map[common.Address]struct{}, allBlocks iter.U64, err error) {
fromAddresses = make(map[common.Address]struct{}, len(req.FromAddress))
toAddresses = make(map[common.Address]struct{}, len(req.ToAddress))
var blocksTo iter.U64
for _, addr := range req.FromAddress {
if addr != nil {
it, err := tx.IndexRange(kv.TracesFromIdx, addr.Bytes(), int(from), int(to), order.Asc, kv.Unlim)
if errors.Is(err, ethdb.ErrKeyNotFound) {
continue
}
allBlocks = iter.Union[uint64](allBlocks, it, order.Asc, -1)
fromAddresses[*addr] = struct{}{}
}
}
for _, addr := range req.ToAddress {
if addr != nil {
it, err := tx.IndexRange(kv.TracesToIdx, addr.Bytes(), int(from), int(to), order.Asc, kv.Unlim)
if errors.Is(err, ethdb.ErrKeyNotFound) {
continue
}
blocksTo = iter.Union[uint64](blocksTo, it, order.Asc, -1)
toAddresses[*addr] = struct{}{}
}
}
switch req.Mode {
case TraceFilterModeIntersection:
allBlocks = iter.Intersect[uint64](allBlocks, blocksTo, -1)
case TraceFilterModeUnion:
fallthrough
default:
allBlocks = iter.Union[uint64](allBlocks, blocksTo, order.Asc, -1)
}
// Special case - if no addresses specified, take all traces
if len(req.FromAddress) == 0 && len(req.ToAddress) == 0 {
allBlocks = iter.Range[uint64](from, to)
//} else {
//allBlocks.RemoveRange(0, from)
//allBlocks.RemoveRange(to, uint64(0x100000000))
}
return fromAddresses, toAddresses, allBlocks, nil
}
// Filter implements trace_filter
// NOTE: We do not store full traces - we just store index for each address
// Pull blocks which have txs with matching address
func (api *TraceAPIImpl) Filter(ctx context.Context, req TraceFilterRequest, gasBailOut *bool, stream *jsoniter.Stream) error {
if gasBailOut == nil {
//nolint
gasBailOut = new(bool) // false by default
}
dbtx, err1 := api.kv.BeginRo(ctx)
if err1 != nil {
return fmt.Errorf("traceFilter cannot open tx: %w", err1)
}
defer dbtx.Rollback()
var fromBlock uint64
var toBlock uint64
if req.FromBlock == nil {
fromBlock = 0
} else {
fromBlock = uint64(*req.FromBlock)
}
if req.ToBlock == nil {
headNumber := rawdb.ReadHeaderNumber(dbtx, rawdb.ReadHeadHeaderHash(dbtx))
toBlock = *headNumber
} else {
toBlock = uint64(*req.ToBlock)
}
if fromBlock > toBlock {
return fmt.Errorf("invalid parameters: fromBlock cannot be greater than toBlock")
}
return api.filterV3(ctx, dbtx.(kv.TemporalTx), fromBlock, toBlock, req, stream, *gasBailOut)
}
func (api *TraceAPIImpl) filterV3(ctx context.Context, dbtx kv.TemporalTx, fromBlock, toBlock uint64, req TraceFilterRequest, stream *jsoniter.Stream, gasBailOut bool) error {
var fromTxNum, toTxNum uint64
var err error
if fromBlock > 0 {
fromTxNum, err = rawdbv3.TxNums.Min(dbtx, fromBlock)
if err != nil {
return err
}
}
toTxNum, err = rawdbv3.TxNums.Max(dbtx, toBlock) // toBlock is an inclusive bound
if err != nil {
return err
}
toTxNum++ //+1 because internally Erigon using semantic [from, to), but some RPC have different semantic
fromAddresses, toAddresses, allTxs, err := traceFilterBitmapsV3(dbtx, req, fromTxNum, toTxNum)
if err != nil {
return err
}
it := rawdbv3.TxNums2BlockNums(dbtx, allTxs, order.Asc)
defer it.Close()
chainConfig, err := api.chainConfig(ctx, dbtx)
if err != nil {
return err
}
engine := api.engine()
var json = jsoniter.ConfigCompatibleWithStandardLibrary
stream.WriteArrayStart()
first := true
// Execute all transactions in picked blocks
count := uint64(^uint(0)) // this just makes it easier to use below
if req.Count != nil {
count = *req.Count
}
after := uint64(0) // this just makes it easier to use below
if req.After != nil {
after = *req.After
}
vmConfig := vm.Config{}
nSeen := uint64(0)
nExported := uint64(0)
includeAll := len(fromAddresses) == 0 && len(toAddresses) == 0
var lastBlockHash common.Hash
var lastHeader *types.Header
var lastSigner *types.Signer
var lastRules *chain.Rules
stateReader := state.NewHistoryReaderV3()
stateReader.SetTx(dbtx)
noop := state.NewNoopWriter()
isPos := false
for it.HasNext() {
txNum, blockNum, txIndex, isFnalTxn, blockNumChanged, err := it.Next()
if err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
if blockNumChanged {
if lastHeader, err = api._blockReader.HeaderByNumber(ctx, dbtx, blockNum); err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
if lastHeader == nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(fmt.Errorf("header not found: %d", blockNum), stream)
stream.WriteObjectEnd()
continue
}
if !isPos && chainConfig.TerminalTotalDifficulty != nil {
header := lastHeader
isPos = header.Difficulty.Cmp(common.Big0) == 0 || header.Difficulty.Cmp(chainConfig.TerminalTotalDifficulty) >= 0
}
lastBlockHash = lastHeader.Hash()
lastSigner = types.MakeSigner(chainConfig, blockNum, lastHeader.Time)
lastRules = chainConfig.Rules(blockNum, lastHeader.Time)
}
if isFnalTxn {
// TODO(yperbasis) proper rewards for Gnosis
// if we are in POS
// we don't check for uncles or block rewards
if isPos {
continue
}
body, _, err := api._blockReader.Body(ctx, dbtx, lastBlockHash, blockNum)
if err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
// Block reward section, handle specially
minerReward, uncleRewards := ethash.AccumulateRewards(chainConfig, lastHeader, body.Uncles)
if _, ok := toAddresses[lastHeader.Coinbase]; ok || includeAll {
nSeen++
var tr ParityTrace
var rewardAction = &RewardTraceAction{}
rewardAction.Author = lastHeader.Coinbase
rewardAction.RewardType = "block" // nolint: goconst
rewardAction.Value.ToInt().Set(minerReward.ToBig())
tr.Action = rewardAction
tr.BlockHash = &common.Hash{}
copy(tr.BlockHash[:], lastBlockHash.Bytes())
tr.BlockNumber = new(uint64)
*tr.BlockNumber = blockNum
tr.Type = "reward" // nolint: goconst
tr.TraceAddress = []int{}
b, err := json.Marshal(tr)
if err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
if nSeen > after && nExported < count {
if first {
first = false
} else {
stream.WriteMore()
}
if _, err := stream.Write(b); err != nil {
return err
}
nExported++
}
}
for i, uncle := range body.Uncles {
if _, ok := toAddresses[uncle.Coinbase]; ok || includeAll {
if i < len(uncleRewards) {
nSeen++
var tr ParityTrace
rewardAction := &RewardTraceAction{}
rewardAction.Author = uncle.Coinbase
rewardAction.RewardType = "uncle" // nolint: goconst
rewardAction.Value.ToInt().Set(uncleRewards[i].ToBig())
tr.Action = rewardAction
tr.BlockHash = &common.Hash{}
copy(tr.BlockHash[:], lastBlockHash[:])
tr.BlockNumber = new(uint64)
*tr.BlockNumber = blockNum
tr.Type = "reward" // nolint: goconst
tr.TraceAddress = []int{}
b, err := json.Marshal(tr)
if err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
if nSeen > after && nExported < count {
if first {
first = false
} else {
stream.WriteMore()
}
if _, err := stream.Write(b); err != nil {
return err
}
nExported++
}
}
}
}
continue
}
if txIndex == -1 { //is system tx
continue
}
txIndexU64 := uint64(txIndex)
//fmt.Printf("txNum=%d, blockNum=%d, txIndex=%d\n", txNum, blockNum, txIndex)
txn, err := api._txnReader.TxnByIdxInBlock(ctx, dbtx, blockNum, txIndex)
if err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
if txn == nil {
continue //guess block doesn't have transactions
}
txHash := txn.Hash()
msg, err := txn.AsMessage(*lastSigner, lastHeader.BaseFee, lastRules)
if err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
stateReader.SetTxNum(txNum)
//stateCache := shards.NewStateCache(32, 0 /* no limit */) // this cache living only during current RPC call, but required to store state writes
//cachedReader := state.NewCachedReader(stateReader, stateCache)
cachedReader := stateReader
//cachedWriter := state.NewCachedWriter(noop, stateCache)
cachedWriter := noop
vmConfig.SkipAnalysis = core.SkipAnalysis(chainConfig, blockNum)
traceResult := &TraceCallResult{Trace: []*ParityTrace{}}
var ot OeTracer
ot.compat = api.compatibility
ot.r = traceResult
ot.idx = []string{fmt.Sprintf("%d-", txIndex)}
ot.traceAddr = []int{}
vmConfig.Debug = true
vmConfig.Tracer = &ot
ibs := state.New(cachedReader)
blockCtx := transactions.NewEVMBlockContext(engine, lastHeader, true /* requireCanonical */, dbtx, api._blockReader, chainConfig)
txCtx := core.NewEVMTxContext(msg)
evm := vm.NewEVM(blockCtx, txCtx, ibs, chainConfig, vmConfig)
gp := new(core.GasPool).AddGas(msg.Gas()).AddBlobGas(msg.BlobGas())
ibs.SetTxContext(txHash, lastBlockHash, txIndex)
var execResult *evmtypes.ExecutionResult
execResult, err = core.ApplyMessage(evm, msg, gp, true /* refunds */, gasBailOut)
if err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
traceResult.Output = common.Copy(execResult.ReturnData)
if err = ibs.FinalizeTx(evm.ChainRules(), noop); err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
if err = ibs.CommitBlock(evm.ChainRules(), cachedWriter); err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
isIntersectionMode := req.Mode == TraceFilterModeIntersection
for _, pt := range traceResult.Trace {
if includeAll || filterTrace(pt, fromAddresses, toAddresses, isIntersectionMode) {
nSeen++
pt.BlockHash = &lastBlockHash
pt.BlockNumber = &blockNum
pt.TransactionHash = &txHash
pt.TransactionPosition = &txIndexU64
b, err := json.Marshal(pt)
if err != nil {
if first {
first = false
} else {
stream.WriteMore()
}
stream.WriteObjectStart()
rpc.HandleError(err, stream)
stream.WriteObjectEnd()
continue
}
if nSeen > after && nExported < count {
if first {
first = false
} else {
stream.WriteMore()
}
if _, err := stream.Write(b); err != nil {
return err
}
nExported++
}
}
}
}
stream.WriteArrayEnd()
return stream.Flush()
}
func filterTrace(pt *ParityTrace, fromAddresses map[common.Address]struct{}, toAddresses map[common.Address]struct{}, isIntersectionMode bool) bool {
f, t := false, false
switch action := pt.Action.(type) {
case *CallTraceAction:
_, f = fromAddresses[action.From]
_, t = toAddresses[action.To]
case *CreateTraceAction:
_, f = fromAddresses[action.From]
if res, ok := pt.Result.(*CreateTraceResult); ok {
if res.Address != nil {
_, t = toAddresses[*res.Address]
}
}
case *SuicideTraceAction:
_, f = fromAddresses[action.Address]
_, t = toAddresses[action.RefundAddress]
}
if isIntersectionMode {
return f && t
} else {
return f || t
}
}
func (api *TraceAPIImpl) callManyTransactions(
ctx context.Context,
dbtx kv.Tx,
block *types.Block,
traceTypes []string,
txIndex int,
gasBailOut bool,
signer *types.Signer,
cfg *chain.Config,
) ([]*TraceCallResult, consensus.SystemCall, error) {
blockNumber := block.NumberU64()
pNo := blockNumber
if pNo > 0 {
pNo -= 1
}
parentNo := rpc.BlockNumber(pNo)
rules := cfg.Rules(blockNumber, block.Time())
header := block.Header()
txs := block.Transactions()
var borStateSyncTxn types.Transaction
var borStateSyncTxnHash common.Hash
if cfg.Bor != nil {
// check if this block has state sync txn
blockHash := block.Hash()
borStateSyncTxnHash = bortypes.ComputeBorTxHash(blockNumber, blockHash)
_, ok, err := api._blockReader.EventLookup(ctx, dbtx, borStateSyncTxnHash)
if err != nil {
return nil, nil, err
}
if ok {
borStateSyncTxn = bortypes.NewBorTransaction()
txs = append(txs, borStateSyncTxn)
}
}
callParams := make([]TraceCallParam, 0, len(txs))
reader, err := rpchelper.CreateHistoryStateReader(dbtx, blockNumber, txIndex, cfg.ChainName)
if err != nil {
return nil, nil, err
}
initialState := state.New(reader)
if err != nil {
return nil, nil, err
}
engine := api.engine()
consensusHeaderReader := consensuschain.NewReader(cfg, dbtx, nil, nil)
logger := log.New("trace_filtering")
err = core.InitializeBlockExecution(engine.(consensus.Engine), consensusHeaderReader, block.HeaderNoCopy(), cfg, initialState, logger)
if err != nil {
return nil, nil, err
}
msgs := make([]types.Message, len(txs))
for i, tx := range txs {
isBorStateSyncTxn := tx == borStateSyncTxn
var txnHash common.Hash
var msg types.Message
var err error
if isBorStateSyncTxn {
txnHash = borStateSyncTxnHash
// we use an empty message for bor state sync txn since it gets handled differently
} else {
txnHash = tx.Hash()
msg, err = tx.AsMessage(*signer, header.BaseFee, rules)
if err != nil {
return nil, nil, fmt.Errorf("convert tx into msg: %w", err)
}
// gnosis might have a fee free account here
if msg.FeeCap().IsZero() && engine != nil {
syscall := func(contract common.Address, data []byte) ([]byte, error) {
return core.SysCallContract(contract, data, cfg, initialState, header, engine, true /* constCall */)
}
msg.SetIsFree(engine.IsServiceTransaction(msg.From(), syscall))
}
}
callParams = append(callParams, TraceCallParam{
txHash: &txnHash,
traceTypes: traceTypes,
isBorStateSyncTxn: isBorStateSyncTxn,
})
msgs[i] = msg
}
parentHash := block.ParentHash()
traces, lastState, cmErr := api.doCallMany(ctx, dbtx, msgs, callParams, &rpc.BlockNumberOrHash{
BlockNumber: &parentNo,
BlockHash: &parentHash,
RequireCanonical: true,
}, header, gasBailOut /* gasBailout */, txIndex)
if cmErr != nil {
return nil, nil, cmErr
}
syscall := func(contract common.Address, data []byte) ([]byte, error) {
return core.SysCallContract(contract, data, cfg, lastState, header, engine, false /* constCall */)
}
return traces, syscall, nil
}
// TraceFilterRequest represents the arguments for trace_filter
type TraceFilterRequest struct {
FromBlock *hexutil.Uint64 `json:"fromBlock"`
ToBlock *hexutil.Uint64 `json:"toBlock"`
FromAddress []*common.Address `json:"fromAddress"`
ToAddress []*common.Address `json:"toAddress"`
Mode TraceFilterMode `json:"mode"`
After *uint64 `json:"after"`
Count *uint64 `json:"count"`
}
type TraceFilterMode string
const (
// TraceFilterModeUnion is default mode for TraceFilter.
// Unions results referred to addresses from FromAddress or ToAddress
TraceFilterModeUnion = "union"
// TraceFilterModeIntersection retrieves results referred to addresses provided both in FromAddress and ToAddress
TraceFilterModeIntersection = "intersection"
)