-
Notifications
You must be signed in to change notification settings - Fork 184
/
neutrino.go
1783 lines (1532 loc) · 53.4 KB
/
neutrino.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.
// TODO: Add functional options to ChainService instantiation.
package neutrino
import (
"errors"
"fmt"
"net"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/addrmgr"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/connmgr"
"github.com/btcsuite/btcd/peer"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lightninglabs/neutrino/banman"
"github.com/lightninglabs/neutrino/blockntfns"
"github.com/lightninglabs/neutrino/cache/lru"
"github.com/lightninglabs/neutrino/chanutils"
"github.com/lightninglabs/neutrino/filterdb"
"github.com/lightninglabs/neutrino/headerfs"
"github.com/lightninglabs/neutrino/pushtx"
"github.com/lightninglabs/neutrino/query"
)
// These are exported variables so they can be changed by users.
//
// TODO: Export functional options for these as much as possible so they can be
// changed call-to-call.
var (
// ConnectionRetryInterval is the base amount of time to wait in
// between retries when connecting to persistent peers. It is adjusted
// by the number of retries such that there is a retry backoff.
ConnectionRetryInterval = time.Second * 5
// UserAgentName is the user agent name and is used to help identify
// ourselves to other bitcoin peers.
UserAgentName = "neutrino"
// UserAgentVersion is the user agent version and is used to help
// identify ourselves to other bitcoin peers.
UserAgentVersion = "0.12.0-beta"
// Services describes the services that are supported by the server.
Services = wire.SFNodeWitness | wire.SFNodeCF
// RequiredServices describes the services that are required to be
// supported by outbound peers.
RequiredServices = wire.SFNodeNetwork | wire.SFNodeWitness | wire.SFNodeCF
// BanThreshold is the maximum ban score before a peer is banned.
BanThreshold = uint32(100)
// BanDuration is the duration of a ban.
BanDuration = time.Hour * 24
// TargetOutbound is the number of outbound peers to target.
TargetOutbound = 8
// MaxPeers is the maximum number of connections the client maintains.
MaxPeers = 125
// DisableDNSSeed disables getting initial addresses for Bitcoin nodes
// from DNS.
DisableDNSSeed = false
// DefaultFilterCacheSize is the size (in bytes) of filters neutrino
// will keep in memory if no size is specified in the neutrino.Config.
// Since we utilize the cache during batch filter fetching, it is
// beneficial if it is able to keep a whole batch. The current batch
// size is 1000, so we default to 30 MB, which can fit about 1450 to
// 2300 mainnet filters.
DefaultFilterCacheSize uint64 = 3120 * 10 * 1000
// DefaultBlockCacheSize is the size (in bytes) of blocks neutrino will
// keep in memory if no size is specified in the neutrino.Config.
DefaultBlockCacheSize uint64 = 4096 * 10 * 1000 // 40 MB
)
// isDevNetwork indicates if the chain is a private development network, namely
// simnet or regtest/regnet.
func isDevNetwork(net wire.BitcoinNet) bool {
return net == chaincfg.SimNetParams.Net ||
net == chaincfg.RegressionNetParams.Net
}
// updatePeerHeightsMsg is a message sent from the blockmanager to the server
// after a new block has been accepted. The purpose of the message is to update
// the heights of peers that were known to announce the block before we
// connected it to the main chain or recognized it as an orphan. With these
// updates, peer heights will be kept up to date, allowing for fresh data when
// selecting sync peer candidacy.
type updatePeerHeightsMsg struct {
newHash *chainhash.Hash
newHeight int32
originPeer *ServerPeer
}
// peerState maintains state of inbound, persistent, outbound peers as well
// as banned peers and outbound groups.
type peerState struct {
outboundPeers map[int32]*ServerPeer
persistentPeers map[int32]*ServerPeer
outboundGroups map[string]int
}
// Count returns the count of all known peers.
func (ps *peerState) Count() int {
return len(ps.outboundPeers) + len(ps.persistentPeers)
}
// forAllOutboundPeers is a helper function that runs closure on all outbound
// peers known to peerState.
func (ps *peerState) forAllOutboundPeers(closure func(sp *ServerPeer)) {
for _, e := range ps.outboundPeers {
closure(e)
}
for _, e := range ps.persistentPeers {
closure(e)
}
}
// forAllPeers is a helper function that runs closure on all peers known to
// peerState.
func (ps *peerState) forAllPeers(closure func(sp *ServerPeer)) {
ps.forAllOutboundPeers(closure)
}
// spMsg represents a message over the wire from a specific peer.
type spMsg struct {
sp *ServerPeer
msg wire.Message
}
// spMsgSubscription sends all messages from a peer over a channel, allowing
// pluggable filtering of the messages.
type spMsgSubscription struct {
msgChan chan<- spMsg
quitChan <-chan struct{}
}
// msgSubscription sends all messages from a peer over a channel, allowing
// pluggable filtering of the messages.
type msgSubscription struct {
msgChan chan<- wire.Message
quitChan <-chan struct{}
}
// ServerPeer extends the peer to maintain state shared by the server and the
// blockmanager.
type ServerPeer struct {
// The following variables must only be used atomically
feeFilter int64
*peer.Peer
connReq *connmgr.ConnReq
server *ChainService
persistent bool
knownAddresses *lru.Cache[string, *cachedAddr]
quit chan struct{}
// The following map of subcribers is used to subscribe to messages
// from the peer. This allows broadcast to multiple subscribers at
// once, allowing for multiple queries to be going to multiple peers at
// any one time. The mutex is for subscribe/unsubscribe functionality.
// The sends on these channels WILL NOT block; any messages the channel
// can't accept will be dropped silently.
// TODO(halseth): remove one of the maps when all queries go through
// work manager.
recvSubscribers map[spMsgSubscription]struct{}
recvSubscribers2 map[msgSubscription]struct{}
mtxSubscribers sync.RWMutex
}
// NewServerPeer returns a new ServerPeer instance. The peer needs to be set by
// the caller.
func NewServerPeer(s *ChainService, isPersistent bool) *ServerPeer {
return &ServerPeer{
server: s,
persistent: isPersistent,
knownAddresses: lru.NewCache[string, *cachedAddr](5000),
quit: make(chan struct{}),
recvSubscribers: make(map[spMsgSubscription]struct{}),
recvSubscribers2: make(map[msgSubscription]struct{}),
}
}
// newestBlock returns the current best block hash and height using the format
// required by the configuration for the peer package.
func (sp *ServerPeer) newestBlock() (*chainhash.Hash, int32, error) {
bestHeader, bestHeight, err := sp.server.BlockHeaders.ChainTip()
if err != nil {
return nil, 0, err
}
bestHash := bestHeader.BlockHash()
return &bestHash, int32(bestHeight), nil
}
// addKnownAddresses adds the given addresses to the set of known addresses to
// the peer to prevent sending duplicate addresses.
func (sp *ServerPeer) addKnownAddresses(addresses []*wire.NetAddressV2) {
for _, na := range addresses {
_, err := sp.knownAddresses.Put(
addrmgr.NetAddressKey(na), &cachedAddr{},
)
if err != nil {
log.Debugf("Could not store known addresses: %v", err)
}
}
}
// OnVerAck is invoked when a peer receives a verack bitcoin message and is used
// to kick start communication with them.
func (sp *ServerPeer) OnVerAck(_ *peer.Peer, msg *wire.MsgVerAck) {
sp.server.AddPeer(sp)
}
// OnVersion is invoked when a peer receives a version bitcoin message
// and is used to negotiate the protocol version details as well as kick start
// the communications.
func (sp *ServerPeer) OnVersion(_ *peer.Peer, msg *wire.MsgVersion) *wire.MsgReject {
// Add the remote peer time as a sample for creating an offset against
// the local clock to keep the network time in sync.
sp.server.timeSource.AddTimeSample(sp.Addr(), msg.Timestamp)
// Check to see if the peer supports the latest protocol version and
// service bits required to service us. If not, then we'll disconnect
// so we can find compatible peers.
peerServices := sp.Services()
if peerServices&wire.SFNodeWitness != wire.SFNodeWitness ||
peerServices&wire.SFNodeCF != wire.SFNodeCF {
peerAddr := sp.Addr()
err := sp.server.BanPeer(peerAddr, banman.NoCompactFilters)
if err != nil {
log.Errorf("Unable to ban peer %v: %v", peerAddr, err)
}
// Disconnect the peer even though BanPeer attempts to do so
// because it has yet to be added.
sp.Disconnect()
return nil
}
// Update the address manager with the advertised services for outbound
// connections in case they have changed. This is not done for inbound
// connections to help prevent malicious behavior and is skipped when
// running on the simulation test network since it is only intended to
// connect to specified peers and actively avoids advertising and
// connecting to discovered peers.
if !sp.Inbound() {
sp.server.addrManager.SetServices(sp.NA(), msg.Services)
}
return nil
}
// OnInv is invoked when a peer receives an inv bitcoin message and is
// used to examine the inventory being advertised by the remote peer and react
// accordingly. We pass the message down to blockmanager which will call
// QueueMessage with any appropriate responses.
func (sp *ServerPeer) OnInv(p *peer.Peer, msg *wire.MsgInv) {
log.Tracef("Got inv with %d items from %s", len(msg.InvList), p.Addr())
newInv := wire.NewMsgInvSizeHint(uint(len(msg.InvList)))
for _, invVect := range msg.InvList {
if invVect.Type == wire.InvTypeTx {
log.Tracef("Ignoring tx %s in inv from %v -- "+
"SPV mode", invVect.Hash, sp)
if sp.ProtocolVersion() >= wire.BIP0037Version {
log.Infof("Peer %v is announcing "+
"transactions -- disconnecting", sp)
sp.Disconnect()
return
}
continue
}
err := newInv.AddInvVect(invVect)
if err != nil {
log.Errorf("Failed to add inventory vector: %s", err)
break
}
}
if len(newInv.InvList) > 0 {
sp.server.blockManager.QueueInv(newInv, sp)
}
}
// OnHeaders is invoked when a peer receives a headers bitcoin
// message. The message is passed down to the block manager.
func (sp *ServerPeer) OnHeaders(p *peer.Peer, msg *wire.MsgHeaders) {
log.Tracef("Got headers with %d items from %s", len(msg.Headers),
p.Addr())
sp.server.blockManager.QueueHeaders(msg, sp)
}
// OnFeeFilter is invoked when a peer receives a feefilter bitcoin message and
// is used by remote peers to request that no transactions which have a fee rate
// lower than provided value are inventoried to them. The peer will be
// disconnected if an invalid fee filter value is provided.
func (sp *ServerPeer) OnFeeFilter(_ *peer.Peer, msg *wire.MsgFeeFilter) {
// Check that the passed minimum fee is a valid amount.
if msg.MinFee < 0 || msg.MinFee > btcutil.MaxSatoshi {
log.Debugf("Peer %v sent an invalid feefilter '%v' -- "+
"disconnecting", sp, btcutil.Amount(msg.MinFee))
sp.Disconnect()
return
}
atomic.StoreInt64(&sp.feeFilter, msg.MinFee)
}
// OnReject is invoked when a peer receives a reject bitcoin message and is
// used to notify the server about a rejected transaction.
func (sp *ServerPeer) OnReject(_ *peer.Peer, msg *wire.MsgReject) {
// TODO(roaseef): log?
}
// OnAddr is invoked when a peer receives an addr bitcoin message and is
// used to notify the server about advertised addresses.
func (sp *ServerPeer) OnAddr(_ *peer.Peer, msg *wire.MsgAddr) {
// Ignore addresses when running on a private development network. This
// helps prevent the network from becoming another public test network
// since it will not be able to learn about other peers that have not
// specifically been provided.
if isDevNetwork(sp.server.chainParams.Net) {
return
}
// Ignore old style addresses which don't include a timestamp.
if sp.ProtocolVersion() < wire.NetAddressTimeVersion {
return
}
// A message that has no addresses is invalid.
if len(msg.AddrList) == 0 {
log.Errorf("Command [%s] from %s does not contain any "+
"addresses", msg.Command(), sp.Addr())
sp.Disconnect()
return
}
addrs := make([]*wire.NetAddressV2, 0, len(msg.AddrList))
for _, na := range msg.AddrList {
// Don't add more address if we're disconnecting.
if !sp.Connected() {
return
}
// Skip any that don't advertise our required services.
if na.Services&RequiredServices != RequiredServices {
continue
}
// Set the timestamp to 5 days ago if it's more than 10 minutes
// in the future so this address is one of the first to be
// removed when space is needed.
now := time.Now()
if na.Timestamp.After(now.Add(time.Minute * 10)) {
na.Timestamp = now.Add(-1 * time.Hour * 24 * 5)
}
// Convert the wire.NetAddress to wire.NetAddressV2 since that
// is what is used by the addrmgr.
currentNa := wire.NetAddressV2FromBytes(
na.Timestamp, na.Services, na.IP, na.Port,
)
addrs = append(addrs, currentNa)
}
// Ignore any addr messages if none of them contained our required
// services.
if len(addrs) == 0 {
return
}
// Add addresses to the set of known addresses for this peer.
sp.addKnownAddresses(addrs)
// Add addresses to server address manager. The address manager handles
// the details of things such as preventing duplicate addresses, max
// addresses, and last seen updates.
// XXX bitcoind gives a 2 hour time penalty here, do we want to do the
// same?
sp.server.addrManager.AddAddresses(addrs, sp.NA())
}
// OnAddrV2 is called when a peer receives an AddrV2 message from its peer.
func (sp *ServerPeer) OnAddrV2(_ *peer.Peer, msg *wire.MsgAddrV2) {
// Ignore addresses when running on a private development network for
// the same reason that OnAddr does.
if isDevNetwork(sp.server.chainParams.Net) {
return
}
// An empty AddrV2 message is invalid.
if len(msg.AddrList) == 0 {
log.Errorf("Command [%s] from %s does not contain any "+
"addresses", msg.Command(), sp.Addr())
sp.Disconnect()
return
}
addrs := make([]*wire.NetAddressV2, 0, len(msg.AddrList))
for _, na := range msg.AddrList {
// Don't add more addresses if we're disconnecting.
if !sp.Connected() {
return
}
// Skip any that don't advertise our required services.
if na.Services&RequiredServices != RequiredServices {
continue
}
// Set the timestamp to 5 days ago if it's more than 10 minutes
// in the future so this address is one of the first to be
// removed when space is needed.
now := time.Now()
if na.Timestamp.After(now.Add(time.Minute * 10)) {
na.Timestamp = now.Add(-1 * time.Hour * 24 * 5)
}
addrs = append(addrs, na)
}
// Ignore addrv2 message if no addresses contained our required
// services.
if len(addrs) == 0 {
return
}
// Add the addresses to the set of known addresses for this peer.
sp.addKnownAddresses(addrs)
// Add addresses to the address manager.
sp.server.addrManager.AddAddresses(addrs, sp.NA())
}
// OnRead is invoked when a peer receives a message and it is used to update
// the bytes received by the server.
func (sp *ServerPeer) OnRead(_ *peer.Peer, bytesRead int, msg wire.Message,
err error) {
sp.server.AddBytesReceived(uint64(bytesRead))
// Send a message to each subscriber. Each message gets its own
// goroutine to prevent blocking on the mutex lock.
// TODO: Flood control.
sp.mtxSubscribers.RLock()
defer sp.mtxSubscribers.RUnlock()
for subscription := range sp.recvSubscribers {
go func(subscription spMsgSubscription) {
select {
case <-subscription.quitChan:
case subscription.msgChan <- spMsg{
msg: msg,
sp: sp,
}:
}
}(subscription)
}
for subscription := range sp.recvSubscribers2 {
// Quickly determine if this subscription has been canceled, if
// so delete it.
select {
case <-subscription.quitChan:
delete(sp.recvSubscribers2, subscription)
continue
default:
}
go func(subscription msgSubscription) {
select {
case <-subscription.quitChan:
case subscription.msgChan <- msg:
}
}(subscription)
}
}
// subscribeRecvMsg handles adding OnRead subscriptions to the server peer.
func (sp *ServerPeer) subscribeRecvMsg(subscription spMsgSubscription) {
sp.mtxSubscribers.Lock()
defer sp.mtxSubscribers.Unlock()
sp.recvSubscribers[subscription] = struct{}{}
}
// unsubscribeRecvMsgs handles removing OnRead subscriptions from the server
// peer.
func (sp *ServerPeer) unsubscribeRecvMsgs(subscription spMsgSubscription) {
sp.mtxSubscribers.Lock()
defer sp.mtxSubscribers.Unlock()
delete(sp.recvSubscribers, subscription)
}
// A compile-time check to ensure that ServerPeer implements the query.Peer
// interface.
var _ query.Peer = (*ServerPeer)(nil)
// SubscribeRecvMsg adds a OnRead subscription to the peer. All bitcoin
// messages received from this peer will be sent on the returned channel. A
// closure is also returned, that should be called to cancel the subscription.
//
// NOTE: Part of the query.Peer interface.
func (sp *ServerPeer) SubscribeRecvMsg() (<-chan wire.Message, func()) {
// We won't have to buffer this channel, since we'll always send on it
// from a new goroutine.
msgChan := make(chan wire.Message)
quitChan := make(chan struct{})
sub := msgSubscription{
msgChan: msgChan,
quitChan: quitChan,
}
sp.mtxSubscribers.Lock()
defer sp.mtxSubscribers.Unlock()
sp.recvSubscribers2[sub] = struct{}{}
return msgChan, func() {
close(quitChan)
}
}
// OnDisconnect returns a channel that will be closed when this peer is
// disconnected.
//
// NOTE: Part of the query.Peer interface.
func (sp *ServerPeer) OnDisconnect() <-chan struct{} {
return sp.quit
}
// OnWrite is invoked when a peer sends a message and it is used to update
// the bytes sent by the server.
func (sp *ServerPeer) OnWrite(_ *peer.Peer, bytesWritten int, msg wire.Message, err error) {
sp.server.AddBytesSent(uint64(bytesWritten))
}
// Config is a struct detailing the configuration of the chain service.
type Config struct {
// DataDir is the directory that neutrino will store all header
// information within.
DataDir string
// Database is an *open* database instance that we'll use to storm
// indexes of the chain.
Database walletdb.DB
// ChainParams is the chain that we're running on.
ChainParams chaincfg.Params
// ConnectPeers is a slice of hosts that should be connected to on
// startup, and be established as persistent peers.
//
// NOTE: If specified, we'll *only* connect to this set of peers and
// won't attempt to automatically seek outbound peers.
ConnectPeers []string
// AddPeers is a slice of hosts that should be connected to on startup,
// and be maintained as persistent peers.
AddPeers []string
// Dialer is an optional function closure that will be used to
// establish outbound TCP connections. If specified, then the
// connection manager will use this in place of net.Dial for all
// outbound connection attempts.
Dialer func(addr net.Addr) (net.Conn, error)
// NameResolver is an optional function closure that will be used to
// lookup the IP of any host. If specified, then the address manager,
// along with regular outbound connection attempts will use this
// instead.
NameResolver func(host string) ([]net.IP, error)
// FilterCacheSize indicates the size (in bytes) of filters the cache will
// hold in memory at most.
FilterCacheSize uint64
// BlockCache is an LRU block cache. If none is provided then the a new
// one will be instantiated.
BlockCache *lru.Cache[wire.InvVect, *CacheableBlock]
// BlockCacheSize indicates the size (in bytes) of blocks the block
// cache will hold in memory at most. If a BlockCache is provided then
// BlockCacheSize is ignored.
BlockCacheSize uint64
// persistToDisk indicates whether the filter should also be written
// to disk in addition to the memory cache. For "normal" wallets, they'll
// almost never need to re-match a filter once it's been fetched unless
// they're doing something like a key import.
PersistToDisk bool
// AssertFilterHeader is an optional field that allows the creator of
// the ChainService to ensure that if any chain data exists, it's
// compliant with the expected filter header state. If neutrino starts
// up and this filter header state has diverged, then it'll remove the
// current on disk filter headers to sync them anew.
AssertFilterHeader *headerfs.FilterHeader
// BroadcastTimeout is the amount of time we'll wait before giving up on
// a transaction broadcast attempt. Broadcasting transactions consists
// of three steps:
//
// 1. Neutrino sends an inv for the transaction.
// 2. The recipient node determines if the inv is known, and if it's
// not, replies with a getdata message.
// 3. Neutrino sends the raw transaction.
BroadcastTimeout time.Duration
}
// peerSubscription holds a peer subscription which we'll notify about any
// connected peers.
type peerSubscription struct {
peers chan<- query.Peer
cancel <-chan struct{}
}
// ChainService is instantiated with functional options.
type ChainService struct { // nolint:maligned
// The following variables must only be used atomically.
// Putting the uint64s first makes them 64-bit aligned for 32-bit systems.
bytesReceived uint64 // Total bytes received from all peers since start.
bytesSent uint64 // Total bytes sent by all peers since start.
started int32
shutdown int32
FilterDB filterdb.FilterDatabase
BlockHeaders headerfs.BlockHeaderStore
RegFilterHeaders *headerfs.FilterHeaderStore
persistToDisk bool
FilterCache *lru.Cache[FilterCacheKey, *CacheableFilter]
BlockCache *lru.Cache[wire.InvVect, *CacheableBlock]
chainParams chaincfg.Params
addrManager *addrmgr.AddrManager
connManager *connmgr.ConnManager
blockManager *blockManager
blockSubscriptionMgr *blockntfns.SubscriptionManager
newPeers chan *ServerPeer
donePeers chan *ServerPeer
query chan interface{}
firstPeerConnect chan struct{}
peerHeightsUpdate chan updatePeerHeightsMsg
wg sync.WaitGroup
quit chan struct{}
timeSource blockchain.MedianTimeSource
services wire.ServiceFlag
utxoScanner *UtxoScanner
broadcaster *pushtx.Broadcaster
banStore banman.Store
workManager query.WorkManager
filterBatchWriter *chanutils.BatchWriter[*filterdb.FilterData]
// peerSubscribers is a slice of active peer subscriptions, that we
// will notify each time a new peer is connected.
peerSubscribers []*peerSubscription
// TODO: Add a map for more granular exclusion?
mtxCFilter sync.Mutex
userAgentName string
userAgentVersion string
nameResolver func(string) ([]net.IP, error)
dialer func(net.Addr) (net.Conn, error)
broadcastTimeout time.Duration
}
// NewChainService returns a new chain service configured to connect to the
// bitcoin network type specified by chainParams. Use start to begin syncing
// with peers.
func NewChainService(cfg Config) (*ChainService, error) {
// Use the default broadcast timeout if one isn't provided.
if cfg.BroadcastTimeout == 0 {
cfg.BroadcastTimeout = pushtx.DefaultBroadcastTimeout
}
// First, we'll sort out the methods that we'll use to established
// outbound TCP connections, as well as perform any DNS queries.
//
// If the dialler was specified, then we'll use that in place of the
// default net.Dial function.
var (
nameResolver func(string) ([]net.IP, error)
dialer func(net.Addr) (net.Conn, error)
)
if cfg.Dialer != nil {
dialer = cfg.Dialer
} else {
dialer = func(addr net.Addr) (net.Conn, error) {
return net.Dial(addr.Network(), addr.String())
}
}
// Similarly, if the user specified as function to use for name
// resolution, then we'll use that everywhere as well.
if cfg.NameResolver != nil {
nameResolver = cfg.NameResolver
} else {
nameResolver = net.LookupIP
}
// When creating the addr manager, we'll check to see if the user has
// provided their own resolution function. If so, then we'll use that
// instead as this may be proxying requests over an anonymizing
// network.
amgr := addrmgr.New(cfg.DataDir, nameResolver)
s := ChainService{
chainParams: cfg.ChainParams,
addrManager: amgr,
newPeers: make(chan *ServerPeer, MaxPeers),
donePeers: make(chan *ServerPeer, MaxPeers),
query: make(chan interface{}),
quit: make(chan struct{}),
firstPeerConnect: make(chan struct{}),
peerHeightsUpdate: make(chan updatePeerHeightsMsg),
timeSource: blockchain.NewMedianTime(),
services: Services,
userAgentName: UserAgentName,
userAgentVersion: UserAgentVersion,
nameResolver: nameResolver,
dialer: dialer,
persistToDisk: cfg.PersistToDisk,
broadcastTimeout: cfg.BroadcastTimeout,
}
s.workManager = query.NewWorkManager(&query.Config{
ConnectedPeers: s.ConnectedPeers,
NewWorker: query.NewWorker,
Ranking: query.NewPeerRanking(),
})
var err error
s.FilterDB, err = filterdb.New(cfg.Database, cfg.ChainParams)
if err != nil {
return nil, err
}
if s.persistToDisk {
cfg := &chanutils.BatchWriterConfig[*filterdb.FilterData]{
QueueBufferSize: chanutils.DefaultQueueSize,
MaxBatch: 10,
DBWritesTickerDuration: time.Millisecond * 500,
PutItems: s.FilterDB.PutFilters,
}
batchWriter := chanutils.NewBatchWriter[*filterdb.FilterData](
cfg,
)
s.filterBatchWriter = batchWriter
}
filterCacheSize := DefaultFilterCacheSize
if cfg.FilterCacheSize != 0 {
filterCacheSize = cfg.FilterCacheSize
}
s.FilterCache = lru.NewCache[FilterCacheKey, *CacheableFilter](
filterCacheSize,
)
if cfg.BlockCache != nil {
s.BlockCache = cfg.BlockCache
} else {
blockCacheSize := DefaultBlockCacheSize
if cfg.BlockCacheSize != 0 {
blockCacheSize = cfg.BlockCacheSize
}
s.BlockCache = lru.NewCache[wire.InvVect, *CacheableBlock](
blockCacheSize,
)
}
s.BlockHeaders, err = headerfs.NewBlockHeaderStore(
cfg.DataDir, cfg.Database, &cfg.ChainParams,
)
if err != nil {
return nil, err
}
s.RegFilterHeaders, err = headerfs.NewFilterHeaderStore(
cfg.DataDir, cfg.Database, headerfs.RegularFilter,
&cfg.ChainParams, cfg.AssertFilterHeader,
)
if err != nil {
return nil, err
}
bm, err := newBlockManager(&blockManagerCfg{
ChainParams: s.chainParams,
BlockHeaders: s.BlockHeaders,
RegFilterHeaders: s.RegFilterHeaders,
TimeSource: s.timeSource,
QueryDispatcher: s.workManager,
BanPeer: s.BanPeer,
GetBlock: s.GetBlock,
firstPeerSignal: s.firstPeerConnect,
queryAllPeers: s.queryAllPeers,
})
if err != nil {
return nil, err
}
s.blockManager = bm
s.blockSubscriptionMgr = blockntfns.NewSubscriptionManager(s.blockManager)
// Only setup a function to return new addresses to connect to when not
// running in connect-only mode. Private development networks are always in
// connect-only mode since it is only intended to connect to specified peers
// and actively avoid advertising and connecting to discovered peers in
// order to prevent it from becoming a public test network.
var newAddressFunc func() (net.Addr, error)
if !isDevNetwork(s.chainParams.Net) {
newAddressFunc = func() (net.Addr, error) {
// Gather our set of currently connected peers to avoid
// connecting to them again.
connectedPeers := make(map[string]struct{})
for _, peer := range s.Peers() {
peerAddr := addrmgr.NetAddressKey(peer.NA())
connectedPeers[peerAddr] = struct{}{}
}
for tries := 0; tries < 100; tries++ {
select {
case <-s.quit:
return nil, ErrShuttingDown
default:
}
addr := s.addrManager.GetAddress()
if addr == nil {
break
}
// Ignore peers that we've already banned.
addrString := addrmgr.NetAddressKey(addr.NetAddress())
if s.IsBanned(addrString) {
log.Debugf("Ignoring banned peer: %v", addrString)
continue
}
// Skip any addresses that correspond to our set
// of currently connected peers.
if _, ok := connectedPeers[addrString]; ok {
continue
}
// The peer behind this address should support
// all of our required services.
if addr.Services()&RequiredServices != RequiredServices {
continue
}
// Address will not be invalid, local or unroutable
// because addrmanager rejects those on addition.
// Just check that we don't already have an address
// in the same group so that we are not connecting
// to the same network segment at the expense of
// others.
key := addrmgr.GroupKey(addr.NetAddress())
if s.OutboundGroupCount(key) != 0 {
continue
}
// only allow recent nodes (10mins) after we failed 30
// times
if tries < 30 && time.Since(addr.LastAttempt()) < 10*time.Minute {
continue
}
// allow nondefault ports after 50 failed tries.
if tries < 50 && fmt.Sprintf("%d", addr.NetAddress().Port) !=
s.chainParams.DefaultPort {
continue
}
// Mark an attempt for the valid address.
s.addrManager.Attempt(addr.NetAddress())
return s.addrStringToNetAddr(addrString)
}
return nil, errors.New("no valid connect address")
}
}
cmgrCfg := &connmgr.Config{
RetryDuration: ConnectionRetryInterval,
TargetOutbound: uint32(TargetOutbound),
OnConnection: s.outboundPeerConnected,
Dial: dialer,
}
if len(cfg.ConnectPeers) == 0 {
cmgrCfg.GetNewAddress = newAddressFunc
}
// Create a connection manager.
if MaxPeers < TargetOutbound {
TargetOutbound = MaxPeers
}
cmgr, err := connmgr.New(cmgrCfg)
if err != nil {
return nil, err
}
s.connManager = cmgr
s.utxoScanner = NewUtxoScanner(&UtxoScannerConfig{
BestSnapshot: s.BestBlock,
GetBlockHash: s.GetBlockHash,
GetBlock: s.GetBlock,
BlockFilterMatches: func(ro *rescanOptions,
blockHash *chainhash.Hash) (bool, error) {
matches, _, err := blockFilterMatches(
&RescanChainSource{&s}, ro, blockHash,
)
return matches, err
},
})
s.broadcaster = pushtx.NewBroadcaster(&pushtx.Config{
Broadcast: func(tx *wire.MsgTx) error {
return s.sendTransaction(tx)
},
SubscribeBlocks: func() (*blockntfns.Subscription, error) {
return s.blockSubscriptionMgr.NewSubscription(0)
},
RebroadcastInterval: pushtx.DefaultRebroadcastInterval,
})
s.banStore, err = banman.NewStore(cfg.Database)
if err != nil {
return nil, fmt.Errorf("unable to initialize ban store: %v", err)
}
// Start up persistent peers.
permanentPeers := cfg.ConnectPeers
if len(permanentPeers) == 0 {
permanentPeers = cfg.AddPeers
}
for _, addr := range permanentPeers {
addr := addr
s.wg.Add(1)
go func() {
defer s.wg.Done()
// Since netwok access might not be established yet, we
// loop until we are able to look up the permanent
// peer.
var tcpAddr net.Addr
for {
var err error
tcpAddr, err = s.addrStringToNetAddr(addr)
if err != nil {
log.Warnf("unable to lookup IP for "+
"%v: %v", addr, err)
select {
// Try again in 5 seconds.
case <-time.After(ConnectionRetryInterval):
case <-s.quit:
return
}
continue
}
break
}
s.connManager.Connect(&connmgr.ConnReq{
Addr: tcpAddr,
Permanent: true,
})
}()
}
return &s, nil
}
// BestBlock retrieves the most recent block's height and hash where we
// have both the header and filter header ready.
func (s *ChainService) BestBlock() (*headerfs.BlockStamp, error) {
bestHeader, bestHeight, err := s.BlockHeaders.ChainTip()
if err != nil {
return nil, err