-
Notifications
You must be signed in to change notification settings - Fork 139
/
blockchain.go
2215 lines (1954 loc) · 84.7 KB
/
blockchain.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
// (c) 2019-2020, Ava Labs, Inc.
//
// This file is a derived work, based on the go-ethereum library whose original
// notices appear below.
//
// It is distributed under a license compatible with the licensing terms of the
// original code from which it is derived.
//
// Much love to the original authors for their work.
// **********
// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package core implements the Ethereum consensus protocol.
package core
import (
"context"
"errors"
"fmt"
"io"
"math/big"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/ava-labs/coreth/consensus"
"github.com/ava-labs/coreth/consensus/misc/eip4844"
"github.com/ava-labs/coreth/core/rawdb"
"github.com/ava-labs/coreth/core/state"
"github.com/ava-labs/coreth/core/state/snapshot"
"github.com/ava-labs/coreth/core/types"
"github.com/ava-labs/coreth/core/vm"
"github.com/ava-labs/coreth/internal/version"
"github.com/ava-labs/coreth/metrics"
"github.com/ava-labs/coreth/params"
"github.com/ava-labs/coreth/trie"
"github.com/ava-labs/coreth/trie/triedb/hashdb"
"github.com/ava-labs/coreth/trie/triedb/pathdb"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/lru"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/log"
)
var (
accountReadTimer = metrics.NewRegisteredCounter("chain/account/reads", nil)
accountHashTimer = metrics.NewRegisteredCounter("chain/account/hashes", nil)
accountUpdateTimer = metrics.NewRegisteredCounter("chain/account/updates", nil)
accountCommitTimer = metrics.NewRegisteredCounter("chain/account/commits", nil)
storageReadTimer = metrics.NewRegisteredCounter("chain/storage/reads", nil)
storageHashTimer = metrics.NewRegisteredCounter("chain/storage/hashes", nil)
storageUpdateTimer = metrics.NewRegisteredCounter("chain/storage/updates", nil)
storageCommitTimer = metrics.NewRegisteredCounter("chain/storage/commits", nil)
snapshotAccountReadTimer = metrics.NewRegisteredCounter("chain/snapshot/account/reads", nil)
snapshotStorageReadTimer = metrics.NewRegisteredCounter("chain/snapshot/storage/reads", nil)
snapshotCommitTimer = metrics.NewRegisteredCounter("chain/snapshot/commits", nil)
triedbCommitTimer = metrics.NewRegisteredCounter("chain/triedb/commits", nil)
blockInsertTimer = metrics.NewRegisteredCounter("chain/block/inserts", nil)
blockInsertCount = metrics.NewRegisteredCounter("chain/block/inserts/count", nil)
blockContentValidationTimer = metrics.NewRegisteredCounter("chain/block/validations/content", nil)
blockStateInitTimer = metrics.NewRegisteredCounter("chain/block/inits/state", nil)
blockExecutionTimer = metrics.NewRegisteredCounter("chain/block/executions", nil)
blockTrieOpsTimer = metrics.NewRegisteredCounter("chain/block/trie", nil)
blockValidationTimer = metrics.NewRegisteredCounter("chain/block/validations/state", nil)
blockWriteTimer = metrics.NewRegisteredCounter("chain/block/writes", nil)
acceptorQueueGauge = metrics.NewRegisteredGauge("chain/acceptor/queue/size", nil)
acceptorWorkTimer = metrics.NewRegisteredCounter("chain/acceptor/work", nil)
acceptorWorkCount = metrics.NewRegisteredCounter("chain/acceptor/work/count", nil)
processedBlockGasUsedCounter = metrics.NewRegisteredCounter("chain/block/gas/used/processed", nil)
acceptedBlockGasUsedCounter = metrics.NewRegisteredCounter("chain/block/gas/used/accepted", nil)
badBlockCounter = metrics.NewRegisteredCounter("chain/block/bad/count", nil)
txUnindexTimer = metrics.NewRegisteredCounter("chain/txs/unindex", nil)
acceptedTxsCounter = metrics.NewRegisteredCounter("chain/txs/accepted", nil)
processedTxsCounter = metrics.NewRegisteredCounter("chain/txs/processed", nil)
acceptedLogsCounter = metrics.NewRegisteredCounter("chain/logs/accepted", nil)
processedLogsCounter = metrics.NewRegisteredCounter("chain/logs/processed", nil)
ErrRefuseToCorruptArchiver = errors.New("node has operated with pruning disabled, shutting down to prevent missing tries")
errFutureBlockUnsupported = errors.New("future block insertion not supported")
errCacheConfigNotSpecified = errors.New("must specify cache config")
errInvalidOldChain = errors.New("invalid old chain")
errInvalidNewChain = errors.New("invalid new chain")
)
const (
bodyCacheLimit = 256
blockCacheLimit = 256
receiptsCacheLimit = 32
txLookupCacheLimit = 1024
badBlockLimit = 10
// BlockChainVersion ensures that an incompatible database forces a resync from scratch.
//
// Changelog:
//
// - Version 4
// The following incompatible database changes were added:
// * the `BlockNumber`, `TxHash`, `TxIndex`, `BlockHash` and `Index` fields of log are deleted
// * the `Bloom` field of receipt is deleted
// * the `BlockIndex` and `TxIndex` fields of txlookup are deleted
// - Version 5
// The following incompatible database changes were added:
// * the `TxHash`, `GasCost`, and `ContractAddress` fields are no longer stored for a receipt
// * the `TxHash`, `GasCost`, and `ContractAddress` fields are computed by looking up the
// receipts' corresponding block
// - Version 6
// The following incompatible database changes were added:
// * Transaction lookup information stores the corresponding block number instead of block hash
// - Version 7
// The following incompatible database changes were added:
// * Use freezer as the ancient database to maintain all ancient data
// - Version 8
// The following incompatible database changes were added:
// * New scheme for contract code in order to separate the codes and trie nodes
BlockChainVersion uint64 = 8
// statsReportLimit is the time limit during import and export after which we
// always print out progress. This avoids the user wondering what's going on.
statsReportLimit = 8 * time.Second
// trieCleanCacheStatsNamespace is the namespace to surface stats from the trie
// clean cache's underlying fastcache.
trieCleanCacheStatsNamespace = "hashdb/memcache/clean/fastcache"
)
// CacheConfig contains the configuration values for the trie database
// and state snapshot these are resident in a blockchain.
type CacheConfig struct {
TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory
TrieDirtyLimit int // Memory limit (MB) at which to block on insert and force a flush of dirty trie nodes to disk
TrieDirtyCommitTarget int // Memory limit (MB) to target for the dirties cache before invoking commit
TriePrefetcherParallelism int // Max concurrent disk reads trie prefetcher should perform at once
CommitInterval uint64 // Commit the trie every [CommitInterval] blocks.
Pruning bool // Whether to disable trie write caching and GC altogether (archive node)
AcceptorQueueLimit int // Blocks to queue before blocking during acceptance
PopulateMissingTries *uint64 // If non-nil, sets the starting height for re-generating historical tries.
PopulateMissingTriesParallelism int // Number of readers to use when trying to populate missing tries.
AllowMissingTries bool // Whether to allow an archive node to run with pruning enabled
SnapshotDelayInit bool // Whether to initialize snapshots on startup or wait for external call (= StateSyncEnabled)
SnapshotLimit int // Memory allowance (MB) to use for caching snapshot entries in memory
SnapshotVerify bool // Verify generated snapshots
Preimages bool // Whether to store preimage of trie key to the disk
AcceptedCacheSize int // Depth of accepted headers cache and accepted logs cache at the accepted tip
TxLookupLimit uint64 // Number of recent blocks for which to maintain transaction lookup indices
SkipTxIndexing bool // Whether to skip transaction indexing
StateHistory uint64 // Number of blocks from head whose state histories are reserved.
StateScheme string // Scheme used to store ethereum states and merkle tree nodes on top
SnapshotNoBuild bool // Whether the background generation is allowed
SnapshotWait bool // Wait for snapshot construction on startup. TODO(karalabe): This is a dirty hack for testing, nuke it
}
// triedbConfig derives the configures for trie database.
func (c *CacheConfig) triedbConfig() *trie.Config {
config := &trie.Config{Preimages: c.Preimages}
if c.StateScheme == rawdb.HashScheme {
config.HashDB = &hashdb.Config{
CleanCacheSize: c.TrieCleanLimit * 1024 * 1024,
StatsPrefix: trieCleanCacheStatsNamespace,
}
}
if c.StateScheme == rawdb.PathScheme {
config.PathDB = &pathdb.Config{
StateHistory: c.StateHistory,
CleanCacheSize: c.TrieCleanLimit * 1024 * 1024,
DirtyCacheSize: c.TrieDirtyLimit * 1024 * 1024,
}
}
return config
}
// DefaultCacheConfig are the default caching values if none are specified by the
// user (also used during testing).
var DefaultCacheConfig = &CacheConfig{
TrieCleanLimit: 256,
TrieDirtyLimit: 256,
TrieDirtyCommitTarget: 20, // 20% overhead in memory counting (this targets 16 MB)
TriePrefetcherParallelism: 16,
Pruning: true,
CommitInterval: 4096,
AcceptorQueueLimit: 64, // Provides 2 minutes of buffer (2s block target) for a commit delay
SnapshotLimit: 256,
AcceptedCacheSize: 32,
StateScheme: rawdb.HashScheme,
}
// DefaultCacheConfigWithScheme returns a deep copied default cache config with
// a provided trie node scheme.
func DefaultCacheConfigWithScheme(scheme string) *CacheConfig {
config := *DefaultCacheConfig
config.StateScheme = scheme
return &config
}
// BlockChain represents the canonical chain given a database with a genesis
// block. The Blockchain manages chain imports, reverts, chain reorganisations.
//
// Importing blocks in to the block chain happens according to the set of rules
// defined by the two stage Validator. Processing of blocks is done using the
// Processor which processes the included transaction. The validation of the state
// is done in the second part of the Validator. Failing results in aborting of
// the import.
//
// The BlockChain also helps in returning blocks from **any** chain included
// in the database as well as blocks that represents the canonical chain. It's
// important to note that GetBlock can return any block and does not need to be
// included in the canonical one where as GetBlockByNumber always represents the
// canonical chain.
type BlockChain struct {
chainConfig *params.ChainConfig // Chain & network configuration
cacheConfig *CacheConfig // Cache configuration for pruning
db ethdb.Database // Low level persistent database to store final content in
snaps *snapshot.Tree // Snapshot tree for fast trie leaf access
triedb *trie.Database // The database handler for maintaining trie nodes.
stateCache state.Database // State database to reuse between imports (contains state cache)
stateManager TrieWriter
hc *HeaderChain
rmLogsFeed event.Feed
chainFeed event.Feed
chainSideFeed event.Feed
chainHeadFeed event.Feed
chainAcceptedFeed event.Feed
logsFeed event.Feed
logsAcceptedFeed event.Feed
blockProcFeed event.Feed
txAcceptedFeed event.Feed
scope event.SubscriptionScope
genesisBlock *types.Block
// This mutex synchronizes chain write operations.
// Readers don't need to take it, they can just read the database.
chainmu sync.RWMutex
currentBlock atomic.Pointer[types.Header] // Current head of the block chain
bodyCache *lru.Cache[common.Hash, *types.Body] // Cache for the most recent block bodies
receiptsCache *lru.Cache[common.Hash, []*types.Receipt] // Cache for the most recent receipts per block
blockCache *lru.Cache[common.Hash, *types.Block] // Cache for the most recent entire blocks
txLookupCache *lru.Cache[common.Hash, *rawdb.LegacyTxLookupEntry] // Cache for the most recent transaction lookup data.
badBlocks *lru.Cache[common.Hash, *badBlock] // Cache for bad blocks
stopping atomic.Bool // false if chain is running, true when stopped
engine consensus.Engine
validator Validator // Block and state validator interface
processor Processor // Block transaction processor interface
vmConfig vm.Config
lastAccepted *types.Block // Prevents reorgs past this height
senderCacher *TxSenderCacher
// [acceptorQueue] is a processing queue for the Acceptor. This is
// different than [chainAcceptedFeed], which is sent an event after an accepted
// block is processed (after each loop of the accepted worker). If there is a
// clean shutdown, all items inserted into the [acceptorQueue] will be processed.
acceptorQueue chan *types.Block
// [acceptorClosingLock], and [acceptorClosed] are used
// to synchronize the closing of the [acceptorQueue] channel.
//
// Because we can't check if a channel is closed without reading from it
// (which we don't want to do as we may remove a processing block), we need
// to use a second variable to ensure we don't close a closed channel.
acceptorClosingLock sync.RWMutex
acceptorClosed bool
// [acceptorWg] is used to wait for the acceptorQueue to clear. This is used
// during shutdown and in tests.
acceptorWg sync.WaitGroup
// [wg] is used to wait for the async blockchain processes to finish on shutdown.
wg sync.WaitGroup
// quit channel is used to listen for when the blockchain is shut down to close
// async processes.
// WaitGroups are used to ensure that async processes have finished during shutdown.
quit chan struct{}
// [acceptorTip] is the last block processed by the acceptor. This is
// returned as the LastAcceptedBlock() to ensure clients get only fully
// processed blocks. This may be equal to [lastAccepted].
acceptorTip *types.Block
acceptorTipLock sync.Mutex
// [flattenLock] prevents the [acceptor] from flattening snapshots while
// a block is being verified.
flattenLock sync.Mutex
// [acceptedLogsCache] stores recently accepted logs to improve the performance of eth_getLogs.
acceptedLogsCache FIFOCache[common.Hash, [][]*types.Log]
// [txIndexTailLock] is used to synchronize the updating of the tx index tail.
txIndexTailLock sync.Mutex
}
// NewBlockChain returns a fully initialised block chain using information
// available in the database. It initialises the default Ethereum Validator and
// Processor.
func NewBlockChain(
db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis, engine consensus.Engine,
vmConfig vm.Config, lastAcceptedHash common.Hash, skipChainConfigCheckCompatible bool,
) (*BlockChain, error) {
if cacheConfig == nil {
return nil, errCacheConfigNotSpecified
}
// Open trie database with provided config
triedb := trie.NewDatabase(db, cacheConfig.triedbConfig())
// Setup the genesis block, commit the provided genesis specification
// to database if the genesis block is not present yet, or load the
// stored one from database.
// Note: In go-ethereum, the code rewinds the chain on an incompatible config upgrade.
// We don't do this and expect the node operator to always update their node's configuration
// before network upgrades take effect.
chainConfig, _, err := SetupGenesisBlock(db, triedb, genesis, lastAcceptedHash, skipChainConfigCheckCompatible)
if err != nil {
return nil, err
}
log.Info("")
log.Info(strings.Repeat("-", 153))
for _, line := range strings.Split(chainConfig.Description(), "\n") {
log.Info(line)
}
log.Info(strings.Repeat("-", 153))
log.Info("")
bc := &BlockChain{
chainConfig: chainConfig,
cacheConfig: cacheConfig,
db: db,
triedb: triedb,
bodyCache: lru.NewCache[common.Hash, *types.Body](bodyCacheLimit),
receiptsCache: lru.NewCache[common.Hash, []*types.Receipt](receiptsCacheLimit),
blockCache: lru.NewCache[common.Hash, *types.Block](blockCacheLimit),
txLookupCache: lru.NewCache[common.Hash, *rawdb.LegacyTxLookupEntry](txLookupCacheLimit),
badBlocks: lru.NewCache[common.Hash, *badBlock](badBlockLimit),
engine: engine,
vmConfig: vmConfig,
senderCacher: NewTxSenderCacher(runtime.NumCPU()),
acceptorQueue: make(chan *types.Block, cacheConfig.AcceptorQueueLimit),
quit: make(chan struct{}),
acceptedLogsCache: NewFIFOCache[common.Hash, [][]*types.Log](cacheConfig.AcceptedCacheSize),
}
bc.stateCache = state.NewDatabaseWithNodeDB(bc.db, bc.triedb)
bc.validator = NewBlockValidator(chainConfig, bc, engine)
bc.processor = NewStateProcessor(chainConfig, bc, engine)
bc.hc, err = NewHeaderChain(db, chainConfig, cacheConfig, engine)
if err != nil {
return nil, err
}
bc.genesisBlock = bc.GetBlockByNumber(0)
if bc.genesisBlock == nil {
return nil, ErrNoGenesis
}
bc.currentBlock.Store(nil)
// Create the state manager
bc.stateManager = NewTrieWriter(bc.triedb, cacheConfig)
// Re-generate current block state if it is missing
if err := bc.loadLastState(lastAcceptedHash); err != nil {
return nil, err
}
// After loading the last state (and reprocessing if necessary), we are
// guaranteed that [acceptorTip] is equal to [lastAccepted].
//
// It is critical to update this vaue before performing any state repairs so
// that all accepted blocks can be considered.
bc.acceptorTip = bc.lastAccepted
// Make sure the state associated with the block is available
head := bc.CurrentBlock()
if !bc.HasState(head.Root) {
return nil, fmt.Errorf("head state missing %d:%s", head.Number, head.Hash())
}
if err := bc.protectTrieIndex(); err != nil {
return nil, err
}
// Populate missing tries if required
if err := bc.populateMissingTries(); err != nil {
return nil, fmt.Errorf("could not populate missing tries: %v", err)
}
// If snapshot initialization is delayed for fast sync, skip initializing it here.
// This assumes that no blocks will be processed until ResetState is called to initialize
// the state of fast sync.
if !bc.cacheConfig.SnapshotDelayInit {
// Load any existing snapshot, regenerating it if loading failed (if not
// already initialized in recovery)
bc.initSnapshot(head)
}
// Warm up [hc.acceptedNumberCache] and [acceptedLogsCache]
bc.warmAcceptedCaches()
// if txlookup limit is 0 (uindexing disabled), we don't need to repair the tx index tail.
if bc.cacheConfig.TxLookupLimit != 0 {
latestStateSynced := rawdb.GetLatestSyncPerformed(bc.db)
bc.setTxIndexTail(latestStateSynced)
}
// Start processing accepted blocks effects in the background
go bc.startAcceptor()
// Start tx indexer/unindexer if required.
if bc.cacheConfig.TxLookupLimit != 0 {
bc.wg.Add(1)
var (
headCh = make(chan ChainEvent, 1) // Buffered to avoid locking up the event feed
sub = bc.SubscribeChainAcceptedEvent(headCh)
)
go func() {
defer bc.wg.Done()
if sub == nil {
log.Warn("could not create chain accepted subscription to unindex txs")
return
}
defer sub.Unsubscribe()
bc.maintainTxIndex(headCh)
}()
}
return bc, nil
}
// unindexBlocks unindexes transactions depending on user configuration
func (bc *BlockChain) unindexBlocks(tail uint64, head uint64, done chan struct{}) {
start := time.Now()
txLookupLimit := bc.cacheConfig.TxLookupLimit
bc.txIndexTailLock.Lock()
defer func() {
txUnindexTimer.Inc(time.Since(start).Milliseconds())
bc.txIndexTailLock.Unlock()
close(done)
bc.wg.Done()
}()
// If head is 0, it means the chain is just initialized and no blocks are inserted,
// so don't need to indexing anything.
if head == 0 {
return
}
if head-txLookupLimit+1 >= tail {
// Unindex a part of stale indices and forward index tail to HEAD-limit
rawdb.UnindexTransactions(bc.db, tail, head-txLookupLimit+1, bc.quit)
}
}
// maintainTxIndex is responsible for the deletion of the
// transaction index. This does not support reconstruction of removed indexes.
// Invariant: If TxLookupLimit is 0, it means all tx indices will be preserved.
// Meaning that this function should never be called.
func (bc *BlockChain) maintainTxIndex(headCh <-chan ChainEvent) {
txLookupLimit := bc.cacheConfig.TxLookupLimit
// If the user just upgraded to a new version which supports transaction
// index pruning, write the new tail and remove anything older.
if rawdb.ReadTxIndexTail(bc.db) == nil {
rawdb.WriteTxIndexTail(bc.db, 0)
}
// Any reindexing done, start listening to chain events and moving the index window
var (
done chan struct{} // Non-nil if background unindexing or reindexing routine is active.
)
log.Info("Initialized transaction unindexer", "limit", txLookupLimit)
// Launch the initial processing if chain is not empty. This step is
// useful in these scenarios that chain has no progress and indexer
// is never triggered.
if head := bc.CurrentBlock(); head != nil && head.Number.Uint64() > txLookupLimit {
done = make(chan struct{})
tail := rawdb.ReadTxIndexTail(bc.db)
bc.wg.Add(1)
go bc.unindexBlocks(*tail, head.Number.Uint64(), done)
}
for {
select {
case head := <-headCh:
headNum := head.Block.NumberU64()
if headNum < txLookupLimit {
break
}
if done == nil {
done = make(chan struct{})
// Note: tail will not be nil since it is initialized in this function.
tail := rawdb.ReadTxIndexTail(bc.db)
bc.wg.Add(1)
go bc.unindexBlocks(*tail, headNum, done)
}
case <-done:
done = nil
case <-bc.quit:
if done != nil {
log.Info("Waiting background transaction unindexer to exit")
<-done
}
return
}
}
}
// writeBlockAcceptedIndices writes any indices that must be persisted for accepted block.
// This includes the following:
// - transaction lookup indices
// - updating the acceptor tip index
func (bc *BlockChain) writeBlockAcceptedIndices(b *types.Block) error {
batch := bc.db.NewBatch()
if err := bc.batchBlockAcceptedIndices(batch, b); err != nil {
return err
}
if err := batch.Write(); err != nil {
return fmt.Errorf("%w: failed to write accepted indices entries batch", err)
}
return nil
}
func (bc *BlockChain) batchBlockAcceptedIndices(batch ethdb.Batch, b *types.Block) error {
if !bc.cacheConfig.SkipTxIndexing {
rawdb.WriteTxLookupEntriesByBlock(batch, b)
}
if err := rawdb.WriteAcceptorTip(batch, b.Hash()); err != nil {
return fmt.Errorf("%w: failed to write acceptor tip key", err)
}
return nil
}
// flattenSnapshot attempts to flatten a block of [hash] to disk.
func (bc *BlockChain) flattenSnapshot(postAbortWork func() error, hash common.Hash) error {
// If snapshots are not initialized, perform [postAbortWork] immediately.
if bc.snaps == nil {
return postAbortWork()
}
// Abort snapshot generation before pruning anything from trie database
// (could occur in AcceptTrie)
bc.snaps.AbortGeneration()
// Perform work after snapshot generation is aborted (typically trie updates)
if err := postAbortWork(); err != nil {
return err
}
// Ensure we avoid flattening the snapshot while we are processing a block, or
// block execution will fallback to reading from the trie (which is much
// slower).
bc.flattenLock.Lock()
defer bc.flattenLock.Unlock()
// Flatten the entire snap Trie to disk
//
// Note: This resumes snapshot generation.
return bc.snaps.Flatten(hash)
}
// warmAcceptedCaches fetches previously accepted headers and logs from disk to
// pre-populate [hc.acceptedNumberCache] and [acceptedLogsCache].
func (bc *BlockChain) warmAcceptedCaches() {
var (
startTime = time.Now()
lastAccepted = bc.LastAcceptedBlock().NumberU64()
startIndex = uint64(1)
targetCacheSize = uint64(bc.cacheConfig.AcceptedCacheSize)
)
if targetCacheSize == 0 {
log.Info("Not warming accepted cache because disabled")
return
}
if lastAccepted < startIndex {
// This could occur if we haven't accepted any blocks yet
log.Info("Not warming accepted cache because there are no accepted blocks")
return
}
cacheDiff := targetCacheSize - 1 // last accepted lookback is inclusive, so we reduce size by 1
if cacheDiff < lastAccepted {
startIndex = lastAccepted - cacheDiff
}
for i := startIndex; i <= lastAccepted; i++ {
block := bc.GetBlockByNumber(i)
if block == nil {
// This could happen if a node state-synced
log.Info("Exiting accepted cache warming early because header is nil", "height", i, "t", time.Since(startTime))
break
}
// TODO: handle blocks written to disk during state sync
bc.hc.acceptedNumberCache.Put(block.NumberU64(), block.Header())
logs := bc.collectUnflattenedLogs(block, false)
bc.acceptedLogsCache.Put(block.Hash(), logs)
}
log.Info("Warmed accepted caches", "start", startIndex, "end", lastAccepted, "t", time.Since(startTime))
}
// startAcceptor starts processing items on the [acceptorQueue]. If a [nil]
// object is placed on the [acceptorQueue], the [startAcceptor] will exit.
func (bc *BlockChain) startAcceptor() {
log.Info("Starting Acceptor", "queue length", bc.cacheConfig.AcceptorQueueLimit)
for next := range bc.acceptorQueue {
start := time.Now()
acceptorQueueGauge.Dec(1)
if err := bc.flattenSnapshot(func() error {
return bc.stateManager.AcceptTrie(next)
}, next.Hash()); err != nil {
log.Crit("unable to flatten snapshot from acceptor", "blockHash", next.Hash(), "err", err)
}
// Update last processed and transaction lookup index
if err := bc.writeBlockAcceptedIndices(next); err != nil {
log.Crit("failed to write accepted block effects", "err", err)
}
// Ensure [hc.acceptedNumberCache] and [acceptedLogsCache] have latest content
bc.hc.acceptedNumberCache.Put(next.NumberU64(), next.Header())
logs := bc.collectUnflattenedLogs(next, false)
bc.acceptedLogsCache.Put(next.Hash(), logs)
// Update the acceptor tip before sending events to ensure that any client acting based off of
// the events observes the updated acceptorTip on subsequent requests
bc.acceptorTipLock.Lock()
bc.acceptorTip = next
bc.acceptorTipLock.Unlock()
// Update accepted feeds
flattenedLogs := types.FlattenLogs(logs)
bc.chainAcceptedFeed.Send(ChainEvent{Block: next, Hash: next.Hash(), Logs: flattenedLogs})
if len(flattenedLogs) > 0 {
bc.logsAcceptedFeed.Send(flattenedLogs)
}
if len(next.Transactions()) != 0 {
bc.txAcceptedFeed.Send(NewTxsEvent{next.Transactions()})
}
bc.acceptorWg.Done()
acceptorWorkTimer.Inc(time.Since(start).Milliseconds())
acceptorWorkCount.Inc(1)
// Note: in contrast to most accepted metrics, we increment the accepted log metrics in the acceptor queue because
// the logs are already processed in the acceptor queue.
acceptedLogsCounter.Inc(int64(len(logs)))
}
}
// addAcceptorQueue adds a new *types.Block to the [acceptorQueue]. This will
// block if there are [AcceptorQueueLimit] items in [acceptorQueue].
func (bc *BlockChain) addAcceptorQueue(b *types.Block) {
// We only acquire a read lock here because it is ok to add items to the
// [acceptorQueue] concurrently.
bc.acceptorClosingLock.RLock()
defer bc.acceptorClosingLock.RUnlock()
if bc.acceptorClosed {
return
}
acceptorQueueGauge.Inc(1)
bc.acceptorWg.Add(1)
bc.acceptorQueue <- b
}
// DrainAcceptorQueue blocks until all items in [acceptorQueue] have been
// processed.
func (bc *BlockChain) DrainAcceptorQueue() {
bc.acceptorClosingLock.RLock()
defer bc.acceptorClosingLock.RUnlock()
if bc.acceptorClosed {
return
}
bc.acceptorWg.Wait()
}
// stopAcceptor sends a signal to the Acceptor to stop processing accepted
// blocks. The Acceptor will exit once all items in [acceptorQueue] have been
// processed.
func (bc *BlockChain) stopAcceptor() {
bc.acceptorClosingLock.Lock()
defer bc.acceptorClosingLock.Unlock()
// If [acceptorClosed] is already false, we should just return here instead
// of attempting to close [acceptorQueue] more than once (will cause
// a panic).
//
// This typically happens when a test calls [stopAcceptor] directly (prior to
// shutdown) and then [stopAcceptor] is called again in shutdown.
if bc.acceptorClosed {
return
}
// Although nothing should be added to [acceptorQueue] after
// [acceptorClosed] is updated, we close the channel so the Acceptor
// goroutine exits.
bc.acceptorWg.Wait()
bc.acceptorClosed = true
close(bc.acceptorQueue)
}
func (bc *BlockChain) InitializeSnapshots() {
bc.chainmu.Lock()
defer bc.chainmu.Unlock()
head := bc.CurrentBlock()
bc.initSnapshot(head)
}
// SenderCacher returns the *TxSenderCacher used within the core package.
func (bc *BlockChain) SenderCacher() *TxSenderCacher {
return bc.senderCacher
}
// loadLastState loads the last known chain state from the database. This method
// assumes that the chain manager mutex is held.
func (bc *BlockChain) loadLastState(lastAcceptedHash common.Hash) error {
// Initialize genesis state
if lastAcceptedHash == (common.Hash{}) {
return bc.loadGenesisState()
}
// Restore the last known head block
head := rawdb.ReadHeadBlockHash(bc.db)
if head == (common.Hash{}) {
return errors.New("could not read head block hash")
}
// Make sure the entire head block is available
headBlock := bc.GetBlockByHash(head)
if headBlock == nil {
return fmt.Errorf("could not load head block %s", head.Hex())
}
// Everything seems to be fine, set as the head block
bc.currentBlock.Store(headBlock.Header())
// Restore the last known head header
currentHeader := headBlock.Header()
if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
if header := bc.GetHeaderByHash(head); header != nil {
currentHeader = header
}
}
bc.hc.SetCurrentHeader(currentHeader)
log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "age", common.PrettyAge(time.Unix(int64(currentHeader.Time), 0)))
log.Info("Loaded most recent local full block", "number", headBlock.Number(), "hash", headBlock.Hash(), "age", common.PrettyAge(time.Unix(int64(headBlock.Time()), 0)))
// Otherwise, set the last accepted block and perform a re-org.
bc.lastAccepted = bc.GetBlockByHash(lastAcceptedHash)
if bc.lastAccepted == nil {
return fmt.Errorf("could not load last accepted block")
}
// This ensures that the head block is updated to the last accepted block on startup
if err := bc.setPreference(bc.lastAccepted); err != nil {
return fmt.Errorf("failed to set preference to last accepted block while loading last state: %w", err)
}
// reprocessState is necessary to ensure that the last accepted state is
// available. The state may not be available if it was not committed due
// to an unclean shutdown.
return bc.reprocessState(bc.lastAccepted, 2*bc.cacheConfig.CommitInterval)
}
func (bc *BlockChain) loadGenesisState() error {
// Prepare the genesis block and reinitialise the chain
batch := bc.db.NewBatch()
rawdb.WriteBlock(batch, bc.genesisBlock)
if err := batch.Write(); err != nil {
log.Crit("Failed to write genesis block", "err", err)
}
bc.writeHeadBlock(bc.genesisBlock)
// Last update all in-memory chain markers
bc.lastAccepted = bc.genesisBlock
bc.currentBlock.Store(bc.genesisBlock.Header())
bc.hc.SetGenesis(bc.genesisBlock.Header())
bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
return nil
}
// Export writes the active chain to the given writer.
func (bc *BlockChain) Export(w io.Writer) error {
return bc.ExportN(w, uint64(0), bc.CurrentBlock().Number.Uint64())
}
// ExportN writes a subset of the active chain to the given writer.
func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
return bc.ExportCallback(func(block *types.Block) error {
return block.EncodeRLP(w)
}, first, last)
}
// ExportCallback invokes [callback] for every block from [first] to [last] in order.
func (bc *BlockChain) ExportCallback(callback func(block *types.Block) error, first uint64, last uint64) error {
if first > last {
return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
}
log.Info("Exporting batch of blocks", "count", last-first+1)
var (
parentHash common.Hash
start = time.Now()
reported = time.Now()
)
for nr := first; nr <= last; nr++ {
block := bc.GetBlockByNumber(nr)
if block == nil {
return fmt.Errorf("export failed on #%d: not found", nr)
}
if nr > first && block.ParentHash() != parentHash {
return errors.New("export failed: chain reorg during export")
}
parentHash = block.Hash()
if err := callback(block); err != nil {
return err
}
if time.Since(reported) >= statsReportLimit {
log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
reported = time.Now()
}
}
return nil
}
// writeHeadBlock injects a new head block into the current block chain. This method
// assumes that the block is indeed a true head. It will also reset the head
// header to this very same block if they are older or if they are on a different side chain.
//
// Note, this function assumes that the `mu` mutex is held!
func (bc *BlockChain) writeHeadBlock(block *types.Block) {
// If the block is on a side chain or an unknown one, force other heads onto it too
// Add the block to the canonical chain number scheme and mark as the head
batch := bc.db.NewBatch()
rawdb.WriteCanonicalHash(batch, block.Hash(), block.NumberU64())
rawdb.WriteHeadBlockHash(batch, block.Hash())
rawdb.WriteHeadHeaderHash(batch, block.Hash())
// Flush the whole batch into the disk, exit the node if failed
if err := batch.Write(); err != nil {
log.Crit("Failed to update chain indexes and markers", "err", err)
}
// Update all in-memory chain markers in the last step
bc.hc.SetCurrentHeader(block.Header())
bc.currentBlock.Store(block.Header())
}
// ValidateCanonicalChain confirms a canonical chain is well-formed.
func (bc *BlockChain) ValidateCanonicalChain() error {
// Ensure all accepted blocks are fully processed
bc.DrainAcceptorQueue()
current := bc.CurrentBlock()
i := 0
log.Info("Beginning to validate canonical chain", "startBlock", current.Number)
for current.Hash() != bc.genesisBlock.Hash() {
blkByHash := bc.GetBlockByHash(current.Hash())
if blkByHash == nil {
return fmt.Errorf("couldn't find block by hash %s at height %d", current.Hash().String(), current.Number)
}
if blkByHash.Hash() != current.Hash() {
return fmt.Errorf("blockByHash returned a block with an unexpected hash: %s, expected: %s", blkByHash.Hash().String(), current.Hash().String())
}
blkByNumber := bc.GetBlockByNumber(current.Number.Uint64())
if blkByNumber == nil {
return fmt.Errorf("couldn't find block by number at height %d", current.Number)
}
if blkByNumber.Hash() != current.Hash() {
return fmt.Errorf("blockByNumber returned a block with unexpected hash: %s, expected: %s", blkByNumber.Hash().String(), current.Hash().String())
}
hdrByHash := bc.GetHeaderByHash(current.Hash())
if hdrByHash == nil {
return fmt.Errorf("couldn't find block header by hash %s at height %d", current.Hash().String(), current.Number)
}
if hdrByHash.Hash() != current.Hash() {
return fmt.Errorf("hdrByHash returned a block header with an unexpected hash: %s, expected: %s", hdrByHash.Hash().String(), current.Hash().String())
}
hdrByNumber := bc.GetHeaderByNumber(current.Number.Uint64())
if hdrByNumber == nil {
return fmt.Errorf("couldn't find block header by number at height %d", current.Number)
}
if hdrByNumber.Hash() != current.Hash() {
return fmt.Errorf("hdrByNumber returned a block header with unexpected hash: %s, expected: %s", hdrByNumber.Hash().String(), current.Hash().String())
}
// Lookup the full block to get the transactions
block := bc.GetBlock(current.Hash(), current.Number.Uint64())
if block == nil {
log.Error("Current block not found in database", "block", current.Number, "hash", current.Hash())
return fmt.Errorf("current block missing: #%d [%x..]", current.Number, current.Hash().Bytes()[:4])
}
txs := block.Transactions()
// Transactions are only indexed beneath the last accepted block, so we only check
// that the transactions have been indexed, if we are checking below the last accepted
// block.
shouldIndexTxs := !bc.cacheConfig.SkipTxIndexing &&
(bc.cacheConfig.TxLookupLimit == 0 || bc.lastAccepted.NumberU64() < current.Number.Uint64()+bc.cacheConfig.TxLookupLimit)
if current.Number.Uint64() <= bc.lastAccepted.NumberU64() && shouldIndexTxs {
// Ensure that all of the transactions have been stored correctly in the canonical
// chain
for txIndex, tx := range txs {
txLookup := bc.GetTransactionLookup(tx.Hash())
if txLookup == nil {
return fmt.Errorf("failed to find transaction %s", tx.Hash().String())
}
if txLookup.BlockHash != current.Hash() {
return fmt.Errorf("tx lookup returned with incorrect block hash: %s, expected: %s", txLookup.BlockHash.String(), current.Hash().String())
}
if txLookup.BlockIndex != current.Number.Uint64() {
return fmt.Errorf("tx lookup returned with incorrect block index: %d, expected: %d", txLookup.BlockIndex, current.Number)
}
if txLookup.Index != uint64(txIndex) {
return fmt.Errorf("tx lookup returned with incorrect transaction index: %d, expected: %d", txLookup.Index, txIndex)
}
}
}
blkReceipts := bc.GetReceiptsByHash(current.Hash())
if blkReceipts.Len() != len(txs) {
return fmt.Errorf("found %d transaction receipts, expected %d", blkReceipts.Len(), len(txs))
}
for index, txReceipt := range blkReceipts {
if txReceipt.TxHash != txs[index].Hash() {
return fmt.Errorf("transaction receipt mismatch, expected %s, but found: %s", txs[index].Hash().String(), txReceipt.TxHash.String())
}
if txReceipt.BlockHash != current.Hash() {
return fmt.Errorf("transaction receipt had block hash %s, but expected %s", txReceipt.BlockHash.String(), current.Hash().String())
}
if txReceipt.BlockNumber.Uint64() != current.Number.Uint64() {
return fmt.Errorf("transaction receipt had block number %d, but expected %d", txReceipt.BlockNumber.Uint64(), current.Number)
}
}
i += 1
if i%1000 == 0 {
log.Info("Validate Canonical Chain Update", "totalBlocks", i)
}
parent := bc.GetHeaderByHash(current.ParentHash)
if parent.Hash() != current.ParentHash {
return fmt.Errorf("getBlockByHash retrieved parent block with incorrect hash, found %s, expected: %s", parent.Hash().String(), current.ParentHash.String())
}
current = parent
}
return nil
}
// stopWithoutSaving stops the blockchain service. If any imports are currently in progress
// it will abort them using the procInterrupt. This method stops all running
// goroutines, but does not do all the post-stop work of persisting data.
// OBS! It is generally recommended to use the Stop method!
// This method has been exposed to allow tests to stop the blockchain while simulating
// a crash.
func (bc *BlockChain) stopWithoutSaving() {
if !bc.stopping.CompareAndSwap(false, true) {
return
}
log.Info("Closing quit channel")
close(bc.quit)
// Wait for accepted feed to process all remaining items
log.Info("Stopping Acceptor")
start := time.Now()
bc.stopAcceptor()