-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.go
1226 lines (1083 loc) · 30.8 KB
/
sync.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) 2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package spv
import (
"context"
"net"
"runtime"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/fistchain/fistd/addrmgr"
"github.com/fistchain/fistd/chaincfg/chainhash"
"github.com/fistchain/fistd/gcs/blockcf"
"github.com/fistchain/fistd/wire"
"github.com/fistchain/fistwallet/errors"
"github.com/fistchain/fistwallet/lru"
"github.com/fistchain/fistwallet/p2p"
"github.com/fistchain/fistwallet/validate"
"github.com/fistchain/fistwallet/wallet"
"golang.org/x/sync/errgroup"
)
// reqSvcs defines the services that must be supported by outbounded peers.
// After fetching more addresses (if needed), peers are disconnected from if
// they do not provide each of these services.
const reqSvcs = wire.SFNodeNetwork | wire.SFNodeCF
// Syncer implements wallet synchronization services by over the Decred wire
// protocol using Simplified Payment Verification (SPV) with compact filters.
type Syncer struct {
// atomics
atomicCatchUpTryLock uint32 // CAS (entered=1) to perform discovery/rescan
atomicWalletSynced uint32 // CAS (synced=1) when wallet syncing complete
wallet *wallet.Wallet
lp *p2p.LocalPeer
// Protected by atomicCatchUpTryLock
discoverAccounts bool
loadedFilters bool
persistantPeers []string
connectingRemotes map[string]struct{}
remotes map[string]*p2p.RemotePeer
remotesMu sync.Mutex
// Data filters
//
// TODO: Replace precise rescan filter with wallet db accesses to avoid
// needing to keep all relevant data in memory.
rescanFilter *wallet.RescanFilter
filterData blockcf.Entries
filterMu sync.Mutex
// seenTxs records hashes of received inventoried transactions. Once a
// transaction is fetched and processed from one peer, the hash is added to
// this cache to avoid fetching it again from other peers that announce the
// transaction.
seenTxs lru.Cache
// Sidechain management
sidechains wallet.SidechainForest
sidechainMu sync.Mutex
currentLocators []*chainhash.Hash
locatorGeneration uint
locatorMu sync.Mutex
// Holds all potential callbacks used to notify clients
notifications *Notifications
}
// Notifications struct to contain all of the upcoming callbacks that will
// be used to update the rpc streams for syncing.
type Notifications struct {
Synced func(sync bool)
PeerConnected func(peerCount int32, addr string)
PeerDisconnected func(peerCount int32, addr string)
FetchMissingCFiltersStarted func()
FetchMissingCFiltersProgress func(startCFiltersHeight, endCFiltersHeight int32)
FetchMissingCFiltersFinished func()
FetchHeadersStarted func()
FetchHeadersProgress func(lastHeaderHeight int32, lastHeaderTime int64)
FetchHeadersFinished func()
DiscoverAddressesStarted func()
DiscoverAddressesFinished func()
RescanStarted func()
RescanProgress func(rescannedThrough int32)
RescanFinished func()
}
// NewSyncer creates a Syncer that will sync the wallet using SPV.
func NewSyncer(w *wallet.Wallet, lp *p2p.LocalPeer) *Syncer {
return &Syncer{
wallet: w,
discoverAccounts: !w.Locked(),
connectingRemotes: make(map[string]struct{}),
remotes: make(map[string]*p2p.RemotePeer),
rescanFilter: wallet.NewRescanFilter(nil, nil),
seenTxs: lru.NewCache(2000),
lp: lp,
}
}
// SetPersistantPeers sets each peer as a persistant peer and disables DNS
// seeding and peer discovery.
func (s *Syncer) SetPersistantPeers(peers []string) {
s.persistantPeers = peers
}
// SetNotifications sets the possible various callbacks that are used
// to notify interested parties to the syncing progress.
func (s *Syncer) SetNotifications(ntfns *Notifications) {
s.notifications = ntfns
}
// synced checks the atomic that controls wallet syncness and if previously
// unsynced, updates to synced and notifies the callback, if set.
func (s *Syncer) synced() {
if atomic.CompareAndSwapUint32(&s.atomicWalletSynced, 0, 1) &&
s.notifications != nil &&
s.notifications.Synced != nil {
s.notifications.Synced(true)
}
}
// unsynced checks the atomic that controls wallet syncness and if previously
// synced, updates to unsynced and notifies the callback, if set.
func (s *Syncer) unsynced() {
if atomic.CompareAndSwapUint32(&s.atomicWalletSynced, 1, 0) &&
s.notifications != nil &&
s.notifications.Synced != nil {
s.notifications.Synced(false)
}
}
// peerConnected updates the notification for peer count, if set.
func (s *Syncer) peerConnected(remotesCount int, addr string) {
if s.notifications != nil && s.notifications.PeerConnected != nil {
s.notifications.PeerConnected(int32(remotesCount), addr)
}
}
// peerDisconnected updates the notification for peer count, if set.
func (s *Syncer) peerDisconnected(remotesCount int, addr string) {
if s.notifications != nil && s.notifications.PeerDisconnected != nil {
s.notifications.PeerDisconnected(int32(remotesCount), addr)
}
}
func (s *Syncer) fetchMissingCfiltersStart() {
if s.notifications != nil && s.notifications.FetchMissingCFiltersStarted != nil {
s.notifications.FetchMissingCFiltersStarted()
}
}
func (s *Syncer) fetchMissingCfiltersProgress(startMissingCFilterHeight, endMissinCFilterHeight int32) {
if s.notifications != nil && s.notifications.FetchMissingCFiltersProgress != nil {
s.notifications.FetchMissingCFiltersProgress(startMissingCFilterHeight, endMissinCFilterHeight)
}
}
func (s *Syncer) fetchMissingCfiltersFinished() {
if s.notifications != nil && s.notifications.FetchMissingCFiltersFinished != nil {
s.notifications.FetchMissingCFiltersFinished()
}
}
func (s *Syncer) fetchHeadersStart() {
if s.notifications != nil && s.notifications.FetchHeadersStarted != nil {
s.notifications.FetchHeadersStarted()
}
}
func (s *Syncer) fetchHeadersProgress(fetchedHeadersCount int32, lastHeaderTime int64) {
if s.notifications != nil && s.notifications.FetchHeadersProgress != nil {
s.notifications.FetchHeadersProgress(fetchedHeadersCount, lastHeaderTime)
}
}
func (s *Syncer) fetchHeadersFinished() {
if s.notifications != nil && s.notifications.FetchHeadersFinished != nil {
s.notifications.FetchHeadersFinished()
}
}
func (s *Syncer) discoverAddressesStart() {
if s.notifications != nil && s.notifications.DiscoverAddressesStarted != nil {
s.notifications.DiscoverAddressesStarted()
}
}
func (s *Syncer) discoverAddressesFinished() {
if s.notifications != nil && s.notifications.DiscoverAddressesFinished != nil {
s.notifications.DiscoverAddressesFinished()
}
}
func (s *Syncer) rescanStart() {
if s.notifications != nil && s.notifications.RescanStarted != nil {
s.notifications.RescanStarted()
}
}
func (s *Syncer) rescanProgress(rescannedThrough int32) {
if s.notifications != nil && s.notifications.RescanProgress != nil {
s.notifications.RescanProgress(rescannedThrough)
}
}
func (s *Syncer) rescanFinished() {
if s.notifications != nil && s.notifications.RescanFinished != nil {
s.notifications.RescanFinished()
}
}
// Run synchronizes the wallet, returning when synchronization fails or the
// context is cancelled.
func (s *Syncer) Run(ctx context.Context) error {
tipHash, tipHeight := s.wallet.MainChainTip()
rescanPoint, err := s.wallet.RescanPoint()
if err != nil {
return err
}
log.Infof("Headers synced through block %v height %d", &tipHash, tipHeight)
if rescanPoint != nil {
h, err := s.wallet.BlockHeader(rescanPoint)
if err != nil {
return err
}
// The rescan point is the first block that does not have synced
// transactions, so we are synced with the parent.
log.Infof("Transactions synced through block %v height %d", &h.PrevBlock, h.Height-1)
} else {
log.Infof("Transactions synced through block %v height %d", &tipHash, tipHeight)
}
locators, err := s.wallet.BlockLocators(nil)
if err != nil {
return err
}
s.currentLocators = locators
s.lp.AddrManager().Start()
defer func() {
err := s.lp.AddrManager().Stop()
if err != nil {
log.Errorf("Failed to cleanly stop address manager: %v", err)
}
}()
// Seed peers over DNS when not disabled by persistant peers.
if len(s.persistantPeers) == 0 {
s.lp.DNSSeed(wire.SFNodeNetwork | wire.SFNodeCF)
}
// Start background handlers to read received messages from remote peers
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return s.receiveGetData(ctx) })
g.Go(func() error { return s.receiveInv(ctx) })
g.Go(func() error { return s.receiveHeadersAnnouncements(ctx) })
s.lp.AddHandledMessages(p2p.MaskGetData | p2p.MaskInv)
if len(s.persistantPeers) != 0 {
for i := range s.persistantPeers {
raddr := s.persistantPeers[i]
g.Go(func() error { return s.connectToPersistent(ctx, raddr) })
}
} else {
g.Go(func() error { return s.connectToCandidates(ctx) })
}
// Wait until cancellation or a handler errors.
return g.Wait()
}
func (s *Syncer) peerCandidate(svcs wire.ServiceFlag) (*wire.NetAddress, error) {
// Try to obtain peer candidates at random, decreasing the requirements
// as more tries are performed.
for tries := 0; tries < 100; tries++ {
kaddr := s.lp.AddrManager().GetAddress()
if kaddr == nil {
break
}
na := kaddr.NetAddress()
// Skip peer if already connected
// TODO: this should work with network blocks, not exact addresses.
k := addrmgr.NetAddressKey(na)
s.remotesMu.Lock()
_, isConnecting := s.connectingRemotes[k]
_, isRemote := s.remotes[k]
s.remotesMu.Unlock()
if isConnecting || isRemote {
continue
}
// Only allow recent nodes (10mins) after we failed 30 times
if tries < 30 && time.Since(kaddr.LastAttempt()) < 10*time.Minute {
continue
}
// Skip peers without matching service flags for the first 50 tries.
if tries < 50 && kaddr.NetAddress().Services&svcs != svcs {
continue
}
return na, nil
}
return nil, errors.New("no addresses")
}
func (s *Syncer) connectToPersistent(ctx context.Context, raddr string) error {
for {
func() {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
rp, err := s.lp.ConnectOutbound(ctx, raddr, reqSvcs)
if err != nil {
if ctx.Err() == nil {
log.Errorf("Peering attempt failed: %v", err)
}
return
}
log.Infof("New peer %v %v %v", raddr, rp.UA(), rp.Services())
k := addrmgr.NetAddressKey(rp.NA())
s.remotesMu.Lock()
s.remotes[k] = rp
n := len(s.remotes)
s.remotesMu.Unlock()
s.peerConnected(n, k)
wait := make(chan struct{})
go func() {
err := s.startupSync(ctx, rp)
if err != nil {
rp.Disconnect(err)
}
wait <- struct{}{}
}()
err = rp.Err()
s.remotesMu.Lock()
delete(s.remotes, k)
n = len(s.remotes)
s.remotesMu.Unlock()
s.peerDisconnected(n, k)
<-wait
if ctx.Err() != nil {
return
}
log.Warnf("Lost peer %v: %v", raddr, err)
}()
if err := ctx.Err(); err != nil {
return err
}
time.Sleep(5 * time.Second)
}
}
func (s *Syncer) connectToCandidates(ctx context.Context) error {
var wg sync.WaitGroup
defer wg.Wait()
sem := make(chan struct{}, 8)
for {
if ctx.Err() != nil {
return ctx.Err()
}
select {
case sem <- struct{}{}:
case <-ctx.Done():
return ctx.Err()
}
na, err := s.peerCandidate(reqSvcs)
if err != nil {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(5 * time.Second):
<-sem
continue
}
}
wg.Add(1)
go func() {
ctx, cancel := context.WithCancel(ctx)
defer func() {
cancel()
wg.Done()
<-sem
}()
// Make outbound connections to remote peers.
port := strconv.FormatUint(uint64(na.Port), 10)
raddr := net.JoinHostPort(na.IP.String(), port)
k := addrmgr.NetAddressKey(na)
s.remotesMu.Lock()
s.connectingRemotes[k] = struct{}{}
s.remotesMu.Unlock()
rp, err := s.lp.ConnectOutbound(ctx, raddr, reqSvcs)
if err != nil {
if ctx.Err() == nil {
log.Warnf("Peering attempt failed: %v", err)
}
return
}
log.Infof("New peer %v %v %v", raddr, rp.UA(), rp.Services())
s.remotesMu.Lock()
delete(s.connectingRemotes, k)
s.remotes[k] = rp
n := len(s.remotes)
s.remotesMu.Unlock()
s.peerConnected(n, k)
wait := make(chan struct{})
go func() {
err := s.startupSync(ctx, rp)
if err != nil {
rp.Disconnect(err)
}
wait <- struct{}{}
}()
err = rp.Err()
if ctx.Err() != context.Canceled {
log.Warnf("Lost peer %v: %v", raddr, err)
}
<-wait
s.remotesMu.Lock()
delete(s.remotes, k)
n = len(s.remotes)
s.remotesMu.Unlock()
s.peerDisconnected(n, k)
}()
}
}
func (s *Syncer) forRemotes(f func(rp *p2p.RemotePeer) error) error {
defer s.remotesMu.Unlock()
s.remotesMu.Lock()
if len(s.remotes) == 0 {
return errors.E(errors.NoPeers)
}
for _, rp := range s.remotes {
err := f(rp)
if err != nil {
return err
}
}
return nil
}
func (s *Syncer) pickRemote(pick func(*p2p.RemotePeer) bool) (*p2p.RemotePeer, error) {
defer s.remotesMu.Unlock()
s.remotesMu.Lock()
for _, rp := range s.remotes {
if pick(rp) {
return rp, nil
}
}
return nil, errors.E(errors.NoPeers)
}
// receiveGetData handles all received getdata requests from peers. An inv
// message declaring knowledge of the data must have been previously sent to the
// peer, or a notfound message reports the data as missing. Only transactions
// may be queried by a peer.
func (s *Syncer) receiveGetData(ctx context.Context) error {
var wg sync.WaitGroup
for {
rp, msg, err := s.lp.ReceiveGetData(ctx)
if err != nil {
wg.Wait()
return err
}
wg.Add(1)
go func() {
defer wg.Done()
// Ensure that the data was (recently) announced using an inv.
var txHashes []*chainhash.Hash
var notFound []*wire.InvVect
for _, inv := range msg.InvList {
if !rp.InvsSent().Contains(inv.Hash) {
notFound = append(notFound, inv)
continue
}
switch inv.Type {
case wire.InvTypeTx:
txHashes = append(txHashes, &inv.Hash)
default:
notFound = append(notFound, inv)
}
}
// Search for requested transactions
var foundTxs []*wire.MsgTx
if len(txHashes) != 0 {
var missing []*wire.InvVect
var err error
foundTxs, missing, err = s.wallet.GetTransactionsByHashes(txHashes)
if err != nil && !errors.Is(errors.NotExist, err) {
log.Warnf("Failed to look up transactions for getdata reply to peer %v: %v",
rp.RemoteAddr(), err)
return
}
if len(missing) != 0 {
notFound = append(notFound, missing...)
}
}
// Send all found transactions
for _, tx := range foundTxs {
err := rp.SendMessage(ctx, tx)
if ctx.Err() != nil {
return
}
if err != nil {
log.Warnf("Failed to send getdata reply to peer %v: %v",
rp.RemoteAddr(), err)
}
}
// Send notfound message for all missing or unannounced data.
if len(notFound) != 0 {
err := rp.SendMessage(ctx, &wire.MsgNotFound{InvList: notFound})
if ctx.Err() != nil {
return
}
if err != nil {
log.Warnf("Failed to send notfound reply to peer %v: %v",
rp.RemoteAddr(), err)
}
}
}()
}
}
// receiveInv receives all inv messages from peers and starts goroutines to
// handle block and tx announcements.
func (s *Syncer) receiveInv(ctx context.Context) error {
var wg sync.WaitGroup
for {
rp, msg, err := s.lp.ReceiveInv(ctx)
if err != nil {
wg.Wait()
return err
}
wg.Add(1)
go func() {
defer wg.Done()
var blocks []*chainhash.Hash
var txs []*chainhash.Hash
for _, inv := range msg.InvList {
switch inv.Type {
case wire.InvTypeBlock:
blocks = append(blocks, &inv.Hash)
case wire.InvTypeTx:
txs = append(txs, &inv.Hash)
}
}
if len(blocks) != 0 {
wg.Add(1)
go func() {
defer wg.Done()
err := s.handleBlockInvs(ctx, rp, blocks)
if ctx.Err() != nil {
return
}
if errors.Is(errors.Protocol, err) || errors.Is(errors.Consensus, err) {
log.Warnf("Disconnecting peer %v: %v", rp, err)
rp.Disconnect(err)
return
}
if err != nil {
log.Warnf("Failed to handle blocks inventoried by %v: %v", rp, err)
}
}()
}
if len(txs) != 0 {
wg.Add(1)
go func() {
s.handleTxInvs(ctx, rp, txs)
wg.Done()
}()
}
}()
}
}
func (s *Syncer) handleBlockInvs(ctx context.Context, rp *p2p.RemotePeer, hashes []*chainhash.Hash) error {
const opf = "spv.handleBlockInvs(%v)"
blocks, err := rp.GetBlocks(ctx, hashes)
if err != nil {
op := errors.Opf(opf, rp)
return errors.E(op, err)
}
headers := make([]*wire.BlockHeader, len(blocks))
bmap := make(map[chainhash.Hash]*wire.MsgBlock)
for i, block := range blocks {
bmap[block.BlockHash()] = block
h := block.Header
headers[i] = &h
}
return s.handleBlockAnnouncements(ctx, rp, headers, bmap)
}
// handleTxInvs responds to the inv message created by rp by fetching
// all unseen transactions announced by the peer. Any transactions
// that are relevant to the wallet are saved as unconfirmed
// transactions. Transaction invs are ignored when a rescan is
// necessary or ongoing.
func (s *Syncer) handleTxInvs(ctx context.Context, rp *p2p.RemotePeer, hashes []*chainhash.Hash) {
const opf = "spv.handleTxInvs(%v)"
rpt, err := s.wallet.RescanPoint()
if err != nil {
op := errors.Opf(opf, rp.RemoteAddr())
log.Warn(errors.E(op, err))
return
}
if rpt != nil {
return
}
// Ignore already-processed transactions
unseen := hashes[:0]
for _, h := range hashes {
if !s.seenTxs.Contains(*h) {
unseen = append(unseen, h)
}
}
if len(unseen) == 0 {
return
}
txs, err := rp.GetTransactions(ctx, unseen)
if errors.Is(errors.NotExist, err) {
err = nil
// Remove notfound txs.
prevTxs, prevUnseen := txs, unseen
txs, unseen = txs[:0], unseen[:0]
for i, tx := range prevTxs {
if tx != nil {
txs = append(txs, tx)
unseen = append(unseen, prevUnseen[i])
}
}
}
if err != nil {
if ctx.Err() == nil {
op := errors.Opf(opf, rp.RemoteAddr())
err := errors.E(op, err)
log.Warn(err)
}
return
}
// Mark transactions as processed so they are not queried from other nodes
// who announce them in the future.
for _, h := range unseen {
s.seenTxs.Add(*h)
}
// Save any relevant transaction.
for _, tx := range s.filterRelevant(txs) {
err := s.wallet.AcceptMempoolTx(tx)
if err != nil {
op := errors.Opf(opf, rp.RemoteAddr())
log.Warn(errors.E(op, err))
}
}
}
// receiveHeaderAnnouncements receives all block announcements through pushed
// headers messages messages from peers and starts goroutines to handle the
// announced header.
func (s *Syncer) receiveHeadersAnnouncements(ctx context.Context) error {
for {
rp, headers, err := s.lp.ReceiveHeadersAnnouncement(ctx)
if err != nil {
return err
}
go func() {
err := s.handleBlockAnnouncements(ctx, rp, headers, nil)
if err != nil {
if ctx.Err() != nil {
return
}
if errors.Is(errors.Protocol, err) || errors.Is(errors.Consensus, err) {
log.Warnf("Disconnecting peer %v: %v", rp, err)
rp.Disconnect(err)
return
}
log.Warnf("Failed to handle headers announced by %v: %v", rp, err)
}
}()
}
}
// scanChain checks for matching filters of chain and returns a map of
// relevant wallet transactions keyed by block hash. bmap is queried
// for the block first with fallback to querying rp using getdata.
func (s *Syncer) scanChain(ctx context.Context, rp *p2p.RemotePeer, chain []*wallet.BlockNode,
bmap map[chainhash.Hash]*wire.MsgBlock) (map[chainhash.Hash][]*wire.MsgTx, error) {
found := make(map[chainhash.Hash][]*wire.MsgTx)
s.filterMu.Lock()
filterData := s.filterData
s.filterMu.Unlock()
fetched := make([]*wire.MsgBlock, len(chain))
if bmap != nil {
for i := range chain {
if b, ok := bmap[*chain[i].Hash]; ok {
fetched[i] = b
}
}
}
idx := 0
FilterLoop:
for idx < len(chain) {
var fmatches []*chainhash.Hash
var fmatchidx []int
var fmatchMu sync.Mutex
// Scan remaining filters with up to ncpu workers
c := make(chan int)
var wg sync.WaitGroup
worker := func() {
for i := range c {
n := chain[i]
f := n.Filter
k := blockcf.Key(n.Hash)
if f.N() != 0 && f.MatchAny(k, filterData) {
fmatchMu.Lock()
fmatches = append(fmatches, n.Hash)
fmatchidx = append(fmatchidx, i)
fmatchMu.Unlock()
}
}
wg.Done()
}
nworkers := 0
for i := idx; i < len(chain); i++ {
if fetched[i] != nil {
continue // Already have block
}
select {
case c <- i:
default:
if nworkers < runtime.NumCPU() {
nworkers++
wg.Add(1)
go worker()
}
c <- i
}
}
close(c)
wg.Wait()
if len(fmatches) != 0 {
blocks, err := rp.GetBlocks(ctx, fmatches)
if err != nil {
return nil, err
}
for j, b := range blocks {
i := fmatchidx[j]
// Perform context-free validation on the block.
// Disconnect peer when invalid.
err := validate.MerkleRoots(b)
if err != nil {
rp.Disconnect(err)
return nil, err
}
err = validate.RegularCFilter(b, chain[i].Filter)
if err != nil {
rp.Disconnect(err)
return nil, err
}
fetched[i] = b
}
}
if err := ctx.Err(); err != nil {
return nil, err
}
for i := idx; i < len(chain); i++ {
b := fetched[i]
if b == nil {
continue
}
matches, fadded := s.rescanBlock(b)
found[*chain[i].Hash] = matches
if len(fadded) != 0 {
idx = i + 1
filterData = fadded
continue FilterLoop
}
}
return found, nil
}
return found, nil
}
// handleBlockAnnouncements handles blocks announced through block invs or
// headers messages by rp. bmap should contain the full blocks of any
// inventoried blocks, but may be nil in case the blocks were announced through
// headers.
func (s *Syncer) handleBlockAnnouncements(ctx context.Context, rp *p2p.RemotePeer, headers []*wire.BlockHeader,
bmap map[chainhash.Hash]*wire.MsgBlock) (err error) {
const opf = "spv.handleBlockAnnouncements(%v)"
defer func() {
if err != nil && ctx.Err() == nil {
op := errors.Opf(opf, rp.RemoteAddr())
err = errors.E(op, err)
}
}()
if len(headers) == 0 {
return nil
}
blockHashes := make([]*chainhash.Hash, 0, len(headers))
for _, h := range headers {
hash := h.BlockHash()
blockHashes = append(blockHashes, &hash)
}
filters, err := rp.GetCFilters(ctx, blockHashes)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return err
}
newBlocks := make([]*wallet.BlockNode, 0, len(headers))
var bestChain []*wallet.BlockNode
var matchingTxs map[chainhash.Hash][]*wire.MsgTx
err = func() error {
defer s.sidechainMu.Unlock()
s.sidechainMu.Lock()
for i := range headers {
haveBlock, _, err := s.wallet.BlockInMainChain(blockHashes[i])
if err != nil {
return err
}
if haveBlock {
continue
}
n := wallet.NewBlockNode(headers[i], blockHashes[i], filters[i])
if s.sidechains.AddBlockNode(n) {
newBlocks = append(newBlocks, n)
}
}
bestChain, err = s.wallet.EvaluateBestChain(&s.sidechains)
if err != nil {
return err
}
if len(bestChain) == 0 {
return nil
}
_, err = s.wallet.ValidateHeaderChainDifficulties(bestChain, 0)
if err != nil {
return err
}
rpt, err := s.wallet.RescanPoint()
if err != nil {
return err
}
if rpt == nil {
matchingTxs, err = s.scanChain(ctx, rp, bestChain, bmap)
if err != nil {
return err
}
}
prevChain, err := s.wallet.ChainSwitch(&s.sidechains, bestChain, matchingTxs)
if err != nil {
return err
}
if len(prevChain) != 0 {
log.Infof("Reorganize from %v to %v (total %d block(s) reorged)",
prevChain[len(prevChain)-1].Hash, bestChain[len(bestChain)-1].Hash, len(prevChain))
for _, n := range prevChain {
s.sidechains.AddBlockNode(n)
}
}
return nil
}()
if err != nil {
return err
}
if len(bestChain) != 0 {
s.locatorMu.Lock()
s.currentLocators = nil
s.locatorGeneration++
s.locatorMu.Unlock()
}
// Log connected blocks.
for _, n := range bestChain {
log.Infof("Connected block %v, height %d, %d wallet transaction(s)",
n.Hash, n.Header.Height, len(matchingTxs[*n.Hash]))
}
// Announced blocks not in the main chain are logged as sidechain or orphan
// blocks.
for _, n := range newBlocks {
haveBlock, _, err := s.wallet.BlockInMainChain(n.Hash)
if err != nil {
return err
}
if haveBlock {
continue
}
log.Infof("Received sidechain or orphan block %v, height %v", n.Hash, n.Header.Height)
}
return nil
}
// hashStop is a zero value stop hash for fetching all possible data using
// locators.
var hashStop chainhash.Hash
// getHeaders iteratively fetches headers from rp using the latest locators.
// Returns when no more headers are available. A sendheaders message is pushed
// to the peer when there are no more headers to fetch.
func (s *Syncer) getHeaders(ctx context.Context, rp *p2p.RemotePeer) error {
var locators []*chainhash.Hash
var generation uint
var err error
s.locatorMu.Lock()
locators = s.currentLocators
generation = s.locatorGeneration
if locators == nil {
locators, err = s.wallet.BlockLocators(nil)
if err != nil {
s.locatorMu.Unlock()
return err
}
s.currentLocators = locators
s.locatorGeneration++
}
s.locatorMu.Unlock()
var lastHeight int32
for {
headers, err := rp.GetHeaders(ctx, locators, &hashStop)
if err != nil {
return err
}
if len(headers) == 0 {
// Ensure that the peer provided headers through the height
// advertised during handshake.
if lastHeight < rp.InitialHeight() {
// Peer may not have provided any headers if our own locators
// were up to date. Compare the best locator hash with the
// advertised height.