-
Notifications
You must be signed in to change notification settings - Fork 466
/
core.go
1208 lines (1038 loc) · 42 KB
/
core.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 core
import (
"context"
"errors"
"io"
"math/big"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"time"
lru "github.com/hnlq715/golang-lru"
"github.com/dominant-strategies/go-quai/common"
"github.com/dominant-strategies/go-quai/common/math"
"github.com/dominant-strategies/go-quai/consensus"
"github.com/dominant-strategies/go-quai/core/rawdb"
"github.com/dominant-strategies/go-quai/core/state"
"github.com/dominant-strategies/go-quai/core/state/snapshot"
"github.com/dominant-strategies/go-quai/core/types"
"github.com/dominant-strategies/go-quai/core/vm"
"github.com/dominant-strategies/go-quai/ethdb"
"github.com/dominant-strategies/go-quai/event"
"github.com/dominant-strategies/go-quai/log"
"github.com/dominant-strategies/go-quai/params"
"github.com/dominant-strategies/go-quai/quaiclient"
"github.com/dominant-strategies/go-quai/rlp"
"github.com/dominant-strategies/go-quai/trie"
)
const (
c_maxAppendQueue = 1000000 // Maximum number of future headers we can store in cache
c_maxFutureTime = 30 // Max time into the future (in seconds) we will accept a block
c_appendQueueRetryPeriod = 1 // Time (in seconds) before retrying to append from AppendQueue
c_appendQueueThreshold = 200 // Number of blocks to load from the disk to ram on every proc of append queue
c_processingCache = 10 // Number of block hashes held to prevent multi simultaneous appends on a single block hash
c_primeRetryThreshold = 1800 // Number of times a block is retry to be appended before eviction from append queue in Prime
c_regionRetryThreshold = 1200 // Number of times a block is retry to be appended before eviction from append queue in Region
c_zoneRetryThreshold = 600 // Number of times a block is retry to be appended before eviction from append queue in Zone
c_maxFutureBlocksPrime uint64 = 3 // Number of blocks ahead of the current block to be put in the hashNumberList
c_maxFutureBlocksRegion uint64 = 150
c_maxFutureBlocksZone uint64 = 2000
c_appendQueueRetryPriorityThreshold = 5 // If retry counter for a block is less than this number, then its put in the special list that is tried first to be appended
c_appendQueueRemoveThreshold = 10 // Number of blocks behind the block should be from the current header to be eligble for removal from the append queue
c_normalListProcCounter = 1 // Ratio of Number of times the PriorityList is serviced over the NormalList
c_statsPrintPeriod = 60 // Time between stats prints
c_appendQueuePrintSize = 10
c_normalListBackoffThreshold = 5 // Max multiple on the c_normalListProcCounter
c_maxRemoteTxQueue = 50000
c_remoteTxProcPeriod = 2 // Time between remote tx pool processing
)
type blockNumberAndRetryCounter struct {
number uint64
retry uint64
}
type Core struct {
sl *Slice
engine consensus.Engine
appendQueue *lru.Cache
processingCache *lru.Cache
remoteTxQueue *lru.Cache
localTxQueue *lru.Cache
writeBlockLock sync.RWMutex
procCounter int
normalListBackoff uint64 // normalListBackoff is the multiple on c_normalListProcCounter which delays the proc on normal list
quit chan struct{} // core quit channel
logger *log.Logger
}
type IndexerConfig struct {
IndexAddressUtxos bool
}
func NewCore(db ethdb.Database, config *Config, isLocalBlock func(block *types.WorkObject) bool, txConfig *TxPoolConfig, txLookupLimit *uint64, chainConfig *params.ChainConfig, slicesRunning []common.Location, currentExpansionNumber uint8, genesisBlock *types.WorkObject, domClientUrl string, subClientUrls []string, engine consensus.Engine, cacheConfig *CacheConfig, vmConfig vm.Config, indexerConfig *IndexerConfig, genesis *Genesis, logger *log.Logger) (*Core, error) {
slice, err := NewSlice(db, config, txConfig, txLookupLimit, isLocalBlock, chainConfig, slicesRunning, currentExpansionNumber, genesisBlock, domClientUrl, subClientUrls, engine, cacheConfig, indexerConfig, vmConfig, genesis, logger)
if err != nil {
return nil, err
}
c := &Core{
sl: slice,
engine: engine,
quit: make(chan struct{}),
procCounter: 0,
normalListBackoff: 1,
logger: logger,
}
// Initialize the sync target to current header parent entropy
appendQueue, _ := lru.New(c_maxAppendQueue)
c.appendQueue = appendQueue
proccesingCache, _ := lru.NewWithExpire(c_processingCache, time.Second*60)
c.processingCache = proccesingCache
remoteTxQueue, _ := lru.New(c_maxRemoteTxQueue)
c.remoteTxQueue = remoteTxQueue
go c.updateAppendQueue()
go c.startStatsTimer()
if c.NodeCtx() == common.ZONE_CTX && c.ProcessingState() {
go c.startRemoteTxQueue()
}
return c, nil
}
// InsertChain attempts to append a list of blocks to the slice, optionally
// caching any pending blocks which cannot yet be appended. InsertChain return
// the number of blocks which were successfully consumed (either appended, or
// cached), and an error.
func (c *Core) InsertChain(blocks types.WorkObjects) (int, error) {
nodeLocation := c.NodeLocation()
nodeCtx := c.NodeCtx()
for idx, block := range blocks {
// Only attempt to append a block, if it is not coincident with our dominant
// chain. If it is dom coincident, then the dom chain node in our slice needs
// to initiate the append.
_, order, err := c.CalcOrder(block)
if err != nil {
return idx, err
}
if order == nodeCtx {
if !c.processingCache.Contains(block.Hash()) {
c.processingCache.Add(block.Hash(), 1)
} else {
c.logger.WithFields(log.Fields{
"Number": block.NumberArray(),
"Hash": block.Hash(),
}).Info("Already processing block")
return idx, errors.New("Already in process of appending this block")
}
newPendingEtxs, _, _, err := c.sl.Append(block, types.EmptyHeader(c.NodeCtx()), common.Hash{}, false, nil)
c.processingCache.Remove(block.Hash())
if err == nil {
// If we have a dom, send the dom any pending ETXs which will become
// referencable by this block. When this block is referenced in the dom's
// subordinate block manifest, then ETXs produced by this block and the rollup
// of ETXs produced by subordinate chain(s) will become referencable.
if nodeCtx > common.PRIME_CTX {
pendingEtx := types.PendingEtxs{Header: block, Etxs: newPendingEtxs}
// Only send the pending Etxs to dom if valid, because in the case of running a slice, for the zones that the node doesn't run, it cannot have the etxs generated
if pendingEtx.IsValid(trie.NewStackTrie(nil)) {
if err := c.SendPendingEtxsToDom(pendingEtx); err != nil {
c.logger.WithFields(log.Fields{
"blockHash": block.Hash(),
"err": err,
}).Error("failed to send ETXs to domclient")
}
}
}
c.removeFromAppendQueue(block)
} else if err.Error() == ErrKnownBlock.Error() {
c.removeFromAppendQueue(block)
} else if err.Error() == consensus.ErrFutureBlock.Error() ||
err.Error() == ErrBodyNotFound.Error() ||
err.Error() == ErrPendingEtxNotFound.Error() ||
err.Error() == consensus.ErrPrunedAncestor.Error() ||
err.Error() == consensus.ErrUnknownAncestor.Error() ||
err.Error() == ErrSubNotSyncedToDom.Error() ||
err.Error() == ErrDomClientNotUp.Error() {
if c.sl.CurrentInfo(block) {
c.logger.WithFields(log.Fields{
"Number": block.NumberArray(),
"Hash": block.Hash(),
"err": err,
}).Info("Cannot append yet.")
} else {
c.logger.WithFields(log.Fields{
"loc": c.NodeLocation().Name(),
"Number": block.NumberArray(),
"Hash": block.Hash(),
"err": err,
}).Debug("Cannot append yet.")
}
if err.Error() == ErrSubNotSyncedToDom.Error() ||
err.Error() == ErrPendingEtxNotFound.Error() {
if nodeCtx != common.ZONE_CTX && c.sl.subClients[block.Location().SubIndex(nodeLocation)] != nil {
c.sl.subClients[block.Location().SubIndex(nodeLocation)].DownloadBlocksInManifest(context.Background(), block.Hash(), block.Manifest(), block.ParentEntropy(nodeCtx))
}
}
return idx, ErrPendingBlock
} else if err.Error() != ErrKnownBlock.Error() {
c.logger.WithFields(log.Fields{
"Hash": block.Hash(),
"err": err,
}).Info("Append failed.")
}
if err != nil && strings.Contains(err.Error(), "connection refused") {
c.logger.Error("Append failed because of connection refused error")
} else {
c.removeFromAppendQueue(block)
}
}
}
return len(blocks), nil
}
// procAppendQueue sorts the append queue and attempts to append
func (c *Core) procAppendQueue() {
nodeCtx := c.NodeLocation().Context()
maxFutureBlocks := c_maxFutureBlocksPrime
if nodeCtx == common.REGION_CTX {
maxFutureBlocks = c_maxFutureBlocksRegion
} else if nodeCtx == common.ZONE_CTX {
maxFutureBlocks = c_maxFutureBlocksZone
}
// Sort the blocks by number and retry attempts and try to insert them
// blocks will be aged out of the append queue after the retry threhsold
var hashNumberList []types.HashAndNumber
var hashNumberPriorityList []types.HashAndNumber
for _, hash := range c.appendQueue.Keys() {
if value, exist := c.appendQueue.Peek(hash); exist {
hashNumber := types.HashAndNumber{Hash: hash.(common.Hash), Number: value.(blockNumberAndRetryCounter).number}
if hashNumber.Number < c.CurrentHeader().NumberU64(nodeCtx)+maxFutureBlocks {
if value.(blockNumberAndRetryCounter).retry < c_appendQueueRetryPriorityThreshold {
hashNumberPriorityList = append(hashNumberPriorityList, hashNumber)
} else {
hashNumberList = append(hashNumberList, hashNumber)
}
}
}
}
c.serviceBlocks(hashNumberPriorityList)
if len(hashNumberPriorityList) > 0 {
c.logger.WithFields(log.Fields{
"len": len(hashNumberPriorityList),
"firstEntry": hashNumberPriorityList[0].Number,
"lastEntry": hashNumberPriorityList[len(hashNumberPriorityList)-1].Number,
}).Info("Size of hashNumberPriorityList")
}
normalListProcCounter := c.normalListBackoff * c_normalListProcCounter
if len(c.appendQueue.Keys()) < c_appendQueueThreshold || c.procCounter%int(normalListProcCounter) == 0 {
c.procCounter = 0
c.serviceBlocks(hashNumberList)
if len(hashNumberList) > 0 {
c.logger.WithFields(log.Fields{
"len": len(hashNumberList),
"firstEntry": hashNumberList[0].Number,
"lastEntry": hashNumberList[len(hashNumberList)-1].Number,
}).Info("Size of hashNumberList")
}
}
c.procCounter++
}
func (c *Core) serviceBlocks(hashNumberList []types.HashAndNumber) {
sort.Slice(hashNumberList, func(i, j int) bool {
return hashNumberList[i].Number < hashNumberList[j].Number
})
var retryThreshold uint64
switch c.NodeLocation().Context() {
case common.PRIME_CTX:
retryThreshold = c_primeRetryThreshold
case common.REGION_CTX:
retryThreshold = c_regionRetryThreshold
case common.ZONE_CTX:
retryThreshold = c_zoneRetryThreshold
}
// Attempt to service the sorted list
for i, hashAndNumber := range hashNumberList {
block := c.GetBlockOrCandidateByHash(hashAndNumber.Hash)
if block != nil {
var numberAndRetryCounter blockNumberAndRetryCounter
if value, exist := c.appendQueue.Peek(block.Hash()); exist {
numberAndRetryCounter = value.(blockNumberAndRetryCounter)
numberAndRetryCounter.retry += 1
if numberAndRetryCounter.retry > retryThreshold && numberAndRetryCounter.number+c_appendQueueRemoveThreshold < c.CurrentHeader().NumberU64(c.NodeCtx()) {
c.appendQueue.Remove(block.Hash())
} else {
c.appendQueue.Add(block.Hash(), numberAndRetryCounter)
}
}
parentBlock := c.sl.hc.GetBlockOrCandidate(block.ParentHash(c.NodeCtx()), block.NumberU64(c.NodeCtx())-1)
if parentBlock != nil {
// If parent header is dom, send a signal to dom to request for the block if it doesnt have it
_, parentHeaderOrder, err := c.sl.engine.CalcOrder(parentBlock)
if err != nil {
c.logger.WithFields(log.Fields{
"Hash": parentBlock.Hash(),
"Number": parentBlock.NumberArray(),
}).Info("Error calculating the parent block order in serviceBlocks")
continue
}
nodeCtx := c.NodeLocation().Context()
if parentHeaderOrder < nodeCtx && c.GetHeaderByHash(parentBlock.Hash()) == nil {
c.logger.WithFields(log.Fields{
"Hash": parentBlock.Hash(),
"Order": parentHeaderOrder,
}).Info("Requesting the dom to get the block if it doesnt have and try to append")
if c.sl.domClient != nil {
// send a signal to the required dom to fetch the block if it doesnt have it, or its not in its appendqueue
go c.sl.domClient.RequestDomToAppendOrFetch(context.Background(), parentBlock.Hash(), parentBlock.ParentEntropy(c.NodeCtx()), parentHeaderOrder)
}
}
c.addToQueueIfNotAppended(parentBlock)
_, err = c.InsertChain([]*types.WorkObject{block})
if err != nil && err.Error() == ErrPendingBlock.Error() {
// Best check here would be to check the first hash in each Fork, until we do that
// checking the first item in the sorted hashNumberList will do
if i == 0 && c.normalListBackoff < c_normalListBackoffThreshold {
c.normalListBackoff++
}
} else {
c.normalListBackoff = 1
}
} else {
c.sl.missingBlockFeed.Send(types.BlockRequest{Hash: block.ParentHash(c.NodeCtx()), Entropy: block.ParentEntropy(c.NodeCtx())})
}
} else {
c.logger.WithField("hash", hashAndNumber.Hash).Info("Entry in the FH cache without being in the db")
}
}
}
func (c *Core) RequestDomToAppendOrFetch(hash common.Hash, entropy *big.Int, order int) {
// TODO: optimize to check if the block is in the appendqueue or already
// appended to reduce the network bandwidth utilization
nodeCtx := c.NodeLocation().Context()
if nodeCtx == common.PRIME_CTX {
// If prime all you can do it to ask for the block
_, exists := c.appendQueue.Get(hash)
if !exists {
c.logger.WithFields(log.Fields{
"Hash": hash,
"Order": order,
}).Debug("Block sub asked doesnt exist in append queue, so request the peers for it")
block := c.GetBlockOrCandidateByHash(hash)
if block == nil {
c.sl.missingBlockFeed.Send(types.BlockRequest{Hash: hash, Entropy: entropy}) // Using the missing parent feed to ask for the block
} else {
c.addToQueueIfNotAppended(block)
}
}
} else if nodeCtx == common.REGION_CTX {
if order < nodeCtx { // Prime block
if c.sl.domClient != nil {
go c.sl.domClient.RequestDomToAppendOrFetch(context.Background(), hash, entropy, order)
}
}
_, exists := c.appendQueue.Get(hash)
if !exists {
c.logger.WithFields(log.Fields{
"Hash": hash,
"Order": order,
}).Debug("Block sub asked doesnt exist in append queue, so request the peers for it")
block := c.GetBlockByHash(hash)
if block == nil {
c.sl.missingBlockFeed.Send(types.BlockRequest{Hash: hash, Entropy: entropy}) // Using the missing parent feed to ask for the block
} else {
c.addToQueueIfNotAppended(block)
}
}
}
}
// addToQueueIfNotAppended checks if block is appended and if its not adds the block to appendqueue
func (c *Core) addToQueueIfNotAppended(block *types.WorkObject) {
// Check if the hash is in the blockchain, otherwise add it to the append queue
if c.GetHeaderByHash(block.Hash()) == nil {
c.addToAppendQueue(block)
}
}
// addToAppendQueue adds a block to the append queue
func (c *Core) addToAppendQueue(block *types.WorkObject) error {
nodeCtx := c.NodeLocation().Context()
_, order, err := c.engine.CalcOrder(block)
if err != nil {
return err
}
if order == nodeCtx {
c.appendQueue.ContainsOrAdd(block.Hash(), blockNumberAndRetryCounter{block.NumberU64(c.NodeCtx()), 0})
}
return nil
}
// removeFromAppendQueue removes a block from the append queue
func (c *Core) removeFromAppendQueue(block *types.WorkObject) {
c.appendQueue.Remove(block.Hash())
}
// updateAppendQueue is a time to procAppendQueue
func (c *Core) updateAppendQueue() {
defer func() {
if r := recover(); r != nil {
c.logger.WithFields(log.Fields{
"error": r,
"stacktrace": string(debug.Stack()),
}).Error("Go-Quai Panicked")
}
}()
futureTimer := time.NewTicker(c_appendQueueRetryPeriod * time.Second)
defer futureTimer.Stop()
for {
select {
case <-futureTimer.C:
c.procAppendQueue()
case <-c.quit:
return
}
}
}
// Insert remotes into the tx pool
func (c *Core) startRemoteTxQueue() {
defer func() {
if r := recover(); r != nil {
c.logger.WithFields(log.Fields{
"error": r,
"stacktrace": string(debug.Stack()),
}).Error("Go-Quai Panicked")
}
}()
futureTimer := time.NewTicker(c_remoteTxProcPeriod * time.Second)
defer futureTimer.Stop()
for {
select {
case <-futureTimer.C:
txs := make([]*types.Transaction, 0, c.remoteTxQueue.Len())
for _, tx := range c.remoteTxQueue.Keys() {
if value, exist := c.remoteTxQueue.Peek(tx); exist {
txs = append(txs, value.(*types.Transaction))
c.remoteTxQueue.Remove(tx)
}
}
c.sl.txPool.AddRemotes(txs)
case <-c.quit:
return
}
}
}
func (c *Core) startStatsTimer() {
futureTimer := time.NewTicker(c_statsPrintPeriod * time.Second)
defer futureTimer.Stop()
defer func() {
if r := recover(); r != nil {
c.logger.WithFields(log.Fields{
"error": r,
"stacktrace": string(debug.Stack()),
}).Fatal("Go-Quai Panicked")
}
}()
for {
select {
case <-futureTimer.C:
c.printStats()
case <-c.quit:
return
}
}
}
// printStats displays stats on syncing, latestHeight, etc.
func (c *Core) printStats() {
c.logger.WithFields(log.Fields{
"loc": c.NodeLocation().Name(),
"len(appendQueue)": len(c.appendQueue.Keys()),
}).Info("Blocks waiting to be appended")
// Print hashes & heights of all queue entries.
for _, hash := range c.appendQueue.Keys()[:math.Min(len(c.appendQueue.Keys()), c_appendQueuePrintSize)] {
if value, exist := c.appendQueue.Peek(hash); exist {
hashNumber := types.HashAndNumber{Hash: hash.(common.Hash), Number: value.(blockNumberAndRetryCounter).number}
c.logger.WithFields(log.Fields{
"Number": strconv.FormatUint(hashNumber.Number, 10),
"Hash": hashNumber.Hash.String(),
}).Debug("AppendQueue entry")
}
}
}
func (c *Core) BadHashExistsInChain() bool {
nodeCtx := c.NodeLocation().Context()
// Lookup the bad hashes list to see if we have it in the database
for _, fork := range BadHashes {
switch nodeCtx {
case common.PRIME_CTX:
if c.GetBlockByHash(fork.PrimeContext) != nil {
return true
}
case common.REGION_CTX:
if c.GetBlockByHash(fork.RegionContext[c.NodeLocation().Region()]) != nil {
return true
}
case common.ZONE_CTX:
if c.GetBlockByHash(fork.ZoneContext[c.NodeLocation().Region()][c.NodeLocation().Zone()]) != nil {
return true
}
}
}
return false
}
func (c *Core) SubscribeMissingBlockEvent(ch chan<- types.BlockRequest) event.Subscription {
return c.sl.SubscribeMissingBlockEvent(ch)
}
// InsertChainWithoutSealVerification works exactly the same
// except for seal verification, seal verification is omitted
func (c *Core) InsertChainWithoutSealVerification(block *types.WorkObject) (int, error) {
return 0, nil
}
func (c *Core) Processor() *StateProcessor {
return c.sl.hc.bc.processor
}
func (c *Core) Config() *params.ChainConfig {
return c.sl.hc.bc.chainConfig
}
// Engine retreives the blake3 consensus engine.
func (c *Core) Engine() consensus.Engine {
return c.engine
}
func (c *Core) CheckIfValidWorkShare(workShare *types.WorkObjectHeader) bool {
return c.engine.CheckIfValidWorkShare(workShare)
}
// Slice retrieves the slice struct.
func (c *Core) Slice() *Slice {
return c.sl
}
func (c *Core) TxPool() *TxPool {
return c.sl.txPool
}
func (c *Core) Stop() {
// Delete the append queue
c.appendQueue.Purge()
close(c.quit)
c.sl.Stop()
}
//---------------//
// Slice methods //
//---------------//
// WriteBlock write the block to the bodydb database
func (c *Core) WriteBlock(block *types.WorkObject) {
c.writeBlockLock.Lock()
defer c.writeBlockLock.Unlock()
nodeCtx := c.NodeCtx()
if block.Location() == nil {
c.logger.Errorf("Block %d has nil location in %d context", block.NumberU64(c.sl.NodeCtx()), c.NodeCtx())
return
}
if c.sl.IsBlockHashABadHash(block.Hash()) {
return
}
if c.GetHeaderByHash(block.Hash()) == nil {
// Only add non dom blocks to the append queue
_, order, err := c.CalcOrder(block)
if err != nil {
return
}
if order == nodeCtx {
parentHeader := c.GetHeaderByHash(block.ParentHash(nodeCtx))
if parentHeader != nil {
c.sl.WriteBlock(block)
c.InsertChain([]*types.WorkObject{block})
}
c.addToAppendQueue(block)
// If a dom block comes in and we havent appended it yet
} else if order < nodeCtx && c.GetHeaderByHash(block.Hash()) == nil {
if c.sl.domClient != nil {
go c.sl.domClient.RequestDomToAppendOrFetch(context.Background(), block.Hash(), block.ParentEntropy(nodeCtx), order)
}
}
}
if c.GetHeaderOrCandidateByHash(block.Hash()) == nil {
c.sl.WriteBlock(block)
}
}
func (c *Core) Append(header *types.WorkObject, manifest types.BlockManifest, domPendingHeader *types.WorkObject, domTerminus common.Hash, domOrigin bool, newInboundEtxs types.Transactions) (types.Transactions, bool, bool, error) {
nodeCtx := c.NodeCtx()
newPendingEtxs, subReorg, setHead, err := c.sl.Append(header, domPendingHeader, domTerminus, domOrigin, newInboundEtxs)
if err != nil {
if err.Error() == ErrBodyNotFound.Error() || err.Error() == consensus.ErrUnknownAncestor.Error() || err.Error() == ErrSubNotSyncedToDom.Error() {
// Fetch the blocks for each hash in the manifest
block := c.GetBlockOrCandidateByHash(header.Hash())
if block == nil {
c.sl.missingBlockFeed.Send(types.BlockRequest{Hash: header.Hash(), Entropy: header.ParentEntropy(nodeCtx)})
} else {
c.addToQueueIfNotAppended(block)
}
for _, m := range manifest {
block := c.GetBlockOrCandidateByHash(m)
if block == nil {
c.sl.missingBlockFeed.Send(types.BlockRequest{Hash: m, Entropy: header.ParentEntropy(nodeCtx)})
} else {
c.addToQueueIfNotAppended(block)
}
}
block = c.GetBlockOrCandidateByHash(header.ParentHash(nodeCtx))
if block == nil {
c.sl.missingBlockFeed.Send(types.BlockRequest{Hash: header.ParentHash(nodeCtx), Entropy: header.ParentEntropy(nodeCtx)})
} else {
c.addToQueueIfNotAppended(block)
}
}
}
return newPendingEtxs, subReorg, setHead, err
}
func (c *Core) DownloadBlocksInManifest(blockHash common.Hash, manifest types.BlockManifest, entropy *big.Int) {
// Fetch the blocks for each hash in the manifest
for _, m := range manifest {
block := c.GetBlockOrCandidateByHash(m)
if block == nil {
c.sl.missingBlockFeed.Send(types.BlockRequest{Hash: m, Entropy: entropy})
} else {
c.addToQueueIfNotAppended(block)
}
}
if c.NodeLocation().Context() == common.REGION_CTX {
block := c.GetBlockOrCandidateByHash(blockHash)
if block != nil {
// If a prime block comes in
if c.sl.subClients[block.Location().SubIndex(c.NodeLocation())] != nil {
c.sl.subClients[block.Location().SubIndex(c.NodeLocation())].DownloadBlocksInManifest(context.Background(), block.Hash(), block.Manifest(), block.ParentEntropy(c.NodeCtx()))
}
}
}
}
// ConstructLocalBlock takes a header and construct the Block locally
func (c *Core) ConstructLocalMinedBlock(woHeader *types.WorkObject) (*types.WorkObject, error) {
return c.sl.ConstructLocalMinedBlock(woHeader)
}
func (c *Core) SubRelayPendingHeader(slPendingHeader types.PendingHeader, newEntropy *big.Int, location common.Location, subReorg bool, order int) {
c.sl.SubRelayPendingHeader(slPendingHeader, newEntropy, location, subReorg, order)
}
func (c *Core) UpdateDom(oldTerminus common.Hash, pendingHeader types.PendingHeader, location common.Location) {
c.sl.UpdateDom(oldTerminus, pendingHeader, location)
}
func (c *Core) NewGenesisPendigHeader(pendingHeader *types.WorkObject, domTerminus common.Hash, genesisHash common.Hash) {
c.sl.NewGenesisPendingHeader(pendingHeader, domTerminus, genesisHash)
}
func (c *Core) SetCurrentExpansionNumber(expansionNumber uint8) {
c.sl.SetCurrentExpansionNumber(expansionNumber)
}
func (c *Core) WriteGenesisBlock(block *types.WorkObject, location common.Location) {
c.sl.WriteGenesisBlock(block, location)
}
func (c *Core) GetPendingHeader() (*types.WorkObject, error) {
return c.sl.GetPendingHeader()
}
func (c *Core) GetManifest(blockHash common.Hash) (types.BlockManifest, error) {
return c.sl.GetManifest(blockHash)
}
func (c *Core) GetSubManifest(slice common.Location, blockHash common.Hash) (types.BlockManifest, error) {
return c.sl.GetSubManifest(slice, blockHash)
}
func (c *Core) GetPendingEtxs(hash common.Hash) *types.PendingEtxs {
return rawdb.ReadPendingEtxs(c.sl.sliceDb, hash)
}
func (c *Core) GetPendingEtxsRollup(hash common.Hash, location common.Location) *types.PendingEtxsRollup {
return rawdb.ReadPendingEtxsRollup(c.sl.sliceDb, hash)
}
func (c *Core) GetPendingEtxsRollupFromSub(hash common.Hash, location common.Location) (types.PendingEtxsRollup, error) {
return c.sl.GetPendingEtxsRollupFromSub(hash, location)
}
func (c *Core) GetPendingEtxsFromSub(hash common.Hash, location common.Location) (types.PendingEtxs, error) {
return c.sl.GetPendingEtxsFromSub(hash, location)
}
func (c *Core) HasPendingEtxs(hash common.Hash) bool {
return c.GetPendingEtxs(hash) != nil
}
func (c *Core) SendPendingEtxsToDom(pEtxs types.PendingEtxs) error {
return c.sl.SendPendingEtxsToDom(pEtxs)
}
func (c *Core) AddPendingEtxs(pEtxs types.PendingEtxs) error {
return c.sl.AddPendingEtxs(pEtxs)
}
func (c *Core) AddPendingEtxsRollup(pEtxsRollup types.PendingEtxsRollup) error {
return c.sl.AddPendingEtxsRollup(pEtxsRollup)
}
func (c *Core) GenerateRecoveryPendingHeader(pendingHeader *types.WorkObject, checkpointHashes types.Termini) error {
return c.sl.GenerateRecoveryPendingHeader(pendingHeader, checkpointHashes)
}
func (c *Core) IsBlockHashABadHash(hash common.Hash) bool {
return c.sl.IsBlockHashABadHash(hash)
}
func (c *Core) ProcessingState() bool {
return c.sl.ProcessingState()
}
func (c *Core) NodeLocation() common.Location {
return c.sl.NodeLocation()
}
func (c *Core) NodeCtx() int {
return c.sl.NodeCtx()
}
func (c *Core) GetSlicesRunning() []common.Location {
return c.sl.GetSlicesRunning()
}
func (c *Core) SetSubClient(client *quaiclient.Client, location common.Location) {
c.sl.SetSubClient(client, location)
}
func (c *Core) AddGenesisPendingEtxs(block *types.WorkObject) {
c.sl.AddGenesisPendingEtxs(block)
}
func (c *Core) SubscribeExpansionEvent(ch chan<- ExpansionEvent) event.Subscription {
return c.sl.SubscribeExpansionEvent(ch)
}
//---------------------//
// HeaderChain methods //
//---------------------//
// GetBlock retrieves a block from the database by hash and number,
// caching it if found.
func (c *Core) GetBlock(hash common.Hash, number uint64) *types.WorkObject {
return c.sl.hc.GetBlock(hash, number)
}
// GetBlockByHash retrieves a block from the database by hash, caching it if found.
func (c *Core) GetBlockByHash(hash common.Hash) *types.WorkObject {
return c.sl.hc.GetBlockByHash(hash)
}
// GetBlockOrCandidateByHash retrieves a block from the database by hash, caching it if found.
func (c *Core) GetBlockOrCandidateByHash(hash common.Hash) *types.WorkObject {
return c.sl.hc.GetBlockOrCandidateByHash(hash)
}
// GetHeaderByNumber retrieves a block header from the database by number,
// caching it (associated with its hash) if found.
func (c *Core) GetHeaderByNumber(number uint64) *types.WorkObject {
return c.sl.hc.GetHeaderByNumber(number)
}
// GetBlockByNumber retrieves a block from the database by number, caching it
// (associated with its hash) if found.
func (c *Core) GetBlockByNumber(number uint64) *types.WorkObject {
return c.sl.hc.GetBlockByNumber(number)
}
// GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
// [deprecated by eth/62]
func (c *Core) GetBlocksFromHash(hash common.Hash, n int) []*types.WorkObject {
return c.sl.hc.GetBlocksFromHash(hash, n)
}
// GetUnclesInChain retrieves all the uncles from a given block backwards until
// a specific distance is reached.
func (c *Core) GetUnclesInChain(block *types.WorkObject, length int) []*types.WorkObjectHeader {
return c.sl.hc.GetUnclesInChain(block, length)
}
// GetGasUsedInChain retrieves all the gas used from a given block backwards until
// a specific distance is reached.
func (c *Core) GetGasUsedInChain(block *types.WorkObject, length int) int64 {
return c.sl.hc.GetGasUsedInChain(block, length)
}
// GetGasUsedInChain retrieves all the gas used from a given block backwards until
// a specific distance is reached.
func (c *Core) CalculateBaseFee(header *types.WorkObject) *big.Int {
return c.sl.hc.CalculateBaseFee(header)
}
// CurrentBlock returns the block for the current header.
func (c *Core) CurrentBlock() *types.WorkObject {
return c.sl.hc.CurrentBlock()
}
// CurrentHeader retrieves the current head header of the canonical chain. The
// header is retrieved from the HeaderChain's internal cache.
func (c *Core) CurrentHeader() *types.WorkObject {
return c.sl.hc.CurrentHeader()
}
// CurrentLogEntropy returns the logarithm of the total entropy reduction since genesis for our current head block
func (c *Core) CurrentLogEntropy() *big.Int {
return c.engine.TotalLogS(c, c.sl.hc.CurrentHeader())
}
// TotalLogS returns the total entropy reduction if the chain since genesis to the given header
func (c *Core) TotalLogS(header *types.WorkObject) *big.Int {
return c.engine.TotalLogS(c, header)
}
// CalcOrder returns the order of the block within the hierarchy of chains
func (c *Core) CalcOrder(header *types.WorkObject) (*big.Int, int, error) {
return c.engine.CalcOrder(header)
}
// GetHeader retrieves a block header from the database by hash and number,
// caching it if found.
func (c *Core) GetHeader(hash common.Hash, number uint64) *types.WorkObject {
return c.sl.hc.GetHeader(hash, number)
}
// GetHeaderByHash retrieves a block header from the database by hash, caching it if
// found.
func (c *Core) GetHeaderByHash(hash common.Hash) *types.WorkObject {
return c.sl.hc.GetHeaderByHash(hash)
}
// GetHeaderOrCandidate retrieves a block header from the database by hash and number,
// caching it if found.
func (c *Core) GetHeaderOrCandidate(hash common.Hash, number uint64) *types.WorkObject {
return c.sl.hc.GetHeaderOrCandidate(hash, number)
}
// GetHeaderOrCandidateByHash retrieves a block header from the database by hash, caching it if
// found.
func (c *Core) GetHeaderOrCandidateByHash(hash common.Hash) *types.WorkObject {
return c.sl.hc.GetHeaderOrCandidateByHash(hash)
}
// HasHeader checks if a block header is present in the database or not, caching
// it if present.
func (c *Core) HasHeader(hash common.Hash, number uint64) bool {
return c.sl.hc.HasHeader(hash, number)
}
// GetCanonicalHash returns the canonical hash for a given block number
func (c *Core) GetCanonicalHash(number uint64) common.Hash {
return c.sl.hc.GetCanonicalHash(number)
}
// GetBlockHashesFromHash retrieves a number of block hashes starting at a given
// hash, fetching towards the genesis block.
func (c *Core) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
return c.sl.hc.GetBlockHashesFromHash(hash, max)
}
// GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
// a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
// number of blocks to be individually checked before we reach the canonical chain.
//
// Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
func (c *Core) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
return c.sl.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
}
// Genesis retrieves the chain's genesis block.
func (c *Core) Genesis() *types.WorkObject {
return c.GetBlockByHash(c.sl.hc.genesisHeader.Hash())
}
// SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
func (c *Core) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
return c.sl.hc.SubscribeChainHeadEvent(ch)
}
// GetBody retrieves a block body (transactions and uncles) from the database by
// hash, caching it if found.
func (c *Core) GetBody(hash common.Hash) *types.WorkObject {
return c.sl.hc.GetBody(hash)
}
// GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
// caching it if found.
func (c *Core) GetBodyRLP(hash common.Hash) rlp.RawValue {
return c.sl.hc.GetBodyRLP(hash)
}
// GetTerminiByHash retrieves the termini stored for a given header hash
func (c *Core) GetTerminiByHash(hash common.Hash) *types.Termini {
return c.sl.hc.GetTerminiByHash(hash)
}
// SubscribeChainSideEvent registers a subscription of ChainSideEvent.
func (c *Core) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
return c.sl.hc.SubscribeChainSideEvent(ch)
}
// ComputeEfficiencyScore computes the efficiency score for the given prime
// block This data is is only valid if called from Prime context, otherwise
// there is no guarantee for this data to be accurate
func (c *Core) ComputeEfficiencyScore(header *types.WorkObject) uint16 {
return c.sl.hc.ComputeEfficiencyScore(header)
}
// IsGenesisHash checks if a hash is the genesis block hash.
func (c *Core) IsGenesisHash(hash common.Hash) bool {
return c.sl.hc.IsGenesisHash(hash)
}
func (c *Core) GetExpansionNumber() uint8 {
return c.sl.hc.GetExpansionNumber()
}
func (c *Core) UpdateEtxEligibleSlices(header *types.WorkObject, location common.Location) common.Hash {
return c.sl.hc.UpdateEtxEligibleSlices(header, location)
}
func (c *Core) GetPrimeTerminus(header *types.WorkObject) *types.WorkObject {
return c.sl.hc.GetPrimeTerminus(header)
}
func (c *Core) CheckIfEtxIsEligible(etxEligibleSlices common.Hash, location common.Location) bool {
return c.sl.hc.CheckIfEtxIsEligible(etxEligibleSlices, location)
}
//--------------------//
// BlockChain methods //
//--------------------//
// HasBlock checks if a block is fully present in the database or not.
func (c *Core) HasBlock(hash common.Hash, number uint64) bool {
return c.sl.hc.bc.HasBlock(hash, number)
}
// SubscribeChainEvent registers a subscription of ChainEvent.
func (c *Core) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
return c.sl.hc.bc.SubscribeChainEvent(ch)
}
// SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
func (c *Core) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
return c.sl.hc.bc.SubscribeRemovedLogsEvent(ch)
}
// SubscribeChainSideEvent registers a subscription of ChainSideEvent.
func (c *Core) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
return c.sl.hc.bc.SubscribeLogsEvent(ch)
}
// SubscribeBlockProcessingEvent registers a subscription of bool where true means
// block processing has started while false means it has stopped.
func (c *Core) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription {
return c.sl.hc.bc.SubscribeBlockProcessingEvent(ch)
}
// Export writes the active chain to the given writer.
func (c *Core) Export(w io.Writer) error {
return c.sl.hc.Export(w)
}
// ExportN writes a subset of the active chain to the given writer.
func (c *Core) ExportN(w io.Writer, first uint64, last uint64) error {
return c.sl.hc.ExportN(w, first, last)
}
// Snapshots returns the blockchain snapshot tree.
func (c *Core) Snapshots() *snapshot.Tree {
return nil
}
func (c *Core) TxLookupLimit() uint64 {
return 0
}