forked from ethereum/go-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfirehose.go
2440 lines (2003 loc) · 79.2 KB
/
firehose.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
package tracers
import (
"bytes"
"cmp"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"os"
"regexp"
"runtime"
"runtime/debug"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/tracing"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/internal/version"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
pbeth "github.com/ethereum/go-ethereum/pb/sf/ethereum/type/v2"
"github.com/ethereum/go-ethereum/rlp"
"github.com/holiman/uint256"
"golang.org/x/exp/maps"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Here what you can expect from the debugging levels:
// - Info == block start/end + trx start/end
// - Debug == Info + call start/end + error
// - Trace == Debug + state db changes, log, balance, nonce, code, storage, gas
// - TraceFull == Trace + opcode
var firehoseTracerLogLevel = strings.ToLower(os.Getenv("FIREHOSE_ETHEREUM_TRACER_LOG_LEVEL"))
var isFirehoseInfoEnabled = firehoseTracerLogLevel == "info" || firehoseTracerLogLevel == "debug" || firehoseTracerLogLevel == "trace" || firehoseTracerLogLevel == "trace_full"
var isFirehoseDebugEnabled = firehoseTracerLogLevel == "debug" || firehoseTracerLogLevel == "trace" || firehoseTracerLogLevel == "trace_full"
var isFirehoseTraceEnabled = firehoseTracerLogLevel == "trace" || firehoseTracerLogLevel == "trace_full"
var isFirehoseTraceFullEnabled = firehoseTracerLogLevel == "trace_full"
var emptyCommonAddress = common.Address{}
var emptyCommonHash = common.Hash{}
func init() {
staticFirehoseChainValidationOnInit()
LiveDirectory.Register("firehose", newFirehoseTracer)
// Those 2 are defined but not used in this branch, they are kept because used in other branches
// so it's easier to keep them here and suppress the warning by faking a usage.
_ = new(Firehose).newIsolatedTransactionTracer
_ = new(FinalityStatus).populate
}
func newFirehoseTracer(cfg json.RawMessage) (*tracing.Hooks, error) {
firehoseTracer, err := NewFirehoseFromRawJSON(cfg)
if err != nil {
return nil, err
}
return NewTracingHooksFromFirehose(firehoseTracer), nil
}
func NewTracingHooksFromFirehose(tracer *Firehose) *tracing.Hooks {
return &tracing.Hooks{
OnBlockchainInit: tracer.OnBlockchainInit,
OnGenesisBlock: tracer.OnGenesisBlock,
OnBlockStart: tracer.OnBlockStart,
OnBlockEnd: tracer.OnBlockEnd,
OnSkippedBlock: tracer.OnSkippedBlock,
OnTxStart: tracer.OnTxStart,
OnTxEnd: tracer.OnTxEnd,
OnEnter: tracer.OnCallEnter,
OnExit: tracer.OnCallExit,
OnOpcode: tracer.OnOpcode,
OnFault: tracer.OnOpcodeFault,
OnBalanceChange: tracer.OnBalanceChange,
OnNonceChange: tracer.OnNonceChange,
OnCodeChange: tracer.OnCodeChange,
OnStorageChange: tracer.OnStorageChange,
OnGasChange: tracer.OnGasChange,
OnLog: tracer.OnLog,
// This is being discussed in PR https://github.com/ethereum/go-ethereum/pull/29355
// but Firehose needs them so we add handling for them in our patch.
OnSystemCallStart: tracer.OnSystemCallStart,
OnSystemCallEnd: tracer.OnSystemCallEnd,
// This should actually be conditional but it's not possible to do it in the hooks
// directly because the chain ID will be known only after the `OnBlockchainInit` call.
// So we register it unconditionally and the actual `OnNewAccount` hook will decide
// what it needs to do.
OnNewAccount: tracer.OnNewAccount,
}
}
type FirehoseConfig struct {
ApplyBackwardCompatibility *bool `json:"applyBackwardCompatibility"`
// Only used for testing, only possible through JSON configuration
private *privateFirehoseConfig
}
type privateFirehoseConfig struct {
FlushToTestBuffer bool `json:"flushToTestBuffer"`
IgnoreGenesisBlock bool `json:"ignoreGenesisBlock"`
}
// LogKeValues returns a list of key-values to be logged when the config is printed.
func (c *FirehoseConfig) LogKeyValues() []any {
applyBackwardCompatibility := "<unspecified>"
if c.ApplyBackwardCompatibility != nil {
applyBackwardCompatibility = strconv.FormatBool(*c.ApplyBackwardCompatibility)
}
return []any{
"config.applyBackwardCompatibility", applyBackwardCompatibility,
}
}
type Firehose struct {
// Global state
outputBuffer *bytes.Buffer
initSent *atomic.Bool
chainConfig *params.ChainConfig
hasher crypto.KeccakState // Keccak256 hasher instance shared across tracer needs (non-concurrent safe)
hasherBuf common.Hash // Keccak256 hasher result array shared across tracer needs (non-concurrent safe)
tracerID string
// The FirehoseTracer is used in multiple chains, some for which were produced using a legacy version
// of the whole tracing infrastructure. This legacy version had many small bugs here and there that
// we must "reproduce" on some chain to ensure that the FirehoseTracer produces the same output
// as the legacy version.
//
// This value is fed from the tracer configuration. If explicitly set, the value set will be used
// here. If not set in the config, then we inspect `OnBlockchainInit` the chain config to determine
// if it's a network for which we must reproduce the legacy bugs.
applyBackwardCompatibility *bool
// Block state
block *pbeth.Block
blockBaseFee *big.Int
blockOrdinal *Ordinal
blockFinality *FinalityStatus
blockRules params.Rules
blockIsPrecompiledAddr func(addr common.Address) bool
blockReorderOrdinal bool
blockReorderOrdinalSnapshot uint64
blockReorderOrdinalOnce sync.Once
// Transaction state
evm *tracing.VMContext
transaction *pbeth.TransactionTrace
transactionLogIndex uint32
inSystemCall bool
transactionIsolated bool
transactionTransient *pbeth.TransactionTrace
// Call state
callStack *CallStack
deferredCallState *DeferredCallState
latestCallEnterSuicided bool
// Testing state, only used in tests and private configs
testingBuffer *bytes.Buffer
testingIgnoreGenesisBlock bool
}
const FirehoseProtocolVersion = "3.0"
func NewFirehoseFromRawJSON(cfg json.RawMessage) (*Firehose, error) {
var config FirehoseConfig
if len([]byte(cfg)) > 0 {
if err := json.Unmarshal(cfg, &config); err != nil {
return nil, fmt.Errorf("failed to parse Firehose config: %w", err)
}
// Special handling of some "private" fields
type privateConfigRoot struct {
Private *privateFirehoseConfig `json:"_private"`
}
var privateConfig privateConfigRoot
if err := json.Unmarshal(cfg, &privateConfig); err != nil {
log.Info("Firehose failed to parse private config, ignoring", "error", err)
} else {
config.private = privateConfig.Private
}
}
return NewFirehose(&config), nil
}
func NewFirehose(config *FirehoseConfig) *Firehose {
log.Info("Firehose tracer created", config.LogKeyValues()...)
firehose := &Firehose{
// Global state
outputBuffer: bytes.NewBuffer(make([]byte, 0, 100*1024*1024)),
initSent: new(atomic.Bool),
chainConfig: nil,
hasher: crypto.NewKeccakState(),
tracerID: "global",
applyBackwardCompatibility: config.ApplyBackwardCompatibility,
// Block state
blockOrdinal: &Ordinal{},
blockFinality: &FinalityStatus{},
blockReorderOrdinal: false,
// Transaction state
transactionLogIndex: 0,
// Call state
callStack: NewCallStack(),
deferredCallState: NewDeferredCallState(),
latestCallEnterSuicided: false,
}
if config.private != nil {
firehose.testingIgnoreGenesisBlock = config.private.IgnoreGenesisBlock
if config.private.FlushToTestBuffer {
firehose.testingBuffer = bytes.NewBuffer(nil)
}
}
return firehose
}
func (f *Firehose) newIsolatedTransactionTracer(tracerID string) *Firehose {
f.ensureInBlock(0)
return &Firehose{
// Global state
initSent: f.initSent,
chainConfig: f.chainConfig,
hasher: crypto.NewKeccakState(),
hasherBuf: common.Hash{},
tracerID: tracerID,
// Block state
block: f.block,
blockBaseFee: f.blockBaseFee,
blockOrdinal: &Ordinal{},
blockFinality: f.blockFinality,
blockIsPrecompiledAddr: f.blockIsPrecompiledAddr,
blockRules: f.blockRules,
// Transaction state
transactionLogIndex: 0,
transactionIsolated: true,
// Call state
callStack: NewCallStack(),
deferredCallState: NewDeferredCallState(),
latestCallEnterSuicided: false,
}
}
// resetBlock resets the block state only, do not reset transaction or call state
func (f *Firehose) resetBlock() {
f.block = nil
f.blockBaseFee = nil
f.blockOrdinal.Reset()
f.blockFinality.Reset()
f.blockIsPrecompiledAddr = nil
f.blockRules = params.Rules{}
f.blockReorderOrdinal = false
f.blockReorderOrdinalSnapshot = 0
f.blockReorderOrdinalOnce = sync.Once{}
}
// resetTransaction resets the transaction state and the call state in one shot
func (f *Firehose) resetTransaction() {
firehoseDebug("resetting transaction state")
f.transaction = nil
f.evm = nil
f.transactionLogIndex = 0
f.inSystemCall = false
f.transactionTransient = nil
f.callStack.Reset()
f.latestCallEnterSuicided = false
f.deferredCallState.Reset()
}
func (f *Firehose) OnBlockchainInit(chainConfig *params.ChainConfig) {
f.chainConfig = chainConfig
if wasNeverSent := f.initSent.CompareAndSwap(false, true); wasNeverSent {
f.printToFirehose("INIT", FirehoseProtocolVersion, "geth", version.Semantic)
} else {
f.panicInvalidState("The OnBlockchainInit callback was called more than once", 0)
}
if f.applyBackwardCompatibility == nil {
f.applyBackwardCompatibility = ptr(chainNeedsLegacyBackwardCompatibility(chainConfig.ChainID))
}
log.Info("Firehose tracer initialized", "chain_id", chainConfig.ChainID, "apply_backward_compatibility", *f.applyBackwardCompatibility, "protocol_version", FirehoseProtocolVersion)
}
var mainnetChainID = big.NewInt(1)
var goerliChainID = big.NewInt(5)
var sepoliaChainID = big.NewInt(11155111)
var holeskyChainID = big.NewInt(17000)
var polygonMainnetChainID = big.NewInt(137)
var polygonMumbaiChainID = big.NewInt(80001)
var polygonAmoyChainID = big.NewInt(80002)
var bscMainnetChainID = big.NewInt(56)
var bscTestnetChainID = big.NewInt(97)
func chainNeedsLegacyBackwardCompatibility(id *big.Int) bool {
return id.Cmp(mainnetChainID) == 0 ||
id.Cmp(goerliChainID) == 0 ||
id.Cmp(sepoliaChainID) == 0 ||
id.Cmp(holeskyChainID) == 0 ||
id.Cmp(polygonMainnetChainID) == 0 ||
id.Cmp(polygonMumbaiChainID) == 0 ||
id.Cmp(polygonAmoyChainID) == 0 ||
id.Cmp(bscMainnetChainID) == 0 ||
id.Cmp(bscTestnetChainID) == 0
}
func (f *Firehose) OnBlockStart(event tracing.BlockEvent) {
// Hash is usually pre-computed within `event.Block`, so it's better to take from there
block := event.Block
hash := block.Hash()
header := event.Block.Header()
firehoseInfo("block start (number=%d hash=%s)", block.NumberU64(), hash)
f.ensureBlockChainInit()
f.blockRules = f.chainConfig.Rules(header.Number, blockIsMerge(event.Block), block.Time())
f.blockIsPrecompiledAddr = getActivePrecompilesChecker(f.blockRules)
f.block = &pbeth.Block{
Hash: hash.Bytes(),
Number: block.NumberU64(),
// FIXME: Avoid calling 'Header()', it makes a copy while accessing event.Block getters directly avoids it
Header: newBlockHeaderFromChainHeader(hash, block.Header(), firehoseBigIntFromNative(new(big.Int).Add(event.TD, block.Difficulty()))),
Ver: 4,
// FIXME: 'block.Size()' is a relatively heavy operation, could we do it async?
Size: block.Size(),
}
if *f.applyBackwardCompatibility {
f.block.Ver = 3
}
for _, uncle := range block.Uncles() {
f.block.Uncles = append(f.block.Uncles, newBlockHeaderFromChainHeader(uncle.Hash(), uncle, nil))
}
if f.block.Header.BaseFeePerGas != nil {
f.blockBaseFee = f.block.Header.BaseFeePerGas.Native()
}
f.blockFinality.populateFromChain(event.Finalized)
}
func blockIsMerge(block *types.Block) bool {
return block.Difficulty().Sign() == 0
}
func (f *Firehose) OnSkippedBlock(event tracing.BlockEvent) {
// Blocks that are skipped from blockchain that were known and should contain 0 transactions.
// It happened in the past, on Polygon if I recall right, that we missed block because some block
// went in this code path.
//
// See https: //github.com/streamingfast/go-ethereum/blob/a46903cf0cad829479ded66b369017914bf82314/core/blockchain.go#L1797-L1814
if event.Block.Transactions().Len() > 0 {
panic(fmt.Sprintf("The tracer received an `OnSkippedBlock` block #%d (%s) with %d transactions, this according to core/blockchain.go should never happen and is an error",
event.Block.NumberU64(),
event.Block.Hash().Hex(),
event.Block.Transactions().Len(),
))
}
// Trace the block as normal, worst case the Firehose system will simply discard it at some point
f.OnBlockStart(event)
f.OnBlockEnd(nil)
}
func getActivePrecompilesChecker(rules params.Rules) func(addr common.Address) bool {
activePrecompiles := vm.ActivePrecompiles(rules)
activePrecompilesMap := make(map[common.Address]bool, len(activePrecompiles))
for _, addr := range activePrecompiles {
activePrecompilesMap[addr] = true
}
return func(addr common.Address) bool {
_, found := activePrecompilesMap[addr]
return found
}
}
func (f *Firehose) OnBlockEnd(err error) {
firehoseInfo("block ending (err=%s)", errorView(err))
if err == nil {
if f.blockReorderOrdinal {
f.reorderIsolatedTransactionsAndOrdinals()
}
f.ensureInBlockAndNotInTrx()
f.printBlockToFirehose(f.block, f.blockFinality)
} else {
// An error occurred, could have happen in transaction/call context, we must not check if in trx/call, only check in block
f.ensureInBlock(0)
}
f.resetBlock()
f.resetTransaction()
firehoseInfo("block end")
}
// reorderIsolatedTransactionsAndOrdinals is called right after all transactions have completed execution. It will sort transactions
// according to their index.
//
// But most importantly, will re-assign all the ordinals of each transaction recursively. When the parallel execution happened,
// all ordinal were made relative to the transaction they were contained in. But now, we are going to re-assign them to the
// global block ordinal by getting the current ordinal and ad it to the transaction ordinal and so forth.
func (f *Firehose) reorderIsolatedTransactionsAndOrdinals() {
if !f.blockReorderOrdinal {
firehoseInfo("post process isolated transactions skipped (block_reorder_ordinals=false)")
return
}
ordinalBase := f.blockReorderOrdinalSnapshot
firehoseInfo("post processing isolated transactions sorting & re-assigning ordinals (ordinal_base=%d)", ordinalBase)
slices.SortStableFunc(f.block.TransactionTraces, func(i, j *pbeth.TransactionTrace) int {
return int(i.Index) - int(j.Index)
})
baseline := ordinalBase
for _, trx := range f.block.TransactionTraces {
trx.BeginOrdinal += baseline
for _, call := range trx.Calls {
f.reorderCallOrdinals(call, baseline)
}
for _, log := range trx.Receipt.Logs {
log.Ordinal += baseline
}
trx.EndOrdinal += baseline
baseline = trx.EndOrdinal
}
for _, ch := range f.block.BalanceChanges {
if ch.Ordinal >= ordinalBase {
ch.Ordinal += baseline
}
}
for _, ch := range f.block.CodeChanges {
if ch.Ordinal >= ordinalBase {
ch.Ordinal += baseline
}
}
for _, call := range f.block.SystemCalls {
if call.BeginOrdinal >= ordinalBase {
f.reorderCallOrdinals(call, baseline)
}
}
}
func (f *Firehose) reorderCallOrdinals(call *pbeth.Call, ordinalBase uint64) (ordinalEnd uint64) {
if *f.applyBackwardCompatibility {
if call.BeginOrdinal != 0 {
call.BeginOrdinal += ordinalBase // consistent with a known small bug: root call has beginOrdinal set to 0
}
} else {
call.BeginOrdinal += ordinalBase
}
for _, log := range call.Logs {
log.Ordinal += ordinalBase
}
for _, act := range call.AccountCreations {
act.Ordinal += ordinalBase
}
for _, ch := range call.BalanceChanges {
ch.Ordinal += ordinalBase
}
for _, ch := range call.GasChanges {
ch.Ordinal += ordinalBase
}
for _, ch := range call.NonceChanges {
ch.Ordinal += ordinalBase
}
for _, ch := range call.StorageChanges {
ch.Ordinal += ordinalBase
}
for _, ch := range call.CodeChanges {
ch.Ordinal += ordinalBase
}
call.EndOrdinal += ordinalBase
return call.EndOrdinal
}
func (f *Firehose) OnSystemCallStart() {
firehoseInfo("system call start")
f.ensureInBlockAndNotInTrx()
f.inSystemCall = true
f.transaction = &pbeth.TransactionTrace{}
}
func (f *Firehose) OnSystemCallEnd() {
f.ensureInBlockAndInTrx()
f.ensureInSystemCall()
f.block.SystemCalls = append(f.block.SystemCalls, f.transaction.Calls...)
f.resetTransaction()
}
func (f *Firehose) OnTxStart(evm *tracing.VMContext, tx *types.Transaction, from common.Address) {
firehoseInfo("trx start (tracer=%s hash=%s type=%d gas=%d isolated=%t input=%s)", f.tracerID, tx.Hash(), tx.Type(), tx.Gas(), f.transactionIsolated, inputView(tx.Data()))
f.ensureInBlockAndNotInTrxAndNotInCall()
f.evm = evm
var to common.Address
if tx.To() == nil {
to = crypto.CreateAddress(from, evm.StateDB.GetNonce(from))
} else {
to = *tx.To()
}
f.onTxStart(tx, tx.Hash(), from, to)
}
// onTxStart is used internally a two places, in the normal "tracer" and in the "OnGenesisBlock",
// we manually pass some override to the `tx` because genesis block has a different way of creating
// the transaction that wraps the genesis block.
func (f *Firehose) onTxStart(tx *types.Transaction, hash common.Hash, from, to common.Address) {
v, r, s := tx.RawSignatureValues()
var blobGas *uint64
if tx.Type() == types.BlobTxType {
blobGas = ptr(tx.BlobGas())
}
f.transaction = &pbeth.TransactionTrace{
BeginOrdinal: f.blockOrdinal.Next(),
Hash: hash.Bytes(),
From: from.Bytes(),
To: to.Bytes(),
Nonce: tx.Nonce(),
GasLimit: tx.Gas(),
GasPrice: gasPrice(tx, f.blockBaseFee),
Value: firehoseBigIntFromNative(tx.Value()),
Input: tx.Data(),
V: emptyBytesToNil(v.Bytes()),
R: normalizeSignaturePoint(r.Bytes()),
S: normalizeSignaturePoint(s.Bytes()),
Type: transactionTypeFromChainTxType(tx.Type()),
AccessList: newAccessListFromChain(tx.AccessList()),
MaxFeePerGas: maxFeePerGas(tx),
MaxPriorityFeePerGas: maxPriorityFeePerGas(tx),
BlobGas: blobGas,
BlobGasFeeCap: firehoseBigIntFromNative(tx.BlobGasFeeCap()),
BlobHashes: newBlobHashesFromChain(tx.BlobHashes()),
}
}
func (f *Firehose) OnTxEnd(receipt *types.Receipt, err error) {
firehoseInfo("trx ending (tracer=%s, isolated=%t, error=%s)", f.tracerID, f.transactionIsolated, errorView(err))
f.ensureInBlockAndInTrx()
trxTrace := f.completeTransaction(receipt)
// In this case, we are in some kind of parallel processing and we must simply add the transaction
// to a transient storage (and not in the block directly). Adding it to the block will be done by the
// `OnTxCommit` callback.
if f.transactionIsolated {
f.transactionTransient = trxTrace
// We must not reset transaction here. In the isolated transaction tracer, the transaction is reset
// by the `OnTxReset` callback which comes from outside the tracer. Second, resetting the transaction
// also resets the [f.transactionTransient] field which is the one we want to keep on completion
// of an isolated transaction.
} else {
f.block.TransactionTraces = append(f.block.TransactionTraces, trxTrace)
// The reset must be done as the very last thing as the CallStack needs to be
// properly populated for the `completeTransaction` call above to complete correctly.
f.resetTransaction()
}
firehoseInfo("trx end (tracer=%s)", f.tracerID)
}
func (f *Firehose) completeTransaction(receipt *types.Receipt) *pbeth.TransactionTrace {
firehoseInfo("completing transaction (call_count=%d receipt=%s)", len(f.transaction.Calls), (*receiptView)(receipt))
// Sorting needs to happen first, before we populate the state reverted
slices.SortFunc(f.transaction.Calls, func(i, j *pbeth.Call) int {
return cmp.Compare(i.Index, j.Index)
})
rootCall := f.transaction.Calls[0]
if !f.deferredCallState.IsEmpty() {
f.deferredCallState.MaybePopulateCallAndReset("root", rootCall)
}
// Receipt can be nil if an error occurred during the transaction execution, right now we don't have it
if receipt != nil {
f.transaction.Index = uint32(receipt.TransactionIndex)
f.transaction.GasUsed = receipt.GasUsed
f.transaction.Receipt = newTxReceiptFromChain(receipt, f.transaction.Type)
f.transaction.Status = transactionStatusFromChainTxReceipt(receipt.Status)
}
// It's possible that the transaction was reverted, but we still have a receipt, in that case, we must
// check the root call
if rootCall.StatusReverted {
f.transaction.Status = pbeth.TransactionTraceStatus_REVERTED
}
// Order is important, we must populate the state reverted before we remove the log block index and re-assign ordinals
f.populateStateReverted()
f.removeLogBlockIndexOnStateRevertedCalls()
f.assignOrdinalAndIndexToReceiptLogs()
if *f.applyBackwardCompatibility {
// Known Firehose issue: Failed call logging a log with no topics were not fixed in the old Firehose instrumentation
// leading to them to be rendered as `topics: [""]` instead of `topics: nil` like successful calls.
// Here we re-apply this bogus behavior.
f.noTopicsLogOnFailedCallSetToEmptyHash()
}
if *f.applyBackwardCompatibility {
// Known Firehose issue: This field has never been populated in the old Firehose instrumentation
} else {
f.transaction.ReturnData = rootCall.ReturnData
}
f.transaction.EndOrdinal = f.blockOrdinal.Next()
return f.transaction
}
func (f *Firehose) populateStateReverted() {
// Calls are ordered by execution index. So the algo is quite simple.
// We loop through the flat calls, at each call, if the parent is present
// and reverted, the current call is reverted. Otherwise, if the current call
// is failed, the state is reverted. In all other cases, we simply continue
// our iteration loop.
//
// This works because we see the parent before its children, and since we
// trickle down the state reverted value down the children, checking the parent
// of a call will always tell us if the whole chain of parent/child should
// be reverted
//
calls := f.transaction.Calls
for _, call := range f.transaction.Calls {
var parent *pbeth.Call
if call.ParentIndex > 0 {
parent = calls[call.ParentIndex-1]
}
call.StateReverted = (parent != nil && parent.StateReverted) || call.StatusFailed
}
}
func (f *Firehose) removeLogBlockIndexOnStateRevertedCalls() {
for _, call := range f.transaction.Calls {
if call.StateReverted {
for _, log := range call.Logs {
log.BlockIndex = 0
}
}
}
}
func (f *Firehose) assignOrdinalAndIndexToReceiptLogs() {
firehoseTrace("assigning ordinal and index to logs")
defer func() {
firehoseTrace("assigning ordinal and index to logs terminated")
}()
trx := f.transaction
callLogs := []*pbeth.Log{}
for _, call := range trx.Calls {
firehoseTrace("checking call (reverted=%t logs=%d)", call.StateReverted, len(call.Logs))
if call.StateReverted {
continue
}
callLogs = append(callLogs, call.Logs...)
}
slices.SortFunc(callLogs, func(i, j *pbeth.Log) int {
return cmp.Compare(i.Ordinal, j.Ordinal)
})
// When a transaction failed the receipt can be nil, so we need to deal with this
var receiptsLogs []*pbeth.Log
if trx.Receipt == nil {
if len(callLogs) == 0 {
// No logs in the transaction (nor in calls), nothing to do
return
}
panic(fmt.Errorf(
"mismatch between Firehose call logs and Ethereum transaction %s receipt logs at block #%d, the transaction has no receipt (failed) so there is no logs but it exists %d Firehose call logs",
hex.EncodeToString(trx.Hash),
f.block.Number,
len(callLogs),
))
} else {
receiptsLogs = trx.Receipt.Logs
}
if len(callLogs) != len(receiptsLogs) {
panic(fmt.Errorf(
"mismatch between Firehose call logs and Ethereum transaction %s receipt logs at block #%d, transaction receipt has %d logs but there is %d Firehose call logs",
hex.EncodeToString(trx.Hash),
f.block.Number,
len(receiptsLogs),
len(callLogs),
))
}
for i := 0; i < len(callLogs); i++ {
callLog := callLogs[i]
receiptsLog := receiptsLogs[i]
result := &validationResult{}
// Ordinal must **not** be checked as we are assigning it here below after the validations
validateBytesField(result, "Address", callLog.Address, receiptsLog.Address)
validateUint32Field(result, "BlockIndex", callLog.BlockIndex, receiptsLog.BlockIndex)
validateBytesField(result, "Data", callLog.Data, receiptsLog.Data)
validateArrayOfBytesField(result, "Topics", callLog.Topics, receiptsLog.Topics)
if len(result.failures) > 0 {
result.panicOnAnyFailures("mismatch between Firehose call log and Ethereum transaction receipt log at index %d", i)
}
receiptsLog.Index = callLog.Index
receiptsLog.Ordinal = callLog.Ordinal
}
}
func (f *Firehose) noTopicsLogOnFailedCallSetToEmptyHash() {
for _, call := range f.transaction.Calls {
if call.StateReverted {
for _, log := range call.Logs {
if len(log.Topics) == 0 {
log.Topics = make([][]byte, 1)
}
}
}
}
}
// OnCallEnter implements the EVMLogger interface to initialize the tracing operation.
func (f *Firehose) OnCallEnter(depth int, typ byte, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
opCode := vm.OpCode(typ)
var callType pbeth.CallType
if isRootCall := depth == 0; isRootCall {
callType = rootCallType(opCode == vm.CREATE)
} else {
// The invocation for vm.SELFDESTRUCT is called while already in another call and is recorded specially
// in the Geth tracer and generates `OnEnter/OnExit` callbacks. However in Firehose, self destruction
// simply sets the call as having called suicided so there is no extra call.
//
// So we ignore `OnEnter/OnExit` callbacks for `SELFDESTRUCT` opcode, we ignore it here and set
// a special sentinel variable that will tell `OnExit` to ignore itself.
if opCode == vm.SELFDESTRUCT {
// Firehose tracer 2.3 is recording the self destruct balance changes in a specific order which is
// the self destruct increase followed by the self destruct decrease. However Geth tracing API
// we now leverages to implement Firehose tracer does record the balance change in reversed order
// which is the self destruct decrease followed by the self destruct increase.
//
// To improve complexity, this is only true for Cancun rules, before Cancun, the order is actually
// still correct. This is because in the older Selfdestruct opcode, the balance was set to 0
// after the opcode ran so the decreased happened there before the increased.
//
// So if we are in compatibility mode and the block is Cancun, we must reorder the balance changes
// to match the Firehose 2.3 behavior.
if *f.applyBackwardCompatibility && f.blockRules.IsCancun {
f.maybeReorderSelfDestructBalanceChanges()
}
firehoseDebug("ignoring OnCallEnter for SELFDESTRUCT opcode, not recorded as a call")
// The next OnCallExit must be ignored, this variable will make the next OnCallExit to be ignored
f.latestCallEnterSuicided = true
return
}
callType = callTypeFromOpCode(opCode)
if callType == pbeth.CallType_UNSPECIFIED {
panic(fmt.Errorf("unexpected call type, received OpCode %s but only call related opcode (CALL, CREATE, CREATE2, STATIC, DELEGATECALL and CALLCODE) or SELFDESTRUCT is accepted", opCode))
}
}
f.callStart(computeCallSource(depth), callType, from, to, input, gas, value)
}
func (f *Firehose) maybeReorderSelfDestructBalanceChanges() {
type indexedBalanceChange struct {
index int
ordinal uint64
change *pbeth.BalanceChange
}
f.ensureInCall()
activeCall := f.callStack.Peek()
var increaseBalanceChange indexedBalanceChange
var decreaseBalanceChange indexedBalanceChange
for index, change := range activeCall.BalanceChanges {
switch change.Reason {
case pbeth.BalanceChange_REASON_SUICIDE_WITHDRAW:
if decreaseBalanceChange.change != nil {
f.panicInvalidState(fmt.Sprintf("more than one balance change with reason REASON_SUICIDE_WITHDRAW found in call #%d, this is not expected", activeCall.Index), 0)
}
decreaseBalanceChange.index = index
decreaseBalanceChange.ordinal = change.Ordinal
decreaseBalanceChange.change = change
case pbeth.BalanceChange_REASON_SUICIDE_REFUND:
if increaseBalanceChange.change != nil {
f.panicInvalidState(fmt.Sprintf("more than one balance change with reason REASON_SUICIDE_REFUND found in call #%d, this is not expected", activeCall.Index), 0)
}
increaseBalanceChange.index = index
increaseBalanceChange.ordinal = change.Ordinal
increaseBalanceChange.change = change
}
}
// Nothing to do if there is only one side
if decreaseBalanceChange.change == nil || increaseBalanceChange.change == nil {
return
}
// Nothing to do if they are already ordered according to Firehose 2.3 rules
if decreaseBalanceChange.index > increaseBalanceChange.index {
return
}
// Otherwise, invert them and their ordinal
decreaseBalanceChange.change.Ordinal = increaseBalanceChange.ordinal
increaseBalanceChange.change.Ordinal = decreaseBalanceChange.ordinal
activeCall.BalanceChanges[decreaseBalanceChange.index] = increaseBalanceChange.change
activeCall.BalanceChanges[increaseBalanceChange.index] = decreaseBalanceChange.change
}
// OnCallExit is called after the call finishes to finalize the tracing.
func (f *Firehose) OnCallExit(depth int, output []byte, gasUsed uint64, err error, reverted bool) {
f.callEnd(computeCallSource(depth), output, gasUsed, err, reverted)
}
// OnOpcode implements the EVMLogger interface to trace a single step of VM execution.
func (f *Firehose) OnOpcode(pc uint64, op byte, gas, cost uint64, scope tracing.OpContext, rData []byte, depth int, err error) {
firehoseTraceFull("on opcode (op=%s gas=%d cost=%d, err=%s)", vm.OpCode(op), gas, cost, errorView(err))
if activeCall := f.callStack.Peek(); activeCall != nil {
opCode := vm.OpCode(op)
f.captureInterpreterStep(activeCall, pc, opCode, gas, cost, scope, rData, depth, err)
// The rest of the logic expects that a call succeeded, nothing to do more here if the interpreter failed on this OpCode
if err != nil {
return
}
// The gas change must come first to retain Firehose backward compatibility. Indeed, before Firehose 3.0,
// we had a specific method `OnKeccakPreimage` that was called during the KECCAK256 opcode. However, in
// the new model, we do it through `OnOpcode`.
//
// The gas change recording in the previous Firehose patch was done before calling `OnKeccakPreimage` so
// we must do the same here.
//
// No need to wrap in apply backward compatibility, the old behavior is fine in all cases.
if cost > 0 {
if reason, found := opCodeToGasChangeReasonMap[opCode]; found {
activeCall.GasChanges = append(activeCall.GasChanges, f.newGasChange("state", gas, gas-cost, reason))
}
}
switch opCode {
case vm.KECCAK256:
f.onOpcodeKeccak256(activeCall, scope.StackData(), Memory(scope.MemoryData()))
case vm.SELFDESTRUCT:
f.ensureInCall()
f.callStack.Peek().Suicide = true
}
}
}
// onOpcodeKeccak256 is called during the SHA3 (a.k.a KECCAK256) opcode it's known
// in Firehose tracer as Keccak preimages. The preimage is the input data that
// was used to produce the given keccak hash.
func (f *Firehose) onOpcodeKeccak256(call *pbeth.Call, stack []uint256.Int, memory Memory) {
if call.KeccakPreimages == nil {
call.KeccakPreimages = make(map[string]string)
}
offset, size := stack[len(stack)-1], stack[len(stack)-2]
preImage := memory.GetPtrUint256(&offset, &size)
// We should have exclusive access to the hasher, we can safely reset it.
f.hasher.Reset()
f.hasher.Write(preImage)
f.hasher.Read(f.hasherBuf[:])
encodedData := hex.EncodeToString(preImage)
if *f.applyBackwardCompatibility {
// Known Firehose issue: It appears the old Firehose instrumentation have a bug
// where when the keccak256 preimage is empty, it is written as "." which is
// completely wrong.
//
// To keep the same behavior, we will write the preimage as a "." when the encoded
// data is an empty string.
if encodedData == "" {
encodedData = "."
}
}
call.KeccakPreimages[hex.EncodeToString(f.hasherBuf[:])] = encodedData
}
var opCodeToGasChangeReasonMap = map[vm.OpCode]pbeth.GasChange_Reason{
vm.CREATE: pbeth.GasChange_REASON_CONTRACT_CREATION,
vm.CREATE2: pbeth.GasChange_REASON_CONTRACT_CREATION2,
vm.CALL: pbeth.GasChange_REASON_CALL,
vm.STATICCALL: pbeth.GasChange_REASON_STATIC_CALL,
vm.CALLCODE: pbeth.GasChange_REASON_CALL_CODE,
vm.DELEGATECALL: pbeth.GasChange_REASON_DELEGATE_CALL,
vm.RETURN: pbeth.GasChange_REASON_RETURN,
vm.REVERT: pbeth.GasChange_REASON_REVERT,
vm.LOG0: pbeth.GasChange_REASON_EVENT_LOG,
vm.LOG1: pbeth.GasChange_REASON_EVENT_LOG,
vm.LOG2: pbeth.GasChange_REASON_EVENT_LOG,
vm.LOG3: pbeth.GasChange_REASON_EVENT_LOG,
vm.LOG4: pbeth.GasChange_REASON_EVENT_LOG,
vm.SELFDESTRUCT: pbeth.GasChange_REASON_SELF_DESTRUCT,
vm.CALLDATACOPY: pbeth.GasChange_REASON_CALL_DATA_COPY,
vm.CODECOPY: pbeth.GasChange_REASON_CODE_COPY,
vm.EXTCODECOPY: pbeth.GasChange_REASON_EXT_CODE_COPY,
vm.RETURNDATACOPY: pbeth.GasChange_REASON_RETURN_DATA_COPY,
}
// OnOpcodeFault implements the EVMLogger interface to trace an execution fault.
func (f *Firehose) OnOpcodeFault(pc uint64, op byte, gas, cost uint64, scope tracing.OpContext, depth int, err error) {
firehoseTraceFull("on opcode fault (op=%s gas=%d cost=%d, err=%s)", vm.OpCode(op), gas, cost, errorView(err))
if activeCall := f.callStack.Peek(); activeCall != nil {
f.captureInterpreterStep(activeCall, pc, vm.OpCode(op), gas, cost, scope, nil, depth, err)
}
}
func (f *Firehose) captureInterpreterStep(activeCall *pbeth.Call, pc uint64, op vm.OpCode, gas, cost uint64, _ tracing.OpContext, rData []byte, depth int, err error) {
if *f.applyBackwardCompatibility {
// for call, we need to process the executed code here
// since in old firehose executed code calculation depends if the code exist
if activeCall.CallType == pbeth.CallType_CALL && !activeCall.ExecutedCode {
activeCall.ExecutedCode = len(activeCall.Input) > 0
}
} else {
activeCall.ExecutedCode = true
}
}
func (f *Firehose) callStart(source string, callType pbeth.CallType, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
firehoseDebug("call start (source=%s index=%d type=%s input=%s)", source, f.callStack.NextIndex(), callType, inputView(input))
f.ensureInBlockAndInTrx()