-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.go
2336 lines (2049 loc) · 77.7 KB
/
chain.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
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2015-2017 The Decred developers
// Copyright (c) 2018-2020 The Hcd developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package blockchain
import (
"container/list"
"fmt"
"math/big"
"sort"
"sync"
"time"
"github.com/coolsnady/hcd/blockchain/stake"
"github.com/coolsnady/hcd/chaincfg"
"github.com/coolsnady/hcd/chaincfg/chainhash"
"github.com/coolsnady/hcd/database"
"github.com/coolsnady/hcd/txscript"
"github.com/coolsnady/hcd/wire"
"github.com/coolsnady/hcutil"
)
const (
// maxOrphanBlocks is the maximum number of orphan blocks that can be
// queued.
maxOrphanBlocks = 500
// minMemoryNodes is the minimum number of consecutive nodes needed
// in memory in order to perform all necessary validation. It is used
// to determine when it's safe to prune nodes from memory without
// causing constant dynamic reloading. This value should be larger than
// that for minMemoryStakeNodes.
minMemoryNodes = 2880
// minMemoryStakeNodes is the maximum height to keep stake nodes
// in memory for in their respective nodes. Beyond this height,
// they will need to be manually recalculated. This value should
// be at least the stake retarget interval.
minMemoryStakeNodes = 288
// mainchainBlockCacheSize is the number of mainchain blocks to
// keep in memory, by height from the tip of the mainchain.
mainchainBlockCacheSize = 12
// maxSearchDepth is the distance in block nodes to search down the
// blockchain to find some parent, loading block nodes from the
// database if necessary. Reorganizations longer than this disance may
// fail.
maxSearchDepth = 2880
)
// VoteVersionTuple contains the extracted vote bits and version from votes
// (SSGen).
type VoteVersionTuple struct {
Version uint32
Bits uint16
}
// blockNode represents a block within the block chain and is primarily used to
// aid in selecting the best chain to be the main chain. The main chain is
// stored into the block database.
type blockNode struct {
// parent is the parent block for this node.
parent *blockNode
// children contains the child nodes for this node. Typically there
// will only be one, but sometimes there can be more than one and that
// is when the best chain selection algorithm is used.
children []*blockNode
// hash is the double sha 256 of the block.
hash chainhash.Hash
// height is the position in the block chain.
height int64
// workSum is the total amount of work in the chain up to and including
// this node.
workSum *big.Int
// inMainChain denotes whether the block node is currently on the
// the main chain or not. This is used to help find the common
// ancestor when switching chains.
inMainChain bool
// header is the full block header.
header wire.BlockHeader
// stakeNode contains all the consensus information required for the
// staking system. The node also caches information required to add or
// remove stake nodes, so that the stake node itself may be pruneable
// to save memory while maintaining high throughput efficiency for the
// evaluation of sidechains.
stakeDataLock sync.Mutex
stakeNode *stake.Node
newTickets []chainhash.Hash
stakeUndoData stake.UndoTicketDataSlice
ticketsSpent []chainhash.Hash
ticketsRevoked []chainhash.Hash
// Keep track of all vote version and bits in this block.
votes []VoteVersionTuple
}
// newBlockNode returns a new block node for the given block header. It is
// completely disconnected from the chain and the workSum value is just the work
// for the passed block. The work sum is updated accordingly when the node is
// inserted into a chain.
func newBlockNode(blockHeader *wire.BlockHeader, ticketsSpent []chainhash.Hash, ticketsRevoked []chainhash.Hash, votes []VoteVersionTuple) *blockNode {
// Make a copy of the hash so the node doesn't keep a reference to part
// of the full block/block header preventing it from being garbage
// collected.
node := blockNode{
hash: blockHeader.BlockHash(),
workSum: CalcWork(blockHeader.Bits),
height: int64(blockHeader.Height),
header: *blockHeader,
ticketsSpent: ticketsSpent,
ticketsRevoked: ticketsRevoked,
votes: votes,
}
return &node
}
// orphanBlock represents a block that we don't yet have the parent for. It
// is a normal block plus an expiration time to prevent caching the orphan
// forever.
type orphanBlock struct {
block *hcutil.Block
expiration time.Time
}
// removeChildNode deletes node from the provided slice of child block
// nodes. It ensures the final pointer reference is set to nil to prevent
// potential memory leaks. The original slice is returned unmodified if node
// is invalid or not in the slice.
//
// This function MUST be called with the chain state lock held (for writes).
func removeChildNode(children []*blockNode, node *blockNode) []*blockNode {
if node == nil {
return children
}
// An indexing for loop is intentionally used over a range here as range
// does not reevaluate the slice on each iteration nor does it adjust
// the index for the modified slice.
for i := 0; i < len(children); i++ {
if children[i].hash == node.hash {
copy(children[i:], children[i+1:])
children[len(children)-1] = nil
return children[:len(children)-1]
}
}
return children
}
// BestState houses information about the current best block and other info
// related to the state of the main chain as it exists from the point of view of
// the current best block.
//
// The BestSnapshot method can be used to obtain access to this information
// in a concurrent safe manner and the data will not be changed out from under
// the caller when chain state changes occur as the function name implies.
// However, the returned snapshot must be treated as immutable since it is
// shared by all callers.
type BestState struct {
Hash *chainhash.Hash // The hash of the block.
Height int64 // The height of the block.
Bits uint32 // The difficulty bits of the block.
BlockSize uint64 // The size of the block.
NumTxns uint64 // The number of txns in the block.
TotalTxns uint64 // The total number of txns in the chain.
MedianTime time.Time // Median time as per calcPastMedianTime.
TotalSubsidy int64 // The total subsidy for the chain.
}
// newBestState returns a new best stats instance for the given parameters.
func newBestState(node *blockNode, blockSize, numTxns, totalTxns uint64, medianTime time.Time, totalSubsidy int64) *BestState {
return &BestState{
Hash: &node.hash,
Height: node.height,
Bits: node.header.Bits,
BlockSize: blockSize,
NumTxns: numTxns,
TotalTxns: totalTxns,
MedianTime: medianTime,
TotalSubsidy: totalSubsidy,
}
}
// BlockChain provides functions for working with the Hcd block chain.
// It includes functionality such as rejecting duplicate blocks, ensuring blocks
// follow all rules, orphan handling, checkpoint handling, and best chain
// selection with reorganization.
type BlockChain struct {
// The following fields are set when the instance is created and can't
// be changed afterwards, so there is no need to protect them with a
// separate mutex.
checkpointsByHeight map[int64]*chaincfg.Checkpoint
db database.DB
dbInfo *databaseInfo
chainParams *chaincfg.Params
timeSource MedianTimeSource
notifications NotificationCallback
sigCache *txscript.SigCache
indexManager IndexManager
// subsidyCache is the cache that provides quick lookup of subsidy
// values.
subsidyCache *SubsidyCache
// chainLock protects concurrent access to the vast majority of the
// fields in this struct below this point.
chainLock sync.RWMutex
// These fields are configuration parameters that can be toggled at
// runtime. They are protected by the chain lock.
noVerify bool
noCheckpoints bool
// These fields are related to the memory block index. They are
// protected by the chain lock.
bestNode *blockNode
index map[chainhash.Hash]*blockNode
depNodes map[chainhash.Hash][]*blockNode
// These fields are related to handling of orphan blocks. They are
// protected by a combination of the chain lock and the orphan lock.
orphanLock sync.RWMutex
orphans map[chainhash.Hash]*orphanBlock
prevOrphans map[chainhash.Hash][]*orphanBlock
oldestOrphan *orphanBlock
blockCacheLock sync.RWMutex
blockCache map[chainhash.Hash]*hcutil.Block
// The block cache for mainchain blocks, to facilitate faster
// reorganizations.
mainchainBlockCacheLock sync.RWMutex
mainchainBlockCache map[chainhash.Hash]*hcutil.Block
mainchainBlockCacheSize int
// These fields are related to checkpoint handling. They are protected
// by the chain lock.
nextCheckpoint *chaincfg.Checkpoint
checkpointBlock *hcutil.Block
// The state is used as a fairly efficient way to cache information
// about the current best chain state that is returned to callers when
// requested. It operates on the principle of MVCC such that any time a
// new block becomes the best block, the state pointer is replaced with
// a new struct and the old state is left untouched. In this way,
// multiple callers can be pointing to different best chain states.
// This is acceptable for most callers because the state is only being
// queried at a specific point in time.
//
// In addition, some of the fields are stored in the database so the
// chain state can be quickly reconstructed on load.
stateLock sync.RWMutex
stateSnapshot *BestState
// The following caches are used to efficiently keep track of the
// current deployment threshold state of each rule change deployment.
//
// This information is stored in the database so it can be quickly
// reconstructed on load.
//
// deploymentCaches caches the current deployment threshold state for
// blocks in each of the actively defined deployments.
deploymentCaches map[uint32][]thresholdStateCache
// pruner is the automatic pruner for block nodes and stake nodes,
// so that the memory may be restored by the garbage collector if
// it is unlikely to be referenced in the future.
pruner *chainPruner
// The following maps are various caches for the stake version/voting
// system. The goal of these is to reduce disk access to load blocks
// from disk. Measurements indicate that it is slightly more expensive
// so setup the cache (<10%) vs doing a straight chain walk. Every
// other subsequent call is >10x faster.
isVoterMajorityVersionCache map[[stakeMajorityCacheKeySize]byte]bool
isStakeMajorityVersionCache map[[stakeMajorityCacheKeySize]byte]bool
calcPriorStakeVersionCache map[[chainhash.HashSize]byte]uint32
calcVoterVersionIntervalCache map[[chainhash.HashSize]byte]uint32
calcStakeVersionCache map[[chainhash.HashSize]byte]uint32
}
const (
// stakeMajorityCacheKeySize is comprised of the stake version and the
// hash size. The stake version is a little endian uint32, hence we
// add 4 to the overall size.
stakeMajorityCacheKeySize = 4 + chainhash.HashSize
)
// StakeVersions is a condensed form of a hcutil.Block that is used to prevent
// using gigabytes of memory.
type StakeVersions struct {
Hash chainhash.Hash
Height int64
BlockVersion int32
StakeVersion uint32
Votes []VoteVersionTuple
}
// GetStakeVersions returns a cooked array of StakeVersions. We do this in
// order to not bloat memory by returning raw blocks.
func (b *BlockChain) GetStakeVersions(hash *chainhash.Hash, count int32) ([]StakeVersions, error) {
exists, err := b.HaveBlock(hash)
if err != nil {
return nil, err
}
if !exists {
return nil, fmt.Errorf("hash '%s' not found on chain", hash.String())
}
// Nothing to do if no count requested.
if count == 0 {
return nil, nil
}
if count < 0 {
return nil, fmt.Errorf("count must not be less than zero - "+
"got %d", count)
}
b.chainLock.Lock()
defer b.chainLock.Unlock()
if count > int32(b.bestNode.height) {
count = int32(b.bestNode.height)
}
startNode, err := b.findNode(hash, 0)
if err != nil {
return nil, err
}
result := make([]StakeVersions, 0, count)
prevNode := startNode
for i := int32(0); prevNode != nil && i < count; i++ {
sv := StakeVersions{
Hash: prevNode.hash,
Height: prevNode.height,
BlockVersion: prevNode.header.Version,
StakeVersion: prevNode.header.StakeVersion,
Votes: prevNode.votes,
}
result = append(result, sv)
prevNode, err = b.getPrevNodeFromNode(prevNode)
if err != nil {
return nil, err
}
}
return result, nil
}
type VoteInfo struct {
Agendas []chaincfg.ConsensusDeployment
AgendaStatus []ThresholdStateTuple
}
// GetVoteInfo returns
func (b *BlockChain) GetVoteInfo(hash *chainhash.Hash, version uint32) (*VoteInfo, error) {
deployments, ok := b.chainParams.Deployments[version]
if !ok {
return nil, VoteVersionError(version)
}
if !ok {
return nil, HashError(hash.String())
}
vi := VoteInfo{
Agendas: make([]chaincfg.ConsensusDeployment,
0, len(deployments)),
AgendaStatus: make([]ThresholdStateTuple, 0, len(deployments)),
}
for _, deployment := range deployments {
vi.Agendas = append(vi.Agendas, deployment)
status, err := b.ThresholdState(hash, version, deployment.Vote.Id)
if err != nil {
return nil, err
}
vi.AgendaStatus = append(vi.AgendaStatus, status)
}
return &vi, nil
}
// DisableVerify provides a mechanism to disable transaction script validation
// which you DO NOT want to do in production as it could allow double spends
// and other undesirable things. It is provided only for debug purposes since
// script validation is extremely intensive and when debugging it is sometimes
// nice to quickly get the chain.
//
// This function is safe for concurrent access.
func (b *BlockChain) DisableVerify(disable bool) {
b.chainLock.Lock()
b.noVerify = disable
b.chainLock.Unlock()
}
// TotalSubsidy returns the total subsidy mined so far in the best chain.
//
// This function is safe for concurrent access.
func (b *BlockChain) TotalSubsidy() int64 {
b.chainLock.RLock()
ts := b.BestSnapshot().TotalSubsidy
b.chainLock.RUnlock()
return ts
}
// FetchSubsidyCache returns the current subsidy cache from the blockchain.
//
// This function is safe for concurrent access.
func (b *BlockChain) FetchSubsidyCache() *SubsidyCache {
return b.subsidyCache
}
// HaveBlock returns whether or not the chain instance has the block represented
// by the passed hash. This includes checking the various places a block can
// be like part of the main chain, on a side chain, or in the orphan pool.
//
// This function is safe for concurrent access.
func (b *BlockChain) HaveBlock(hash *chainhash.Hash) (bool, error) {
b.chainLock.RLock()
exists, err := b.blockExists(hash)
b.chainLock.RUnlock()
if err != nil {
return false, err
}
return exists || b.IsKnownOrphan(hash), nil
}
// IsKnownOrphan returns whether the passed hash is currently a known orphan.
// Keep in mind that only a limited number of orphans are held onto for a
// limited amount of time, so this function must not be used as an absolute
// way to test if a block is an orphan block. A full block (as opposed to just
// its hash) must be passed to ProcessBlock for that purpose. However, calling
// ProcessBlock with an orphan that already exists results in an error, so this
// function provides a mechanism for a caller to intelligently detect *recent*
// duplicate orphans and react accordingly.
//
// This function is safe for concurrent access.
func (b *BlockChain) IsKnownOrphan(hash *chainhash.Hash) bool {
// Protect concurrent access. Using a read lock only so multiple
// readers can query without blocking each other.
b.orphanLock.RLock()
_, exists := b.orphans[*hash]
b.orphanLock.RUnlock()
return exists
}
// GetOrphanRoot returns the head of the chain for the provided hash from the
// map of orphan blocks.
//
// This function is safe for concurrent access.
func (b *BlockChain) GetOrphanRoot(hash *chainhash.Hash) *chainhash.Hash {
// Protect concurrent access. Using a read lock only so multiple
// readers can query without blocking each other.
b.orphanLock.RLock()
defer b.orphanLock.RUnlock()
// Keep looping while the parent of each orphaned block is
// known and is an orphan itself.
orphanRoot := hash
prevHash := hash
for {
orphan, exists := b.orphans[*prevHash]
if !exists {
break
}
orphanRoot = prevHash
prevHash = &orphan.block.MsgBlock().Header.PrevBlock
}
return orphanRoot
}
// removeOrphanBlock removes the passed orphan block from the orphan pool and
// previous orphan index.
func (b *BlockChain) removeOrphanBlock(orphan *orphanBlock) {
// Protect concurrent access.
b.orphanLock.Lock()
defer b.orphanLock.Unlock()
// Remove the orphan block from the orphan pool.
orphanHash := orphan.block.Hash()
delete(b.orphans, *orphanHash)
// Remove the reference from the previous orphan index too. An indexing
// for loop is intentionally used over a range here as range does not
// reevaluate the slice on each iteration nor does it adjust the index
// for the modified slice.
prevHash := &orphan.block.MsgBlock().Header.PrevBlock
orphans := b.prevOrphans[*prevHash]
for i := 0; i < len(orphans); i++ {
hash := orphans[i].block.Hash()
if hash.IsEqual(orphanHash) {
copy(orphans[i:], orphans[i+1:])
orphans[len(orphans)-1] = nil
orphans = orphans[:len(orphans)-1]
i--
}
}
b.prevOrphans[*prevHash] = orphans
// Remove the map entry altogether if there are no longer any orphans
// which depend on the parent hash.
if len(b.prevOrphans[*prevHash]) == 0 {
delete(b.prevOrphans, *prevHash)
}
}
// addOrphanBlock adds the passed block (which is already determined to be
// an orphan prior calling this function) to the orphan pool. It lazily cleans
// up any expired blocks so a separate cleanup poller doesn't need to be run.
// It also imposes a maximum limit on the number of outstanding orphan
// blocks and will remove the oldest received orphan block if the limit is
// exceeded.
func (b *BlockChain) addOrphanBlock(block *hcutil.Block) {
// Remove expired orphan blocks.
for _, oBlock := range b.orphans {
if time.Now().After(oBlock.expiration) {
b.removeOrphanBlock(oBlock)
continue
}
// Update the oldest orphan block pointer so it can be discarded
// in case the orphan pool fills up.
if b.oldestOrphan == nil ||
oBlock.expiration.Before(b.oldestOrphan.expiration) {
b.oldestOrphan = oBlock
}
}
// Limit orphan blocks to prevent memory exhaustion.
if len(b.orphans)+1 > maxOrphanBlocks {
// Remove the oldest orphan to make room for the new one.
b.removeOrphanBlock(b.oldestOrphan)
b.oldestOrphan = nil
}
// Protect concurrent access. This is intentionally done here instead
// of near the top since removeOrphanBlock does its own locking and
// the range iterator is not invalidated by removing map entries.
b.orphanLock.Lock()
defer b.orphanLock.Unlock()
// Insert the block into the orphan map with an expiration time
// 1 hour from now.
expiration := time.Now().Add(time.Hour)
oBlock := &orphanBlock{
block: block,
expiration: expiration,
}
b.orphans[*block.Hash()] = oBlock
// Add to previous hash lookup index for faster dependency lookups.
prevHash := &block.MsgBlock().Header.PrevBlock
b.prevOrphans[*prevHash] = append(b.prevOrphans[*prevHash], oBlock)
return
}
// tipGeneration returns the entire generation of blocks stemming from the
// parent of the current tip.
//
// This function MUST be called with the chain lock held (for reads).
func (b *BlockChain) tipGeneration() ([]chainhash.Hash, error) {
// Get the parent of this tip.
p, err := b.getPrevNodeFromNode(b.bestNode)
if err != nil {
return nil, fmt.Errorf("block is orphan (parent missing)")
}
if p == nil {
return nil, fmt.Errorf("no need to get children of genesis block")
}
// Store all the hashes in a new slice and return them.
lenChildren := len(p.children)
allChildren := make([]chainhash.Hash, lenChildren)
for i := 0; i < lenChildren; i++ {
allChildren[i] = p.children[i].hash
}
return allChildren, nil
}
// TipGeneration returns the entire generation of blocks stemming from the
// parent of the current tip.
//
// The function is safe for concurrent access.
func (b *BlockChain) TipGeneration() ([]chainhash.Hash, error) {
b.chainLock.Lock()
children, err := b.tipGeneration()
b.chainLock.Unlock()
return children, err
}
// getGeneration gets a generation of blocks who all have the same parent by
// taking a hash as input, locating its parent node, and then returning all
// children for that parent node including the hash passed. This can then be
// used by the mempool downstream to locate all potential block template
// parents.
func (b *BlockChain) getGeneration(h chainhash.Hash) ([]chainhash.Hash, error) {
node, err := b.findNode(&h, maxSearchDepth)
// This typically happens because the main chain has recently
// reorganized and the block the miner is looking at is on
// a fork. Usually it corrects itself after failure.
if err != nil {
return nil, fmt.Errorf("couldn't find block node in best chain: %v",
err.Error())
}
// Get the parent of this node.
p, err := b.getPrevNodeFromNode(node)
if err != nil {
return nil, fmt.Errorf("block is orphan (parent missing)")
}
if p == nil {
return nil, fmt.Errorf("no need to get children of genesis block")
}
// Store all the hashes in a new slice and return them.
lenChildren := len(p.children)
allChildren := make([]chainhash.Hash, lenChildren, lenChildren)
for i := 0; i < lenChildren; i++ {
allChildren[i] = p.children[i].hash
}
return allChildren, nil
}
// GetGeneration is the exported version of getGeneration.
func (b *BlockChain) GetGeneration(hash chainhash.Hash) ([]chainhash.Hash, error) {
return b.getGeneration(hash)
}
// loadBlockNode loads the block identified by hash from the block database,
// creates a block node from it, and updates the memory block chain accordingly.
// It is used mainly to dynamically load previous blocks from the database as
// they are needed to avoid needing to put the entire block chain in memory.
//
// This function MUST be called with the chain state lock held (for writes).
// The database transaction may be read-only.
func (b *BlockChain) loadBlockNode(dbTx database.Tx, hash *chainhash.Hash) (*blockNode, error) {
block, err := dbFetchBlockByHash(dbTx, hash)
if err != nil {
return nil, err
}
blockHeader := block.MsgBlock().Header
node := newBlockNode(&blockHeader, ticketsSpentInBlock(block),
ticketsRevokedInBlock(block), voteBitsInBlock(block))
node.inMainChain = true
prevHash := &blockHeader.PrevBlock
// Add the node to the chain.
// There are a few possibilities here:
// 1) This node is a child of an existing block node
// 2) This node is the parent of one or more nodes
// 3) Neither 1 or 2 is true which implies it's an orphan block and
// therefore is an error to insert into the chain
if parentNode, ok := b.index[*prevHash]; ok {
// Case 1 -- This node is a child of an existing block node.
// Update the node's work sum with the sum of the parent node's
// work sum and this node's work, append the node as a child of
// the parent node and set this node's parent to the parent
// node.
node.workSum = node.workSum.Add(parentNode.workSum, node.workSum)
parentNode.children = append(parentNode.children, node)
node.parent = parentNode
} else if childNodes, ok := b.depNodes[*hash]; ok {
// Case 2 -- This node is the parent of one or more nodes.
// Update the node's work sum by subtracting this node's work
// from the sum of its first child, and connect the node to all
// of its children.
node.workSum.Sub(childNodes[0].workSum, node.workSum)
for _, childNode := range childNodes {
childNode.parent = node
node.children = append(node.children, childNode)
}
} else {
// Case 3 -- The node doesn't have a parent in the node cache
// and is not the parent of another node. This means an arbitrary
// orphan block is trying to be loaded which is not allowed.
// Before we return, check and make sure there isn't a parent
// further down the line in the blockchain to which the block
// could be attached, for example if the node had been pruned from
// the index.
foundParent, err := b.findNode(&node.header.PrevBlock, maxSearchDepth)
if err == nil {
node.workSum = node.workSum.Add(foundParent.workSum, node.workSum)
foundParent.children = append(foundParent.children, node)
node.parent = foundParent
} else {
str := "loadBlockNode: attempt to insert orphan block %v"
return nil, AssertError(fmt.Sprintf(str, hash))
}
}
// Add the new node to the indices for faster lookups.
b.index[*hash] = node
b.depNodes[*prevHash] = append(b.depNodes[*prevHash], node)
return node, nil
}
// findNode finds the node scaling backwards from best chain or return an
// error. If searchDepth equal zero there is no searchDepth.
//
// This function MUST be called with the chain state lock held (for writes).
func (b *BlockChain) findNode(nodeHash *chainhash.Hash, searchDepth int) (*blockNode, error) {
var node *blockNode
err := b.db.View(func(dbTx database.Tx) error {
// Most common case; we're checking a block that wants to be connected
// on top of the current main chain.
distance := 0
if *nodeHash == b.bestNode.hash {
node = b.bestNode
} else {
// Look backwards in our blockchain and try to find it in the
// parents of blocks.
foundPrev := b.bestNode
notFound := true
for !foundPrev.hash.IsEqual(b.chainParams.GenesisHash) {
if searchDepth != 0 && distance >= searchDepth {
break
}
if foundPrev.hash.IsEqual(nodeHash) {
notFound = false
break
}
last := foundPrev.header.PrevBlock
foundPrev = foundPrev.parent
if foundPrev == nil {
parent, err := b.loadBlockNode(dbTx, &last)
if err != nil {
return err
}
foundPrev = parent
}
distance++
}
if notFound {
return fmt.Errorf("couldn't find node %v in best chain",
nodeHash)
}
node = foundPrev
}
return nil
})
return node, err
}
// fetchMainChainBlockByHash returns the block from the main chain with the
// given hash. It first attempts to use cache and then falls back to loading it
// from the database.
//
// An error is returned if the block is either not found or not in the main
// chain.
//
// This function is safe for concurrent access.
func (b *BlockChain) fetchMainChainBlockByHash(hash *chainhash.Hash) (*hcutil.Block, error) {
b.mainchainBlockCacheLock.RLock()
block, ok := b.mainchainBlockCache[*hash]
b.mainchainBlockCacheLock.RUnlock()
if ok {
return block, nil
}
// Load the block from the database.
err := b.db.View(func(dbTx database.Tx) error {
var err error
block, err = dbFetchBlockByHash(dbTx, hash)
return err
})
return block, err
}
// fetchBlockByHash returns the block with the given hash from all known sources
// such as the internal caches and the database.
//
// This function is safe for concurrent access.
func (b *BlockChain) fetchBlockByHash(hash *chainhash.Hash) (*hcutil.Block, error) {
// Check side chain block cache.
b.blockCacheLock.RLock()
block, existsSidechain := b.blockCache[*hash]
b.blockCacheLock.RUnlock()
if existsSidechain {
return block, nil
}
// Check orphan cache.
b.orphanLock.RLock()
orphan, existsOrphans := b.orphans[*hash]
b.orphanLock.RUnlock()
if existsOrphans {
return orphan.block, nil
}
// Check main chain cache.
b.mainchainBlockCacheLock.RLock()
block, ok := b.mainchainBlockCache[*hash]
b.mainchainBlockCacheLock.RUnlock()
if ok {
return block, nil
}
// Attempt to load the block from the database.
err := b.db.View(func(dbTx database.Tx) error {
// NOTE: This does not use the dbFetchBlockByHash function since that
// function only works with main chain blocks.
blockBytes, err := dbTx.FetchBlock(hash)
if err != nil {
return err
}
block, err = hcutil.NewBlockFromBytes(blockBytes)
return err
})
if err == nil && block != nil {
return block, nil
}
return nil, fmt.Errorf("unable to find block %v in cache or db", hash)
}
// FetchBlockByHash searches the internal chain block stores and the database
// in an attempt to find the requested block.
//
// This function differs from BlockByHash in that this one also returns blocks
// that are not part of the main chain (if they are known).
//
// This function is safe for concurrent access.
func (b *BlockChain) FetchBlockByHash(hash *chainhash.Hash) (*hcutil.Block, error) {
return b.fetchBlockByHash(hash)
}
// getPrevNodeFromBlock returns a block node for the block previous to the
// passed block (the passed block's parent). When it is already in the memory
// block chain, it simply returns it. Otherwise, it loads the previous block
// header from the block database, creates a new block node from it, and returns
// it. The returned node will be nil if the genesis block is passed.
//
// This function MUST be called with the chain state lock held (for writes).
func (b *BlockChain) getPrevNodeFromBlock(block *hcutil.Block) (*blockNode,
error) {
// Genesis block.
prevHash := &block.MsgBlock().Header.PrevBlock
if prevHash.IsEqual(zeroHash) {
return nil, nil
}
// Return the existing previous block node if it's already there.
if bn, ok := b.index[*prevHash]; ok {
return bn, nil
}
// Dynamically load the previous block from the block database, create
// a new block node for it, and update the memory chain accordingly.
var prevBlockNode *blockNode
err := b.db.View(func(dbTx database.Tx) error {
var err error
prevBlockNode, err = b.loadBlockNode(dbTx, prevHash)
return err
})
return prevBlockNode, err
}
// getPrevNodeFromNode returns a block node for the block previous to the
// passed block node (the passed block node's parent). When the node is already
// connected to a parent, it simply returns it. Otherwise, it loads the
// associated block from the database to obtain the previous hash and uses that
// to dynamically create a new block node and return it. The memory block
// chain is updated accordingly. The returned node will be nil if the genesis
// block is passed.
//
// This function MUST be called with the chain state lock held (for writes).
func (b *BlockChain) getPrevNodeFromNode(node *blockNode) (*blockNode, error) {
// Return the existing previous block node if it's already there.
if node.parent != nil {
return node.parent, nil
}
// Genesis block.
if node.hash.IsEqual(b.chainParams.GenesisHash) {
return nil, nil
}
// Dynamically load the previous block from the block database, create
// a new block node for it, and update the memory chain accordingly.
var prevBlockNode *blockNode
err := b.db.View(func(dbTx database.Tx) error {
var err error
prevBlockNode, err = b.loadBlockNode(dbTx, &node.header.PrevBlock)
return err
})
return prevBlockNode, err
}
// ancestorNode returns the ancestor block node at the provided height by
// following the chain backwards from the given node while dynamically loading
// any pruned nodes from the database and updating the memory block chain as
// needed. The returned block will be nil when a height is requested that is
// after the height of the passed node or is less than zero.
//
// This function MUST be called with the chain state lock held (for writes).
func (b *BlockChain) ancestorNode(node *blockNode, height int64) (*blockNode, error) {
// Nothing to do if the requested height is outside of the valid range.
if height > node.height || height < 0 {
return nil, nil
}
// Iterate backwards until the requested height is reached.
iterNode := node
for iterNode != nil && iterNode.height > height {
// Get the previous block node. This function is used over
// simply accessing iterNode.parent directly as it will
// dynamically create previous block nodes as needed. This
// helps allow only the pieces of the chain that are needed
// to remain in memory.
var err error
iterNode, err = b.getPrevNodeFromNode(iterNode)
if err != nil {
log.Errorf("getPrevNodeFromNode: %v", err)
return nil, err
}
}
return iterNode, nil
}
// GetTopBlock returns the current block at HEAD on the blockchain. Needed
// for mining in the daemon.
func (b *BlockChain) GetTopBlock() (*hcutil.Block, error) {
return b.fetchMainChainBlockByHash(&b.bestNode.hash)
}
// pruneStakeNodes removes references to old stake nodes which should no
// longer be held in memory so as to keep the maximum memory usage down.
// It proceeds from the bestNode back to the determined minimum height node,
// finds all the relevant children, and then drops the the stake nodes from
// them by assigning nil and allowing the memory to be recovered by GC.
//
// This function MUST be called with the chain state lock held (for writes).
func (b *BlockChain) pruneStakeNodes() {
// Find the height to prune to.
pruneToNode := b.bestNode
for i := int64(0); i < minMemoryStakeNodes-1 && pruneToNode != nil; i++ {
pruneToNode = pruneToNode.parent
}
// Nothing to do if there are not enough nodes.
if pruneToNode == nil || pruneToNode.parent == nil {
return
}
// Push the nodes to delete on a list in reverse order since it's easier
// to prune them going forwards than it is backwards. This will
// typically end up being a single node since pruning is currently done
// just before each new node is created. However, that might be tuned
// later to only prune at intervals, so the code needs to account for
// the possibility of multiple nodes.
deleteNodes := list.New()
for node := pruneToNode.parent; node != nil; node = node.parent {
deleteNodes.PushFront(node)
}
// Loop through each node to prune, unlink its children, remove it from
// the dependency index, and remove it from the node index.
for e := deleteNodes.Front(); e != nil; e = e.Next() {
node := e.Value.(*blockNode)
// Do not attempt to prune if the node should already have been pruned,
// for example if you're adding an old side chain block.
if node.height > b.bestNode.height-minMemoryNodes {
node.stakeNode = nil
node.stakeUndoData = nil
node.newTickets = nil
node.ticketsSpent = nil