forked from decred/dcrd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.go
1649 lines (1439 loc) · 53.2 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-2014 The btcsuite developers
// Copyright (c) 2015 The Decred 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"
"errors"
"fmt"
"math/big"
"sort"
"sync"
"time"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/database"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrutil"
)
const (
// maxOrphanBlocks is the maximum number of orphan blocks that can be
// queued.
maxOrphanBlocks = 500
// minMemoryNodesLocal 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.
minMemoryNodesLocal = 4096
// searchDepth is the distance in blocks to search down the blockchain
// to find some parent.
searchDepth = 2048
)
// ErrIndexAlreadyInitialized describes an error that indicates the block index
// is already initialized.
var ErrIndexAlreadyInitialized = errors.New("the block index can only be " +
"initialized before it has been modified")
// 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
// parentHash is the double sha 256 of the parent block. This is kept
// here over simply relying on parent.hash directly since block nodes
// are sparse and the parent node might not be in memory when its hash
// is needed.
parentHash *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
// outputAmtsTotal is amount of fees in the tx tree regular of the parent plus
// the value of the coinbase, which may or may not be given to the child node
// depending on the voters. Doesn't get set until you actually attempt to
// connect the block and calculate the fees/reward for it.
// DECRED TODO: Is this actually used anywhere? If not prune it.
outputAmtsTotal int64
// Decred: Keep the full block header.
header wire.BlockHeader
// VoteBits for the stake voters.
voteBits []uint16
// Some fields from block headers to aid in best chain selection.
version int32
bits uint32
timestamp time.Time
}
// 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, blockSha *chainhash.Hash,
height int64, voteBits []uint16) *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.
prevHash := blockHeader.PrevBlock
node := blockNode{
hash: blockSha,
parentHash: &prevHash,
workSum: CalcWork(blockHeader.Bits),
height: height,
version: blockHeader.Version,
bits: blockHeader.Bits,
timestamp: blockHeader.Timestamp,
header: *blockHeader,
}
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 *dcrutil.Block
expiration time.Time
}
// addChildrenWork adds the passed work amount to all children all the way
// down the chain. It is used primarily to allow a new node to be dynamically
// inserted from the database into the memory chain prior to nodes we already
// have and update their work values accordingly.
func addChildrenWork(node *blockNode, work *big.Int) {
for _, childNode := range node.children {
childNode.workSum.Add(childNode.workSum, work)
addChildrenWork(childNode, work)
}
}
// 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.
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.IsEqual(node.hash) {
copy(children[i:], children[i+1:])
children[len(children)-1] = nil
return children[:len(children)-1]
}
}
return children
}
// BlockChain provides functions for working with the decred 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 {
db database.Db
tmdb *stake.TicketDB
chainParams *chaincfg.Params
checkpointsByHeight map[int64]*chaincfg.Checkpoint
notifications NotificationCallback
minMemoryNodes int64
blocksPerRetarget int64
stakeValidationHeight int64
root *blockNode
bestChain *blockNode
index map[chainhash.Hash]*blockNode
depNodes map[chainhash.Hash][]*blockNode
orphans map[chainhash.Hash]*orphanBlock
prevOrphans map[chainhash.Hash][]*orphanBlock
oldestOrphan *orphanBlock
orphanLock sync.RWMutex
blockCache map[chainhash.Hash]*dcrutil.Block
blockCacheLock sync.RWMutex
noVerify bool
noCheckpoints bool
nextCheckpoint *chaincfg.Checkpoint
checkpointBlock *dcrutil.Block
}
// StakeValidationHeight returns the height at which proof of stake validation
// begins for proof of work block headers.
func (b *BlockChain) StakeValidationHeight() int64 {
return b.stakeValidationHeight
}
// 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 othe 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.
func (b *BlockChain) DisableVerify(disable bool) {
b.noVerify = disable
}
// LiveTickets returns all currently live tickets from the stake database.
//
// This function is NOT safe for concurrent access.
func (b *BlockChain) LiveTickets() ([]*chainhash.Hash, error) {
live, err := b.tmdb.DumpAllLiveTicketHashes()
if err != nil {
return nil, err
}
return live, nil
}
// MissedTickets returns all currently missed tickets from the stake database.
//
// This function is NOT safe for concurrent access.
func (b *BlockChain) MissedTickets() (stake.SStxMemMap, error) {
missed, err := b.tmdb.DumpMissedTickets()
if err != nil {
return nil, err
}
return missed, nil
}
// TicketsWithAddress returns a slice of ticket hashes that are currently live
// corresponding to the given address.
//
// This function is NOT safe for concurrent access.
func (b *BlockChain) TicketsWithAddress(address dcrutil.Address) ([]chainhash.Hash,
error) {
return b.tmdb.GetLiveTicketsForAddress(address)
}
// CheckLiveTicket returns whether or not a ticket exists in the live ticket
// map of the stake database.
//
// This function is NOT safe for concurrent access.
func (b *BlockChain) CheckLiveTicket(hash *chainhash.Hash) (bool, error) {
return b.tmdb.CheckLiveTicket(*hash)
}
// CheckLiveTickets returns whether or not a slice of tickets exist in the live
// ticket map of the stake database.
//
// This function is NOT safe for concurrent access.
func (b *BlockChain) CheckLiveTickets(hashes []*chainhash.Hash) ([]bool, error) {
var err error
existsSlice := make([]bool, len(hashes))
for i, hash := range hashes {
existsSlice[i], err = b.tmdb.CheckLiveTicket(*hash)
if err != nil {
return nil, err
}
}
return existsSlice, nil
}
// TicketPoolValue returns the current value of all the locked funds in the
// ticket pool.
//
// This function is NOT safe for concurrent access.
func (b *BlockChain) TicketPoolValue() (dcrutil.Amount, error) {
tickets, err := b.tmdb.DumpAllLiveTicketHashes()
if err != nil {
return 0, err
}
// Make batches of tickets and retrieve them from the
// db, adding their commitment amounts each time.
ticketsLen := len(tickets)
batchSize := 250
batches := (ticketsLen / batchSize) + 1
lastBatchSize := 0
if ticketsLen%250 != 0 {
lastBatchSize = ticketsLen - ((batches - 1) * batchSize)
}
var amt int64
for i := 0; i < batches; i++ {
// Set up the cursor positions.
start := i * batchSize
end := (i + 1) * batchSize
if i == batches-1 {
// Nothing to do because last batch empty.
if lastBatchSize == 0 {
break
}
end = i*batchSize + lastBatchSize
}
txReplyList := b.db.FetchTxByShaList(tickets[start:end])
for _, txr := range txReplyList {
if txr.Err != nil {
return 0, txr.Err
}
amt += txr.Tx.TxOut[0].Value
}
}
return dcrutil.Amount(amt), nil
}
// 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 NOT safe for concurrent access.
func (b *BlockChain) HaveBlock(hash *chainhash.Hash) (bool, error) {
exists, err := b.blockExists(hash)
if err != nil {
return false, err
}
return b.IsKnownOrphan(hash) || exists, 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()
defer b.orphanLock.RUnlock()
if _, exists := b.orphans[*hash]; exists {
return true
}
return false
}
// 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.Sha()
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.Sha()
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 *dcrutil.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.Sha()] = 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
}
// 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)
// 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)
}
// GenerateInitialIndex is an optional function which generates the required
// number of initial block nodes in an optimized fashion. This is optional
// because the memory block index is sparse and previous nodes are dynamically
// loaded as needed. However, during initial startup (when there are no nodes
// in memory yet), dynamically loading all of the required nodes on the fly in
// the usual way is much slower than preloading them.
//
// This function can only be called once and it must be called before any nodes
// are added to the block index. ErrIndexAlreadyInitialized is returned if
// the former is not the case. In practice, this means the function should be
// called directly after New.
func (b *BlockChain) GenerateInitialIndex() error {
// Return an error if the has already been modified.
if b.root != nil {
return ErrIndexAlreadyInitialized
}
// Grab the latest block height for the main chain from the database.
_, endHeight, err := b.db.NewestSha()
if err != nil {
return err
}
// Calculate the starting height based on the minimum number of nodes
// needed in memory.
startHeight := endHeight - b.minMemoryNodes
if startHeight < 0 {
startHeight = 0
}
// Loop forwards through each block loading the node into the index for
// the block.
//
// Due to a bug in the SQLite dcrdb driver, the FetchBlockBySha call is
// limited to a maximum number of hashes per invocation. Since SQLite
// is going to be nuked eventually, the bug isn't being fixed in the
// driver. In the mean time, work around the issue by calling
// FetchBlockBySha multiple times with the appropriate indices as needed.
for start := startHeight; start <= endHeight; {
hashList, err := b.db.FetchHeightRange(start, endHeight+1)
if err != nil {
return err
}
// The database did not return any further hashes. Break out of
// the loop now.
if len(hashList) == 0 {
break
}
// Loop forwards through each block loading the node into the
// index for the block.
for _, hash := range hashList {
// Make a copy of the hash to make sure there are no
// references into the list so it can be freed.
hashCopy := hash
node, err := b.loadBlockNode(&hashCopy)
if err != nil {
return err
}
// This node is now the end of the best chain.
b.bestChain = node
}
// Start at the next block after the latest one on the next loop
// iteration.
start += int64(len(hashList))
}
return nil
}
// 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 database as they
// are needed to avoid needing to put the entire block chain in memory.
func (b *BlockChain) loadBlockNode(hash *chainhash.Hash) (*blockNode, error) {
block, err := b.db.FetchBlockBySha(hash)
if err != nil {
return nil, err
}
// Create the new block node for the block and set the work.
var voteBitsStake []uint16
for _, stx := range block.STransactions() {
if is, _ := stake.IsSSGen(stx); is {
vb := stake.GetSSGenVoteBits(stx)
voteBitsStake = append(voteBitsStake, vb)
}
}
node := newBlockNode(&block.MsgBlock().Header, hash,
int64(block.MsgBlock().Header.Height), voteBitsStake)
node.inMainChain = true
prevHash := &block.MsgBlock().Header.PrevBlock
// Add the node to the chain.
// There are several 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, and this is not the first node being
// added to the tree which implies it's an orphan block and
// therefore is an error to insert into the chain
// 4) Neither 1 or 2 is true, but this is the first node being added
// to the tree, so it's the root.
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.
// Connect this block node to all of its children and update
// all of the children (and their children) with the new work
// sums.
for _, childNode := range childNodes {
childNode.parent = node
node.children = append(node.children, childNode)
addChildrenWork(childNode, node.workSum)
b.root = node
}
} else {
// Case 3 -- The node doesn't have a parent and is not the parent
// of another node. This is only acceptable for the first node
// inserted into the chain. Otherwise it means an arbitrary
// orphan block is trying to be loaded which is not allowed.
if b.root != nil {
str := "loadBlockNode: attempt to insert orphan block %v"
return nil, fmt.Errorf(str, hash)
}
// Case 4 -- This is the root since it's the first and only node.
b.root = node
}
// 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.
func (b *BlockChain) findNode(nodeHash *chainhash.Hash) (*blockNode, error) {
var node *blockNode
// Most common case; we're checking a block that wants to be connected
// on top of the current main chain.
distance := 0
if nodeHash.IsEqual(b.bestChain.hash) {
node = b.bestChain
} else {
// Look backwards in our blockchain and try to find it in the
// parents of blocks.
foundPrev := b.bestChain
notFound := false
for !foundPrev.hash.IsEqual(b.chainParams.GenesisHash) {
if distance >= searchDepth {
notFound = true
break
}
if foundPrev.hash.IsEqual(b.chainParams.GenesisHash) {
notFound = true
break
}
if foundPrev.hash.IsEqual(nodeHash) {
break
}
foundPrev = foundPrev.parent
if foundPrev == nil {
parent, err := b.loadBlockNode(&foundPrev.header.PrevBlock)
if err != nil {
return nil, err
}
foundPrev = parent
}
distance++
}
if notFound {
return nil, fmt.Errorf("couldn't find node %v in best chain",
nodeHash)
}
node = foundPrev
}
return node, nil
}
// 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
// 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.
func (b *BlockChain) getPrevNodeFromBlock(block *dcrutil.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.
prevBlockNode, err := b.findNode(prevHash)
if err != nil {
return nil, err
}
return prevBlockNode, nil
}
// 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.
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.
prevBlockNode, err := b.findNode(node.parentHash)
if err != nil {
return nil, err
}
return prevBlockNode, nil
}
// GetNodeAtHeightFromTopNode goes backwards through a node until it a reaches
// the node with a desired block height; it returns this block. The benefit is
// this works for both the main chain and the side chain.
func (b *BlockChain) getNodeAtHeightFromTopNode(node *blockNode,
toTraverse int64) (*blockNode, error) {
oldNode := node
var err error
for i := 0; i < int(toTraverse); i++ {
// Get the previous block node.
oldNode, err = b.getPrevNodeFromNode(oldNode)
if err != nil {
return nil, err
}
if oldNode == nil {
return nil, fmt.Errorf("unable to obtain previous node; " +
"ancestor is genesis block")
}
}
return oldNode, nil
}
// getBlockFromHash searches the internal chain block stores and the database in
// an attempt to find the block. If it finds the block, it returns it.
func (b *BlockChain) getBlockFromHash(hash *chainhash.Hash) (*dcrutil.Block,
error) {
// Check block cache
b.blockCacheLock.RLock()
blockSidechain, existsSidechain := b.blockCache[*hash]
b.blockCacheLock.RUnlock()
if existsSidechain {
return blockSidechain, nil
}
// Check orphan cache
b.orphanLock.RLock()
orphan, existsOrphans := b.orphans[*hash]
b.orphanLock.RUnlock()
if existsOrphans {
return orphan.block, nil
}
// Check main chain
blockMainchain, errFetchMainchain := b.db.FetchBlockBySha(hash)
existsMainchain := (errFetchMainchain == nil) || (blockMainchain != nil)
if existsMainchain {
return blockMainchain, nil
}
// Implicit !existsMainchain && !existsSidechain && !existsOrphans
return nil, fmt.Errorf("unable to find block %v in "+
"side chain cache, orphan cache, and main chain db", hash)
}
// GetBlockFromHash is the generalized and exported version of getBlockFromHash.
func (b *BlockChain) GetBlockFromHash(hash *chainhash.Hash) (*dcrutil.Block,
error) {
return b.getBlockFromHash(hash)
}
// GetTopBlock returns the current block at HEAD on the blockchain. Needed
// for mining in the daemon.
func (b *BlockChain) GetTopBlock() (dcrutil.Block, error) {
block, err := b.getBlockFromHash(b.bestChain.hash)
return *block, err
}
// removeBlockNode removes the passed block node from the memory chain by
// unlinking all of its children and removing it from the the node and
// dependency indices.
func (b *BlockChain) removeBlockNode(node *blockNode) error {
if node.parent != nil {
return fmt.Errorf("removeBlockNode must be called with a "+
" node at the front of the chain - node %v", node.hash)
}
// Remove the node from the node index.
delete(b.index, *node.hash)
// Unlink all of the node's children.
for _, child := range node.children {
child.parent = nil
}
node.children = nil
// Remove the reference from the dependency index.
prevHash := node.parentHash
if children, ok := b.depNodes[*prevHash]; ok {
// Find the node amongst the children of the
// dependencies for the parent hash and remove it.
b.depNodes[*prevHash] = removeChildNode(children, node)
// Remove the map entry altogether if there are no
// longer any nodes which depend on the parent hash.
if len(b.depNodes[*prevHash]) == 0 {
delete(b.depNodes, *prevHash)
}
}
return nil
}
// pruneBlockNodes removes references to old block nodes which are no longer
// needed so they may be garbage collected. In order to validate block rules
// and choose the best chain, only a portion of the nodes which form the block
// chain are needed in memory. This function walks the chain backwards from the
// current best chain to find any nodes before the first needed block node.
func (b *BlockChain) pruneBlockNodes() error {
// Nothing to do if there is not a best chain selected yet.
if b.bestChain == nil {
return nil
}
// Walk the chain backwards to find what should be the new root node.
// Intentionally use node.parent instead of getPrevNodeFromNode since
// the latter loads the node and the goal is to find nodes still in
// memory that can be pruned.
newRootNode := b.bestChain
for i := int64(0); i < b.minMemoryNodes-1 && newRootNode != nil; i++ {
newRootNode = newRootNode.parent
}
// Nothing to do if there are not enough nodes.
if newRootNode == nil || newRootNode.parent == nil {
return nil
}
// 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 := newRootNode.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)
err := b.removeBlockNode(node)
if err != nil {
return err
}
}
// Set the new root node.
b.root = newRootNode
return nil
}
// GetCurrentBlockHeader returns the block header of the block at HEAD.
// This function is NOT safe for concurrent access.
func (b *BlockChain) GetCurrentBlockHeader() *wire.BlockHeader {
return &b.bestChain.header
}
// isMajorityVersion determines if a previous number of blocks in the chain
// starting with startNode are at least the minimum passed version.
func (b *BlockChain) isMajorityVersion(minVer int32, startNode *blockNode,
numRequired int32) bool {
numFound := int32(0)
iterNode := startNode
for i := int32(0); i < b.chainParams.CurrentBlockVersion &&
numFound < numRequired && iterNode != nil; i++ {
// This node has a version that is at least the minimum version.
if iterNode.version >= minVer {
numFound++
}
// 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 {
break
}
}
return numFound >= numRequired
}
// calcPastMedianTime calculates the median time of the previous few blocks
// prior to, and including, the passed block node. It is primarily used to
// validate new blocks have sane timestamps.
func (b *BlockChain) calcPastMedianTime(startNode *blockNode) (time.Time, error) {
// Genesis block.
if startNode == nil {
return b.chainParams.GenesisBlock.Header.Timestamp, nil
}
// Create a slice of the previous few block timestamps used to calculate
// the median per the number defined by the constant medianTimeBlocks.
timestamps := make([]time.Time, medianTimeBlocks)
numNodes := 0
iterNode := startNode
for i := 0; i < medianTimeBlocks && iterNode != nil; i++ {
timestamps[i] = iterNode.timestamp
numNodes++
// 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 time.Time{}, err
}
}
// Prune the slice to the actual number of available timestamps which
// will be fewer than desired near the beginning of the block chain
// and sort them.
timestamps = timestamps[:numNodes]
sort.Sort(timeSorter(timestamps))
// NOTE: bitcoind incorrectly calculates the median for even numbers of
// blocks. A true median averages the middle two elements for a set
// with an even number of elements in it. Since the constant for the
// previous number of blocks to be used is odd, this is only an issue
// for a few blocks near the beginning of the chain. I suspect this is
// an optimization even though the result is slightly wrong for a few
// of the first blocks since after the first few blocks, there will
// always be an odd number of blocks in the set per the constant.
//
// This code follows suit to ensure the same rules are used as bitcoind
// however, be aware that should the medianTimeBlocks constant ever be
// changed to an even number, this code will be wrong.
medianTimestamp := timestamps[numNodes/2]
return medianTimestamp, nil
}
// CalcPastMedianTime calculates the median time of the previous few blocks
// prior to, and including, the end of the current best chain. It is primarily
// used to ensure new blocks have sane timestamps.
//