-
Notifications
You must be signed in to change notification settings - Fork 0
/
neutrino.go
1307 lines (1137 loc) · 40.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/bcext/cashutil"
"github.com/bcext/cashwallet/waddrmgr"
"github.com/bcext/cashwallet/walletdb"
"github.com/bcext/gcash/addrmgr"
"github.com/bcext/gcash/blockchain"
"github.com/bcext/gcash/chaincfg"
"github.com/bcext/gcash/chaincfg/chainhash"
"github.com/bcext/gcash/connmgr"
"github.com/bcext/gcash/peer"
"github.com/bcext/gcash/wire"
"github.com/bcext/neutrino/cache/lru"
"github.com/bcext/neutrino/filterdb"
"github.com/bcext/neutrino/headerfs"
)
// 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"
// RequiredServices describes the services that are required to be
// supported by outbound peers.
RequiredServices = wire.SFNodeNetwork
// 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.
DefaultFilterCacheSize uint64 = 4096 * 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
banned map[string]time.Time
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 {
log.Warnf("Misbehaving peer %s -- banning and disconnecting",
sp)
sp.server.BanPeer(sp)
sp.Disconnect()
}
}
}
// 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)
// 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)
}
// Mark the address as a known good address.
addrManager.Good(sp.NA())
}
// Add valid peer to the server.
sp.server.AddPeer(sp)
// TODO(qshuai): sync the code with lightninglabs/neutrino(no return)
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 > cashutil.MaxSatoshi {
log.Debugf("Peer %v sent an invalid feefilter '%v' -- "+
"disconnecting", sp, cashutil.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
}
for _, na := range msg.AddrList {
// Don't add more address if we're disconnecting.
if !sp.Connected() {
return
}
// 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)
}
// Add address to known addresses for this peer.
sp.addKnownAddresses([]*wire.NetAddress{na})
}
// 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(msg.AddrList, 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
}
// 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
newPeers chan *ServerPeer
donePeers chan *ServerPeer
banPeers chan *ServerPeer
query chan interface{}
peerHeightsUpdate chan updatePeerHeightsMsg
wg sync.WaitGroup
quit chan struct{}
timeSource blockchain.MedianTimeSource
blockSubscribers map[*blockSubscription]struct{}
mtxSubscribers sync.RWMutex
utxoScanner *UtxoScanner
// TODO: Add a map for more granular exclusion?
mtxCFilter sync.Mutex
// These are only necessary until the block subscription logic is
// refactored out into its own package and we can have different message
// types sent in the notifications.
//
// TODO(aakselrod): Get rid of this when doing the refactoring above.
reorgedBlockHeaders map[chainhash.Hash]*wire.BlockHeader
mtxReorgHeader sync.RWMutex
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),
banPeers: make(chan *ServerPeer, MaxPeers),
query: make(chan interface{}),
quit: make(chan struct{}),
peerHeightsUpdate: make(chan updatePeerHeightsMsg),
timeSource: blockchain.NewMedianTime(),
userAgentName: UserAgentName,
userAgentVersion: UserAgentVersion,
blockSubscribers: make(map[*blockSubscription]struct{}),
reorgedBlockHeaders: make(map[chainhash.Hash]*wire.BlockHeader),
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,
)
if err != nil {
return nil, err
}
bm, err := newBlockManager(&s)
if err != nil {
return nil, err
}
s.blockManager = bm
// 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) {
for tries := 0; tries < 100; tries++ {
addr := s.addrManager.GetAddress()
if addr == nil {
break
}
// 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
}
addrString := addrmgr.NetAddressKey(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,
BlockFilterMatches: s.blockFilterMatches,
GetBlock: s.GetBlock,
})
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() (*waddrmgr.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 &waddrmgr.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 bans a peer that has already been connected to the server by ip.
func (s *ChainService) BanPeer(sp *ServerPeer) {
s.banPeers <- sp
}
// AddPeer adds a new peer that has already been connected to the server.
func (s *ChainService) AddPeer(sp *ServerPeer) {
s.newPeers <- sp
}
// 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),
atomic.LoadUint64(&s.bytesSent)
}
// rollBackToHeight rolls back all blocks until it hits the specified height.
// It sends notifications along the way.
func (s *ChainService) rollBackToHeight(height uint32) (*waddrmgr.BlockStamp, error) {
header, headerHeight, err := s.BlockHeaders.ChainTip()
if err != nil {
return nil, err
}
bs := &waddrmgr.BlockStamp{
Height: int32(headerHeight),
Hash: header.BlockHash(),
}
_, regHeight, err := s.RegFilterHeaders.ChainTip()
if err != nil {
return nil, err
}
for uint32(bs.Height) > height {
header, _, err := s.BlockHeaders.FetchHeader(&bs.Hash)
if err != nil {
return nil, err
}
newTip := &header.PrevBlock
// Only roll back filter headers if they've caught up this far.
if uint32(bs.Height) <= regHeight {
newFilterTip, err := s.RegFilterHeaders.RollbackLastBlock(newTip)
if err != nil {
return nil, err
}
regHeight = uint32(newFilterTip.Height)
}
bs, err = s.BlockHeaders.RollbackLastBlock()
if err != nil {
return nil, err
}
// Notifications are asynchronous, so we include the previous
// header in the disconnected notification in case we're rolling
// back farther and the notification subscriber needs it but
// can't read it before it's deleted from the store.
//
// TODO(aakselrod): Get rid of this when subscriptions are
// factored out into their own package.
lastHeader, _, err := s.BlockHeaders.FetchHeader(newTip)
if err != nil {
return nil, err
}
s.mtxReorgHeader.Lock()
s.reorgedBlockHeaders[header.PrevBlock] = lastHeader
s.mtxReorgHeader.Unlock()
// Now we send the block disconnected notifications.
s.sendSubscribedMsg(&blockMessage{
msgType: disconnect,
header: header,
})
}
return bs, nil
}
// peerHandler is used to handle peer operations such as adding and removing
// peers to and from the server, banning peers, and broadcasting messages to
// peers. It must be run in a goroutine.
func (s *ChainService) peerHandler() {
// Start the address manager and block manager, both of which are
// needed by peers. This is done here since their lifecycle is closely
// tied to this handler and rather than adding more channels to
// synchronize things, it's easier and slightly faster to simply start
// and stop them in this handler.
s.addrManager.Start()
s.blockManager.Start()
s.utxoScanner.Start()
state := &peerState{
persistentPeers: make(map[int32]*ServerPeer),
outboundPeers: make(map[int32]*ServerPeer),
banned: make(map[string]time.Time),
outboundGroups: make(map[string]int),
}
if !DisableDNSSeed {
// Add peers discovered through DNS to the address manager.
connmgr.SeedFromDNS(&s.chainParams, RequiredServices,
s.nameResolver, func(addrs []*wire.NetAddress) {
// Bitcoind uses a lookup of the dns seeder
// here. This is rather strange since the
// values looked up by the DNS seed lookups
// will vary quite a lot. to replicate this
// behaviour we put all addresses as having
// come from the first one.
s.addrManager.AddAddresses(addrs, addrs[0])
})
}
go s.connManager.Start()
out:
for {
select {
// New peers connected to the server.
case p := <-s.newPeers:
s.handleAddPeerMsg(state, p)
// Disconnected peers.
case p := <-s.donePeers:
s.handleDonePeerMsg(state, p)
// Block accepted in mainchain or orphan, update peer height.
case umsg := <-s.peerHeightsUpdate:
s.handleUpdatePeerHeights(state, umsg)
// Peer to ban.
case p := <-s.banPeers:
s.handleBanPeerMsg(state, p)
case qmsg := <-s.query:
s.handleQuery(state, qmsg)
case <-s.quit:
// Disconnect all peers on server shutdown.
state.forAllPeers(func(sp *ServerPeer) {
log.Tracef("Shutdown peer %s", sp)
sp.Disconnect()
})
break out
}
}
s.connManager.Stop()
s.utxoScanner.Stop()
s.blockManager.Stop()
s.addrManager.Stop()
// Drain channels before exiting so nothing is left waiting around
// to send.
cleanup:
for {
select {
case <-s.newPeers:
case <-s.donePeers:
case <-s.banPeers:
case <-s.peerHeightsUpdate:
case <-s.query:
default:
break cleanup
}
}
s.wg.Done()
log.Tracef("Peer handler done")
}
// addrStringToNetAddr takes an address in the form of 'host:port' or 'host'
// and returns a net.Addr which maps to the original address with any host
// names resolved to IP addresses and a default port added, if not specified,
// from the ChainService's network parameters.
func (s *ChainService) addrStringToNetAddr(addr string) (net.Addr, error) {
host, strPort, err := net.SplitHostPort(addr)
if err != nil {
switch err.(type) {
case *net.AddrError:
host = addr
strPort = s.ChainParams().DefaultPort
default:
return nil, err
}
}
// Attempt to look up an IP address associated with the parsed host.
ips, err := s.nameResolver(host)