forked from lightninglabs/neutrino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockmanager.go
1729 lines (1545 loc) · 54.7 KB
/
blockmanager.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
// NOTE: THIS API IS UNSTABLE RIGHT NOW AND WILL GO MOSTLY PRIVATE SOON.
package neutrino
import (
"container/list"
"fmt"
"math/big"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/lightninglabs/neutrino/headerfs"
)
const (
// minInFlightBlocks is the minimum number of blocks that should be
// in the request queue for headers-first mode before requesting
// more.
minInFlightBlocks = 10
// blockDbNamePrefix is the prefix for the block database name. The
// database type is appended to this value to form the full block
// database name.
blockDbNamePrefix = "blocks"
// maxRequestedBlocks is the maximum number of requested block
// hashes to store in memory.
maxRequestedBlocks = wire.MaxInvPerMsg
// maxTimeOffset is the maximum duration a block time is allowed to be
// ahead of the curent time. This is currently 2 hours.
maxTimeOffset = 2 * time.Hour
)
// TODO: Redo this using query API.
var (
// WaitForMoreCFHeaders is a configurable time to wait for CFHeaders
// messages from peers. It defaults to 3 seconds but can be increased
// for higher security and decreased for faster synchronization.
WaitForMoreCFHeaders = 3 * time.Second
// CFHMinPeers specifies the minimum number of peers to which we
// require to be connected before broadcasting a getcfheaders request.
// This is mostly for testing, but can be useful when being actively
// attacked by peers sending false information.
CFHMinPeers = 1
// CFHTimeBetweenPeerEnums specifies how long to wait between attempts
// to enumerate the peers to which the underlying chain service is
// connected.
CFHTimeBetweenPeerEnums = time.Millisecond * 200
)
// zeroHash is the zero value hash (all zeros). It is defined as a convenience.
var zeroHash chainhash.Hash
// newPeerMsg signifies a newly connected peer to the block handler.
type newPeerMsg struct {
peer *ServerPeer
}
// invMsg packages a bitcoin inv message and the peer it came from together
// so the block handler has access to that information.
type invMsg struct {
inv *wire.MsgInv
peer *ServerPeer
}
// headersMsg packages a bitcoin headers message and the peer it came from
// together so the block handler has access to that information.
type headersMsg struct {
headers *wire.MsgHeaders
peer *ServerPeer
}
// cfheadersMsg packages a bitcoin cfheaders message and the peer it came from
// together so the block handler has access to that information.
type cfheadersMsg struct {
cfheaders *wire.MsgCFHeaders
peer *ServerPeer
}
// cfheadersProcessedMsg tells the block manager to try to see if there are
// enough samples of cfheaders messages to process the committed filter header
// chain. This is kind of a hack until these get soft-forked in, but we do
// verification to avoid getting bamboozled by malicious nodes.
type processCFHeadersMsg struct {
earliestNode *headerNode
stopHash chainhash.Hash
filterType wire.FilterType
}
// donePeerMsg signifies a newly disconnected peer to the block handler.
type donePeerMsg struct {
peer *ServerPeer
}
// txMsg packages a bitcoin tx message and the peer it came from together
// so the block handler has access to that information.
type txMsg struct {
tx *btcutil.Tx
peer *ServerPeer
}
// isCurrentMsg is a message type to be sent across the message channel for
// requesting whether or not the block manager believes it is synced with
// the currently connected peers.
type isCurrentMsg struct {
reply chan bool
}
// headerNode is used as a node in a list of headers that are linked together
// between checkpoints.
type headerNode struct {
height int32
header *wire.BlockHeader
}
// blockManager provides a concurrency safe block manager for handling all
// incoming blocks.
type blockManager struct {
server *ChainService
started int32
shutdown int32
requestedBlocks map[chainhash.Hash]struct{}
progressLogger *blockProgressLogger
syncPeer *ServerPeer
syncPeerMutex sync.Mutex
// peerChan is a channel for messages that come from peers
peerChan chan interface{}
// intChan is a channel for messages that come from internal commands
intChan chan interface{}
wg sync.WaitGroup
quit chan struct{}
headerList *list.List
reorgList *list.List
startHeader *list.Element
nextCheckpoint *chaincfg.Checkpoint
lastRequested chainhash.Hash
basicHeaders map[chainhash.Hash]map[chainhash.Hash][]*ServerPeer
lastBasicCFHeaderHeight int32
numBasicCFHeadersMsgs int32
extendedHeaders map[chainhash.Hash]map[chainhash.Hash][]*ServerPeer
lastExtCFHeaderHeight int32
numExtCFHeadersMsgs int32
mapMutex sync.Mutex
minRetargetTimespan int64 // target timespan / adjustment factor
maxRetargetTimespan int64 // target timespan * adjustment factor
blocksPerRetarget int32 // target timespan / target time per block
}
// newBlockManager returns a new bitcoin block manager. Use Start to begin
// processing asynchronous block and inv updates.
func newBlockManager(s *ChainService) (*blockManager, error) {
targetTimespan := int64(s.chainParams.TargetTimespan / time.Second)
targetTimePerBlock := int64(s.chainParams.TargetTimePerBlock / time.Second)
adjustmentFactor := s.chainParams.RetargetAdjustmentFactor
bm := blockManager{
server: s,
requestedBlocks: make(map[chainhash.Hash]struct{}),
peerChan: make(chan interface{}, MaxPeers*3),
progressLogger: newBlockProgressLogger("Processed", log),
intChan: make(chan interface{}, 1),
headerList: list.New(),
reorgList: list.New(),
quit: make(chan struct{}),
blocksPerRetarget: int32(targetTimespan / targetTimePerBlock),
minRetargetTimespan: targetTimespan / adjustmentFactor,
maxRetargetTimespan: targetTimespan * adjustmentFactor,
basicHeaders: make(
map[chainhash.Hash]map[chainhash.Hash][]*ServerPeer,
),
extendedHeaders: make(
map[chainhash.Hash]map[chainhash.Hash][]*ServerPeer,
),
}
// Initialize the next checkpoint based on the current height.
header, height, err := s.BlockHeaders.ChainTip()
if err != nil {
return nil, err
}
bm.nextCheckpoint = bm.findNextHeaderCheckpoint(int32(height))
bm.resetHeaderState(header, int32(height))
return &bm, nil
}
// Start begins the core block handler which processes block and inv messages.
func (b *blockManager) Start() {
// Already started?
if atomic.AddInt32(&b.started, 1) != 1 {
return
}
log.Trace("Starting block manager")
b.wg.Add(1)
go b.blockHandler()
}
// Stop gracefully shuts down the block manager by stopping all asynchronous
// handlers and waiting for them to finish.
func (b *blockManager) Stop() error {
if atomic.AddInt32(&b.shutdown, 1) != 1 {
log.Warnf("Block manager is already in the process of " +
"shutting down")
return nil
}
log.Infof("Block manager shutting down")
close(b.quit)
b.wg.Wait()
return nil
}
// NewPeer informs the block manager of a newly active peer.
func (b *blockManager) NewPeer(sp *ServerPeer) {
// Ignore if we are shutting down.
if atomic.LoadInt32(&b.shutdown) != 0 {
return
}
b.peerChan <- &newPeerMsg{peer: sp}
}
// handleNewPeerMsg deals with new peers that have signalled they may be
// considered as a sync peer (they have already successfully negotiated). It
// also starts syncing if needed. It is invoked from the syncHandler
// goroutine.
func (b *blockManager) handleNewPeerMsg(peers *list.List, sp *ServerPeer) {
// Ignore if in the process of shutting down.
if atomic.LoadInt32(&b.shutdown) != 0 {
return
}
log.Infof("New valid peer %s (%s)", sp, sp.UserAgent())
// Ignore the peer if it's not a sync candidate.
if !b.isSyncCandidate(sp) {
return
}
// Add the peer as a candidate to sync from.
peers.PushBack(sp)
// If we're current with our sync peer and the new peer is advertising
// a higher block than the newest one we know of, request headers from
// the new peer.
_, height, err := b.server.BlockHeaders.ChainTip()
if err != nil {
log.Criticalf("Couldn't retrieve block header chain tip: %s",
err)
return
}
if b.current() && height < uint32(sp.StartingHeight()) {
locator, err := b.server.BlockHeaders.LatestBlockLocator()
if err != nil {
log.Criticalf("Couldn't retrieve latest block "+
"locator: %s", err)
return
}
stopHash := &chainhash.Hash{}
sp.PushGetHeadersMsg(locator, stopHash)
}
// Start syncing by choosing the best candidate if needed.
b.startSync(peers)
}
// DonePeer informs the blockmanager that a peer has disconnected.
func (b *blockManager) DonePeer(sp *ServerPeer) {
// Ignore if we are shutting down.
if atomic.LoadInt32(&b.shutdown) != 0 {
return
}
b.peerChan <- &donePeerMsg{peer: sp}
}
// handleDonePeerMsg deals with peers that have signalled they are done. It
// removes the peer as a candidate for syncing and in the case where it was the
// current sync peer, attempts to select a new best peer to sync from. It is
// invoked from the syncHandler goroutine.
func (b *blockManager) handleDonePeerMsg(peers *list.List, sp *ServerPeer) {
// Remove the peer from the list of candidate peers.
for e := peers.Front(); e != nil; e = e.Next() {
if e.Value == sp {
peers.Remove(e)
break
}
}
log.Infof("Lost peer %s", sp)
// Attempt to find a new peer to sync from if the quitting peer is the
// sync peer. Also, reset the header state.
if b.syncPeer != nil && b.syncPeer == sp {
b.syncPeerMutex.Lock()
b.syncPeer = nil
b.syncPeerMutex.Unlock()
header, height, err := b.server.BlockHeaders.ChainTip()
if err != nil {
return
}
b.resetHeaderState(header, int32(height))
b.startSync(peers)
}
}
// blockHandler is the main handler for the block manager. It must be run as a
// goroutine. It processes block and inv messages in a separate goroutine from
// the peer handlers so the block (MsgBlock) messages are handled by a single
// thread without needing to lock memory data structures. This is important
// because the block manager controls which blocks are needed and how
// the fetching should proceed.
func (b *blockManager) blockHandler() {
candidatePeers := list.New()
out:
for {
// Check internal messages channel first and continue if
// there's nothing to process.
select {
case m := <-b.intChan:
switch msg := m.(type) {
case *processCFHeadersMsg:
b.handleProcessCFHeadersMsg(msg)
default:
log.Warnf("Invalid message type in block "+
"handler: %T", msg)
}
default:
}
// Now check peer messages and quit channels.
select {
case m := <-b.peerChan:
switch msg := m.(type) {
case *newPeerMsg:
b.handleNewPeerMsg(candidatePeers, msg.peer)
case *invMsg:
b.handleInvMsg(msg)
case *headersMsg:
b.handleHeadersMsg(msg)
case *cfheadersMsg:
b.handleCFHeadersMsg(msg)
case *donePeerMsg:
b.handleDonePeerMsg(candidatePeers, msg.peer)
case isCurrentMsg:
msg.reply <- b.current()
default:
log.Warnf("Invalid message type in block "+
"handler: %T", msg)
}
case <-b.quit:
break out
}
}
b.wg.Done()
log.Trace("Block handler done")
}
// SyncPeer returns the current sync peer.
func (b *blockManager) SyncPeer() *ServerPeer {
b.syncPeerMutex.Lock()
defer b.syncPeerMutex.Unlock()
return b.syncPeer
}
// isSyncCandidate returns whether or not the peer is a candidate to consider
// syncing from.
func (b *blockManager) isSyncCandidate(sp *ServerPeer) bool {
// The peer is not a candidate for sync if it's not a full node.
return sp.Services()&wire.SFNodeNetwork == wire.SFNodeNetwork
}
// findNextHeaderCheckpoint returns the next checkpoint after the passed height.
// It returns nil when there is not one either because the height is already
// later than the final checkpoint or there are none for the current network.
func (b *blockManager) findNextHeaderCheckpoint(height int32) *chaincfg.Checkpoint {
// There is no next checkpoint if there are none for this current
// network.
checkpoints := b.server.chainParams.Checkpoints
if len(checkpoints) == 0 {
return nil
}
// There is no next checkpoint if the height is already after the final
// checkpoint.
finalCheckpoint := &checkpoints[len(checkpoints)-1]
if height >= finalCheckpoint.Height {
return nil
}
// Find the next checkpoint.
nextCheckpoint := finalCheckpoint
for i := len(checkpoints) - 2; i >= 0; i-- {
if height >= checkpoints[i].Height {
break
}
nextCheckpoint = &checkpoints[i]
}
return nextCheckpoint
}
// findPreviousHeaderCheckpoint returns the last checkpoint before the passed
// height. It returns a checkpoint matching the genesis block when the height
// is earlier than the first checkpoint or there are no checkpoints for the
// current network. This is used for resetting state when a malicious peer sends
// us headers that don't lead up to a known checkpoint.
func (b *blockManager) findPreviousHeaderCheckpoint(height int32) *chaincfg.Checkpoint {
// Start with the genesis block - earliest checkpoint to which our
// code will want to reset
prevCheckpoint := &chaincfg.Checkpoint{
Height: 0,
Hash: b.server.chainParams.GenesisHash,
}
// Find the latest checkpoint lower than height or return genesis block
// if there are none.
checkpoints := b.server.chainParams.Checkpoints
for i := 0; i < len(checkpoints); i++ {
if height <= checkpoints[i].Height {
break
}
prevCheckpoint = &checkpoints[i]
}
return prevCheckpoint
}
// resetHeaderState sets the headers-first mode state to values appropriate for
// syncing from a new peer.
func (b *blockManager) resetHeaderState(newestHeader *wire.BlockHeader,
newestHeight int32) {
b.headerList.Init()
b.startHeader = nil
b.mapMutex.Lock()
b.basicHeaders = make(
map[chainhash.Hash]map[chainhash.Hash][]*ServerPeer,
)
b.extendedHeaders = make(
map[chainhash.Hash]map[chainhash.Hash][]*ServerPeer,
)
b.mapMutex.Unlock()
// Add an entry for the latest known block into the header pool.
// This allows the next downloaded header to prove it links to the chain
// properly.
node := headerNode{header: newestHeader, height: newestHeight}
b.headerList.PushBack(&node)
b.mapMutex.Lock()
b.basicHeaders[newestHeader.BlockHash()] = make(
map[chainhash.Hash][]*ServerPeer,
)
b.extendedHeaders[newestHeader.BlockHash()] = make(
map[chainhash.Hash][]*ServerPeer,
)
b.mapMutex.Unlock()
}
// startSync will choose the best peer among the available candidate peers to
// download/sync the blockchain from. When syncing is already running, it
// simply returns. It also examines the candidates for any which are no longer
// candidates and removes them as needed.
func (b *blockManager) startSync(peers *list.List) {
// Return now if we're already syncing.
if b.syncPeer != nil {
return
}
best, err := b.server.BestSnapshot()
if err != nil {
log.Errorf("Failed to get hash and height for the "+
"latest block: %s", err)
return
}
// Get the latest cfheaders committed to storage to make sure that they
// are caught up to the best known block header. If not, the first thing
// we have to do is catch them up. If there was a reorg in the meantime,
// this won't work past the height of the common block between the known
// and the new correct chain but the reorg code will re-request the
// cfheaders after the block headers get reorganized. This does make
// the assumption that the difference between the filter header tips and
// the block header tip is 2000 or fewer blocks. This is a good
// assumption based on how we request headers; however, should be
// improved when the blockmanager code is refactored to use the query
// API.
_, bestRegHeight, err := b.server.RegFilterHeaders.ChainTip()
if err != nil {
log.Errorf("Failed to get height for the latest regular "+
"filter header: %s", err)
return
}
_, bestExtHeight, err := b.server.ExtFilterHeaders.ChainTip()
if err != nil {
log.Errorf("Failed to get height for the latest extended "+
"filter header: %s", err)
return
}
// We fill the header list all the way back to the first header with
// unknown cfheaders.
minHeight := bestRegHeight
if bestExtHeight < minHeight {
minHeight = bestExtHeight
}
maxminHeight := bestRegHeight
if bestExtHeight > maxminHeight {
maxminHeight = bestExtHeight
}
maxHeight := b.headerList.Front().Value.(*headerNode).height
for height := maxHeight - 1; height >= int32(minHeight); height-- {
header, err := b.server.BlockHeaders.FetchHeaderByHeight(uint32(height))
if err != nil {
log.Errorf("Failed to get block header for height %d: "+
"%s", height, err)
}
b.mapMutex.Lock()
b.basicHeaders[header.BlockHash()] = make(
map[chainhash.Hash][]*ServerPeer,
)
b.extendedHeaders[header.BlockHash()] = make(
map[chainhash.Hash][]*ServerPeer,
)
b.mapMutex.Unlock()
node := headerNode{header: header, height: height}
b.headerList.PushFront(&node)
}
if bestRegHeight < uint32(best.Height) {
log.Infof("Catching up regular filter headers from %d to %d",
bestRegHeight, best.Height)
}
if bestExtHeight < uint32(best.Height) {
log.Infof("Catching up extended filter headers from %d to %d",
bestExtHeight, best.Height)
}
for i := minHeight; i < maxminHeight; {
endHeight := i
fType := wire.GCSFilterRegular
if endHeight < bestRegHeight {
// We're catching extended headers up to regular headers
// so we set the header type to extended.
fType = wire.GCSFilterExtended
if endHeight+wire.MaxCFHeadersPerMsg > bestRegHeight {
endHeight = bestRegHeight
} else {
endHeight += wire.MaxCFHeadersPerMsg
}
}
if endHeight < bestExtHeight {
// We're catching regular headers up to extended headers
// so we set the header type to regular.
fType = wire.GCSFilterRegular
if endHeight+wire.MaxCFHeadersPerMsg > bestRegHeight {
endHeight = bestExtHeight
} else {
endHeight += wire.MaxCFHeadersPerMsg
}
}
if endHeight > uint32(best.Height) {
endHeight = uint32(best.Height)
}
endHeader, err := b.server.BlockHeaders.
FetchHeaderByHeight(endHeight)
if err != nil {
log.Errorf("Failed to get block header for height %d: "+
"%s", endHeight, err)
break
}
endHash := endHeader.BlockHash()
b.sendGetcfheaders(i+1, &endHash, int(endHeight-i), fType)
i = endHeight
}
for i := maxminHeight; i < uint32(best.Height); {
endHeight := i + wire.MaxCFHeadersPerMsg
if endHeight > uint32(best.Height) {
endHeight = uint32(best.Height)
}
endHeader, err := b.server.BlockHeaders.
FetchHeaderByHeight(endHeight)
if err != nil {
log.Errorf("Failed to get block header for height %d: "+
"%s", endHeight, err)
break
}
endHash := endHeader.BlockHash()
b.sendGetcfheaders(i+1, &endHash, int(endHeight-i),
wire.GCSFilterRegular)
b.sendGetcfheaders(i+1, &endHash, int(endHeight-i),
wire.GCSFilterExtended)
i = endHeight
}
var bestPeer *ServerPeer
var enext *list.Element
for e := peers.Front(); e != nil; e = enext {
enext = e.Next()
sp := e.Value.(*ServerPeer)
// Remove sync candidate peers that are no longer candidates
// due to passing their latest known block.
//
// NOTE: The < is intentional as opposed to <=. While
// techcnically the peer doesn't have a later block when it's
// equal, it will likely have one soon so it is a reasonable
// choice. It also allows the case where both are at 0 such as
// during regression test.
if sp.LastBlock() < best.Height {
peers.Remove(e)
continue
}
// TODO: Use a better algorithm to choose the best peer.
// For now, just pick the candidate with the highest last block.
if bestPeer == nil || sp.LastBlock() > bestPeer.LastBlock() {
bestPeer = sp
}
}
// Start syncing from the best peer if one was selected.
if bestPeer != nil {
// Clear the requestedBlocks if the sync peer changes,
// otherwise we may ignore blocks we need that the last sync
// peer failed to send.
b.requestedBlocks = make(map[chainhash.Hash]struct{})
locator, err := b.server.BlockHeaders.LatestBlockLocator()
if err != nil {
log.Errorf("Failed to get block locator for the "+
"latest block: %s", err)
return
}
log.Infof("Syncing to block height %d from peer %s",
bestPeer.LastBlock(), bestPeer.Addr())
// When the current height is less than a known checkpoint we
// can use block headers to learn about which blocks comprise
// the chain up to the checkpoint and perform less validation
// for them. This is possible since each header contains the
// hash of the previous header and a merkle root. Therefore if
// we validate all of the received headers link together
// properly and the checkpoint hashes match, we can be sure the
// hashes for the blocks in between are accurate. Further,
// once the full blocks are downloaded, the merkle root is
// computed and compared against the value in the header which
// proves the full block hasn't been tampered with.
//
// Once we have passed the final checkpoint, or checkpoints are
// disabled, use standard inv messages learn about the blocks
// and fully validate them. Finally, regression test mode does
// not support the headers-first approach so do normal block
// downloads when in regression test mode.
b.syncPeerMutex.Lock()
b.syncPeer = bestPeer
b.syncPeerMutex.Unlock()
if b.nextCheckpoint != nil && best.Height < b.nextCheckpoint.Height {
b.syncPeer.PushGetHeadersMsg(locator, b.nextCheckpoint.Hash)
log.Infof("Downloading headers for blocks %d to "+
"%d from peer %s", best.Height+1,
b.nextCheckpoint.Height, bestPeer.Addr())
// This will get adjusted when we process headers if we
// request more headers than the peer is willing to
// give us in one message.
} else {
b.syncPeer.PushGetBlocksMsg(locator, &zeroHash)
}
} else {
log.Warnf("No sync peer candidates available")
}
}
// current returns true if we believe we are synced with our peers, false if we
// still have blocks to check
func (b *blockManager) current() bool {
// Figure out the latest block we know.
header, height, err := b.server.BlockHeaders.ChainTip()
if err != nil {
return false
}
// There is no last checkpoint if checkpoints are disabled or there are
// none for this current network.
checkpoints := b.server.chainParams.Checkpoints
if len(checkpoints) != 0 {
// We aren't current if the newest block we know of isn't ahead
// of all checkpoints.
if checkpoints[len(checkpoints)-1].Height >= int32(height) {
return false
}
}
// If we have a syncPeer and are below the block we are syncing to, we
// are not current.
if b.syncPeer != nil && int32(height) < b.syncPeer.LastBlock() {
return false
}
// If our time source (median times of all the connected peers) is at
// least 24 hours ahead of our best known block, we aren't current.
minus24Hours := b.server.timeSource.AdjustedTime().Add(-24 * time.Hour)
if header.Timestamp.Before(minus24Hours) {
return false
}
// If we have no sync peer, we can assume we're current for now.
if b.syncPeer == nil {
return true
}
// If we have a syncPeer and the peer reported a higher known block
// height on connect than we know the peer already has, we're probably
// not current. If the peer is lying to us, other code will disconnect
// it and then we'll re-check and notice that we're actually current.
return b.SyncPeer().LastBlock() >= b.SyncPeer().StartingHeight()
}
// IsCurrent returns whether or not the block manager believes it is synced with
// the connected peers.
//
// TODO(roasbeef): hook into WC implementation
func (b *blockManager) IsCurrent() bool {
reply := make(chan bool)
b.peerChan <- isCurrentMsg{reply: reply}
return <-reply
}
// QueueInv adds the passed inv message and peer to the block handling queue.
func (b *blockManager) QueueInv(inv *wire.MsgInv, sp *ServerPeer) {
// No channel handling here because peers do not need to block on inv
// messages.
if atomic.LoadInt32(&b.shutdown) != 0 {
return
}
b.peerChan <- &invMsg{inv: inv, peer: sp}
}
// handleInvMsg handles inv messages from all peers.
// We examine the inventory advertised by the remote peer and act accordingly.
func (b *blockManager) handleInvMsg(imsg *invMsg) {
// Attempt to find the final block in the inventory list. There may
// not be one.
lastBlock := -1
invVects := imsg.inv.InvList
for i := len(invVects) - 1; i >= 0; i-- {
if invVects[i].Type == wire.InvTypeBlock {
lastBlock = i
break
}
}
// If this inv contains a block announcement, and this isn't coming from
// our current sync peer or we're current, then update the last
// announced block for this peer. We'll use this information later to
// update the heights of peers based on blocks we've accepted that they
// previously announced.
if lastBlock != -1 && (imsg.peer != b.syncPeer || b.current()) {
imsg.peer.UpdateLastAnnouncedBlock(&invVects[lastBlock].Hash)
}
// Ignore invs from peers that aren't the sync if we are not current.
// Helps prevent dealing with orphans.
if imsg.peer != b.syncPeer && !b.current() {
return
}
// If our chain is current and a peer announces a block we already
// know of, then update their current block height.
if lastBlock != -1 && b.current() {
height, err := b.server.BlockHeaders.HeightFromHash(&invVects[lastBlock].Hash)
if err == nil {
imsg.peer.UpdateLastBlockHeight(int32(height))
}
}
// Add blocks to the cache of known inventory for the peer.
for _, iv := range invVects {
if iv.Type == wire.InvTypeBlock {
imsg.peer.AddKnownInventory(iv)
}
}
// If this is the sync peer or we're current, get the headers for the
// announced blocks and update the last announced block.
if lastBlock != -1 && (imsg.peer == b.syncPeer || b.current()) {
lastEl := b.headerList.Back()
var lastHash chainhash.Hash
if lastEl != nil {
lastHash = lastEl.Value.(*headerNode).header.BlockHash()
}
// Only send getheaders if we don't already know about the last
// block hash being announced.
if lastHash != invVects[lastBlock].Hash && lastEl != nil &&
b.lastRequested != invVects[lastBlock].Hash {
// Make a locator starting from the latest known header
// we've processed.
locator := make(blockchain.BlockLocator, 0,
wire.MaxBlockLocatorsPerMsg)
locator = append(locator, &lastHash)
// Add locator from the database as backup.
knownLocator, err := b.server.BlockHeaders.LatestBlockLocator()
if err == nil {
locator = append(locator, knownLocator...)
}
// Get headers based on locator.
err = imsg.peer.PushGetHeadersMsg(locator,
&invVects[lastBlock].Hash)
if err != nil {
log.Warnf("Failed to send getheaders message "+
"to peer %s: %s", imsg.peer.Addr(), err)
return
}
b.lastRequested = invVects[lastBlock].Hash
}
}
}
// QueueHeaders adds the passed headers message and peer to the block handling
// queue.
func (b *blockManager) QueueHeaders(headers *wire.MsgHeaders, sp *ServerPeer) {
// No channel handling here because peers do not need to block on
// headers messages.
if atomic.LoadInt32(&b.shutdown) != 0 {
return
}
b.peerChan <- &headersMsg{headers: headers, peer: sp}
}
// handleHeadersMsg handles headers messages from all peers.
func (b *blockManager) handleHeadersMsg(hmsg *headersMsg) {
msg := hmsg.headers
numHeaders := len(msg.Headers)
// Nothing to do for an empty headers message.
if numHeaders == 0 {
return
}
// For checking to make sure blocks aren't too far in the future as of
// the time we receive the headers message.
maxTimestamp := b.server.timeSource.AdjustedTime().
Add(maxTimeOffset)
// We'll attempt to write the entire batch of validated headers
// atomically in order to improve peformance.
headerWriteBatch := make([]headerfs.BlockHeader, 0, len(msg.Headers))
// Process all of the received headers ensuring each one connects to
// the previous and that checkpoints match.
receivedCheckpoint := false
var finalHash *chainhash.Hash
var finalHeight int32
for i, blockHeader := range msg.Headers {
blockHash := blockHeader.BlockHash()
finalHash = &blockHash
// Ensure there is a previous header to compare against.
prevNodeEl := b.headerList.Back()
if prevNodeEl == nil {
log.Warnf("Header list does not contain a previous" +
"element as expected -- disconnecting peer")
hmsg.peer.Disconnect()
return
}
// Ensure the header properly connects to the previous one,
// that the proof of work is good, and that the header's
// timestamp isn't too far in the future, and add it to the
// list of headers.
node := headerNode{header: blockHeader}
prevNode := prevNodeEl.Value.(*headerNode)
prevHash := prevNode.header.BlockHash()
if prevHash.IsEqual(&blockHeader.PrevBlock) {
err := b.checkHeaderSanity(blockHeader, maxTimestamp,
false)
if err != nil {
log.Warnf("Header doesn't pass sanity check: "+
"%s -- disconnecting peer", err)
hmsg.peer.Disconnect()
return
}
node.height = prevNode.height + 1
finalHeight = node.height
// This header checks out, so we'll add it to our write
// batch.
headerWriteBatch = append(headerWriteBatch, headerfs.BlockHeader{
BlockHeader: blockHeader,
Height: uint32(node.height),
})
hmsg.peer.UpdateLastBlockHeight(node.height)
b.progressLogger.LogBlockHeight(blockHeader, node.height)
// Finally initialize the header ->
// map[filterHash]*peer map for filter header
// validation purposes later.
e := b.headerList.PushBack(&node)
b.mapMutex.Lock()
b.basicHeaders[node.header.BlockHash()] = make(
map[chainhash.Hash][]*ServerPeer,
)
b.extendedHeaders[node.header.BlockHash()] = make(
map[chainhash.Hash][]*ServerPeer,
)
b.mapMutex.Unlock()
if b.startHeader == nil {
b.startHeader = e
}
} else {
// The block doesn't connect to the last block we know.
// We will need to do some additional checks to process
// possible reorganizations or incorrect chain on
// either our or the peer's side.
//
// If we got these headers from a peer that's not our
// sync peer, they might not be aligned correctly or
// even on the right chain. Just ignore the rest of the
// message. However, if we're current, this might be a
// reorg, in which case we'll either change our sync
// peer or disconnect the peer that sent us these bad
// headers.
if hmsg.peer != b.syncPeer && !b.current() {
return
}
// Check if this is the last block we know of. This is
// a shortcut for sendheaders so that each redundant
// header doesn't cause a disk read.
if blockHash == prevHash {
continue
}
// Check if this block is known. If so, we continue to
// the next one.
_, _, err := b.server.BlockHeaders.FetchHeader(&blockHash)
if err == nil {
continue
}
// Check if the previous block is known. If it is, this
// is probably a reorg based on the estimated latest
// block that matches between us and the peer as
// derived from the block locator we sent to request
// these headers. Otherwise, the headers don't connect
// to anything we know and we should disconnect the
// peer.
backHead, backHeight, err := b.server.BlockHeaders.FetchHeader(
&blockHeader.PrevBlock,
)
if err != nil {
log.Warnf("Received block header that does not"+
" properly connect to the chain from"+
" peer %s (%s) -- disconnecting",
hmsg.peer.Addr(), err)
hmsg.peer.Disconnect()
return
}
// We've found a branch we weren't aware of. If the
// branch is earlier than the latest synchronized
// checkpoint, it's invalid and we need to disconnect
// the reporting peer.
prevCheckpoint := b.findPreviousHeaderCheckpoint(
prevNode.height)
if backHeight < uint32(prevCheckpoint.Height) {
log.Errorf("Attempt at a reorg earlier than a "+
"checkpoint past which we've already "+
"synchronized -- disconnecting peer "+
"%s", hmsg.peer.Addr())
hmsg.peer.Disconnect()