-
Notifications
You must be signed in to change notification settings - Fork 189
/
blockchain.go
2815 lines (2446 loc) · 102 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
// Modifications Copyright 2018 The klaytn Authors
// Copyright 2015 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/>.
//
// This file is derived from core/blockchain.go (2018/06/04).
// Modified and improved for the klaytn development.
package blockchain
import (
"errors"
"fmt"
"io"
"math/big"
mrand "math/rand"
"reflect"
"runtime"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/klaytn/klaytn/snapshot"
"github.com/go-redis/redis/v7"
lru "github.com/hashicorp/golang-lru"
"github.com/klaytn/klaytn/blockchain/state"
"github.com/klaytn/klaytn/blockchain/types"
"github.com/klaytn/klaytn/blockchain/vm"
"github.com/klaytn/klaytn/common"
"github.com/klaytn/klaytn/common/hexutil"
"github.com/klaytn/klaytn/common/mclock"
"github.com/klaytn/klaytn/common/prque"
"github.com/klaytn/klaytn/consensus"
"github.com/klaytn/klaytn/crypto"
"github.com/klaytn/klaytn/event"
"github.com/klaytn/klaytn/fork"
"github.com/klaytn/klaytn/log"
klaytnmetrics "github.com/klaytn/klaytn/metrics"
"github.com/klaytn/klaytn/params"
"github.com/klaytn/klaytn/rlp"
"github.com/klaytn/klaytn/storage/database"
"github.com/klaytn/klaytn/storage/statedb"
"github.com/rcrowley/go-metrics"
)
// If total insertion time of a block exceeds insertTimeLimit,
// that time will be logged by blockLongInsertTimeGauge.
const insertTimeLimit = common.PrettyDuration(time.Second)
var (
accountReadTimer = klaytnmetrics.NewRegisteredHybridTimer("state/account/reads", nil)
accountHashTimer = klaytnmetrics.NewRegisteredHybridTimer("state/account/hashes", nil)
accountUpdateTimer = klaytnmetrics.NewRegisteredHybridTimer("state/account/updates", nil)
accountCommitTimer = klaytnmetrics.NewRegisteredHybridTimer("state/account/commits", nil)
storageReadTimer = klaytnmetrics.NewRegisteredHybridTimer("state/storage/reads", nil)
storageHashTimer = klaytnmetrics.NewRegisteredHybridTimer("state/storage/hashes", nil)
storageUpdateTimer = klaytnmetrics.NewRegisteredHybridTimer("state/storage/updates", nil)
storageCommitTimer = klaytnmetrics.NewRegisteredHybridTimer("state/storage/commits", nil)
snapshotAccountReadTimer = metrics.NewRegisteredTimer("state/snapshot/account/reads", nil)
snapshotStorageReadTimer = metrics.NewRegisteredTimer("state/snapshot/storage/reads", nil)
snapshotCommitTimer = metrics.NewRegisteredTimer("state/snapshot/commits", nil)
blockBaseFee = metrics.NewRegisteredGauge("chain/basefee", nil)
blockInsertTimer = klaytnmetrics.NewRegisteredHybridTimer("chain/inserts", nil)
blockProcessTimer = klaytnmetrics.NewRegisteredHybridTimer("chain/process", nil)
blockExecutionTimer = klaytnmetrics.NewRegisteredHybridTimer("chain/execution", nil)
blockFinalizeTimer = klaytnmetrics.NewRegisteredHybridTimer("chain/finalize", nil)
blockValidateTimer = klaytnmetrics.NewRegisteredHybridTimer("chain/validate", nil)
blockAgeTimer = klaytnmetrics.NewRegisteredHybridTimer("chain/age", nil)
blockPrefetchExecuteTimer = klaytnmetrics.NewRegisteredHybridTimer("chain/prefetch/executes", nil)
blockPrefetchInterruptMeter = metrics.NewRegisteredMeter("chain/prefetch/interrupts", nil)
ErrNoGenesis = errors.New("genesis not found in chain")
ErrNotExistNode = errors.New("the node does not exist in cached node")
ErrQuitBySignal = errors.New("quit by signal")
ErrNotInWarmUp = errors.New("not in warm up")
logger = log.NewModuleLogger(log.Blockchain)
kesCachePrefixBlockLogs = []byte("blockLogs")
)
// Below is the list of the constants for cache size.
// TODO-Klaytn: Below should be handled by ini or other configurations.
const (
maxFutureBlocks = 256
maxTimeFutureBlocks = 30
// TODO-Klaytn-Issue1911 This flag needs to be adjusted to the appropriate value.
// Currently, this value is taken to cache all 10 million accounts
// and should be optimized considering memory size and performance.
maxAccountForCache = 10000000
)
const (
DefaultTriesInMemory = 128
DefaultBlockInterval = 128
DefaultLivePruningRetention = 172800 // 2*params.DefaultStakeUpdateInterval
MaxPrefetchTxs = 20000
// BlockChainVersion ensures that an incompatible database forces a resync from scratch.
// Changelog:
// - Version 4
// The following incompatible database changes were added:
// * New scheme for contract code in order to separate the codes and trie nodes
BlockChainVersion = 4
)
// CacheConfig contains the configuration values for the 1) stateDB caching and
// 2) trie caching/pruning resident in a blockchain.
type CacheConfig struct {
// TODO-Klaytn-Issue1666 Need to check the benefit of trie caching.
ArchiveMode bool // If true, state trie is not pruned and always written to database
CacheSize int // Size of in-memory cache of a trie (MiB) to flush matured singleton trie nodes to disk
BlockInterval uint // Block interval to flush the trie. Each interval state trie will be flushed into disk
TriesInMemory uint64 // Maximum number of recent state tries according to its block number
LivePruningRetention uint64 // Number of blocks before trie nodes in pruning marks to be deleted. If zero, obsolete nodes are not deleted.
SenderTxHashIndexing bool // Enables saving senderTxHash to txHash mapping information to database and cache
TrieNodeCacheConfig *statedb.TrieNodeCacheConfig // Configures trie node cache
SnapshotCacheSize int // Memory allowance (MB) to use for caching snapshot entries in memory
SnapshotAsyncGen bool // Enables snapshot data generation asynchronously
}
// gcBlock is used for priority queue for GC.
type gcBlock struct {
root common.Hash
blockNum uint64
}
// 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 // stateDB caching and trie caching/pruning configuration
db database.DBManager // Low level persistent database to store final content in
snaps *snapshot.Tree // Snapshot tree for fast trie leaf access
triegc *prque.Prque // Priority queue mapping block numbers to tries to gc
chBlock chan gcBlock // chPushBlockGCPrque is a channel for delivering the gc item to gc loop.
chPrune chan uint64 // chPrune is a channel for delivering the current block number for pruning loop.
hc *HeaderChain
rmLogsFeed event.Feed
chainFeed event.Feed
chainSideFeed event.Feed
chainHeadFeed event.Feed
logsFeed event.Feed
scope event.SubscriptionScope
genesisBlock *types.Block
mu sync.RWMutex // global mutex for locking chain operations
checkpoint int // checkpoint counts towards the new checkpoint
currentBlock atomic.Value // Current head of the block chain
currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
stateCache state.Database // State database to reuse between imports (contains state cache)
futureBlocks *lru.Cache // future blocks are blocks added for later processing
quit chan struct{} // blockchain quit channel
running int32 // running must be called atomically
// procInterrupt must be atomically called
procInterrupt int32 // interrupt signaler for block processing
wg sync.WaitGroup // chain processing wait group for shutting down
engine consensus.Engine
processor Processor // block processor interface
prefetcher Prefetcher // Block state prefetcher interface
validator Validator // block and state validator interface
vmConfig vm.Config
parallelDBWrite bool // TODO-Klaytn-Storage parallelDBWrite will be replaced by number of goroutines when worker pool pattern is introduced.
// State migration
prepareStateMigration bool
stopStateMigration chan struct{}
readCnt int
committedCnt int
pendingCnt int
progress float64
migrationErr error
testMigrationHook func()
// Warm up
lastCommittedBlock uint64
quitWarmUp chan struct{}
prefetchTxCh chan prefetchTx
}
// prefetchTx is used to prefetch transactions, when fetcher works.
type prefetchTx struct {
ti int
block *types.Block
followupInterrupt *uint32
}
// NewBlockChain returns a fully initialised block chain using information
// available in the database. It initialises the default Klaytn validator and
// Processor.
func NewBlockChain(db database.DBManager, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config) (*BlockChain, error) {
if cacheConfig == nil {
cacheConfig = &CacheConfig{
ArchiveMode: false,
CacheSize: 512,
BlockInterval: DefaultBlockInterval,
TriesInMemory: DefaultTriesInMemory,
LivePruningRetention: DefaultLivePruningRetention,
TrieNodeCacheConfig: statedb.GetEmptyTrieNodeCacheConfig(),
SnapshotCacheSize: 512,
SnapshotAsyncGen: true,
}
}
if cacheConfig.TrieNodeCacheConfig == nil {
cacheConfig.TrieNodeCacheConfig = statedb.GetEmptyTrieNodeCacheConfig()
}
state.EnabledExpensive = db.GetDBConfig().EnableDBPerfMetrics
futureBlocks, _ := lru.New(maxFutureBlocks)
bc := &BlockChain{
chainConfig: chainConfig,
cacheConfig: cacheConfig,
db: db,
triegc: prque.New(),
chBlock: make(chan gcBlock, 2048), // downloader.maxResultsProcess
chPrune: make(chan uint64, 2048), // downloader.maxResultsProcess
stateCache: state.NewDatabaseWithNewCache(db, cacheConfig.TrieNodeCacheConfig),
quit: make(chan struct{}),
futureBlocks: futureBlocks,
engine: engine,
vmConfig: vmConfig,
parallelDBWrite: db.IsParallelDBWrite(),
stopStateMigration: make(chan struct{}),
prefetchTxCh: make(chan prefetchTx, MaxPrefetchTxs),
}
// set hardForkBlockNumberConfig which will be used as a global variable
if err := fork.SetHardForkBlockNumberConfig(bc.chainConfig); err != nil {
return nil, err
}
bc.validator = NewBlockValidator(chainConfig, bc, engine)
bc.prefetcher = newStatePrefetcher(chainConfig, bc, engine)
bc.processor = NewStateProcessor(chainConfig, bc, engine)
var err error
bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.getProcInterrupt)
if err != nil {
return nil, err
}
bc.genesisBlock = bc.GetBlockByNumber(0)
if bc.genesisBlock == nil {
return nil, ErrNoGenesis
}
var nilBlock *types.Block
bc.currentBlock.Store(nilBlock)
bc.currentFastBlock.Store(nilBlock)
if err := bc.loadLastState(); err != nil {
return nil, err
}
// Make sure the state associated with the block is available
head := bc.CurrentBlock()
if _, err := state.New(head.Root(), bc.stateCache, bc.snaps, nil); err != nil {
// Head state is missing, before the state recovery, find out the
// disk layer point of snapshot(if it's enabled). Make sure the
// rewound point is lower than disk layer.
var diskRoot common.Hash
if bc.cacheConfig.SnapshotCacheSize > 0 {
diskRoot = bc.db.ReadSnapshotRoot()
}
if diskRoot != (common.Hash{}) {
logger.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash(), "snaproot", diskRoot)
snapDisk, err := bc.setHeadBeyondRoot(head.NumberU64(), diskRoot, true)
if err != nil {
return nil, err
}
// Chain rewound, persist old snapshot number to indicate recovery procedure
if snapDisk != 0 {
bc.db.WriteSnapshotRecoveryNumber(snapDisk)
}
} else {
// Dangling block without a state associated, init from scratch
logger.Warn("Head state missing, repairing chain",
"number", head.NumberU64(), "hash", head.Hash().String())
if _, err := bc.setHeadBeyondRoot(head.NumberU64(), common.Hash{}, true); err != nil {
return nil, err
}
}
}
// Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
for hash := range BadHashes {
if header := bc.GetHeaderByHash(hash); header != nil {
// get the canonical block corresponding to the offending header's number
headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
// make sure the headerByNumber (if present) is in our current canonical chain
if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
logger.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
bc.SetHead(header.Number.Uint64() - 1)
logger.Error("Chain rewind was successful, resuming normal operation")
}
}
}
// Load any existing snapshot, regenerating it if loading failed
if bc.cacheConfig.SnapshotCacheSize > 0 {
// If the chain was rewound past the snapshot persistent layer (causing
// a recovery block number to be persisted to disk), check if we're still
// in recovery mode and in that case, don't invalidate the snapshot on a
// head mismatch.
var recover bool
head := bc.CurrentBlock()
if layer := bc.db.ReadSnapshotRecoveryNumber(); layer != nil && *layer > head.NumberU64() {
logger.Warn("Enabling snapshot recovery", "chainhead", head.NumberU64(), "diskbase", *layer)
recover = true
}
bc.snaps, _ = snapshot.New(bc.db, bc.stateCache.TrieDB(), bc.cacheConfig.SnapshotCacheSize, head.Root(), bc.cacheConfig.SnapshotAsyncGen, true, recover)
}
for i := 1; i <= bc.cacheConfig.TrieNodeCacheConfig.NumFetcherPrefetchWorker; i++ {
bc.wg.Add(1)
go bc.prefetchTxWorker(i)
}
logger.Info("prefetchTxWorkers are started", "num", bc.cacheConfig.TrieNodeCacheConfig.NumFetcherPrefetchWorker)
// Take ownership of this particular state
go bc.update()
bc.gcCachedNodeLoop()
bc.pruneTrieNodeLoop()
bc.restartStateMigration()
if cacheConfig.TrieNodeCacheConfig.DumpPeriodically() {
logger.Info("LocalCache is used for trie node cache, start saving cache to file periodically",
"dir", bc.cacheConfig.TrieNodeCacheConfig.FastCacheFileDir,
"period", bc.cacheConfig.TrieNodeCacheConfig.FastCacheSavePeriod)
trieDB := bc.stateCache.TrieDB()
bc.wg.Add(1)
go func() {
defer bc.wg.Done()
trieDB.SaveCachePeriodically(bc.cacheConfig.TrieNodeCacheConfig, bc.quit)
}()
}
return bc, nil
}
// prefetchTxWorker receives a block and a transaction index, which it pre-executes
// to retrieve and cache the data for the actual block processing.
func (bc *BlockChain) prefetchTxWorker(index int) {
defer bc.wg.Done()
logger.Debug("prefetchTxWorker is started", "index", index)
var snaps *snapshot.Tree
if bc.cacheConfig.TrieNodeCacheConfig.UseSnapshotForPrefetch {
snaps = bc.snaps
}
for followup := range bc.prefetchTxCh {
stateDB, err := state.New(bc.CurrentBlock().Root(), bc.stateCache, snaps,
&statedb.TrieOpts{Prefetching: true})
if err != nil {
logger.Debug("failed to retrieve stateDB for prefetchTxWorker", "err", err)
continue
}
vmCfg := bc.vmConfig
vmCfg.Prefetching = true
bc.prefetcher.PrefetchTx(followup.block, followup.ti, stateDB, vmCfg, followup.followupInterrupt)
}
logger.Debug("prefetchTxWorker is terminated", "index", index)
}
// SetCanonicalBlock resets the canonical as the block with the given block number.
// It works as rewinding the head block to the previous one, but does not delete the data.
func (bc *BlockChain) SetCanonicalBlock(blockNum uint64) {
// If the given block number is zero (it is zero by default), it does nothing
if blockNum == 0 {
return
}
// Read the block with the given block number and set it as canonical block
targetBlock := bc.db.ReadBlockByNumber(blockNum)
if targetBlock == nil {
logger.Error("failed to retrieve the block", "blockNum", blockNum)
return
}
bc.insert(targetBlock)
if err := bc.loadLastState(); err != nil {
logger.Error("failed to load last state after setting the canonical block", "err", err)
return
}
// Make sure the state associated with the block is available
head := bc.CurrentBlock()
if _, err := state.New(head.Root(), bc.stateCache, bc.snaps, nil); err != nil {
// Dangling block without a state associated, init from scratch
logger.Warn("Head state missing, repairing chain",
"number", head.NumberU64(), "hash", head.Hash().String())
if _, err := bc.setHeadBeyondRoot(head.NumberU64(), common.Hash{}, true); err != nil {
logger.Error("Repairing chain is failed", "number", head.NumberU64(), "hash", head.Hash().String(), "err", err)
return
}
}
logger.Info("successfully set the canonical block", "blockNum", blockNum)
}
func (bc *BlockChain) UseGiniCoeff() bool {
return bc.chainConfig.Governance.Reward.UseGiniCoeff
}
func (bc *BlockChain) ProposerPolicy() uint64 {
return bc.chainConfig.Istanbul.ProposerPolicy
}
func (bc *BlockChain) getProcInterrupt() bool {
return atomic.LoadInt32(&bc.procInterrupt) == 1
}
// loadLastState loads the last known chain state from the database. This method
// assumes that the chain manager mutex is held.
func (bc *BlockChain) loadLastState() error {
// Restore the last known head block
head := bc.db.ReadHeadBlockHash()
if head == (common.Hash{}) {
// Corrupt or empty database, init from scratch
logger.Info("Empty database, resetting chain")
return bc.Reset()
}
// Make sure the entire head block is available
currentBlock := bc.GetBlockByHash(head)
if currentBlock == nil {
head = bc.db.ReadHeadBlockBackupHash()
if head == (common.Hash{}) {
// Corrupt or empty database, init from scratch
logger.Info("Empty database, resetting chain")
return bc.Reset()
}
currentBlock = bc.GetBlockByHash(head)
if currentBlock == nil {
// Corrupt or empty database, init from scratch
logger.Error("Head block missing, resetting chain", "hash", head.String())
return bc.Reset()
}
}
// Everything seems to be fine, set as the head block
bc.currentBlock.Store(currentBlock)
bc.lastCommittedBlock = currentBlock.NumberU64()
// Restore the last known head header
currentHeader := currentBlock.Header()
if head := bc.db.ReadHeadHeaderHash(); head != (common.Hash{}) {
if header := bc.GetHeaderByHash(head); header != nil {
currentHeader = header
}
}
bc.hc.SetCurrentHeader(currentHeader)
// Restore the last known head fast block
bc.currentFastBlock.Store(currentBlock)
if head := bc.db.ReadHeadFastBlockHash(); head != (common.Hash{}) {
if block := bc.GetBlockByHash(head); block != nil {
bc.currentFastBlock.Store(block)
} else if head := bc.db.ReadHeadFastBlockBackupHash(); head != (common.Hash{}) {
if block := bc.GetBlockByHash(head); block != nil {
bc.currentFastBlock.Store(block)
}
}
}
// Issue a status log for the user
currentFastBlock := bc.CurrentFastBlock()
headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64())
logger.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time.Uint64()), 0)))
logger.Info("Loaded most recent local full block", "number", currentBlock.Number(), "hash", currentBlock.Hash(), "td", blockTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time.Uint64()), 0)))
logger.Info("Loaded most recent local fast block", "number", currentFastBlock.Number(), "hash", currentFastBlock.Hash(), "td", fastTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time.Uint64()), 0)))
return nil
}
// SetHead rewinds the local chain to a new head with the extra condition
// that the rewind must pass the specified state root. The method will try to
// delete minimal data from disk whilst retaining chain consistency.
func (bc *BlockChain) SetHead(head uint64) error {
// With the live pruning enabled, an attempt to SetHead into a state-pruned block number
// may result in an infinite loop, trying to find the existing block (probably the genesis block).
// If the target `head` is below the surviving block numbers, SetHead early exits with an error.
if lastPruned, err := bc.db.ReadLastPrunedBlockNumber(); err == nil {
if head <= lastPruned {
return fmt.Errorf("[SetHead] Cannot rewind to a state-pruned block number. lastPrunedBlock=%d targetHead=%d",
lastPruned, head)
}
}
_, err := bc.setHeadBeyondRoot(head, common.Hash{}, false)
return err
}
// setHeadBeyondRoot rewinds the local chain to a new head with the extra condition
// that the rewind must pass the specified state root. This method is meant to be
// used when rewinding with snapshots enabled to ensure that we go back further than
// persistent disk layer. Depending on whether the node was fast synced or full, and
// in which state, the method will try to delete minimal data from disk whilst
// retaining chain consistency.
//
// The method returns the block number where the requested root cap was found.
func (bc *BlockChain) setHeadBeyondRoot(head uint64, root common.Hash, repair bool) (uint64, error) {
bc.mu.Lock()
defer bc.mu.Unlock()
// Track the block number of the requested root hash
var rootNumber uint64 // (no root == always 0)
originLatestBlkNum := bc.CurrentBlock().Number().Uint64()
updateFn := func(header *types.Header) (uint64, error) {
// Rewind the block chain, ensuring we don't end up with a stateless head block
if currentBlock := bc.CurrentBlock(); currentBlock != nil && header.Number.Uint64() <= currentBlock.NumberU64() {
newHeadBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
if newHeadBlock == nil {
logger.Error("Gap in the chain, rewinding to genesis", "number", header.Number, "hash", header.Hash())
newHeadBlock = bc.genesisBlock
} else {
// Block exists, keep rewinding until we find one with state,
// keeping rewinding until we exceed the optional threshold
// root hash
beyondRoot := (root == common.Hash{}) // Flag whether we're beyond the requested root (no root, always true)
for {
// If a root threshold was requested but not yet crossed, check
if root != (common.Hash{}) && !beyondRoot && newHeadBlock.Root() == root {
beyondRoot, rootNumber = true, newHeadBlock.NumberU64()
}
if _, err := state.New(newHeadBlock.Root(), bc.stateCache, bc.snaps, nil); err != nil {
// Rewound state missing, rolled back to the parent block, reset to genesis
logger.Trace("Block state missing, rewinding further", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash())
parent := bc.GetBlock(newHeadBlock.ParentHash(), newHeadBlock.NumberU64()-1)
if parent != nil {
newHeadBlock = parent
continue
}
logger.Error("Missing block in the middle, aiming genesis", "number", newHeadBlock.NumberU64()-1, "hash", newHeadBlock.ParentHash())
newHeadBlock = bc.genesisBlock
}
if beyondRoot || newHeadBlock.NumberU64() == 0 {
logger.Debug("Rewound to block with state", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash().String())
break
}
// if newHeadBlock has state, then rewind first
logger.Debug("Skipping block with threshold state", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash().String(), "root", newHeadBlock.Root().String())
newHeadBlock = bc.GetBlock(newHeadBlock.ParentHash(), newHeadBlock.NumberU64()-1) // Keep rewinding
}
}
if newHeadBlock.NumberU64() == 0 {
return 0, errors.New("rewound to block number 0, but repair failed")
}
bc.db.WriteHeadBlockHash(newHeadBlock.Hash())
// Degrade the chain markers if they are explicitly reverted.
// In theory we should update all in-memory markers in the
// last step, however the direction of SetHead is from high
// to low, so it's safe the update in-memory markers directly.
bc.currentBlock.Store(newHeadBlock)
headBlockNumberGauge.Update(int64(newHeadBlock.NumberU64()))
}
// Rewind the fast block in a simpleton way to the target head
if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && header.Number.Uint64() < currentFastBlock.NumberU64() {
newHeadFastBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
// If either blocks reached nil, reset to the genesis state
if newHeadFastBlock == nil {
newHeadFastBlock = bc.genesisBlock
}
bc.db.WriteHeadFastBlockHash(newHeadFastBlock.Hash())
// Degrade the chain markers if they are explicitly reverted.
// In theory we should update all in-memory markers in the
// last step, however the direction of SetHead is from high
// to low, so it's safe the update in-memory markers directly.
bc.currentFastBlock.Store(newHeadFastBlock)
}
return bc.CurrentBlock().Number().Uint64(), nil
}
// Rewind the header chain, deleting all block bodies until then
delFn := func(hash common.Hash, num uint64) {
// Remove relative body, receipts, header-governance database,
// istanbul snapshot database, and staking info database from the active store.
// The header, total difficulty and canonical hash will be
// removed in the hc.SetHead function.
bc.db.DeleteBody(hash, num)
bc.db.DeleteReceipts(hash, num)
bc.db.DeleteGovernance(num)
if params.IsCheckpointInterval(num) {
bc.db.DeleteIstanbulSnapshot(hash)
}
if bc.Config().Istanbul.ProposerPolicy == params.WeightedRandom && params.IsStakingUpdateInterval(num) {
bc.db.DeleteStakingInfo(num)
}
}
// If SetHead was only called as a chain reparation method, try to skip
// touching the header chain altogether
if repair {
if _, err := updateFn(bc.CurrentBlock().Header()); err != nil {
return 0, err
}
} else {
// Rewind the chain to the requested head and keep going backwards until a
// block with a state is found
logger.Warn("Rewinding blockchain", "target", head)
if err := bc.hc.SetHead(head, updateFn, delFn); err != nil {
return 0, err
}
}
// Delete istanbul snapshot database further two epochs
var (
curBlkNum = bc.CurrentBlock().Number().Uint64()
epoch = bc.Config().Istanbul.Epoch
votingEpoch = curBlkNum - (curBlkNum % epoch)
)
if votingEpoch == 0 {
votingEpoch = 1
}
// Delete the snapshot state beyond the block number of the previous epoch on the right
for i := curBlkNum; i >= votingEpoch; i-- {
if params.IsCheckpointInterval(i) {
// delete from sethead number to previous two epoch block nums
// to handle a block that contains non-empty vote data to make sure
// the `HandleGovernanceVote()` cannot be skipped
bc.db.DeleteIstanbulSnapshot(bc.GetBlockByNumber(i).Hash())
}
}
logger.Trace("[SetHead] Snapshot database deleted", "from", originLatestBlkNum, "to", votingEpoch)
// Clear out any stale content from the caches
bc.futureBlocks.Purge()
bc.db.ClearBlockChainCache()
return rootNumber, bc.loadLastState()
}
// FastSyncCommitHead sets the current head block to the one defined by the hash
// irrelevant what the chain contents were prior.
func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
// Make sure that both the block as well at its state trie exists
block := bc.GetBlockByHash(hash)
if block == nil {
return fmt.Errorf("non existent block [%x…]", hash[:4])
}
if _, err := statedb.NewSecureTrie(block.Root(), bc.stateCache.TrieDB(), nil); err != nil {
return err
}
// If all checks out, manually set the head block
bc.mu.Lock()
bc.currentBlock.Store(block)
bc.lastCommittedBlock = block.NumberU64()
bc.mu.Unlock()
// Destroy any existing state snapshot and regenerate it in the background,
// also resuming the normal maintenance of any previously paused snapshot.
if bc.snaps != nil {
bc.snaps.Rebuild(block.Root())
}
logger.Info("Committed new head block", "number", block.Number(), "hash", hash)
return nil
}
// CurrentBlock retrieves the current head block of the canonical chain. The
// block is retrieved from the blockchain's internal cache.
func (bc *BlockChain) CurrentBlock() *types.Block {
return bc.currentBlock.Load().(*types.Block)
}
// CurrentFastBlock retrieves the current fast-sync head block of the canonical
// chain. The block is retrieved from the blockchain's internal cache.
func (bc *BlockChain) CurrentFastBlock() *types.Block {
return bc.currentFastBlock.Load().(*types.Block)
}
// Validator returns the current validator.
func (bc *BlockChain) Validator() Validator {
return bc.validator
}
// Processor returns the current processor.
func (bc *BlockChain) Processor() Processor {
return bc.processor
}
// State returns a new mutable state based on the current HEAD block.
func (bc *BlockChain) State() (*state.StateDB, error) {
return bc.StateAt(bc.CurrentBlock().Root())
}
// StateAt returns a new mutable state based on a particular point in time.
func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
return state.New(root, bc.stateCache, bc.snaps, nil)
}
// PrunableStateAt returns a new mutable state based on a particular point in time.
// If live pruning is enabled on the databse, and num is nonzero, then trie will mark obsolete nodes for pruning.
func (bc *BlockChain) PrunableStateAt(root common.Hash, num uint64) (*state.StateDB, error) {
if bc.IsLivePruningRequired() {
return state.New(root, bc.stateCache, bc.snaps, &statedb.TrieOpts{
PruningBlockNumber: num,
})
} else {
return bc.StateAt(root)
}
}
// StateAtWithPersistent returns a new mutable state based on a particular point in time with persistent trie nodes.
func (bc *BlockChain) StateAtWithPersistent(root common.Hash) (*state.StateDB, error) {
exist := bc.stateCache.TrieDB().DoesExistNodeInPersistent(root.ExtendZero())
if !exist {
return nil, ErrNotExistNode
}
return state.New(root, bc.stateCache, bc.snaps, nil)
}
// StateAtWithGCLock returns a new mutable state based on a particular point in time with read lock of the state nodes.
func (bc *BlockChain) StateAtWithGCLock(root common.Hash) (*state.StateDB, error) {
bc.RLockGCCachedNode()
exist := bc.stateCache.TrieDB().DoesExistCachedNode(root.ExtendZero())
if !exist {
bc.RUnlockGCCachedNode()
return nil, ErrNotExistNode
}
stateDB, err := state.New(root, bc.stateCache, bc.snaps, nil)
if err != nil {
bc.RUnlockGCCachedNode()
return nil, err
}
return stateDB, nil
}
// StateCache returns the caching database underpinning the blockchain instance.
func (bc *BlockChain) StateCache() state.Database {
return bc.stateCache
}
// Reset purges the entire blockchain, restoring it to its genesis state.
func (bc *BlockChain) Reset() error {
return bc.ResetWithGenesisBlock(bc.genesisBlock)
}
// ResetWithGenesisBlock purges the entire blockchain, restoring it to the
// specified genesis state.
func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
// Dump the entire block chain and purge the caches
if err := bc.SetHead(0); err != nil {
return err
}
bc.mu.Lock()
defer bc.mu.Unlock()
// Prepare the genesis block and reinitialise the chain
bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.BlockScore())
bc.db.WriteBlock(genesis)
bc.genesisBlock = genesis
bc.insert(bc.genesisBlock)
bc.currentBlock.Store(bc.genesisBlock)
bc.hc.SetGenesis(bc.genesisBlock.Header())
bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
bc.currentFastBlock.Store(bc.genesisBlock)
return nil
}
// repair tries to repair the current blockchain by rolling back the current block
// until one with associated state is found. This is needed to fix incomplete db
// writes caused either by crashes/power outages, or simply non-committed tries.
//
// This method only rolls back the current block. The current header and current
// fast block are left intact.
// Deprecated: in order to repair chain, please use SetHead or setHeadBeyondRoot methods
func (bc *BlockChain) repair(head **types.Block) error {
for {
// Abort if we've rewound to a head block that does have associated state
if _, err := state.New((*head).Root(), bc.stateCache, bc.snaps, nil); err == nil {
logger.Info("Rewound blockchain to past state", "number", (*head).Number(), "hash", (*head).Hash())
return nil
} else {
// Should abort and return error, otherwise it will fall into infinite loop
if (*head).NumberU64() == 0 {
return errors.New("rewound to block number 0, but repair failed")
} else {
// If headBlockNumber > 0, rewind one block and recheck state availability there
block := bc.GetBlock((*head).ParentHash(), (*head).NumberU64()-1)
if block == nil {
return fmt.Errorf("missing block %d [%x]", (*head).NumberU64()-1, (*head).ParentHash())
}
*head = block
}
}
}
}
// 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().NumberU64())
}
// ExportN writes a subset of the active chain to the given writer.
func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
bc.mu.RLock()
defer bc.mu.RUnlock()
if first > last {
return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
}
logger.Info("Exporting batch of blocks", "count", last-first+1)
start, reported := time.Now(), 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 err := block.EncodeRLP(w); err != nil {
return err
}
if time.Since(reported) >= log.StatsReportLimit {
logger.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
reported = time.Now()
}
}
return nil
}
// insert 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 and the head fast sync block 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) insert(block *types.Block) {
// If the block is on a side chain or an unknown one, force other heads onto it too
updateHeads := bc.db.ReadCanonicalHash(block.NumberU64()) != block.Hash()
// Add the block to the canonical chain number scheme and mark as the head
bc.db.WriteCanonicalHash(block.Hash(), block.NumberU64())
bc.db.WriteHeadBlockHash(block.Hash())
bc.currentBlock.Store(block)
// If the block is better than our head or is on a different chain, force update heads
if updateHeads {
bc.hc.SetCurrentHeader(block.Header())
bc.db.WriteHeadFastBlockHash(block.Hash())
bc.currentFastBlock.Store(block)
}
}
// Genesis retrieves the chain's genesis block.
func (bc *BlockChain) Genesis() *types.Block {
return bc.genesisBlock
}
// GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
// caching it if found.
func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
return bc.db.ReadBodyRLPByHash(hash)
}
// HasBlock checks if a block is fully present in the database or not.
func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
return bc.db.HasBlock(hash, number)
}
// HasState checks if state trie is fully present in the database or not.
func (bc *BlockChain) HasState(hash common.Hash) bool {
_, err := bc.stateCache.OpenTrie(hash, nil)
return err == nil
}
// HasBlockAndState checks if a block and associated state trie is fully present
// in the database or not, caching it if present.
func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
// Check first that the block itself is known
block := bc.GetBlock(hash, number)
if block == nil {
return false
}
return bc.HasState(block.Root())
}
// ShouldTryInserting returns the state whether the block should be inserted.
// If a node doesn't have the given block or the block number of given block is higher than the node's head block, it can try inserting the block.
func (bc *BlockChain) ShouldTryInserting(block *types.Block) bool {
return !bc.HasBlockAndState(block.Hash(), block.NumberU64()) || bc.CurrentBlock().NumberU64() < block.NumberU64()
}
// GetBlock retrieves a block from the database by hash and number,
// caching it if found.
func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
return bc.db.ReadBlock(hash, number)
}
// GetBlockByHash retrieves a block from the database by hash, caching it if found.
func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
return bc.db.ReadBlockByHash(hash)
}
// GetBlockNumber retrieves a blockNumber from the database by hash, caching it if found.
func (bc *BlockChain) GetBlockNumber(hash common.Hash) *uint64 {
return bc.hc.GetBlockNumber(hash)
}
// GetBlockByNumber retrieves a block from the database by number, caching it
// (associated with its hash) if found.
func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
return bc.db.ReadBlockByNumber(number)
}
// GetTxAndLookupInfo retrieves a tx and lookup info for a given transaction hash.
func (bc *BlockChain) GetTxAndLookupInfo(txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
tx, blockHash, blockNumber, index := bc.GetTxAndLookupInfoInCache(txHash)
if tx == nil {
tx, blockHash, blockNumber, index = bc.db.ReadTxAndLookupInfo(txHash)
}
return tx, blockHash, blockNumber, index
}
// GetTxLookupInfoAndReceipt retrieves a tx and lookup info and receipt for a given transaction hash.
func (bc *BlockChain) GetTxLookupInfoAndReceipt(txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, *types.Receipt) {
tx, blockHash, blockNumber, index := bc.GetTxAndLookupInfo(txHash)
if tx == nil {
return nil, common.Hash{}, 0, 0, nil
}
receipt := bc.GetReceiptByTxHash(txHash)
if receipt == nil {
return nil, common.Hash{}, 0, 0, nil
}
return tx, blockHash, blockNumber, index, receipt
}
// GetTxLookupInfoAndReceiptInCache retrieves a tx and lookup info and receipt for a given transaction hash in cache.
func (bc *BlockChain) GetTxLookupInfoAndReceiptInCache(txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, *types.Receipt) {
tx, blockHash, blockNumber, index := bc.GetTxAndLookupInfoInCache(txHash)
if tx == nil {
return nil, common.Hash{}, 0, 0, nil
}
receipt := bc.GetTxReceiptInCache(txHash)
if receipt == nil {
return nil, common.Hash{}, 0, 0, nil
}
return tx, blockHash, blockNumber, index, receipt
}
// GetReceiptsByBlockHash retrieves the receipts for all transactions with given block hash.
func (bc *BlockChain) GetReceiptsByBlockHash(blockHash common.Hash) types.Receipts {
return bc.db.ReadReceiptsByBlockHash(blockHash)
}
// GetReceiptByTxHash retrieves a receipt for a given transaction hash.
func (bc *BlockChain) GetReceiptByTxHash(txHash common.Hash) *types.Receipt {