-
Notifications
You must be signed in to change notification settings - Fork 153
/
sync.go
1902 lines (1685 loc) · 50.9 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-2024 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"
"fmt"
"runtime"
"sync"
"sync/atomic"
"time"
"decred.org/dcrwallet/v4/errors"
"decred.org/dcrwallet/v4/lru"
"decred.org/dcrwallet/v4/p2p"
"decred.org/dcrwallet/v4/validate"
"decred.org/dcrwallet/v4/wallet"
"github.com/decred/dcrd/addrmgr/v2"
"github.com/decred/dcrd/blockchain/stake/v5"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrec/secp256k1/v4/schnorr"
"github.com/decred/dcrd/gcs/v4/blockcf2"
"github.com/decred/dcrd/mixing"
"github.com/decred/dcrd/mixing/mixpool"
"github.com/decred/dcrd/txscript/v4"
"github.com/decred/dcrd/wire"
"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
const (
targetPeerCount = 8
// Require a subset of all connected outbounded peers to meet some
// minimum protocol version.
minVersion = wire.MixVersion
minVersionTarget = 3
)
// Syncer implements wallet synchronization services by over the Decred wire
// protocol using Simplified Payment Verification (SPV) with compact filters.
type Syncer struct {
// atomics
atomicWalletSynced atomic.Uint32 // CAS (synced=1) when wallet syncing complete
wallet *wallet.Wallet
lp *p2p.LocalPeer
// discoverAccounts is true if the initial sync should perform account
// discovery. Only used during initial sync.
discoverAccounts bool
persistentPeers []string
connectingRemotes map[string]struct{}
remotes map[string]*p2p.RemotePeer
remoteAvailable chan struct{}
remotesMu sync.Mutex
// initialSyncDone is closed when the initial sync loop has finished.
initialSyncDone chan struct{}
// 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 blockcf2.Entries
filterMu sync.Mutex
// These LRU caches record hashes of received inventoried messages.
// Once a message is fetched and processed from one peer, the hash is
// added to the cache to avoid fetching it again from other peers that
// also announce it.
seenTxs lru.Cache[chainhash.Hash]
seenMixMsgs lru.Cache[chainhash.Hash]
// Sidechain management
sidechains wallet.SidechainForest
sidechainMu sync.Mutex
// Holds all potential callbacks used to notify clients
notifications *Notifications
// Mempool for non-wallet-relevant transactions.
mempool sync.Map // k=chainhash.Hash v=*wire.MsgTx
mempoolAdds chan *chainhash.Hash
}
// 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()
// MempoolTxs is called whenever new relevant unmined transactions are
// observed and saved.
MempoolTxs func(txs []*wire.MsgTx)
// TipChanged is called when the main chain tip block changes.
// When reorgDepth is zero, the new block is a direct child of the previous tip.
// If non-zero, one or more blocks described by the parameter were removed from
// the previous main chain.
// txs contains all relevant transactions mined in each attached block in
// unspecified order.
// reorgDepth is guaranteed to be non-negative.
TipChanged func(tip *wire.BlockHeader, reorgDepth int32, txs []*wire.MsgTx)
}
// 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[chainhash.Hash](2000),
seenMixMsgs: lru.NewCache[chainhash.Hash](2000),
lp: lp,
mempoolAdds: make(chan *chainhash.Hash),
initialSyncDone: make(chan struct{}),
}
}
// SetPersistentPeers sets each peer as a persistent peer and disables DNS
// seeding and peer discovery.
func (s *Syncer) SetPersistentPeers(peers []string) {
s.persistentPeers = 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
}
// DisableDiscoverAccounts disables account discovery. This has an effect only
// if called before the main Run() executes the account discovery process.
func (s *Syncer) DisableDiscoverAccounts() {
s.discoverAccounts = false
}
// 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 s.atomicWalletSynced.CompareAndSwap(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 s.atomicWalletSynced.CompareAndSwap(1, 0) &&
s.notifications != nil &&
s.notifications.Synced != nil {
s.notifications.Synced(false)
}
}
// Synced returns whether this wallet is completely synced to the network and
// the target height it is attempting to sync to.
func (s *Syncer) Synced(ctx context.Context) (bool, int32) {
synced := s.atomicWalletSynced.Load() == 1
var targetHeight int32
if !synced {
s.forRemotes(func(rp *p2p.RemotePeer) error {
if rp.InitialHeight() > targetHeight {
targetHeight = rp.InitialHeight()
}
return nil
})
} else {
_, targetHeight = s.wallet.MainChainTip(ctx)
}
return synced, targetHeight
}
// GetRemotePeers returns a map of connected remote peers.
func (s *Syncer) GetRemotePeers() map[string]*p2p.RemotePeer {
s.remotesMu.Lock()
defer s.remotesMu.Unlock()
remotes := make(map[string]*p2p.RemotePeer, len(s.remotes))
for k, rp := range s.remotes {
remotes[k] = rp
}
return remotes
}
// 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(lastHeader *wire.BlockHeader) {
if s.notifications != nil && s.notifications.FetchHeadersProgress != nil {
s.notifications.FetchHeadersProgress(int32(lastHeader.Height), lastHeader.Timestamp.Unix())
}
}
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()
}
}
func (s *Syncer) mempoolTxs(txs []*wire.MsgTx) {
if s.notifications != nil && s.notifications.MempoolTxs != nil {
s.notifications.MempoolTxs(txs)
}
}
func (s *Syncer) tipChanged(tip *wire.BlockHeader, reorgDepth int32, matchingTxs map[chainhash.Hash][]*wire.MsgTx) {
if s.notifications != nil && s.notifications.TipChanged != nil {
var txs []*wire.MsgTx
for _, matching := range matchingTxs {
txs = append(txs, matching...)
}
s.notifications.TipChanged(tip, reorgDepth, txs)
}
}
// setRequiredHeight sets the required height a peer must advertise as their
// last height. Initial height 6 blocks below the current chain tip height
// result in a handshake error.
func (s *Syncer) setRequiredHeight(tipHeight int32) {
requireHeight := tipHeight
if requireHeight > 6 {
requireHeight -= 6
}
s.lp.RequirePeerHeight(requireHeight)
}
// 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(ctx)
s.setRequiredHeight(tipHeight)
rescanPoint, err := s.wallet.RescanPoint(ctx)
if err != nil {
return err
}
log.Infof("Headers synced through block %v height %d", &tipHash, tipHeight)
if rescanPoint != nil {
h, err := s.wallet.BlockHeader(ctx, 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)
}
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 persistent peers.
if len(s.persistentPeers) == 0 {
s.lp.SeedPeers(ctx, wire.SFNodeNetwork)
}
// 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) })
g.Go(func() error { return s.receiveMixMsgs(ctx) })
s.lp.AddHandledMessages(p2p.MaskGetData | p2p.MaskInv)
if len(s.persistentPeers) != 0 {
for i := range s.persistentPeers {
raddr := s.persistentPeers[i]
g.Go(func() error { return s.connectToPersistent(ctx, raddr) })
}
} else {
g.Go(func() error { return s.connectToCandidates(ctx) })
}
g.Go(func() error { return s.handleMempool(ctx) })
s.wallet.SetNetworkBackend(s)
defer s.wallet.SetNetworkBackend(nil)
// Perform the initial startup sync.
g.Go(func() error {
// First step: fetch missing CFilters.
progress := make(chan wallet.MissingCFilterProgress, 1)
go s.wallet.FetchMissingCFiltersWithProgress(ctx, s, progress)
log.Debugf("Fetching missing CFilters...")
s.fetchMissingCfiltersStart()
for p := range progress {
if p.Err != nil {
return p.Err
}
s.fetchMissingCfiltersProgress(p.BlockHeightStart, p.BlockHeightEnd)
}
s.fetchMissingCfiltersFinished()
log.Debugf("Fetched all missing cfilters")
// Next: fetch headers and cfilters up to mainchain tip.
s.fetchHeadersStart()
log.Debugf("Fetching headers and CFilters...")
err = s.initialSyncHeaders(ctx)
if err != nil {
return err
}
s.fetchHeadersFinished()
// Finally: Perform the initial rescan over the received blocks.
err = s.initialSyncRescan(ctx)
if err != nil {
return err
}
// Signal that the initial sync has completed.
close(s.initialSyncDone)
return nil
})
// Run wallet background goroutines (currently, this just runs
// mixclient).
g.Go(func() error {
return s.wallet.Run(ctx)
})
// Wait until cancellation or a handler errors.
return g.Wait()
}
// peerCandidate returns a peer address that we shall attempt to connect to.
// Only peers not already remotes or in the process of connecting are returned.
// Any address returned is marked in s.connectingRemotes before returning.
func (s *Syncer) peerCandidate(svcs wire.ServiceFlag) (*addrmgr.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()
k := na.Key()
s.remotesMu.Lock()
_, isConnecting := s.connectingRemotes[k]
_, isRemote := s.remotes[k]
switch {
// Skip peer if already connected, or in process of connecting
// TODO: this should work with network blocks, not exact addresses.
case isConnecting || isRemote:
fallthrough
// Only allow recent nodes (10mins) after we failed 30 times
case tries < 30 && time.Since(kaddr.LastAttempt()) < 10*time.Minute:
fallthrough
// Skip peers without matching service flags for the first 50 tries.
case tries < 50 && kaddr.NetAddress().Services&svcs != svcs:
s.remotesMu.Unlock()
continue
}
s.connectingRemotes[k] = struct{}{}
s.remotesMu.Unlock()
return na, nil
}
return nil, errors.New("no addresses")
}
var errBreaksMinVersionTarget = errors.New("peer uses too low version to satisify " +
"minimum target version count")
// connectAndRunPeer connects to and runs the syncing process with the specified
// peer. It blocks until the peer disconnects and logs any errors.
func (s *Syncer) connectAndRunPeer(ctx context.Context, raddr string, persistent bool) {
// Attempt connection to peer.
rp, err := s.lp.ConnectOutbound(ctx, raddr, reqSvcs)
if err != nil {
// Remove from list of connecting remotes if it was a peer
// candidate (as opposed to a persistent peer).
s.remotesMu.Lock()
delete(s.connectingRemotes, raddr)
s.remotesMu.Unlock()
if !errors.Is(err, context.Canceled) {
log.Warnf("Peering attempt failed: %v", err)
}
return
}
// Track peer as running as opposed to attempting connection.
s.remotesMu.Lock()
delete(s.connectingRemotes, raddr)
if !persistent && s.breaksMinVersionTarget(rp) {
s.remotesMu.Unlock()
log.Debugf("Disconnecting %v: %v", raddr, errBreaksMinVersionTarget)
rp.Disconnect(errBreaksMinVersionTarget)
return
}
s.remotes[raddr] = rp
n := len(s.remotes)
if s.remoteAvailable != nil {
close(s.remoteAvailable)
s.remoteAvailable = nil
}
s.remotesMu.Unlock()
log.Infof("New peer %v %v version=%d %v", raddr, rp.UA(), rp.Pver(), rp.Services())
s.peerConnected(n, raddr)
// Alert disconnection once this peer is done.
defer func() {
s.remotesMu.Lock()
delete(s.remotes, raddr)
n = len(s.remotes)
s.remotesMu.Unlock()
s.peerDisconnected(n, raddr)
if n == 0 {
s.unsynced()
}
}()
// Perform peer startup.
err = s.peerStartup(ctx, rp)
if err != nil {
if !errors.Is(err, context.Canceled) {
log.Warnf("Unable to complete startup sync with peer %v: %v", raddr, err)
} else {
log.Infof("Lost peer %v", raddr)
}
rp.Disconnect(err)
return
}
// Finally, block until the peer disconnects.
err = rp.Err()
if !errors.Is(err, context.Canceled) {
log.Warnf("Lost peer %v: %v", raddr, err)
} else {
log.Infof("Lost peer %v", raddr)
}
}
func (s *Syncer) breaksMinVersionTarget(rp *p2p.RemotePeer) bool {
if rp.Pver() >= minVersion {
return false
}
n := len(s.remotes)
if n < targetPeerCount-minVersionTarget {
return false
}
var meetsMin int
for _, rp := range s.remotes {
if rp.Pver() >= minVersion {
meetsMin++
if meetsMin == minVersionTarget {
return false
}
}
}
return true
}
func (s *Syncer) connectToPersistent(ctx context.Context, raddr string) error {
for {
s.connectAndRunPeer(ctx, raddr, true)
// Retry persistent peer after 5 seconds.
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(5 * time.Second):
}
}
}
func (s *Syncer) connectToCandidates(ctx context.Context) error {
var wg sync.WaitGroup
defer wg.Wait()
sem := make(chan struct{}, targetPeerCount)
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() {
raddr := na.String()
s.connectAndRunPeer(ctx, raddr, false)
wg.Done()
<-sem
}()
}
}
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
}
// waitForAnyRemote blocks until there is one or more remote peers available or
// the context is canceled.
//
// The [isEligible] callback determines which peers are eligible for selection.
//
// This function may return a nil peer with nil error if there are peers
// available but none of them are eligible.
//
// If waitEligible is true, then this function will wait until at least one
// remote is eligible. Otherwise, this function returns a nil peer with nil
// error when there are peers but none of them are eligible.
func (s *Syncer) waitForRemote(ctx context.Context, isEligible func(rp *p2p.RemotePeer) bool, waitEligible bool) (*p2p.RemotePeer, error) {
for {
s.remotesMu.Lock()
if len(s.remotes) == 0 {
c := s.remoteAvailable
if c == nil {
c = make(chan struct{})
s.remoteAvailable = c
}
s.remotesMu.Unlock()
// Wait until a peer is available.
select {
case <-c:
case <-ctx.Done():
return nil, ctx.Err()
}
} else {
for _, rp := range s.remotes {
if isEligible(rp) {
s.remotesMu.Unlock()
return rp, nil
}
}
s.remotesMu.Unlock()
if !waitEligible {
return nil, nil
}
}
}
}
// 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 mixHashes []*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)
case wire.InvTypeMix:
if !s.wallet.MixingEnabled() {
notFound = append(notFound, inv)
continue
}
mixHashes = append(mixHashes, &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(ctx, txHashes)
if err != nil && !errors.Is(err, errors.NotExist) {
log.Warnf("Failed to look up transactions for getdata reply to peer %v: %v",
rp.RemoteAddr(), err)
return
}
// For the missing ones, attempt to search in
// the non-wallet-relevant syncer mempool.
for _, miss := range missing {
if v, ok := s.mempool.Load(miss.Hash); ok {
tx := v.(*wire.MsgTx)
foundTxs = append(foundTxs, tx)
continue
}
notFound = append(notFound, miss)
}
}
// Search for requested mix messages
var foundMixMsgs []mixing.Message
if len(mixHashes) != 0 {
for _, hash := range mixHashes {
msg, err := s.wallet.MixMessage(hash)
if err != nil {
invvect := wire.NewInvVect(wire.InvTypeMix, hash)
notFound = append(notFound, invvect)
continue
}
foundMixMsgs = append(foundMixMsgs, msg)
}
}
// 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 all found mix messages
for _, msg := range foundMixMsgs {
err := rp.SendMessage(ctx, msg)
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
}
var blocks []*chainhash.Hash
var txs []*chainhash.Hash
var mixMsgs []*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)
case wire.InvTypeMix:
if s.wallet.MixingEnabled() {
mixMsgs = append(mixMsgs, &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(err, errors.Protocol) || errors.Is(err, errors.Consensus) {
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()
}()
}
if len(mixMsgs) != 0 {
wg.Add(1)
go func() {
s.handleMixInvs(ctx, rp, mixMsgs, nil)
wg.Done()
}()
}
}
}
// verifyTSpendSignature verifies that the provided signature and public key
// were the ones that signed the provided message transaction.
func (s *Syncer) verifyTSpendSignature(msgTx *wire.MsgTx, signature, pubKey []byte) error {
// Calculate signature hash.
sigHash, err := txscript.CalcSignatureHash(nil,
txscript.SigHashAll, msgTx, 0, nil)
if err != nil {
return errors.Errorf("CalcSignatureHash: %w", err)
}
// Lift Signature from bytes.
sig, err := schnorr.ParseSignature(signature)
if err != nil {
return errors.Errorf("ParseSignature: %w", err)
}
// Lift public PI key from bytes.
pk, err := schnorr.ParsePubKey(pubKey)
if err != nil {
return errors.Errorf("ParsePubKey: %w", err)
}
// Verify transaction was properly signed.
if !sig.Verify(sigHash, pk) {
return errors.Errorf("Verify failed")
}
return nil
}
func (s *Syncer) checkTSpend(ctx context.Context, tx *wire.MsgTx) bool {
var (
isTSpend bool
signature, pubKey []byte
err error
)
signature, pubKey, err = stake.CheckTSpend(tx)
isTSpend = err == nil
if !isTSpend {
return false
}
_, height := s.wallet.MainChainTip(ctx)
if uint32(height) > tx.Expiry {
return false
}
// If we have a TSpend verify the signature.
// Check if this is a sanctioned PI key.
if !s.wallet.ChainParams().PiKeyExists(pubKey) {
return false
}
// Verify that the signature is valid and corresponds to the
// provided public key.
err = s.verifyTSpendSignature(tx, signature, pubKey)
if err != nil {
return false
}
return true
}
// GetInitState requests the init state, then using the tspend hashes requests
// all unseen tspend txs, validates them, and adds them to the tspends cache.
func (s *Syncer) GetInitState(ctx context.Context, rp *p2p.RemotePeer) error {
msg := wire.NewMsgGetInitState()
msg.AddTypes(wire.InitStateTSpends)
initState, err := rp.GetInitState(ctx, msg)
if err != nil {
return err
}
unseenTSpends := make([]*chainhash.Hash, 0)
for h := range initState.TSpendHashes {
if !s.wallet.IsTSpendCached(&initState.TSpendHashes[h]) {
unseenTSpends = append(unseenTSpends, &initState.TSpendHashes[h])
}
}
if len(unseenTSpends) == 0 {
return nil
}
tspendTxs, err := rp.Transactions(ctx, unseenTSpends)
if errors.Is(err, errors.NotExist) {
err = nil
// Remove notfound txs.
prevTxs := tspendTxs
tspendTxs = tspendTxs[:0]
for _, tx := range prevTxs {
if tx != nil {
tspendTxs = append(tspendTxs, tx)
}
}
}
if err != nil {
return nil
}
for _, v := range tspendTxs {
if s.checkTSpend(ctx, v) {
s.wallet.AddTSpend(*v)
}
}
return nil
}
func (s *Syncer) handleBlockInvs(ctx context.Context, rp *p2p.RemotePeer, hashes []*chainhash.Hash) error {
const opf = "spv.handleBlockInvs(%v)"
// We send a sendheaders msg at the end of our startup stage. Ignore
// any invs sent before that happens, since we'll still be performing
// an initial sync with the peer.
if !rp.SendHeadersSent() {
log.Debugf("Ignoring block invs from %v before "+
"sendheaders is sent", rp)
return nil
}
blocks, err := rp.Blocks(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(ctx)
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)