forked from gcash/bchd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer.go
2403 lines (2054 loc) · 71.2 KB
/
peer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2013-2018 The btcsuite developers
// Copyright (c) 2016-2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package peer
import (
"bytes"
"container/list"
"errors"
"fmt"
"io"
"math/rand"
"net"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/go-socks/socks"
"github.com/davecgh/go-spew/spew"
"github.com/gcash/bchd/blockchain"
"github.com/gcash/bchd/chaincfg"
"github.com/gcash/bchd/chaincfg/chainhash"
"github.com/gcash/bchd/wire"
)
const (
// MaxProtocolVersion is the max protocol version the peer supports.
MaxProtocolVersion = wire.NoValidationRelayVersion
// DefaultTrickleInterval is the min time between attempts to send an
// inv message to a peer.
DefaultTrickleInterval = 50 * time.Millisecond
// MinAcceptableProtocolVersion is the lowest protocol version that a
// connected peer may support.
MinAcceptableProtocolVersion = wire.MultipleAddressVersion
// DefaultMaxKnownInventory is the maximum number of items to keep in the known
// inventory cache.
DefaultMaxKnownInventory = 2000
// outputBufferSize is the number of elements the output channels use.
outputBufferSize = 50
// invTrickleSize is the maximum amount of inventory to send in a single
// message when trickling inventory to remote peers.
maxInvTrickleSize = 5000
// pingInterval is the interval of time to wait in between sending ping
// messages.
pingInterval = 2 * time.Minute
// negotiateTimeout is the duration of inactivity before we timeout a
// peer that hasn't completed the initial version negotiation.
negotiateTimeout = 30 * time.Second
// idleTimeout is the duration of inactivity before we time out a peer.
idleTimeout = 5 * time.Minute
// stallTickInterval is the interval of time between each check for
// stalled peers.
stallTickInterval = 15 * time.Second
// stallResponseTimeout is the base maximum amount of time messages that
// expect a response will wait before disconnecting the peer for
// stalling. The deadlines are adjusted for callback running times and
// only checked on each stall tick interval.
stallResponseTimeout = 30 * time.Second
)
var (
// nodeCount is the total number of peer connections made since startup
// and is used to assign an id to a peer.
nodeCount int32
// zeroHash is the zero value hash (all zeros). It is defined as a
// convenience.
zeroHash chainhash.Hash
// sentNonces houses the unique nonces that are generated when pushing
// version messages that are used to detect self connections.
sentNonces = newMruNonceMap(50)
)
// MessageListeners defines callback function pointers to invoke with message
// listeners for a peer. Any listener which is not set to a concrete callback
// during peer initialization is ignored. Execution of multiple message
// listeners occurs serially, so one callback blocks the execution of the next.
//
// NOTE: Unless otherwise documented, these listeners must NOT directly call any
// blocking calls (such as WaitForShutdown) on the peer instance since the input
// handler goroutine blocks until the callback has completed. Doing so will
// result in a deadlock.
type MessageListeners struct {
// OnGetAddr is invoked when a peer receives a getaddr bitcoin message.
OnGetAddr func(p *Peer, msg *wire.MsgGetAddr)
// OnAddr is invoked when a peer receives an addr bitcoin message.
OnAddr func(p *Peer, msg *wire.MsgAddr)
// OnPing is invoked when a peer receives a ping bitcoin message.
OnPing func(p *Peer, msg *wire.MsgPing)
// OnPong is invoked when a peer receives a pong bitcoin message.
OnPong func(p *Peer, msg *wire.MsgPong)
// OnMemPool is invoked when a peer receives a mempool bitcoin message.
OnMemPool func(p *Peer, msg *wire.MsgMemPool)
// OnTx is invoked when a peer receives a tx bitcoin message.
OnTx func(p *Peer, msg *wire.MsgTx)
// OnBlock is invoked when a peer receives a block bitcoin message.
OnBlock func(p *Peer, msg *wire.MsgBlock, buf []byte)
// OnCFilter is invoked when a peer receives a cfilter bitcoin message.
OnCFilter func(p *Peer, msg *wire.MsgCFilter)
// OnCFHeaders is invoked when a peer receives a cfheaders bitcoin
// message.
OnCFHeaders func(p *Peer, msg *wire.MsgCFHeaders)
// OnCFCheckpt is invoked when a peer receives a cfcheckpt bitcoin
// message.
OnCFCheckpt func(p *Peer, msg *wire.MsgCFCheckpt)
// OnInv is invoked when a peer receives an inv bitcoin message.
OnInv func(p *Peer, msg *wire.MsgInv)
// OnHeaders is invoked when a peer receives a headers bitcoin message.
OnHeaders func(p *Peer, msg *wire.MsgHeaders)
// OnNotFound is invoked when a peer receives a notfound bitcoin
// message.
OnNotFound func(p *Peer, msg *wire.MsgNotFound)
// OnGetData is invoked when a peer receives a getdata bitcoin message.
OnGetData func(p *Peer, msg *wire.MsgGetData)
// OnGetBlocks is invoked when a peer receives a getblocks bitcoin
// message.
OnGetBlocks func(p *Peer, msg *wire.MsgGetBlocks)
// OnGetHeaders is invoked when a peer receives a getheaders bitcoin
// message.
OnGetHeaders func(p *Peer, msg *wire.MsgGetHeaders)
// OnGetCFilters is invoked when a peer receives a getcfilters bitcoin
// message.
OnGetCFilters func(p *Peer, msg *wire.MsgGetCFilters)
// OnGetCFHeaders is invoked when a peer receives a getcfheaders
// bitcoin message.
OnGetCFHeaders func(p *Peer, msg *wire.MsgGetCFHeaders)
// OnGetCFCheckpt is invoked when a peer receives a getcfcheckpt
// bitcoin message.
OnGetCFCheckpt func(p *Peer, msg *wire.MsgGetCFCheckpt)
// OnGetCFMempool is invoked when a peer receives a getcfmempool
// bitcoin message.
OnGetCFMempool func(p *Peer, msg *wire.MsgGetCFMempool)
// OnFeeFilter is invoked when a peer receives a feefilter bitcoin message.
OnFeeFilter func(p *Peer, msg *wire.MsgFeeFilter)
// OnFilterAdd is invoked when a peer receives a filteradd bitcoin message.
OnFilterAdd func(p *Peer, msg *wire.MsgFilterAdd)
// OnFilterClear is invoked when a peer receives a filterclear bitcoin
// message.
OnFilterClear func(p *Peer, msg *wire.MsgFilterClear)
// OnFilterLoad is invoked when a peer receives a filterload bitcoin
// message.
OnFilterLoad func(p *Peer, msg *wire.MsgFilterLoad)
// OnMerkleBlock is invoked when a peer receives a merkleblock bitcoin
// message.
OnMerkleBlock func(p *Peer, msg *wire.MsgMerkleBlock)
// OnVersion is invoked when a peer receives a version bitcoin message.
// The caller may return a reject message in which case the message will
// be sent to the peer and the peer will be disconnected.
OnVersion func(p *Peer, msg *wire.MsgVersion) *wire.MsgReject
// OnXVersion is invoked when a peer receives an xversion bitcoin message.
OnXVersion func(p *Peer, msg *wire.MsgXVersion)
// OnVerAck is invoked when a peer receives a verack bitcoin message.
OnVerAck func(p *Peer, msg *wire.MsgVerAck)
// OnReject is invoked when a peer receives a reject bitcoin message.
OnReject func(p *Peer, msg *wire.MsgReject)
// OnSendHeaders is invoked when a peer receives a sendheaders bitcoin
// message.
OnSendHeaders func(p *Peer, msg *wire.MsgSendHeaders)
// OnSendCmpct is invoked when a peer receives a sendcmpct bitcoin
// message.
OnSendCmpct func(p *Peer, msg *wire.MsgSendCmpct)
// OnCmpctBlock is invoked when a peer receives a cmpctblock bitcoin
// message.
OnCmpctBlock func(p *Peer, msg *wire.MsgCmpctBlock)
// OnGetBlockTxns is invoked when a peer receives a getblocktxn bitcoin
// message.
OnGetBlockTxns func(p *Peer, msg *wire.MsgGetBlockTxns)
// OnBlockTxns is invoked when a peer receives a blocktxns bitcoin
// message.
OnBlockTxns func(p *Peer, msg *wire.MsgBlockTxns)
// OnRead is invoked when a peer receives a bitcoin message. It
// consists of the number of bytes read, the message, and whether or not
// an error in the read occurred. Typically, callers will opt to use
// the callbacks for the specific message types, however this can be
// useful for circumstances such as keeping track of server-wide byte
// counts or working with custom message types for which the peer does
// not directly provide a callback.
OnRead func(p *Peer, bytesRead int, msg wire.Message, err error)
// OnWrite is invoked when we write a bitcoin message to a peer. It
// consists of the number of bytes written, the message, and whether or
// not an error in the write occurred. This can be useful for
// circumstances such as keeping track of server-wide byte counts.
OnWrite func(p *Peer, bytesWritten int, msg wire.Message, err error)
}
// Config is the struct to hold configuration options useful to Peer.
type Config struct {
// AddrMe specifies the server address to send peers. This is only
// set when an external IP is used.
AddrMe *wire.NetAddress
// NewestBlock specifies a callback which provides the newest block
// details to the peer as needed. This can be nil in which case the
// peer will report a block height of 0, however it is good practice for
// peers to specify this so their currently best known is accurately
// reported.
NewestBlock HashFunc
// HostToNetAddress returns the netaddress for the given host. This can be
// nil in which case the host will be parsed as an IP address.
HostToNetAddress HostToNetAddrFunc
// Proxy indicates a proxy is being used for connections. The only
// effect this has is to prevent leaking the tor proxy address, so it
// only needs to specified if using a tor proxy.
Proxy string
// UserAgentName specifies the user agent name to advertise. It is
// highly recommended to specify this value.
UserAgentName string
// UserAgentVersion specifies the user agent version to advertise. It
// is highly recommended to specify this value and that it follows the
// form "major.minor.revision" e.g. "2.6.41".
UserAgentVersion string
// UserAgentComments specify the user agent comments to advertise. These
// values must not contain the illegal characters specified in BIP 14:
// '/', ':', '(', ')'.
UserAgentComments []string
// ChainParams identifies which chain parameters the peer is associated
// with. It is highly recommended to specify this field, however it can
// be omitted in which case the test network will be used.
ChainParams *chaincfg.Params
// Services specifies which services to advertise as supported by the
// local peer. This field can be omitted in which case it will be 0
// and therefore advertise no supported services.
Services wire.ServiceFlag
// ProtocolVersion specifies the maximum protocol version to use and
// advertise. This field can be omitted in which case
// peer.MaxProtocolVersion will be used.
ProtocolVersion uint32
// DisableRelayTx specifies if the remote peer should be informed to
// not send inv messages for transactions.
DisableRelayTx bool
// Listeners houses callback functions to be invoked on receiving peer
// messages.
Listeners MessageListeners
// TrickleInterval is the duration of the ticker which trickles down the
// inventory to a peer.
TrickleInterval time.Duration
// TstAllowSelfConnection is only used to allow the tests to bypass the self
// connection detecting and disconnect logic since they intentionally
// do so for testing purposes.
TstAllowSelfConnection bool
// MaxKnownInventory is the maximum number of known inventory items we will hold
// in memory for this peer.
MaxKnownInventory uint
}
// minUint32 is a helper function to return the minimum of two uint32s.
// This avoids a math import and the need to cast to floats.
func minUint32(a, b uint32) uint32 {
if a < b {
return a
}
return b
}
// newNetAddress attempts to extract the IP address and port from the passed
// net.Addr interface and create a bitcoin NetAddress structure using that
// information.
func newNetAddress(addr net.Addr, services wire.ServiceFlag) (*wire.NetAddress, error) {
// addr will be a net.TCPAddr when not using a proxy.
if tcpAddr, ok := addr.(*net.TCPAddr); ok {
ip := tcpAddr.IP
port := uint16(tcpAddr.Port)
na := wire.NewNetAddressIPPort(ip, port, services)
return na, nil
}
// addr will be a socks.ProxiedAddr when using a proxy.
if proxiedAddr, ok := addr.(*socks.ProxiedAddr); ok {
ip := net.ParseIP(proxiedAddr.Host)
if ip == nil {
ip = net.ParseIP("0.0.0.0")
}
port := uint16(proxiedAddr.Port)
na := wire.NewNetAddressIPPort(ip, port, services)
return na, nil
}
// For the most part, addr should be one of the two above cases, but
// to be safe, fall back to trying to parse the information from the
// address string as a last resort.
host, portStr, err := net.SplitHostPort(addr.String())
if err != nil {
return nil, err
}
ip := net.ParseIP(host)
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, err
}
na := wire.NewNetAddressIPPort(ip, uint16(port), services)
return na, nil
}
// outMsg is used to house a message to be sent along with a channel to signal
// when the message has been sent (or won't be sent due to things such as
// shutdown)
type outMsg struct {
msg wire.Message
doneChan chan<- struct{}
encoding wire.MessageEncoding
}
// stallControlCmd represents the command of a stall control message.
type stallControlCmd uint8
// Constants for the command of a stall control message.
const (
// sccSendMessage indicates a message is being sent to the remote peer.
sccSendMessage stallControlCmd = iota
// sccReceiveMessage indicates a message has been received from the
// remote peer.
sccReceiveMessage
// sccHandlerStart indicates a callback handler is about to be invoked.
sccHandlerStart
// sccHandlerStart indicates a callback handler has completed.
sccHandlerDone
)
// stallControlMsg is used to signal the stall handler about specific events
// so it can properly detect and handle stalled remote peers.
type stallControlMsg struct {
command stallControlCmd
message wire.Message
}
// StatsSnap is a snapshot of peer stats at a point in time.
type StatsSnap struct {
ID int32
Addr string
Services wire.ServiceFlag
LastSend time.Time
LastRecv time.Time
BytesSent uint64
BytesRecv uint64
ConnTime time.Time
TimeOffset int64
Version uint32
UserAgent string
Inbound bool
StartingHeight int32
LastBlock int32
LastPingNonce uint64
LastPingTime time.Time
LastPingMicros int64
SyncPeer bool
}
// HashFunc is a function which returns a block hash, height and error
// It is used as a callback to get newest block details.
type HashFunc func() (hash *chainhash.Hash, height int32, err error)
// AddrFunc is a func which takes an address and returns a related address.
type AddrFunc func(remoteAddr *wire.NetAddress) *wire.NetAddress
// HostToNetAddrFunc is a func which takes a host, port, services and returns
// the netaddress.
type HostToNetAddrFunc func(host string, port uint16,
services wire.ServiceFlag) (*wire.NetAddress, error)
// NOTE: The overall data flow of a peer is split into 3 goroutines. Inbound
// messages are read via the inHandler goroutine and generally dispatched to
// their own handler. For inbound data-related messages such as blocks,
// transactions, and inventory, the data is handled by the corresponding
// message handlers. The data flow for outbound messages is split into 2
// goroutines, queueHandler and outHandler. The first, queueHandler, is used
// as a way for external entities to queue messages, by way of the QueueMessage
// function, quickly regardless of whether the peer is currently sending or not.
// It acts as the traffic cop between the external world and the actual
// goroutine which writes to the network socket.
// Peer provides a basic concurrent safe bitcoin peer for handling bitcoin
// communications via the peer-to-peer protocol. It provides full duplex
// reading and writing, automatic handling of the initial handshake process,
// querying of usage statistics and other information about the remote peer such
// as its address, user agent, and protocol version, output message queuing,
// inventory trickling, and the ability to dynamically register and unregister
// callbacks for handling bitcoin protocol messages.
//
// Outbound messages are typically queued via QueueMessage or QueueInventory.
// QueueMessage is intended for all messages, including responses to data such
// as blocks and transactions. QueueInventory, on the other hand, is only
// intended for relaying inventory as it employs a trickling mechanism to batch
// the inventory together. However, some helper functions for pushing messages
// of specific types that typically require common special handling are
// provided as a convenience.
type Peer struct {
// The following variables must only be used atomically.
bytesReceived uint64
bytesSent uint64
lastRecv int64
lastSend int64
connected int32
disconnect int32
conn net.Conn
// These fields are set at creation time and never modified, so they are
// safe to read from concurrently without a mutex.
addr string
cfg Config
inbound bool
flagsMtx sync.Mutex // protects the peer flags below
na *wire.NetAddress
id int32
userAgent string
services wire.ServiceFlag
versionKnown bool
advertisedProtoVer uint32 // protocol version advertised by remote
protocolVersion uint32 // negotiated protocol version
sendHeadersPreferred bool // peer sent a sendheaders message
verAckReceived bool
xVersionReceived bool
syncPeer bool
wireEncoding wire.MessageEncoding
knownInventory *mruInventoryMap
prevGetBlocksMtx sync.Mutex
prevGetBlocksBegin *chainhash.Hash
prevGetBlocksStop *chainhash.Hash
prevGetHdrsMtx sync.Mutex
prevGetHdrsBegin *chainhash.Hash
prevGetHdrsStop *chainhash.Hash
// These fields keep track of statistics for the peer and are protected
// by the statsMtx mutex.
statsMtx sync.RWMutex
timeOffset int64
timeConnected time.Time
startingHeight int32
lastBlock int32
lastAnnouncedBlock *chainhash.Hash
lastPingNonce uint64 // Set to nonce if we have a pending ping.
lastPingTime time.Time // Time we sent last ping.
lastPingMicros int64 // Time for last ping to return.
stallControl chan stallControlMsg
outputQueue chan outMsg
sendQueue chan outMsg
sendDoneQueue chan struct{}
outputInvChan chan *wire.InvVect
inQuit chan struct{}
queueQuit chan struct{}
outQuit chan struct{}
quit chan struct{}
// CompactBlocks
compactBlocksPreferred bool
directBlockRelayPreferred bool
}
// String returns the peer's address and directionality as a human-readable
// string.
//
// This function is safe for concurrent access.
func (p *Peer) String() string {
return fmt.Sprintf("%s (%s)", p.addr, directionString(p.inbound))
}
// UpdateLastBlockHeight updates the last known block for the peer.
//
// This function is safe for concurrent access.
func (p *Peer) UpdateLastBlockHeight(newHeight int32) {
p.statsMtx.Lock()
log.Tracef("Updating last block height of peer %v from %v to %v",
p.addr, p.lastBlock, newHeight)
p.lastBlock = newHeight
p.statsMtx.Unlock()
}
// UpdateLastAnnouncedBlock updates meta-data about the last block hash this
// peer is known to have announced.
//
// This function is safe for concurrent access.
func (p *Peer) UpdateLastAnnouncedBlock(blkHash *chainhash.Hash) {
log.Tracef("Updating last blk for peer %v, %v", p.addr, blkHash)
p.statsMtx.Lock()
p.lastAnnouncedBlock = blkHash
p.statsMtx.Unlock()
}
// AddKnownInventory adds the passed inventory to the cache of known inventory
// for the peer.
//
// This function is safe for concurrent access.
func (p *Peer) AddKnownInventory(invVect *wire.InvVect) {
p.knownInventory.Add(invVect)
}
// DeleteKnownInventory deletes the passed inventory from the cache of known inventory
// for the peer.
//
// This function is safe for concurrent access.
func (p *Peer) DeleteKnownInventory(invVect *wire.InvVect) {
p.knownInventory.Delete(invVect)
}
// HasKnownInventory checks whether the inventory exists in the peer's known
// inventory map.
//
// This function is safe for concurrent access.
func (p *Peer) HasKnownInventory(invVect *wire.InvVect) bool {
return p.knownInventory.Exists(invVect)
}
// GetKnownTxInventory returns a map of the known transaction inventory for this peer.
//
// This function is safe for concurrent access.
func (p *Peer) GetKnownTxInventory() map[chainhash.Hash]bool {
p.knownInventory.invMtx.Lock()
defer p.knownInventory.invMtx.Unlock()
ki := make(map[chainhash.Hash]bool)
for iv := range p.knownInventory.invMap {
if iv.Type == wire.InvTypeTx {
ki[iv.Hash] = true
}
}
return ki
}
// StatsSnapshot returns a snapshot of the current peer flags and statistics.
//
// This function is safe for concurrent access.
func (p *Peer) StatsSnapshot() *StatsSnap {
p.statsMtx.RLock()
p.flagsMtx.Lock()
id := p.id
addr := p.addr
userAgent := p.userAgent
services := p.services
protocolVersion := p.advertisedProtoVer
p.flagsMtx.Unlock()
// Get a copy of all relevant flags and stats.
statsSnap := &StatsSnap{
ID: id,
Addr: addr,
UserAgent: userAgent,
Services: services,
LastSend: p.LastSend(),
LastRecv: p.LastRecv(),
BytesSent: p.BytesSent(),
BytesRecv: p.BytesReceived(),
ConnTime: p.timeConnected,
TimeOffset: p.timeOffset,
Version: protocolVersion,
Inbound: p.inbound,
StartingHeight: p.startingHeight,
LastBlock: p.lastBlock,
LastPingNonce: p.lastPingNonce,
LastPingMicros: p.lastPingMicros,
LastPingTime: p.lastPingTime,
SyncPeer: p.SyncPeer(),
}
p.statsMtx.RUnlock()
return statsSnap
}
// ID returns the peer id.
//
// This function is safe for concurrent access.
func (p *Peer) ID() int32 {
p.flagsMtx.Lock()
id := p.id
p.flagsMtx.Unlock()
return id
}
// SyncPeer returns if this is the sync peer.
//
// This function is safe for concurrent access.
func (p *Peer) SyncPeer() bool {
p.flagsMtx.Lock()
sp := p.syncPeer
p.flagsMtx.Unlock()
return sp
}
// SetSyncPeer sets the syncPeer flag.
//
// This function is safe for concurrent access.
func (p *Peer) SetSyncPeer(val bool) {
p.flagsMtx.Lock()
defer p.flagsMtx.Unlock()
p.syncPeer = val
}
// NA returns the peer network address.
//
// This function is safe for concurrent access.
func (p *Peer) NA() *wire.NetAddress {
p.flagsMtx.Lock()
na := p.na
p.flagsMtx.Unlock()
return na
}
// Addr returns the peer address.
//
// This function is safe for concurrent access.
func (p *Peer) Addr() string {
// The address doesn't change after initialization, therefore it is not
// protected by a mutex.
return p.addr
}
// Inbound returns whether the peer is inbound.
//
// This function is safe for concurrent access.
func (p *Peer) Inbound() bool {
return p.inbound
}
// Services returns the services flag of the remote peer.
//
// This function is safe for concurrent access.
func (p *Peer) Services() wire.ServiceFlag {
p.flagsMtx.Lock()
services := p.services
p.flagsMtx.Unlock()
return services
}
// UserAgent returns the user agent of the remote peer.
//
// This function is safe for concurrent access.
func (p *Peer) UserAgent() string {
p.flagsMtx.Lock()
userAgent := p.userAgent
p.flagsMtx.Unlock()
return userAgent
}
// LastAnnouncedBlock returns the last announced block of the remote peer.
//
// This function is safe for concurrent access.
func (p *Peer) LastAnnouncedBlock() *chainhash.Hash {
p.statsMtx.RLock()
lastAnnouncedBlock := p.lastAnnouncedBlock
p.statsMtx.RUnlock()
return lastAnnouncedBlock
}
// LastPingNonce returns the last ping nonce of the remote peer.
//
// This function is safe for concurrent access.
func (p *Peer) LastPingNonce() uint64 {
p.statsMtx.RLock()
lastPingNonce := p.lastPingNonce
p.statsMtx.RUnlock()
return lastPingNonce
}
// LastPingTime returns the last ping time of the remote peer.
//
// This function is safe for concurrent access.
func (p *Peer) LastPingTime() time.Time {
p.statsMtx.RLock()
lastPingTime := p.lastPingTime
p.statsMtx.RUnlock()
return lastPingTime
}
// LastPingMicros returns the last ping micros of the remote peer.
//
// This function is safe for concurrent access.
func (p *Peer) LastPingMicros() int64 {
p.statsMtx.RLock()
lastPingMicros := p.lastPingMicros
p.statsMtx.RUnlock()
return lastPingMicros
}
// VersionKnown returns the whether or not the version of a peer is known
// locally.
//
// This function is safe for concurrent access.
func (p *Peer) VersionKnown() bool {
p.flagsMtx.Lock()
versionKnown := p.versionKnown
p.flagsMtx.Unlock()
return versionKnown
}
// VerAckReceived returns whether or not a verack message was received by the
// peer.
//
// This function is safe for concurrent access.
func (p *Peer) VerAckReceived() bool {
p.flagsMtx.Lock()
verAckReceived := p.verAckReceived
p.flagsMtx.Unlock()
return verAckReceived
}
// ProtocolVersion returns the negotiated peer protocol version.
//
// This function is safe for concurrent access.
func (p *Peer) ProtocolVersion() uint32 {
p.flagsMtx.Lock()
protocolVersion := p.protocolVersion
p.flagsMtx.Unlock()
return protocolVersion
}
// LastBlock returns the last block of the peer.
//
// This function is safe for concurrent access.
func (p *Peer) LastBlock() int32 {
p.statsMtx.RLock()
lastBlock := p.lastBlock
p.statsMtx.RUnlock()
return lastBlock
}
// LastSend returns the last send time of the peer.
//
// This function is safe for concurrent access.
func (p *Peer) LastSend() time.Time {
return time.Unix(atomic.LoadInt64(&p.lastSend), 0)
}
// LastRecv returns the last recv time of the peer.
//
// This function is safe for concurrent access.
func (p *Peer) LastRecv() time.Time {
return time.Unix(atomic.LoadInt64(&p.lastRecv), 0)
}
// LocalAddr returns the local address of the connection.
//
// This function is safe fo concurrent access.
func (p *Peer) LocalAddr() net.Addr {
var localAddr net.Addr
if atomic.LoadInt32(&p.connected) != 0 {
localAddr = p.conn.LocalAddr()
}
return localAddr
}
// BytesSent returns the total number of bytes sent by the peer.
//
// This function is safe for concurrent access.
func (p *Peer) BytesSent() uint64 {
return atomic.LoadUint64(&p.bytesSent)
}
// BytesReceived returns the total number of bytes received by the peer.
//
// This function is safe for concurrent access.
func (p *Peer) BytesReceived() uint64 {
return atomic.LoadUint64(&p.bytesReceived)
}
// TimeConnected returns the time at which the peer connected.
//
// This function is safe for concurrent access.
func (p *Peer) TimeConnected() time.Time {
p.statsMtx.RLock()
timeConnected := p.timeConnected
p.statsMtx.RUnlock()
return timeConnected
}
// TimeOffset returns the number of seconds the local time was offset from the
// time the peer reported during the initial negotiation phase. Negative values
// indicate the remote peer's time is before the local time.
//
// This function is safe for concurrent access.
func (p *Peer) TimeOffset() int64 {
p.statsMtx.RLock()
timeOffset := p.timeOffset
p.statsMtx.RUnlock()
return timeOffset
}
// StartingHeight returns the last known height the peer reported during the
// initial negotiation phase.
//
// This function is safe for concurrent access.
func (p *Peer) StartingHeight() int32 {
p.statsMtx.RLock()
startingHeight := p.startingHeight
p.statsMtx.RUnlock()
return startingHeight
}
// WantsHeaders returns if the peer wants header messages instead of
// inventory vectors for blocks.
//
// This function is safe for concurrent access.
func (p *Peer) WantsHeaders() bool {
p.flagsMtx.Lock()
sendHeadersPreferred := p.sendHeadersPreferred
p.flagsMtx.Unlock()
return sendHeadersPreferred
}
// WantsCompactBlocks returns if the peer wants header cmpctblocks instead of
// regular blocks.
//
// This function is safe for concurrent access.
func (p *Peer) WantsCompactBlocks() bool {
p.flagsMtx.Lock()
compactBlocksPreferred := p.compactBlocksPreferred
p.flagsMtx.Unlock()
return compactBlocksPreferred
}
// WantsDirectBlockRelay returns if the peer wants us to relay blocks without
// announcing them in inv messages.
//
// This function is safe for concurrent access.
func (p *Peer) WantsDirectBlockRelay() bool {
p.flagsMtx.Lock()
directBlockRelayPreferred := p.directBlockRelayPreferred
p.flagsMtx.Unlock()
return directBlockRelayPreferred
}
// PushAddrMsg sends an addr message to the connected peer using the provided
// addresses. This function is useful over manually sending the message via
// QueueMessage since it automatically limits the addresses to the maximum
// number allowed by the message and randomizes the chosen addresses when there
// are too many. It returns the addresses that were actually sent and no
// message will be sent if there are no entries in the provided addresses slice.
//
// This function is safe for concurrent access.
func (p *Peer) PushAddrMsg(addresses []*wire.NetAddress) ([]*wire.NetAddress, error) {
addressCount := len(addresses)
// Nothing to send.
if addressCount == 0 {
return nil, nil
}
msg := wire.NewMsgAddr()
msg.AddrList = make([]*wire.NetAddress, addressCount)
copy(msg.AddrList, addresses)
// Randomize the addresses sent if there are more than the maximum allowed.
if addressCount > wire.MaxAddrPerMsg {
// Shuffle the address list.
for i := 0; i < wire.MaxAddrPerMsg; i++ {
j := i + rand.Intn(addressCount-i)
msg.AddrList[i], msg.AddrList[j] = msg.AddrList[j], msg.AddrList[i]
}
// Truncate it to the maximum size.
msg.AddrList = msg.AddrList[:wire.MaxAddrPerMsg]
}
p.QueueMessage(msg, nil)
return msg.AddrList, nil
}
// PushGetBlocksMsg sends a getblocks message for the provided block locator
// and stop hash. It will ignore back-to-back duplicate requests.
//
// This function is safe for concurrent access.
func (p *Peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *chainhash.Hash) error {
// Extract the begin hash from the block locator, if one was specified,
// to use for filtering duplicate getblocks requests.
var beginHash *chainhash.Hash
if len(locator) > 0 {
beginHash = locator[0]
}
// Filter duplicate getblocks requests.
p.prevGetBlocksMtx.Lock()
isDuplicate := p.prevGetBlocksStop != nil && p.prevGetBlocksBegin != nil &&
beginHash != nil && stopHash.IsEqual(p.prevGetBlocksStop) &&
beginHash.IsEqual(p.prevGetBlocksBegin)
p.prevGetBlocksMtx.Unlock()
if isDuplicate {
log.Tracef("Filtering duplicate [getblocks] with begin "+
"hash %v, stop hash %v", beginHash, stopHash)
return nil
}
// Construct the getblocks request and queue it to be sent.
msg := wire.NewMsgGetBlocks(stopHash)
for _, hash := range locator {
err := msg.AddBlockLocatorHash(hash)
if err != nil {
return err
}
}
p.QueueMessage(msg, nil)
// Update the previous getblocks request information for filtering
// duplicates.
p.prevGetBlocksMtx.Lock()
p.prevGetBlocksBegin = beginHash
p.prevGetBlocksStop = stopHash
p.prevGetBlocksMtx.Unlock()
return nil
}
// PushGetHeadersMsg sends a getblocks message for the provided block locator
// and stop hash. It will ignore back-to-back duplicate requests.
//
// This function is safe for concurrent access.
func (p *Peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *chainhash.Hash) error {
// Extract the begin hash from the block locator, if one was specified,
// to use for filtering duplicate getheaders requests.
var beginHash *chainhash.Hash
if len(locator) > 0 {
beginHash = locator[0]