forked from lightninglabs/neutrino
-
Notifications
You must be signed in to change notification settings - Fork 1
/
neutrino.go
1561 lines (1349 loc) · 47.6 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"
"sync"
"sync/atomic"
"time"
"github.com/BTCGPU/neutrino/banman"
"github.com/BTCGPU/neutrino/blockntfns"
"github.com/BTCGPU/neutrino/cache/lru"
"github.com/BTCGPU/neutrino/filterdb"
"github.com/BTCGPU/neutrino/headerfs"
"github.com/BTCGPU/neutrino/pushtx"
"github.com/btgsuite/btgd/addrmgr"
"github.com/btgsuite/btgd/blockchain"
"github.com/btgsuite/btgd/chaincfg"
"github.com/btgsuite/btgd/chaincfg/chainhash"
"github.com/btgsuite/btgd/connmgr"
"github.com/btgsuite/btgd/peer"
"github.com/btgsuite/btgd/wire"
btcutil "github.com/btgsuite/btgutil"
"github.com/btgsuite/btgwallet/walletdb"
)
// 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.0.4-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 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
)
// 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{}
}
// 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
continueHash *chainhash.Hash
requestQueue []*wire.InvVect
knownAddresses map[string]struct{}
banScore connmgr.DynamicBanScore
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.
recvSubscribers map[spMsgSubscription]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: make(map[string]struct{}),
quit: make(chan struct{}),
recvSubscribers: make(map[spMsgSubscription]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.NetAddress) {
for _, na := range addresses {
sp.knownAddresses[addrmgr.NetAddressKey(na)] = struct{}{}
}
}
// addressKnown true if the given address is already known to the peer.
func (sp *ServerPeer) addressKnown(na *wire.NetAddress) bool {
_, exists := sp.knownAddresses[addrmgr.NetAddressKey(na)]
return exists
}
// addBanScore increases the persistent and decaying ban score fields by the
// values passed as parameters. If the resulting score exceeds half of the ban
// threshold, a warning is logged including the reason provided. Further, if
// the score is above the ban threshold, the peer will be banned and
// disconnected.
func (sp *ServerPeer) addBanScore(persistent, transient uint32, reason string) {
// No warning is logged and no score is calculated if banning is
// disabled.
warnThreshold := BanThreshold >> 1
if transient == 0 && persistent == 0 {
// The score is not being increased, but a warning message is
// still logged if the score is above the warn threshold.
score := sp.banScore.Int()
if score > warnThreshold {
log.Warnf("Misbehaving peer %s: %s -- ban score is "+
"%d, it was not increased this time", sp,
reason, score)
}
return
}
score := sp.banScore.Increase(persistent, transient)
if score > warnThreshold {
log.Warnf("Misbehaving peer %s: %s -- ban score increased to %d",
sp, reason, score)
if score > BanThreshold {
peerAddr := sp.Addr()
err := sp.server.BanPeer(
peerAddr, banman.ExceededBanThreshold,
)
if err != nil {
log.Errorf("Unable to ban peer %v: %v",
peerAddr, err)
}
}
}
}
// pushSendHeadersMsg sends a sendheaders message to the connected peer.
func (sp *ServerPeer) pushSendHeadersMsg() error {
if sp.VersionKnown() {
if sp.ProtocolVersion() > wire.SendHeadersVersion {
sp.QueueMessage(wire.NewMsgSendHeaders(), nil)
}
}
return nil
}
// OnVerAck is invoked when a peer receives a verack bitcoin message and is used
// to send the "sendheaders" command to peers that are of a sufficienty new
// protocol version.
func (sp *ServerPeer) OnVerAck(_ *peer.Peer, msg *wire.MsgVerAck) {
sp.pushSendHeadersMsg()
}
// 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
}
// Signal the block manager this peer is a new sync candidate.
sp.server.blockManager.NewPeer(sp)
// Update the address manager and request known addresses from the
// remote peer for outbound connections. This 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.server.chainParams.Net != chaincfg.SimNetParams.Net {
addrManager := sp.server.addrManager
// Request known addresses if the server address manager needs
// more and the peer has a protocol version new enough to
// include a timestamp with addresses.
hasTimestamp := sp.ProtocolVersion() >=
wire.NetAddressTimeVersion
if addrManager.NeedMoreAddresses() && hasTimestamp {
sp.QueueMessage(wire.NewMsgGetAddr(), nil)
}
// Add the address to the addr manager anew, and also mark it
// as a good address.
sp.server.addrManager.AddAddresses(
[]*wire.NetAddress{sp.NA()}, sp.NA(),
)
addrManager.Good(sp.NA())
// 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)
}
}
// Add valid peer to the server.
sp.server.AddPeer(sp)
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 the simulation test 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 sp.server.chainParams.Net == chaincfg.SimNetParams.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
}
var addrsSupportingServices []*wire.NetAddress
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 24 hours
// 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)
}
addrsSupportingServices = append(addrsSupportingServices, na)
}
// Ignore any addr messages if none of them contained our required
// services.
if len(addrsSupportingServices) == 0 {
return
}
// Add address to known addresses for this peer.
sp.addKnownAddresses(addrsSupportingServices)
// 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(addrsSupportingServices, 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)
}
}
// 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)
}
// 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 teh 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
// BlockCacheSize indicates the size (in bytes) of blocks the block
// cache will hold in memory at most.
BlockCacheSize uint64
// 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
}
// ChainService is instantiated with functional options
type ChainService struct {
// 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
FilterCache *lru.Cache
BlockCache *lru.Cache
// queryPeers will be called to send messages to one or more peers,
// expecting a response.
queryPeers func(wire.Message, func(*ServerPeer, wire.Message,
chan<- struct{}), ...QueryOption)
// queryBatch will be called to distribute a batch of messages across
// our connected peers.
queryBatch func([]wire.Message, func(*ServerPeer, wire.Message,
wire.Message) bool, <-chan struct{}, ...QueryOption)
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
// 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)
}
// 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) {
// 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,
}
// We set the queryPeers method to point to queryChainServicePeers,
// passing a reference to the newly created ChainService.
s.queryPeers = func(msg wire.Message, f func(*ServerPeer,
wire.Message, chan<- struct{}), qo ...QueryOption) {
queryChainServicePeers(&s, msg, f, qo...)
}
// We do the same for queryBatch.
s.queryBatch = func(msgs []wire.Message, f func(*ServerPeer,
wire.Message, wire.Message) bool, q <-chan struct{},
qo ...QueryOption) {
queryChainServiceBatch(&s, msgs, f, q, qo...)
}
var err error
s.FilterDB, err = filterdb.New(cfg.Database, cfg.ChainParams)
if err != nil {
return nil, err
}
filterCacheSize := DefaultFilterCacheSize
if cfg.FilterCacheSize != 0 {
filterCacheSize = cfg.FilterCacheSize
}
s.FilterCache = lru.NewCache(filterCacheSize)
blockCacheSize := DefaultBlockCacheSize
if cfg.BlockCacheSize != 0 {
blockCacheSize = cfg.BlockCacheSize
}
s.BlockCache = lru.NewCache(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(&s, s.firstPeerConnect)
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. The simulation network is 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 s.chainParams.Net != chaincfg.SimNetParams.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
// Start up persistent peers.
permanentPeers := cfg.ConnectPeers
if len(permanentPeers) == 0 {
permanentPeers = cfg.AddPeers
}
for _, addr := range permanentPeers {
tcpAddr, err := s.addrStringToNetAddr(addr)
if err != nil {
return nil, err
}
go s.connManager.Connect(&connmgr.ConnReq{
Addr: tcpAddr,
Permanent: true,
})
}
s.utxoScanner = NewUtxoScanner(&UtxoScannerConfig{
BestSnapshot: s.BestBlock,
GetBlockHash: s.GetBlockHash,
GetBlock: s.GetBlock,
BlockFilterMatches: func(ro *rescanOptions,
blockHash *chainhash.Hash) (bool, error) {
return blockFilterMatches(
&RescanChainSource{&s}, ro, blockHash,
)
},
})
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)
}
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
}
_, filterHeight, err := s.RegFilterHeaders.ChainTip()
if err != nil {
return nil, err
}
// Filter headers might lag behind block headers, so we can can fetch a
// previous block header if the filter headers are not caught up.
if filterHeight < bestHeight {
bestHeight = filterHeight
bestHeader, err = s.BlockHeaders.FetchHeaderByHeight(
bestHeight,
)
if err != nil {
return nil, err
}
}
return &headerfs.BlockStamp{
Height: int32(bestHeight),
Hash: bestHeader.BlockHash(),
}, nil
}
// GetBlockHash returns the block hash at the given height.
func (s *ChainService) GetBlockHash(height int64) (*chainhash.Hash, error) {
header, err := s.BlockHeaders.FetchHeaderByHeight(uint32(height))
if err != nil {
return nil, err
}
hash := header.BlockHash()
return &hash, err
}
// GetBlockHeader returns the block header for the given block hash, or an
// error if the hash doesn't exist or is unknown.
func (s *ChainService) GetBlockHeader(
blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
header, _, err := s.BlockHeaders.FetchHeader(blockHash)
return header, err
}
// GetBlockHeight gets the height of a block by its hash. An error is returned
// if the given block hash is unknown.
func (s *ChainService) GetBlockHeight(hash *chainhash.Hash) (int32, error) {
_, height, err := s.BlockHeaders.FetchHeader(hash)
if err != nil {
return 0, err
}
return int32(height), nil
}
// BanPeer disconnects and bans a peer due to a specific reason for a duration
// of BanDuration.
func (s *ChainService) BanPeer(addr string, reason banman.Reason) error {
log.Warnf("Banning peer %v: duration=%v, reason=%v", addr, BanDuration,
reason)
// We'll want to disconnect the peer after we return regardless of
// whether we ban the peer or not. We do this to prevent a possible race
// condition where we end up reconnecting with the peer slightly
// before the ban succeeds.
defer func() {
// We do so in a goroutine to prevent blocking if the server is
// handling a query or a new/stale peer.
go func() {
if sp := s.PeerByAddr(addr); sp != nil {
sp.Disconnect()
}
}()
}()
ipNet, err := banman.ParseIPNet(addr, nil)
if err != nil {
return fmt.Errorf("unable to parse IP network for peer %v: %v",
addr, err)
}
return s.banStore.BanIPNet(ipNet, reason, BanDuration)
}
// IsBanned returns true if the peer is banned, and false otherwise.
func (s *ChainService) IsBanned(addr string) bool {
ipNet, err := banman.ParseIPNet(addr, nil)
if err != nil {
log.Errorf("Unable to parse IP network for peer %v: %v", addr,
err)
return false
}
banStatus, err := s.banStore.Status(ipNet)
if err != nil {
log.Errorf("Unable to determine ban status for peer %v: %v",
addr, err)
return false
}
// Log how much time left the peer will remain banned for, if any.
if time.Now().Before(banStatus.Expiration) {
log.Debugf("Peer %v is banned for another %v", addr,
banStatus.Expiration.Sub(time.Now()))
}
return banStatus.Banned
}
// AddPeer adds a new peer that has already been connected to the server.
func (s *ChainService) AddPeer(sp *ServerPeer) {
select {
case s.newPeers <- sp:
case <-s.quit:
return
}
}
// AddBytesSent adds the passed number of bytes to the total bytes sent counter
// for the server. It is safe for concurrent access.
func (s *ChainService) AddBytesSent(bytesSent uint64) {
atomic.AddUint64(&s.bytesSent, bytesSent)
}
// AddBytesReceived adds the passed number of bytes to the total bytes received
// counter for the server. It is safe for concurrent access.
func (s *ChainService) AddBytesReceived(bytesReceived uint64) {
atomic.AddUint64(&s.bytesReceived, bytesReceived)
}
// NetTotals returns the sum of all bytes received and sent across the network
// for all peers. It is safe for concurrent access.
func (s *ChainService) NetTotals() (uint64, uint64) {
return atomic.LoadUint64(&s.bytesReceived),