github.com/lbryio/lbcd@v0.22.119/peer/peer.go (about) 1 // Copyright (c) 2013-2018 The btcsuite developers 2 // Copyright (c) 2016-2018 The Decred developers 3 // Use of this source code is governed by an ISC 4 // license that can be found in the LICENSE file. 5 6 package peer 7 8 import ( 9 "bytes" 10 "container/list" 11 "errors" 12 "fmt" 13 "io" 14 "math/rand" 15 "net" 16 "strconv" 17 "sync" 18 "sync/atomic" 19 "time" 20 21 "github.com/btcsuite/go-socks/socks" 22 "github.com/davecgh/go-spew/spew" 23 "github.com/decred/dcrd/lru" 24 "github.com/lbryio/lbcd/blockchain" 25 "github.com/lbryio/lbcd/chaincfg" 26 "github.com/lbryio/lbcd/chaincfg/chainhash" 27 "github.com/lbryio/lbcd/wire" 28 ) 29 30 const ( 31 // MaxProtocolVersion is the max protocol version the peer supports. 32 MaxProtocolVersion = wire.FeeFilterVersion 33 34 // DefaultTrickleInterval is the min time between attempts to send an 35 // inv message to a peer. 36 DefaultTrickleInterval = 10 * time.Second 37 38 // MinAcceptableProtocolVersion is the lowest protocol version that a 39 // connected peer may support. 40 MinAcceptableProtocolVersion = wire.MultipleAddressVersion 41 42 // outputBufferSize is the number of elements the output channels use. 43 outputBufferSize = 50 44 45 // invTrickleSize is the maximum amount of inventory to send in a single 46 // message when trickling inventory to remote peers. 47 maxInvTrickleSize = 1000 48 49 // maxKnownInventory is the maximum number of items to keep in the known 50 // inventory cache. 51 maxKnownInventory = 1000 52 53 // pingInterval is the interval of time to wait in between sending ping 54 // messages. 55 pingInterval = 2 * time.Minute 56 57 // negotiateTimeout is the duration of inactivity before we timeout a 58 // peer that hasn't completed the initial version negotiation. 59 negotiateTimeout = 30 * time.Second 60 61 // idleTimeout is the duration of inactivity before we time out a peer. 62 idleTimeout = 5 * time.Minute 63 64 // stallTickInterval is the interval of time between each check for 65 // stalled peers. 66 stallTickInterval = 15 * time.Second 67 68 // stallResponseTimeout is the base maximum amount of time messages that 69 // expect a response will wait before disconnecting the peer for 70 // stalling. The deadlines are adjusted for callback running times and 71 // only checked on each stall tick interval. 72 stallResponseTimeout = 30 * time.Second 73 ) 74 75 var ( 76 // nodeCount is the total number of peer connections made since startup 77 // and is used to assign an id to a peer. 78 nodeCount int32 79 80 // zeroHash is the zero value hash (all zeros). It is defined as a 81 // convenience. 82 zeroHash chainhash.Hash 83 84 // sentNonces houses the unique nonces that are generated when pushing 85 // version messages that are used to detect self connections. 86 sentNonces = lru.NewCache(50) 87 ) 88 89 // MessageListeners defines callback function pointers to invoke with message 90 // listeners for a peer. Any listener which is not set to a concrete callback 91 // during peer initialization is ignored. Execution of multiple message 92 // listeners occurs serially, so one callback blocks the execution of the next. 93 // 94 // NOTE: Unless otherwise documented, these listeners must NOT directly call any 95 // blocking calls (such as WaitForShutdown) on the peer instance since the input 96 // handler goroutine blocks until the callback has completed. Doing so will 97 // result in a deadlock. 98 type MessageListeners struct { 99 // OnGetAddr is invoked when a peer receives a getaddr bitcoin message. 100 OnGetAddr func(p *Peer, msg *wire.MsgGetAddr) 101 102 // OnAddr is invoked when a peer receives an addr bitcoin message. 103 OnAddr func(p *Peer, msg *wire.MsgAddr) 104 105 // OnPing is invoked when a peer receives a ping bitcoin message. 106 OnPing func(p *Peer, msg *wire.MsgPing) 107 108 // OnPong is invoked when a peer receives a pong bitcoin message. 109 OnPong func(p *Peer, msg *wire.MsgPong) 110 111 // OnAlert is invoked when a peer receives an alert bitcoin message. 112 OnAlert func(p *Peer, msg *wire.MsgAlert) 113 114 // OnMemPool is invoked when a peer receives a mempool bitcoin message. 115 OnMemPool func(p *Peer, msg *wire.MsgMemPool) 116 117 // OnTx is invoked when a peer receives a tx bitcoin message. 118 OnTx func(p *Peer, msg *wire.MsgTx) 119 120 // OnBlock is invoked when a peer receives a block bitcoin message. 121 OnBlock func(p *Peer, msg *wire.MsgBlock, buf []byte) 122 123 // OnCFilter is invoked when a peer receives a cfilter bitcoin message. 124 OnCFilter func(p *Peer, msg *wire.MsgCFilter) 125 126 // OnCFHeaders is invoked when a peer receives a cfheaders bitcoin 127 // message. 128 OnCFHeaders func(p *Peer, msg *wire.MsgCFHeaders) 129 130 // OnCFCheckpt is invoked when a peer receives a cfcheckpt bitcoin 131 // message. 132 OnCFCheckpt func(p *Peer, msg *wire.MsgCFCheckpt) 133 134 // OnInv is invoked when a peer receives an inv bitcoin message. 135 OnInv func(p *Peer, msg *wire.MsgInv) 136 137 // OnHeaders is invoked when a peer receives a headers bitcoin message. 138 OnHeaders func(p *Peer, msg *wire.MsgHeaders) 139 140 // OnNotFound is invoked when a peer receives a notfound bitcoin 141 // message. 142 OnNotFound func(p *Peer, msg *wire.MsgNotFound) 143 144 // OnGetData is invoked when a peer receives a getdata bitcoin message. 145 OnGetData func(p *Peer, msg *wire.MsgGetData) 146 147 // OnGetBlocks is invoked when a peer receives a getblocks bitcoin 148 // message. 149 OnGetBlocks func(p *Peer, msg *wire.MsgGetBlocks) 150 151 // OnGetHeaders is invoked when a peer receives a getheaders bitcoin 152 // message. 153 OnGetHeaders func(p *Peer, msg *wire.MsgGetHeaders) 154 155 // OnGetCFilters is invoked when a peer receives a getcfilters bitcoin 156 // message. 157 OnGetCFilters func(p *Peer, msg *wire.MsgGetCFilters) 158 159 // OnGetCFHeaders is invoked when a peer receives a getcfheaders 160 // bitcoin message. 161 OnGetCFHeaders func(p *Peer, msg *wire.MsgGetCFHeaders) 162 163 // OnGetCFCheckpt is invoked when a peer receives a getcfcheckpt 164 // bitcoin message. 165 OnGetCFCheckpt func(p *Peer, msg *wire.MsgGetCFCheckpt) 166 167 // OnFeeFilter is invoked when a peer receives a feefilter bitcoin message. 168 OnFeeFilter func(p *Peer, msg *wire.MsgFeeFilter) 169 170 // OnFilterAdd is invoked when a peer receives a filteradd bitcoin message. 171 OnFilterAdd func(p *Peer, msg *wire.MsgFilterAdd) 172 173 // OnFilterClear is invoked when a peer receives a filterclear bitcoin 174 // message. 175 OnFilterClear func(p *Peer, msg *wire.MsgFilterClear) 176 177 // OnFilterLoad is invoked when a peer receives a filterload bitcoin 178 // message. 179 OnFilterLoad func(p *Peer, msg *wire.MsgFilterLoad) 180 181 // OnMerkleBlock is invoked when a peer receives a merkleblock bitcoin 182 // message. 183 OnMerkleBlock func(p *Peer, msg *wire.MsgMerkleBlock) 184 185 // OnVersion is invoked when a peer receives a version bitcoin message. 186 // The caller may return a reject message in which case the message will 187 // be sent to the peer and the peer will be disconnected. 188 OnVersion func(p *Peer, msg *wire.MsgVersion) *wire.MsgReject 189 190 // OnVerAck is invoked when a peer receives a verack bitcoin message. 191 OnVerAck func(p *Peer, msg *wire.MsgVerAck) 192 193 // OnReject is invoked when a peer receives a reject bitcoin message. 194 OnReject func(p *Peer, msg *wire.MsgReject) 195 196 // OnSendHeaders is invoked when a peer receives a sendheaders bitcoin 197 // message. 198 OnSendHeaders func(p *Peer, msg *wire.MsgSendHeaders) 199 200 // OnRead is invoked when a peer receives a bitcoin message. It 201 // consists of the number of bytes read, the message, and whether or not 202 // an error in the read occurred. Typically, callers will opt to use 203 // the callbacks for the specific message types, however this can be 204 // useful for circumstances such as keeping track of server-wide byte 205 // counts or working with custom message types for which the peer does 206 // not directly provide a callback. 207 OnRead func(p *Peer, bytesRead int, msg wire.Message, err error) 208 209 // OnWrite is invoked when we write a bitcoin message to a peer. It 210 // consists of the number of bytes written, the message, and whether or 211 // not an error in the write occurred. This can be useful for 212 // circumstances such as keeping track of server-wide byte counts. 213 OnWrite func(p *Peer, bytesWritten int, msg wire.Message, err error) 214 } 215 216 // Config is the struct to hold configuration options useful to Peer. 217 type Config struct { 218 // NewestBlock specifies a callback which provides the newest block 219 // details to the peer as needed. This can be nil in which case the 220 // peer will report a block height of 0, however it is good practice for 221 // peers to specify this so their currently best known is accurately 222 // reported. 223 NewestBlock HashFunc 224 225 // HostToNetAddress returns the netaddress for the given host. This can be 226 // nil in which case the host will be parsed as an IP address. 227 HostToNetAddress HostToNetAddrFunc 228 229 // Proxy indicates a proxy is being used for connections. The only 230 // effect this has is to prevent leaking the tor proxy address, so it 231 // only needs to specified if using a tor proxy. 232 Proxy string 233 234 // UserAgentName specifies the user agent name to advertise. It is 235 // highly recommended to specify this value. 236 UserAgentName string 237 238 // UserAgentVersion specifies the user agent version to advertise. It 239 // is highly recommended to specify this value and that it follows the 240 // form "major.minor.revision" e.g. "2.6.41". 241 UserAgentVersion string 242 243 // UserAgentComments specify the user agent comments to advertise. These 244 // values must not contain the illegal characters specified in BIP 14: 245 // '/', ':', '(', ')'. 246 UserAgentComments []string 247 248 // ChainParams identifies which chain parameters the peer is associated 249 // with. It is highly recommended to specify this field, however it can 250 // be omitted in which case the test network will be used. 251 ChainParams *chaincfg.Params 252 253 // Services specifies which services to advertise as supported by the 254 // local peer. This field can be omitted in which case it will be 0 255 // and therefore advertise no supported services. 256 Services wire.ServiceFlag 257 258 // ProtocolVersion specifies the maximum protocol version to use and 259 // advertise. This field can be omitted in which case 260 // peer.MaxProtocolVersion will be used. 261 ProtocolVersion uint32 262 263 // DisableRelayTx specifies if the remote peer should be informed to 264 // not send inv messages for transactions. 265 DisableRelayTx bool 266 267 // Listeners houses callback functions to be invoked on receiving peer 268 // messages. 269 Listeners MessageListeners 270 271 // TrickleInterval is the duration of the ticker which trickles down the 272 // inventory to a peer. 273 TrickleInterval time.Duration 274 275 // AllowSelfConns is only used to allow the tests to bypass the self 276 // connection detecting and disconnect logic since they intentionally 277 // do so for testing purposes. 278 AllowSelfConns bool 279 280 // DisableStallHandler if true, then the stall handler that attempts to 281 // disconnect from peers that appear to be taking too long to respond 282 // to requests won't be activated. This can be useful in certain simnet 283 // scenarios where the stall behavior isn't important to the system 284 // under test. 285 DisableStallHandler bool 286 } 287 288 // minUint32 is a helper function to return the minimum of two uint32s. 289 // This avoids a math import and the need to cast to floats. 290 func minUint32(a, b uint32) uint32 { 291 if a < b { 292 return a 293 } 294 return b 295 } 296 297 // newNetAddress attempts to extract the IP address and port from the passed 298 // net.Addr interface and create a bitcoin NetAddress structure using that 299 // information. 300 func newNetAddress(addr net.Addr, services wire.ServiceFlag) (*wire.NetAddress, error) { 301 // addr will be a net.TCPAddr when not using a proxy. 302 if tcpAddr, ok := addr.(*net.TCPAddr); ok { 303 ip := tcpAddr.IP 304 port := uint16(tcpAddr.Port) 305 na := wire.NewNetAddressIPPort(ip, port, services) 306 return na, nil 307 } 308 309 // addr will be a socks.ProxiedAddr when using a proxy. 310 if proxiedAddr, ok := addr.(*socks.ProxiedAddr); ok { 311 ip := net.ParseIP(proxiedAddr.Host) 312 if ip == nil { 313 ip = net.ParseIP("0.0.0.0") 314 } 315 port := uint16(proxiedAddr.Port) 316 na := wire.NewNetAddressIPPort(ip, port, services) 317 return na, nil 318 } 319 320 // For the most part, addr should be one of the two above cases, but 321 // to be safe, fall back to trying to parse the information from the 322 // address string as a last resort. 323 host, portStr, err := net.SplitHostPort(addr.String()) 324 if err != nil { 325 return nil, err 326 } 327 ip := net.ParseIP(host) 328 port, err := strconv.ParseUint(portStr, 10, 16) 329 if err != nil { 330 return nil, err 331 } 332 na := wire.NewNetAddressIPPort(ip, uint16(port), services) 333 return na, nil 334 } 335 336 // outMsg is used to house a message to be sent along with a channel to signal 337 // when the message has been sent (or won't be sent due to things such as 338 // shutdown) 339 type outMsg struct { 340 msg wire.Message 341 doneChan chan<- struct{} 342 encoding wire.MessageEncoding 343 } 344 345 // stallControlCmd represents the command of a stall control message. 346 type stallControlCmd uint8 347 348 // Constants for the command of a stall control message. 349 const ( 350 // sccSendMessage indicates a message is being sent to the remote peer. 351 sccSendMessage stallControlCmd = iota 352 353 // sccReceiveMessage indicates a message has been received from the 354 // remote peer. 355 sccReceiveMessage 356 357 // sccHandlerStart indicates a callback handler is about to be invoked. 358 sccHandlerStart 359 360 // sccHandlerStart indicates a callback handler has completed. 361 sccHandlerDone 362 ) 363 364 // stallControlMsg is used to signal the stall handler about specific events 365 // so it can properly detect and handle stalled remote peers. 366 type stallControlMsg struct { 367 command stallControlCmd 368 message wire.Message 369 } 370 371 // StatsSnap is a snapshot of peer stats at a point in time. 372 type StatsSnap struct { 373 ID int32 374 Addr string 375 Services wire.ServiceFlag 376 LastSend time.Time 377 LastRecv time.Time 378 BytesSent uint64 379 BytesRecv uint64 380 ConnTime time.Time 381 TimeOffset int64 382 Version uint32 383 UserAgent string 384 Inbound bool 385 StartingHeight int32 386 LastBlock int32 387 LastPingNonce uint64 388 LastPingTime time.Time 389 LastPingMicros int64 390 } 391 392 // HashFunc is a function which returns a block hash, height and error 393 // It is used as a callback to get newest block details. 394 type HashFunc func() (hash *chainhash.Hash, height int32, err error) 395 396 // AddrFunc is a func which takes an address and returns a related address. 397 type AddrFunc func(remoteAddr *wire.NetAddress) *wire.NetAddress 398 399 // HostToNetAddrFunc is a func which takes a host, port, services and returns 400 // the netaddress. 401 type HostToNetAddrFunc func(host string, port uint16, 402 services wire.ServiceFlag) (*wire.NetAddress, error) 403 404 // NOTE: The overall data flow of a peer is split into 3 goroutines. Inbound 405 // messages are read via the inHandler goroutine and generally dispatched to 406 // their own handler. For inbound data-related messages such as blocks, 407 // transactions, and inventory, the data is handled by the corresponding 408 // message handlers. The data flow for outbound messages is split into 2 409 // goroutines, queueHandler and outHandler. The first, queueHandler, is used 410 // as a way for external entities to queue messages, by way of the QueueMessage 411 // function, quickly regardless of whether the peer is currently sending or not. 412 // It acts as the traffic cop between the external world and the actual 413 // goroutine which writes to the network socket. 414 415 // Peer provides a basic concurrent safe bitcoin peer for handling bitcoin 416 // communications via the peer-to-peer protocol. It provides full duplex 417 // reading and writing, automatic handling of the initial handshake process, 418 // querying of usage statistics and other information about the remote peer such 419 // as its address, user agent, and protocol version, output message queuing, 420 // inventory trickling, and the ability to dynamically register and unregister 421 // callbacks for handling bitcoin protocol messages. 422 // 423 // Outbound messages are typically queued via QueueMessage or QueueInventory. 424 // QueueMessage is intended for all messages, including responses to data such 425 // as blocks and transactions. QueueInventory, on the other hand, is only 426 // intended for relaying inventory as it employs a trickling mechanism to batch 427 // the inventory together. However, some helper functions for pushing messages 428 // of specific types that typically require common special handling are 429 // provided as a convenience. 430 type Peer struct { 431 // The following variables must only be used atomically. 432 bytesReceived uint64 433 bytesSent uint64 434 lastRecv int64 435 lastSend int64 436 connected int32 437 disconnect int32 438 439 conn net.Conn 440 441 // These fields are set at creation time and never modified, so they are 442 // safe to read from concurrently without a mutex. 443 addr string 444 cfg Config 445 inbound bool 446 447 flagsMtx sync.Mutex // protects the peer flags below 448 na *wire.NetAddress 449 id int32 450 userAgent string 451 services wire.ServiceFlag 452 versionKnown bool 453 advertisedProtoVer uint32 // protocol version advertised by remote 454 protocolVersion uint32 // negotiated protocol version 455 sendHeadersPreferred bool // peer sent a sendheaders message 456 verAckReceived bool 457 witnessEnabled bool 458 459 wireEncoding wire.MessageEncoding 460 461 knownInventory lru.Cache 462 prevGetBlocksMtx sync.Mutex 463 prevGetBlocksBegin *chainhash.Hash 464 prevGetBlocksStop *chainhash.Hash 465 prevGetHdrsMtx sync.Mutex 466 prevGetHdrsBegin *chainhash.Hash 467 prevGetHdrsStop *chainhash.Hash 468 469 // These fields keep track of statistics for the peer and are protected 470 // by the statsMtx mutex. 471 statsMtx sync.RWMutex 472 timeOffset int64 473 timeConnected time.Time 474 startingHeight int32 475 lastBlock int32 476 lastAnnouncedBlock *chainhash.Hash 477 lastPingNonce uint64 // Set to nonce if we have a pending ping. 478 lastPingTime time.Time // Time we sent last ping. 479 lastPingMicros int64 // Time for last ping to return. 480 481 stallControl chan stallControlMsg 482 outputQueue chan outMsg 483 sendQueue chan outMsg 484 sendDoneQueue chan struct{} 485 outputInvChan chan *wire.InvVect 486 inQuit chan struct{} 487 queueQuit chan struct{} 488 outQuit chan struct{} 489 quit chan struct{} 490 } 491 492 // String returns the peer's address and directionality as a human-readable 493 // string. 494 // 495 // This function is safe for concurrent access. 496 func (p *Peer) String() string { 497 return fmt.Sprintf("%s (%s)", p.addr, directionString(p.inbound)) 498 } 499 500 // UpdateLastBlockHeight updates the last known block for the peer. 501 // 502 // This function is safe for concurrent access. 503 func (p *Peer) UpdateLastBlockHeight(newHeight int32) { 504 p.statsMtx.Lock() 505 if newHeight <= p.lastBlock { 506 p.statsMtx.Unlock() 507 return 508 } 509 log.Tracef("Updating last block height of peer %v from %v to %v", 510 p.addr, p.lastBlock, newHeight) 511 p.lastBlock = newHeight 512 p.statsMtx.Unlock() 513 } 514 515 // UpdateLastAnnouncedBlock updates meta-data about the last block hash this 516 // peer is known to have announced. 517 // 518 // This function is safe for concurrent access. 519 func (p *Peer) UpdateLastAnnouncedBlock(blkHash *chainhash.Hash) { 520 log.Tracef("Updating last blk for peer %v, %v", p.addr, blkHash) 521 522 p.statsMtx.Lock() 523 p.lastAnnouncedBlock = blkHash 524 p.statsMtx.Unlock() 525 } 526 527 // AddKnownInventory adds the passed inventory to the cache of known inventory 528 // for the peer. 529 // 530 // This function is safe for concurrent access. 531 func (p *Peer) AddKnownInventory(invVect *wire.InvVect) { 532 p.knownInventory.Add(invVect) 533 } 534 535 // StatsSnapshot returns a snapshot of the current peer flags and statistics. 536 // 537 // This function is safe for concurrent access. 538 func (p *Peer) StatsSnapshot() *StatsSnap { 539 p.statsMtx.RLock() 540 541 p.flagsMtx.Lock() 542 id := p.id 543 addr := p.addr 544 userAgent := p.userAgent 545 services := p.services 546 protocolVersion := p.advertisedProtoVer 547 p.flagsMtx.Unlock() 548 549 // Get a copy of all relevant flags and stats. 550 statsSnap := &StatsSnap{ 551 ID: id, 552 Addr: addr, 553 UserAgent: userAgent, 554 Services: services, 555 LastSend: p.LastSend(), 556 LastRecv: p.LastRecv(), 557 BytesSent: p.BytesSent(), 558 BytesRecv: p.BytesReceived(), 559 ConnTime: p.timeConnected, 560 TimeOffset: p.timeOffset, 561 Version: protocolVersion, 562 Inbound: p.inbound, 563 StartingHeight: p.startingHeight, 564 LastBlock: p.lastBlock, 565 LastPingNonce: p.lastPingNonce, 566 LastPingMicros: p.lastPingMicros, 567 LastPingTime: p.lastPingTime, 568 } 569 570 p.statsMtx.RUnlock() 571 return statsSnap 572 } 573 574 // ID returns the peer id. 575 // 576 // This function is safe for concurrent access. 577 func (p *Peer) ID() int32 { 578 p.flagsMtx.Lock() 579 id := p.id 580 p.flagsMtx.Unlock() 581 582 return id 583 } 584 585 // NA returns the peer network address. 586 // 587 // This function is safe for concurrent access. 588 func (p *Peer) NA() *wire.NetAddress { 589 p.flagsMtx.Lock() 590 na := p.na 591 p.flagsMtx.Unlock() 592 593 return na 594 } 595 596 // Addr returns the peer address. 597 // 598 // This function is safe for concurrent access. 599 func (p *Peer) Addr() string { 600 // The address doesn't change after initialization, therefore it is not 601 // protected by a mutex. 602 return p.addr 603 } 604 605 // Inbound returns whether the peer is inbound. 606 // 607 // This function is safe for concurrent access. 608 func (p *Peer) Inbound() bool { 609 return p.inbound 610 } 611 612 // Services returns the services flag of the remote peer. 613 // 614 // This function is safe for concurrent access. 615 func (p *Peer) Services() wire.ServiceFlag { 616 p.flagsMtx.Lock() 617 services := p.services 618 p.flagsMtx.Unlock() 619 620 return services 621 } 622 623 // UserAgent returns the user agent of the remote peer. 624 // 625 // This function is safe for concurrent access. 626 func (p *Peer) UserAgent() string { 627 p.flagsMtx.Lock() 628 userAgent := p.userAgent 629 p.flagsMtx.Unlock() 630 631 return userAgent 632 } 633 634 // LastAnnouncedBlock returns the last announced block of the remote peer. 635 // 636 // This function is safe for concurrent access. 637 func (p *Peer) LastAnnouncedBlock() *chainhash.Hash { 638 p.statsMtx.RLock() 639 lastAnnouncedBlock := p.lastAnnouncedBlock 640 p.statsMtx.RUnlock() 641 642 return lastAnnouncedBlock 643 } 644 645 // LastPingNonce returns the last ping nonce of the remote peer. 646 // 647 // This function is safe for concurrent access. 648 func (p *Peer) LastPingNonce() uint64 { 649 p.statsMtx.RLock() 650 lastPingNonce := p.lastPingNonce 651 p.statsMtx.RUnlock() 652 653 return lastPingNonce 654 } 655 656 // LastPingTime returns the last ping time of the remote peer. 657 // 658 // This function is safe for concurrent access. 659 func (p *Peer) LastPingTime() time.Time { 660 p.statsMtx.RLock() 661 lastPingTime := p.lastPingTime 662 p.statsMtx.RUnlock() 663 664 return lastPingTime 665 } 666 667 // LastPingMicros returns the last ping micros of the remote peer. 668 // 669 // This function is safe for concurrent access. 670 func (p *Peer) LastPingMicros() int64 { 671 p.statsMtx.RLock() 672 lastPingMicros := p.lastPingMicros 673 p.statsMtx.RUnlock() 674 675 return lastPingMicros 676 } 677 678 // VersionKnown returns the whether or not the version of a peer is known 679 // locally. 680 // 681 // This function is safe for concurrent access. 682 func (p *Peer) VersionKnown() bool { 683 p.flagsMtx.Lock() 684 versionKnown := p.versionKnown 685 p.flagsMtx.Unlock() 686 687 return versionKnown 688 } 689 690 // VerAckReceived returns whether or not a verack message was received by the 691 // peer. 692 // 693 // This function is safe for concurrent access. 694 func (p *Peer) VerAckReceived() bool { 695 p.flagsMtx.Lock() 696 verAckReceived := p.verAckReceived 697 p.flagsMtx.Unlock() 698 699 return verAckReceived 700 } 701 702 // ProtocolVersion returns the negotiated peer protocol version. 703 // 704 // This function is safe for concurrent access. 705 func (p *Peer) ProtocolVersion() uint32 { 706 p.flagsMtx.Lock() 707 protocolVersion := p.protocolVersion 708 p.flagsMtx.Unlock() 709 710 return protocolVersion 711 } 712 713 // LastBlock returns the last block of the peer. 714 // 715 // This function is safe for concurrent access. 716 func (p *Peer) LastBlock() int32 { 717 p.statsMtx.RLock() 718 lastBlock := p.lastBlock 719 p.statsMtx.RUnlock() 720 721 return lastBlock 722 } 723 724 // LastSend returns the last send time of the peer. 725 // 726 // This function is safe for concurrent access. 727 func (p *Peer) LastSend() time.Time { 728 return time.Unix(atomic.LoadInt64(&p.lastSend), 0) 729 } 730 731 // LastRecv returns the last recv time of the peer. 732 // 733 // This function is safe for concurrent access. 734 func (p *Peer) LastRecv() time.Time { 735 return time.Unix(atomic.LoadInt64(&p.lastRecv), 0) 736 } 737 738 // LocalAddr returns the local address of the connection. 739 // 740 // This function is safe fo concurrent access. 741 func (p *Peer) LocalAddr() net.Addr { 742 var localAddr net.Addr 743 if atomic.LoadInt32(&p.connected) != 0 { 744 localAddr = p.conn.LocalAddr() 745 } 746 return localAddr 747 } 748 749 // BytesSent returns the total number of bytes sent by the peer. 750 // 751 // This function is safe for concurrent access. 752 func (p *Peer) BytesSent() uint64 { 753 return atomic.LoadUint64(&p.bytesSent) 754 } 755 756 // BytesReceived returns the total number of bytes received by the peer. 757 // 758 // This function is safe for concurrent access. 759 func (p *Peer) BytesReceived() uint64 { 760 return atomic.LoadUint64(&p.bytesReceived) 761 } 762 763 // TimeConnected returns the time at which the peer connected. 764 // 765 // This function is safe for concurrent access. 766 func (p *Peer) TimeConnected() time.Time { 767 p.statsMtx.RLock() 768 timeConnected := p.timeConnected 769 p.statsMtx.RUnlock() 770 771 return timeConnected 772 } 773 774 // TimeOffset returns the number of seconds the local time was offset from the 775 // time the peer reported during the initial negotiation phase. Negative values 776 // indicate the remote peer's time is before the local time. 777 // 778 // This function is safe for concurrent access. 779 func (p *Peer) TimeOffset() int64 { 780 p.statsMtx.RLock() 781 timeOffset := p.timeOffset 782 p.statsMtx.RUnlock() 783 784 return timeOffset 785 } 786 787 // StartingHeight returns the last known height the peer reported during the 788 // initial negotiation phase. 789 // 790 // This function is safe for concurrent access. 791 func (p *Peer) StartingHeight() int32 { 792 p.statsMtx.RLock() 793 startingHeight := p.startingHeight 794 p.statsMtx.RUnlock() 795 796 return startingHeight 797 } 798 799 // WantsHeaders returns if the peer wants header messages instead of 800 // inventory vectors for blocks. 801 // 802 // This function is safe for concurrent access. 803 func (p *Peer) WantsHeaders() bool { 804 p.flagsMtx.Lock() 805 sendHeadersPreferred := p.sendHeadersPreferred 806 p.flagsMtx.Unlock() 807 808 return sendHeadersPreferred 809 } 810 811 // IsWitnessEnabled returns true if the peer has signalled that it supports 812 // segregated witness. 813 // 814 // This function is safe for concurrent access. 815 func (p *Peer) IsWitnessEnabled() bool { 816 p.flagsMtx.Lock() 817 witnessEnabled := p.witnessEnabled 818 p.flagsMtx.Unlock() 819 820 return witnessEnabled 821 } 822 823 // PushAddrMsg sends an addr message to the connected peer using the provided 824 // addresses. This function is useful over manually sending the message via 825 // QueueMessage since it automatically limits the addresses to the maximum 826 // number allowed by the message and randomizes the chosen addresses when there 827 // are too many. It returns the addresses that were actually sent and no 828 // message will be sent if there are no entries in the provided addresses slice. 829 // 830 // This function is safe for concurrent access. 831 func (p *Peer) PushAddrMsg(addresses []*wire.NetAddress) ([]*wire.NetAddress, error) { 832 addressCount := len(addresses) 833 834 // Nothing to send. 835 if addressCount == 0 { 836 return nil, nil 837 } 838 839 msg := wire.NewMsgAddr() 840 msg.AddrList = make([]*wire.NetAddress, addressCount) 841 copy(msg.AddrList, addresses) 842 843 // Randomize the addresses sent if there are more than the maximum allowed. 844 if addressCount > wire.MaxAddrPerMsg { 845 // Shuffle the address list. 846 for i := 0; i < wire.MaxAddrPerMsg; i++ { 847 j := i + rand.Intn(addressCount-i) 848 msg.AddrList[i], msg.AddrList[j] = msg.AddrList[j], msg.AddrList[i] 849 } 850 851 // Truncate it to the maximum size. 852 msg.AddrList = msg.AddrList[:wire.MaxAddrPerMsg] 853 } 854 855 p.QueueMessage(msg, nil) 856 return msg.AddrList, nil 857 } 858 859 // PushGetBlocksMsg sends a getblocks message for the provided block locator 860 // and stop hash. It will ignore back-to-back duplicate requests. 861 // 862 // This function is safe for concurrent access. 863 func (p *Peer) PushGetBlocksMsg(locator blockchain.BlockLocator, stopHash *chainhash.Hash) error { 864 // Extract the begin hash from the block locator, if one was specified, 865 // to use for filtering duplicate getblocks requests. 866 var beginHash *chainhash.Hash 867 if len(locator) > 0 { 868 beginHash = locator[0] 869 } 870 871 // Filter duplicate getblocks requests. 872 p.prevGetBlocksMtx.Lock() 873 isDuplicate := p.prevGetBlocksStop != nil && p.prevGetBlocksBegin != nil && 874 beginHash != nil && stopHash.IsEqual(p.prevGetBlocksStop) && 875 beginHash.IsEqual(p.prevGetBlocksBegin) 876 p.prevGetBlocksMtx.Unlock() 877 878 if isDuplicate { 879 log.Tracef("Filtering duplicate [getblocks] with begin "+ 880 "hash %v, stop hash %v", beginHash, stopHash) 881 return nil 882 } 883 884 // Construct the getblocks request and queue it to be sent. 885 msg := wire.NewMsgGetBlocks(stopHash) 886 for _, hash := range locator { 887 err := msg.AddBlockLocatorHash(hash) 888 if err != nil { 889 return err 890 } 891 } 892 p.QueueMessage(msg, nil) 893 894 // Update the previous getblocks request information for filtering 895 // duplicates. 896 p.prevGetBlocksMtx.Lock() 897 p.prevGetBlocksBegin = beginHash 898 p.prevGetBlocksStop = stopHash 899 p.prevGetBlocksMtx.Unlock() 900 return nil 901 } 902 903 // PushGetHeadersMsg sends a getblocks message for the provided block locator 904 // and stop hash. It will ignore back-to-back duplicate requests. 905 // 906 // This function is safe for concurrent access. 907 func (p *Peer) PushGetHeadersMsg(locator blockchain.BlockLocator, stopHash *chainhash.Hash) error { 908 // Extract the begin hash from the block locator, if one was specified, 909 // to use for filtering duplicate getheaders requests. 910 var beginHash *chainhash.Hash 911 if len(locator) > 0 { 912 beginHash = locator[0] 913 } 914 915 // Filter duplicate getheaders requests. 916 p.prevGetHdrsMtx.Lock() 917 isDuplicate := p.prevGetHdrsStop != nil && p.prevGetHdrsBegin != nil && 918 beginHash != nil && stopHash.IsEqual(p.prevGetHdrsStop) && 919 beginHash.IsEqual(p.prevGetHdrsBegin) 920 p.prevGetHdrsMtx.Unlock() 921 922 if isDuplicate { 923 log.Tracef("Filtering duplicate [getheaders] with begin hash %v", 924 beginHash) 925 return nil 926 } 927 928 // Construct the getheaders request and queue it to be sent. 929 msg := wire.NewMsgGetHeaders() 930 msg.HashStop = *stopHash 931 for _, hash := range locator { 932 err := msg.AddBlockLocatorHash(hash) 933 if err != nil { 934 return err 935 } 936 } 937 p.QueueMessage(msg, nil) 938 939 // Update the previous getheaders request information for filtering 940 // duplicates. 941 p.prevGetHdrsMtx.Lock() 942 p.prevGetHdrsBegin = beginHash 943 p.prevGetHdrsStop = stopHash 944 p.prevGetHdrsMtx.Unlock() 945 return nil 946 } 947 948 // PushRejectMsg sends a reject message for the provided command, reject code, 949 // reject reason, and hash. The hash will only be used when the command is a tx 950 // or block and should be nil in other cases. The wait parameter will cause the 951 // function to block until the reject message has actually been sent. 952 // 953 // This function is safe for concurrent access. 954 func (p *Peer) PushRejectMsg(command string, code wire.RejectCode, reason string, hash *chainhash.Hash, wait bool) { 955 // Don't bother sending the reject message if the protocol version 956 // is too low. 957 if p.VersionKnown() && p.ProtocolVersion() < wire.RejectVersion { 958 return 959 } 960 961 msg := wire.NewMsgReject(command, code, reason) 962 if command == wire.CmdTx || command == wire.CmdBlock { 963 if hash == nil { 964 log.Warnf("Sending a reject message for command "+ 965 "type %v which should have specified a hash "+ 966 "but does not", command) 967 hash = &zeroHash 968 } 969 msg.Hash = *hash 970 } 971 972 // Send the message without waiting if the caller has not requested it. 973 if !wait { 974 p.QueueMessage(msg, nil) 975 return 976 } 977 978 // Send the message and block until it has been sent before returning. 979 doneChan := make(chan struct{}, 1) 980 p.QueueMessage(msg, doneChan) 981 <-doneChan 982 } 983 984 // handlePingMsg is invoked when a peer receives a ping bitcoin message. For 985 // recent clients (protocol version > BIP0031Version), it replies with a pong 986 // message. For older clients, it does nothing and anything other than failure 987 // is considered a successful ping. 988 func (p *Peer) handlePingMsg(msg *wire.MsgPing) { 989 // Only reply with pong if the message is from a new enough client. 990 if p.ProtocolVersion() > wire.BIP0031Version { 991 // Include nonce from ping so pong can be identified. 992 p.QueueMessage(wire.NewMsgPong(msg.Nonce), nil) 993 } 994 } 995 996 // handlePongMsg is invoked when a peer receives a pong bitcoin message. It 997 // updates the ping statistics as required for recent clients (protocol 998 // version > BIP0031Version). There is no effect for older clients or when a 999 // ping was not previously sent. 1000 func (p *Peer) handlePongMsg(msg *wire.MsgPong) { 1001 // Arguably we could use a buffered channel here sending data 1002 // in a fifo manner whenever we send a ping, or a list keeping track of 1003 // the times of each ping. For now we just make a best effort and 1004 // only record stats if it was for the last ping sent. Any preceding 1005 // and overlapping pings will be ignored. It is unlikely to occur 1006 // without large usage of the ping rpc call since we ping infrequently 1007 // enough that if they overlap we would have timed out the peer. 1008 if p.ProtocolVersion() > wire.BIP0031Version { 1009 p.statsMtx.Lock() 1010 if p.lastPingNonce != 0 && msg.Nonce == p.lastPingNonce { 1011 p.lastPingMicros = time.Since(p.lastPingTime).Nanoseconds() 1012 p.lastPingMicros /= 1000 // convert to usec. 1013 p.lastPingNonce = 0 1014 } 1015 p.statsMtx.Unlock() 1016 } 1017 } 1018 1019 // readMessage reads the next bitcoin message from the peer with logging. 1020 func (p *Peer) readMessage(encoding wire.MessageEncoding) (wire.Message, []byte, error) { 1021 n, msg, buf, err := wire.ReadMessageWithEncodingN(p.conn, 1022 p.ProtocolVersion(), p.cfg.ChainParams.Net, encoding) 1023 atomic.AddUint64(&p.bytesReceived, uint64(n)) 1024 if p.cfg.Listeners.OnRead != nil { 1025 p.cfg.Listeners.OnRead(p, n, msg, err) 1026 } 1027 if err != nil { 1028 return nil, nil, err 1029 } 1030 1031 // Use closures to log expensive operations so they are only run when 1032 // the logging level requires it. 1033 log.Debugf("%v", newLogClosure(func() string { 1034 // Debug summary of message. 1035 summary := messageSummary(msg) 1036 if len(summary) > 0 { 1037 summary = " (" + summary + ")" 1038 } 1039 return fmt.Sprintf("Received %v%s from %s", 1040 msg.Command(), summary, p) 1041 })) 1042 log.Tracef("%v", newLogClosure(func() string { 1043 return spew.Sdump(msg) 1044 })) 1045 log.Tracef("%v", newLogClosure(func() string { 1046 return spew.Sdump(buf) 1047 })) 1048 1049 return msg, buf, nil 1050 } 1051 1052 // writeMessage sends a bitcoin message to the peer with logging. 1053 func (p *Peer) writeMessage(msg wire.Message, enc wire.MessageEncoding) error { 1054 // Don't do anything if we're disconnecting. 1055 if atomic.LoadInt32(&p.disconnect) != 0 { 1056 return nil 1057 } 1058 1059 // Use closures to log expensive operations so they are only run when 1060 // the logging level requires it. 1061 log.Debugf("%v", newLogClosure(func() string { 1062 // Debug summary of message. 1063 summary := messageSummary(msg) 1064 if len(summary) > 0 { 1065 summary = " (" + summary + ")" 1066 } 1067 return fmt.Sprintf("Sending %v%s to %s", msg.Command(), 1068 summary, p) 1069 })) 1070 log.Tracef("%v", newLogClosure(func() string { 1071 return spew.Sdump(msg) 1072 })) 1073 log.Tracef("%v", newLogClosure(func() string { 1074 var buf bytes.Buffer 1075 _, err := wire.WriteMessageWithEncodingN(&buf, msg, p.ProtocolVersion(), 1076 p.cfg.ChainParams.Net, enc) 1077 if err != nil { 1078 return err.Error() 1079 } 1080 return spew.Sdump(buf.Bytes()) 1081 })) 1082 1083 // Write the message to the peer. 1084 n, err := wire.WriteMessageWithEncodingN(p.conn, msg, 1085 p.ProtocolVersion(), p.cfg.ChainParams.Net, enc) 1086 atomic.AddUint64(&p.bytesSent, uint64(n)) 1087 if p.cfg.Listeners.OnWrite != nil { 1088 p.cfg.Listeners.OnWrite(p, n, msg, err) 1089 } 1090 return err 1091 } 1092 1093 // isAllowedReadError returns whether or not the passed error is allowed without 1094 // disconnecting the peer. In particular, regression tests need to be allowed 1095 // to send malformed messages without the peer being disconnected. 1096 func (p *Peer) isAllowedReadError(err error) bool { 1097 // Only allow read errors in regression test mode. 1098 if p.cfg.ChainParams.Net != wire.TestNet { 1099 return false 1100 } 1101 1102 // Don't allow the error if it's not specifically a malformed message error. 1103 if _, ok := err.(*wire.MessageError); !ok { 1104 return false 1105 } 1106 1107 // Don't allow the error if it's not coming from localhost or the 1108 // hostname can't be determined for some reason. 1109 host, _, err := net.SplitHostPort(p.addr) 1110 if err != nil { 1111 return false 1112 } 1113 1114 if host != "127.0.0.1" && host != "localhost" { 1115 return false 1116 } 1117 1118 // Allowed if all checks passed. 1119 return true 1120 } 1121 1122 // shouldHandleReadError returns whether or not the passed error, which is 1123 // expected to have come from reading from the remote peer in the inHandler, 1124 // should be logged and responded to with a reject message. 1125 func (p *Peer) shouldHandleReadError(err error) bool { 1126 // No logging or reject message when the peer is being forcibly 1127 // disconnected. 1128 if atomic.LoadInt32(&p.disconnect) != 0 { 1129 return false 1130 } 1131 1132 // No logging or reject message when the remote peer has been 1133 // disconnected. 1134 if err == io.EOF { 1135 return false 1136 } 1137 if opErr, ok := err.(*net.OpError); ok && !opErr.Temporary() { 1138 return false 1139 } 1140 1141 return true 1142 } 1143 1144 // maybeAddDeadline potentially adds a deadline for the appropriate expected 1145 // response for the passed wire protocol command to the pending responses map. 1146 func (p *Peer) maybeAddDeadline(pendingResponses map[string]time.Time, msgCmd string) { 1147 // Setup a deadline for each message being sent that expects a response. 1148 // 1149 // NOTE: Pings are intentionally ignored here since they are typically 1150 // sent asynchronously and as a result of a long backlock of messages, 1151 // such as is typical in the case of initial block download, the 1152 // response won't be received in time. 1153 deadline := time.Now().Add(stallResponseTimeout) 1154 switch msgCmd { 1155 case wire.CmdVersion: 1156 // Expects a verack message. 1157 pendingResponses[wire.CmdVerAck] = deadline 1158 1159 case wire.CmdMemPool: 1160 // Expects an inv message. 1161 pendingResponses[wire.CmdInv] = deadline 1162 1163 case wire.CmdGetBlocks: 1164 // Expects an inv message. 1165 pendingResponses[wire.CmdInv] = deadline 1166 1167 case wire.CmdGetData: 1168 // Expects a block, merkleblock, tx, or notfound message. 1169 pendingResponses[wire.CmdBlock] = deadline 1170 pendingResponses[wire.CmdMerkleBlock] = deadline 1171 pendingResponses[wire.CmdTx] = deadline 1172 pendingResponses[wire.CmdNotFound] = deadline 1173 1174 case wire.CmdGetHeaders: 1175 // Expects a headers message. Use a longer deadline since it 1176 // can take a while for the remote peer to load all of the 1177 // headers. 1178 deadline = time.Now().Add(stallResponseTimeout * 3) 1179 pendingResponses[wire.CmdHeaders] = deadline 1180 } 1181 } 1182 1183 // stallHandler handles stall detection for the peer. This entails keeping 1184 // track of expected responses and assigning them deadlines while accounting for 1185 // the time spent in callbacks. It must be run as a goroutine. 1186 func (p *Peer) stallHandler() { 1187 // These variables are used to adjust the deadline times forward by the 1188 // time it takes callbacks to execute. This is done because new 1189 // messages aren't read until the previous one is finished processing 1190 // (which includes callbacks), so the deadline for receiving a response 1191 // for a given message must account for the processing time as well. 1192 var handlerActive bool 1193 var handlersStartTime time.Time 1194 var deadlineOffset time.Duration 1195 1196 // pendingResponses tracks the expected response deadline times. 1197 pendingResponses := make(map[string]time.Time) 1198 1199 // stallTicker is used to periodically check pending responses that have 1200 // exceeded the expected deadline and disconnect the peer due to 1201 // stalling. 1202 stallTicker := time.NewTicker(stallTickInterval) 1203 defer stallTicker.Stop() 1204 1205 // ioStopped is used to detect when both the input and output handler 1206 // goroutines are done. 1207 var ioStopped bool 1208 out: 1209 for { 1210 select { 1211 case msg := <-p.stallControl: 1212 if p.cfg.DisableStallHandler { 1213 continue 1214 } 1215 1216 switch msg.command { 1217 case sccSendMessage: 1218 // Add a deadline for the expected response 1219 // message if needed. 1220 p.maybeAddDeadline(pendingResponses, 1221 msg.message.Command()) 1222 1223 case sccReceiveMessage: 1224 // Remove received messages from the expected 1225 // response map. Since certain commands expect 1226 // one of a group of responses, remove 1227 // everything in the expected group accordingly. 1228 switch msgCmd := msg.message.Command(); msgCmd { 1229 case wire.CmdBlock: 1230 fallthrough 1231 case wire.CmdMerkleBlock: 1232 fallthrough 1233 case wire.CmdTx: 1234 fallthrough 1235 case wire.CmdNotFound: 1236 delete(pendingResponses, wire.CmdBlock) 1237 delete(pendingResponses, wire.CmdMerkleBlock) 1238 delete(pendingResponses, wire.CmdTx) 1239 delete(pendingResponses, wire.CmdNotFound) 1240 1241 default: 1242 delete(pendingResponses, msgCmd) 1243 } 1244 1245 case sccHandlerStart: 1246 // Warn on unbalanced callback signalling. 1247 if handlerActive { 1248 log.Warn("Received handler start " + 1249 "control command while a " + 1250 "handler is already active") 1251 continue 1252 } 1253 1254 handlerActive = true 1255 handlersStartTime = time.Now() 1256 1257 case sccHandlerDone: 1258 // Warn on unbalanced callback signalling. 1259 if !handlerActive { 1260 log.Warn("Received handler done " + 1261 "control command when a " + 1262 "handler is not already active") 1263 continue 1264 } 1265 1266 // Extend active deadlines by the time it took 1267 // to execute the callback. 1268 duration := time.Since(handlersStartTime) 1269 deadlineOffset += duration 1270 handlerActive = false 1271 1272 default: 1273 log.Warnf("Unsupported message command %v", 1274 msg.command) 1275 } 1276 1277 case <-stallTicker.C: 1278 if p.cfg.DisableStallHandler { 1279 continue 1280 } 1281 1282 // Calculate the offset to apply to the deadline based 1283 // on how long the handlers have taken to execute since 1284 // the last tick. 1285 now := time.Now() 1286 offset := deadlineOffset 1287 if handlerActive { 1288 offset += now.Sub(handlersStartTime) 1289 } 1290 1291 // Disconnect the peer if any of the pending responses 1292 // don't arrive by their adjusted deadline. 1293 for command, deadline := range pendingResponses { 1294 if now.Before(deadline.Add(offset)) { 1295 continue 1296 } 1297 1298 log.Debugf("Peer %s appears to be stalled or "+ 1299 "misbehaving, %s timeout -- "+ 1300 "disconnecting", p, command) 1301 p.Disconnect() 1302 break 1303 } 1304 1305 // Reset the deadline offset for the next tick. 1306 deadlineOffset = 0 1307 1308 case <-p.inQuit: 1309 // The stall handler can exit once both the input and 1310 // output handler goroutines are done. 1311 if ioStopped { 1312 break out 1313 } 1314 ioStopped = true 1315 1316 case <-p.outQuit: 1317 // The stall handler can exit once both the input and 1318 // output handler goroutines are done. 1319 if ioStopped { 1320 break out 1321 } 1322 ioStopped = true 1323 } 1324 } 1325 1326 // Drain any wait channels before going away so there is nothing left 1327 // waiting on this goroutine. 1328 cleanup: 1329 for { 1330 select { 1331 case <-p.stallControl: 1332 default: 1333 break cleanup 1334 } 1335 } 1336 log.Tracef("Peer stall handler done for %s", p) 1337 } 1338 1339 // inHandler handles all incoming messages for the peer. It must be run as a 1340 // goroutine. 1341 func (p *Peer) inHandler() { 1342 // The timer is stopped when a new message is received and reset after it 1343 // is processed. 1344 idleTimer := time.AfterFunc(idleTimeout, func() { 1345 log.Warnf("Peer %s no answer for %s -- disconnecting", p, idleTimeout) 1346 p.Disconnect() 1347 }) 1348 1349 out: 1350 for atomic.LoadInt32(&p.disconnect) == 0 { 1351 // Read a message and stop the idle timer as soon as the read 1352 // is done. The timer is reset below for the next iteration if 1353 // needed. 1354 rmsg, buf, err := p.readMessage(p.wireEncoding) 1355 idleTimer.Stop() 1356 if err != nil { 1357 // In order to allow regression tests with malformed messages, don't 1358 // disconnect the peer when we're in regression test mode and the 1359 // error is one of the allowed errors. 1360 if p.isAllowedReadError(err) { 1361 log.Errorf("Allowed test error from %s: %v", p, err) 1362 idleTimer.Reset(idleTimeout) 1363 continue 1364 } 1365 1366 // Only log the error and send reject message if the 1367 // local peer is not forcibly disconnecting and the 1368 // remote peer has not disconnected. 1369 if p.shouldHandleReadError(err) { 1370 errMsg := fmt.Sprintf("Can't read message from %s: %v", p, err) 1371 if err != io.ErrUnexpectedEOF { 1372 log.Errorf(errMsg) 1373 } 1374 1375 // Push a reject message for the malformed message and wait for 1376 // the message to be sent before disconnecting. 1377 // 1378 // NOTE: Ideally this would include the command in the header if 1379 // at least that much of the message was valid, but that is not 1380 // currently exposed by wire, so just used malformed for the 1381 // command. 1382 p.PushRejectMsg("malformed", wire.RejectMalformed, errMsg, nil, 1383 true) 1384 } 1385 break out 1386 } 1387 atomic.StoreInt64(&p.lastRecv, time.Now().Unix()) 1388 p.stallControl <- stallControlMsg{sccReceiveMessage, rmsg} 1389 1390 // Handle each supported message type. 1391 p.stallControl <- stallControlMsg{sccHandlerStart, rmsg} 1392 switch msg := rmsg.(type) { 1393 case *wire.MsgVersion: 1394 // Limit to one version message per peer. 1395 p.PushRejectMsg(msg.Command(), wire.RejectDuplicate, 1396 "duplicate version message", nil, true) 1397 break out 1398 1399 case *wire.MsgVerAck: 1400 // Limit to one verack message per peer. 1401 p.PushRejectMsg( 1402 msg.Command(), wire.RejectDuplicate, 1403 "duplicate verack message", nil, true, 1404 ) 1405 break out 1406 1407 case *wire.MsgGetAddr: 1408 if p.cfg.Listeners.OnGetAddr != nil { 1409 p.cfg.Listeners.OnGetAddr(p, msg) 1410 } 1411 1412 case *wire.MsgAddr: 1413 if p.cfg.Listeners.OnAddr != nil { 1414 p.cfg.Listeners.OnAddr(p, msg) 1415 } 1416 1417 case *wire.MsgPing: 1418 p.handlePingMsg(msg) 1419 if p.cfg.Listeners.OnPing != nil { 1420 p.cfg.Listeners.OnPing(p, msg) 1421 } 1422 1423 case *wire.MsgPong: 1424 p.handlePongMsg(msg) 1425 if p.cfg.Listeners.OnPong != nil { 1426 p.cfg.Listeners.OnPong(p, msg) 1427 } 1428 1429 case *wire.MsgAlert: 1430 if p.cfg.Listeners.OnAlert != nil { 1431 p.cfg.Listeners.OnAlert(p, msg) 1432 } 1433 1434 case *wire.MsgMemPool: 1435 if p.cfg.Listeners.OnMemPool != nil { 1436 p.cfg.Listeners.OnMemPool(p, msg) 1437 } 1438 1439 case *wire.MsgTx: 1440 if p.cfg.Listeners.OnTx != nil { 1441 p.cfg.Listeners.OnTx(p, msg) 1442 } 1443 1444 case *wire.MsgBlock: 1445 if p.cfg.Listeners.OnBlock != nil { 1446 p.cfg.Listeners.OnBlock(p, msg, buf) 1447 } 1448 1449 case *wire.MsgInv: 1450 if p.cfg.Listeners.OnInv != nil { 1451 p.cfg.Listeners.OnInv(p, msg) 1452 } 1453 1454 case *wire.MsgHeaders: 1455 if p.cfg.Listeners.OnHeaders != nil { 1456 p.cfg.Listeners.OnHeaders(p, msg) 1457 } 1458 1459 case *wire.MsgNotFound: 1460 if p.cfg.Listeners.OnNotFound != nil { 1461 p.cfg.Listeners.OnNotFound(p, msg) 1462 } 1463 1464 case *wire.MsgGetData: 1465 if p.cfg.Listeners.OnGetData != nil { 1466 p.cfg.Listeners.OnGetData(p, msg) 1467 } 1468 1469 case *wire.MsgGetBlocks: 1470 if p.cfg.Listeners.OnGetBlocks != nil { 1471 p.cfg.Listeners.OnGetBlocks(p, msg) 1472 } 1473 1474 case *wire.MsgGetHeaders: 1475 if p.cfg.Listeners.OnGetHeaders != nil { 1476 p.cfg.Listeners.OnGetHeaders(p, msg) 1477 } 1478 1479 case *wire.MsgGetCFilters: 1480 if p.cfg.Listeners.OnGetCFilters != nil { 1481 p.cfg.Listeners.OnGetCFilters(p, msg) 1482 } 1483 1484 case *wire.MsgGetCFHeaders: 1485 if p.cfg.Listeners.OnGetCFHeaders != nil { 1486 p.cfg.Listeners.OnGetCFHeaders(p, msg) 1487 } 1488 1489 case *wire.MsgGetCFCheckpt: 1490 if p.cfg.Listeners.OnGetCFCheckpt != nil { 1491 p.cfg.Listeners.OnGetCFCheckpt(p, msg) 1492 } 1493 1494 case *wire.MsgCFilter: 1495 if p.cfg.Listeners.OnCFilter != nil { 1496 p.cfg.Listeners.OnCFilter(p, msg) 1497 } 1498 1499 case *wire.MsgCFHeaders: 1500 if p.cfg.Listeners.OnCFHeaders != nil { 1501 p.cfg.Listeners.OnCFHeaders(p, msg) 1502 } 1503 1504 case *wire.MsgFeeFilter: 1505 if p.cfg.Listeners.OnFeeFilter != nil { 1506 p.cfg.Listeners.OnFeeFilter(p, msg) 1507 } 1508 1509 case *wire.MsgFilterAdd: 1510 if p.cfg.Listeners.OnFilterAdd != nil { 1511 p.cfg.Listeners.OnFilterAdd(p, msg) 1512 } 1513 1514 case *wire.MsgFilterClear: 1515 if p.cfg.Listeners.OnFilterClear != nil { 1516 p.cfg.Listeners.OnFilterClear(p, msg) 1517 } 1518 1519 case *wire.MsgFilterLoad: 1520 if p.cfg.Listeners.OnFilterLoad != nil { 1521 p.cfg.Listeners.OnFilterLoad(p, msg) 1522 } 1523 1524 case *wire.MsgMerkleBlock: 1525 if p.cfg.Listeners.OnMerkleBlock != nil { 1526 p.cfg.Listeners.OnMerkleBlock(p, msg) 1527 } 1528 1529 case *wire.MsgReject: 1530 if p.cfg.Listeners.OnReject != nil { 1531 p.cfg.Listeners.OnReject(p, msg) 1532 } 1533 1534 case *wire.MsgSendHeaders: 1535 p.flagsMtx.Lock() 1536 p.sendHeadersPreferred = true 1537 p.flagsMtx.Unlock() 1538 1539 if p.cfg.Listeners.OnSendHeaders != nil { 1540 p.cfg.Listeners.OnSendHeaders(p, msg) 1541 } 1542 1543 default: 1544 log.Debugf("Received unhandled message of type %v "+ 1545 "from %v", rmsg.Command(), p) 1546 } 1547 p.stallControl <- stallControlMsg{sccHandlerDone, rmsg} 1548 1549 // A message was received so reset the idle timer. 1550 idleTimer.Reset(idleTimeout) 1551 } 1552 1553 // Ensure the idle timer is stopped to avoid leaking the resource. 1554 idleTimer.Stop() 1555 1556 // Ensure connection is closed. 1557 p.Disconnect() 1558 1559 close(p.inQuit) 1560 log.Tracef("Peer input handler done for %s", p) 1561 } 1562 1563 // queueHandler handles the queuing of outgoing data for the peer. This runs as 1564 // a muxer for various sources of input so we can ensure that server and peer 1565 // handlers will not block on us sending a message. That data is then passed on 1566 // to outHandler to be actually written. 1567 func (p *Peer) queueHandler() { 1568 pendingMsgs := list.New() 1569 invSendQueue := list.New() 1570 trickleTicker := time.NewTicker(p.cfg.TrickleInterval) 1571 defer trickleTicker.Stop() 1572 1573 // We keep the waiting flag so that we know if we have a message queued 1574 // to the outHandler or not. We could use the presence of a head of 1575 // the list for this but then we have rather racy concerns about whether 1576 // it has gotten it at cleanup time - and thus who sends on the 1577 // message's done channel. To avoid such confusion we keep a different 1578 // flag and pendingMsgs only contains messages that we have not yet 1579 // passed to outHandler. 1580 waiting := false 1581 1582 // To avoid duplication below. 1583 queuePacket := func(msg outMsg, list *list.List, waiting bool) bool { 1584 if !waiting { 1585 p.sendQueue <- msg 1586 } else { 1587 list.PushBack(msg) 1588 } 1589 // we are always waiting now. 1590 return true 1591 } 1592 out: 1593 for { 1594 select { 1595 case msg := <-p.outputQueue: 1596 waiting = queuePacket(msg, pendingMsgs, waiting) 1597 1598 // This channel is notified when a message has been sent across 1599 // the network socket. 1600 case <-p.sendDoneQueue: 1601 // No longer waiting if there are no more messages 1602 // in the pending messages queue. 1603 next := pendingMsgs.Front() 1604 if next == nil { 1605 waiting = false 1606 continue 1607 } 1608 1609 // Notify the outHandler about the next item to 1610 // asynchronously send. 1611 val := pendingMsgs.Remove(next) 1612 p.sendQueue <- val.(outMsg) 1613 1614 case iv := <-p.outputInvChan: 1615 // No handshake? They'll find out soon enough. 1616 if p.VersionKnown() { 1617 // If this is a new block, then we'll blast it 1618 // out immediately, sipping the inv trickle 1619 // queue. 1620 if iv.Type == wire.InvTypeBlock || 1621 iv.Type == wire.InvTypeWitnessBlock { 1622 1623 invMsg := wire.NewMsgInvSizeHint(1) 1624 invMsg.AddInvVect(iv) 1625 waiting = queuePacket(outMsg{msg: invMsg}, 1626 pendingMsgs, waiting) 1627 } else { 1628 invSendQueue.PushBack(iv) 1629 } 1630 } 1631 1632 case <-trickleTicker.C: 1633 // Don't send anything if we're disconnecting or there 1634 // is no queued inventory. 1635 // version is known if send queue has any entries. 1636 if atomic.LoadInt32(&p.disconnect) != 0 || 1637 invSendQueue.Len() == 0 { 1638 continue 1639 } 1640 1641 // Create and send as many inv messages as needed to 1642 // drain the inventory send queue. 1643 invMsg := wire.NewMsgInvSizeHint(uint(invSendQueue.Len())) 1644 for e := invSendQueue.Front(); e != nil; e = invSendQueue.Front() { 1645 iv := invSendQueue.Remove(e).(*wire.InvVect) 1646 1647 // Don't send inventory that became known after 1648 // the initial check. 1649 if p.knownInventory.Contains(iv) { 1650 continue 1651 } 1652 1653 invMsg.AddInvVect(iv) 1654 if len(invMsg.InvList) >= maxInvTrickleSize { 1655 waiting = queuePacket( 1656 outMsg{msg: invMsg}, 1657 pendingMsgs, waiting) 1658 invMsg = wire.NewMsgInvSizeHint(uint(invSendQueue.Len())) 1659 } 1660 1661 // Add the inventory that is being relayed to 1662 // the known inventory for the peer. 1663 p.AddKnownInventory(iv) 1664 } 1665 if len(invMsg.InvList) > 0 { 1666 waiting = queuePacket(outMsg{msg: invMsg}, 1667 pendingMsgs, waiting) 1668 } 1669 1670 case <-p.quit: 1671 break out 1672 } 1673 } 1674 1675 // Drain any wait channels before we go away so we don't leave something 1676 // waiting for us. 1677 for e := pendingMsgs.Front(); e != nil; e = pendingMsgs.Front() { 1678 val := pendingMsgs.Remove(e) 1679 msg := val.(outMsg) 1680 if msg.doneChan != nil { 1681 msg.doneChan <- struct{}{} 1682 } 1683 } 1684 cleanup: 1685 for { 1686 select { 1687 case msg := <-p.outputQueue: 1688 if msg.doneChan != nil { 1689 msg.doneChan <- struct{}{} 1690 } 1691 case <-p.outputInvChan: 1692 // Just drain channel 1693 // sendDoneQueue is buffered so doesn't need draining. 1694 default: 1695 break cleanup 1696 } 1697 } 1698 close(p.queueQuit) 1699 log.Tracef("Peer queue handler done for %s", p) 1700 } 1701 1702 // shouldLogWriteError returns whether or not the passed error, which is 1703 // expected to have come from writing to the remote peer in the outHandler, 1704 // should be logged. 1705 func (p *Peer) shouldLogWriteError(err error) bool { 1706 // No logging when the peer is being forcibly disconnected. 1707 if atomic.LoadInt32(&p.disconnect) != 0 { 1708 return false 1709 } 1710 1711 // No logging when the remote peer has been disconnected. 1712 if err == io.EOF { 1713 return false 1714 } 1715 if opErr, ok := err.(*net.OpError); ok && !opErr.Temporary() { 1716 return false 1717 } 1718 1719 return true 1720 } 1721 1722 // outHandler handles all outgoing messages for the peer. It must be run as a 1723 // goroutine. It uses a buffered channel to serialize output messages while 1724 // allowing the sender to continue running asynchronously. 1725 func (p *Peer) outHandler() { 1726 out: 1727 for { 1728 select { 1729 case msg := <-p.sendQueue: 1730 switch m := msg.msg.(type) { 1731 case *wire.MsgPing: 1732 // Only expects a pong message in later protocol 1733 // versions. Also set up statistics. 1734 if p.ProtocolVersion() > wire.BIP0031Version { 1735 p.statsMtx.Lock() 1736 p.lastPingNonce = m.Nonce 1737 p.lastPingTime = time.Now() 1738 p.statsMtx.Unlock() 1739 } 1740 } 1741 1742 p.stallControl <- stallControlMsg{sccSendMessage, msg.msg} 1743 1744 err := p.writeMessage(msg.msg, msg.encoding) 1745 if err != nil { 1746 p.Disconnect() 1747 if p.shouldLogWriteError(err) { 1748 log.Errorf("Failed to send message to "+ 1749 "%s: %v", p, err) 1750 } 1751 if msg.doneChan != nil { 1752 msg.doneChan <- struct{}{} 1753 } 1754 continue 1755 } 1756 1757 // At this point, the message was successfully sent, so 1758 // update the last send time, signal the sender of the 1759 // message that it has been sent (if requested), and 1760 // signal the send queue to the deliver the next queued 1761 // message. 1762 atomic.StoreInt64(&p.lastSend, time.Now().Unix()) 1763 if msg.doneChan != nil { 1764 msg.doneChan <- struct{}{} 1765 } 1766 p.sendDoneQueue <- struct{}{} 1767 1768 case <-p.quit: 1769 break out 1770 } 1771 } 1772 1773 <-p.queueQuit 1774 1775 // Drain any wait channels before we go away so we don't leave something 1776 // waiting for us. We have waited on queueQuit and thus we can be sure 1777 // that we will not miss anything sent on sendQueue. 1778 cleanup: 1779 for { 1780 select { 1781 case msg := <-p.sendQueue: 1782 if msg.doneChan != nil { 1783 msg.doneChan <- struct{}{} 1784 } 1785 // no need to send on sendDoneQueue since queueHandler 1786 // has been waited on and already exited. 1787 default: 1788 break cleanup 1789 } 1790 } 1791 close(p.outQuit) 1792 log.Tracef("Peer output handler done for %s", p) 1793 } 1794 1795 // pingHandler periodically pings the peer. It must be run as a goroutine. 1796 func (p *Peer) pingHandler() { 1797 pingTicker := time.NewTicker(pingInterval) 1798 defer pingTicker.Stop() 1799 1800 out: 1801 for { 1802 select { 1803 case <-pingTicker.C: 1804 nonce, err := wire.RandomUint64() 1805 if err != nil { 1806 log.Errorf("Not sending ping to %s: %v", p, err) 1807 continue 1808 } 1809 p.QueueMessage(wire.NewMsgPing(nonce), nil) 1810 1811 case <-p.quit: 1812 break out 1813 } 1814 } 1815 } 1816 1817 // QueueMessage adds the passed bitcoin message to the peer send queue. 1818 // 1819 // This function is safe for concurrent access. 1820 func (p *Peer) QueueMessage(msg wire.Message, doneChan chan<- struct{}) { 1821 p.QueueMessageWithEncoding(msg, doneChan, wire.BaseEncoding) 1822 } 1823 1824 // QueueMessageWithEncoding adds the passed bitcoin message to the peer send 1825 // queue. This function is identical to QueueMessage, however it allows the 1826 // caller to specify the wire encoding type that should be used when 1827 // encoding/decoding blocks and transactions. 1828 // 1829 // This function is safe for concurrent access. 1830 func (p *Peer) QueueMessageWithEncoding(msg wire.Message, doneChan chan<- struct{}, 1831 encoding wire.MessageEncoding) { 1832 1833 // Avoid risk of deadlock if goroutine already exited. The goroutine 1834 // we will be sending to hangs around until it knows for a fact that 1835 // it is marked as disconnected and *then* it drains the channels. 1836 if !p.Connected() { 1837 if doneChan != nil { 1838 go func() { 1839 doneChan <- struct{}{} 1840 }() 1841 } 1842 return 1843 } 1844 p.outputQueue <- outMsg{msg: msg, encoding: encoding, doneChan: doneChan} 1845 } 1846 1847 // QueueInventory adds the passed inventory to the inventory send queue which 1848 // might not be sent right away, rather it is trickled to the peer in batches. 1849 // Inventory that the peer is already known to have is ignored. 1850 // 1851 // This function is safe for concurrent access. 1852 func (p *Peer) QueueInventory(invVect *wire.InvVect) { 1853 // Don't add the inventory to the send queue if the peer is already 1854 // known to have it. 1855 if p.knownInventory.Contains(invVect) { 1856 return 1857 } 1858 1859 // Avoid risk of deadlock if goroutine already exited. The goroutine 1860 // we will be sending to hangs around until it knows for a fact that 1861 // it is marked as disconnected and *then* it drains the channels. 1862 if !p.Connected() { 1863 return 1864 } 1865 1866 p.outputInvChan <- invVect 1867 } 1868 1869 // Connected returns whether or not the peer is currently connected. 1870 // 1871 // This function is safe for concurrent access. 1872 func (p *Peer) Connected() bool { 1873 return atomic.LoadInt32(&p.connected) != 0 && 1874 atomic.LoadInt32(&p.disconnect) == 0 1875 } 1876 1877 // Disconnect disconnects the peer by closing the connection. Calling this 1878 // function when the peer is already disconnected or in the process of 1879 // disconnecting will have no effect. 1880 func (p *Peer) Disconnect() { 1881 if atomic.AddInt32(&p.disconnect, 1) != 1 { 1882 return 1883 } 1884 1885 log.Tracef("Disconnecting %s", p) 1886 if atomic.LoadInt32(&p.connected) != 0 { 1887 p.conn.Close() 1888 } 1889 close(p.quit) 1890 } 1891 1892 // readRemoteVersionMsg waits for the next message to arrive from the remote 1893 // peer. If the next message is not a version message or the version is not 1894 // acceptable then return an error. 1895 func (p *Peer) readRemoteVersionMsg() error { 1896 // Read their version message. 1897 remoteMsg, _, err := p.readMessage(wire.LatestEncoding) 1898 if err != nil { 1899 return err 1900 } 1901 1902 // Notify and disconnect clients if the first message is not a version 1903 // message. 1904 msg, ok := remoteMsg.(*wire.MsgVersion) 1905 if !ok { 1906 reason := "a version message must precede all others" 1907 rejectMsg := wire.NewMsgReject(msg.Command(), wire.RejectMalformed, 1908 reason) 1909 _ = p.writeMessage(rejectMsg, wire.LatestEncoding) 1910 return errors.New(reason) 1911 } 1912 1913 // Detect self connections. 1914 if !p.cfg.AllowSelfConns && sentNonces.Contains(msg.Nonce) { 1915 return errors.New("disconnecting peer connected to self") 1916 } 1917 1918 // Negotiate the protocol version and set the services to what the remote 1919 // peer advertised. 1920 p.flagsMtx.Lock() 1921 p.advertisedProtoVer = uint32(msg.ProtocolVersion) 1922 p.protocolVersion = minUint32(p.protocolVersion, p.advertisedProtoVer) 1923 p.versionKnown = true 1924 p.services = msg.Services 1925 p.flagsMtx.Unlock() 1926 log.Debugf("Negotiated protocol version %d for peer %s", 1927 p.protocolVersion, p) 1928 1929 // Updating a bunch of stats including block based stats, and the 1930 // peer's time offset. 1931 p.statsMtx.Lock() 1932 p.lastBlock = msg.LastBlock 1933 p.startingHeight = msg.LastBlock 1934 p.timeOffset = msg.Timestamp.Unix() - time.Now().Unix() 1935 p.statsMtx.Unlock() 1936 1937 // Set the peer's ID, user agent, and potentially the flag which 1938 // specifies the witness support is enabled. 1939 p.flagsMtx.Lock() 1940 p.id = atomic.AddInt32(&nodeCount, 1) 1941 p.userAgent = msg.UserAgent 1942 1943 // Determine if the peer would like to receive witness data with 1944 // transactions, or not. 1945 if p.services&wire.SFNodeWitness == wire.SFNodeWitness { 1946 p.witnessEnabled = true 1947 } 1948 p.flagsMtx.Unlock() 1949 1950 // Once the version message has been exchanged, we're able to determine 1951 // if this peer knows how to encode witness data over the wire 1952 // protocol. If so, then we'll switch to a decoding mode which is 1953 // prepared for the new transaction format introduced as part of 1954 // BIP0144. 1955 if p.services&wire.SFNodeWitness == wire.SFNodeWitness { 1956 p.wireEncoding = wire.WitnessEncoding 1957 } 1958 1959 // Invoke the callback if specified. 1960 if p.cfg.Listeners.OnVersion != nil { 1961 rejectMsg := p.cfg.Listeners.OnVersion(p, msg) 1962 if rejectMsg != nil { 1963 _ = p.writeMessage(rejectMsg, wire.LatestEncoding) 1964 return errors.New(rejectMsg.Reason) 1965 } 1966 } 1967 1968 // Notify and disconnect clients that have a protocol version that is 1969 // too old. 1970 // 1971 // NOTE: If minAcceptableProtocolVersion is raised to be higher than 1972 // wire.RejectVersion, this should send a reject packet before 1973 // disconnecting. 1974 if uint32(msg.ProtocolVersion) < MinAcceptableProtocolVersion { 1975 // Send a reject message indicating the protocol version is 1976 // obsolete and wait for the message to be sent before 1977 // disconnecting. 1978 reason := fmt.Sprintf("protocol version must be %d or greater", 1979 MinAcceptableProtocolVersion) 1980 rejectMsg := wire.NewMsgReject(msg.Command(), wire.RejectObsolete, 1981 reason) 1982 _ = p.writeMessage(rejectMsg, wire.LatestEncoding) 1983 return errors.New(reason) 1984 } 1985 1986 return nil 1987 } 1988 1989 // readRemoteVerAckMsg waits for the next message to arrive from the remote 1990 // peer. If this message is not a verack message, then an error is returned. 1991 // This method is to be used as part of the version negotiation upon a new 1992 // connection. 1993 func (p *Peer) readRemoteVerAckMsg() error { 1994 // Read the next message from the wire. 1995 remoteMsg, _, err := p.readMessage(wire.LatestEncoding) 1996 if err != nil { 1997 return err 1998 } 1999 2000 // It should be a verack message, otherwise send a reject message to the 2001 // peer explaining why. 2002 msg, ok := remoteMsg.(*wire.MsgVerAck) 2003 if !ok { 2004 reason := "a verack message must follow version" 2005 rejectMsg := wire.NewMsgReject( 2006 msg.Command(), wire.RejectMalformed, reason, 2007 ) 2008 _ = p.writeMessage(rejectMsg, wire.LatestEncoding) 2009 return errors.New(reason) 2010 } 2011 2012 p.flagsMtx.Lock() 2013 p.verAckReceived = true 2014 p.flagsMtx.Unlock() 2015 2016 if p.cfg.Listeners.OnVerAck != nil { 2017 p.cfg.Listeners.OnVerAck(p, msg) 2018 } 2019 2020 return nil 2021 } 2022 2023 // localVersionMsg creates a version message that can be used to send to the 2024 // remote peer. 2025 func (p *Peer) localVersionMsg() (*wire.MsgVersion, error) { 2026 var blockNum int32 2027 if p.cfg.NewestBlock != nil { 2028 var err error 2029 _, blockNum, err = p.cfg.NewestBlock() 2030 if err != nil { 2031 return nil, err 2032 } 2033 } 2034 2035 theirNA := p.na 2036 2037 // If we are behind a proxy and the connection comes from the proxy then 2038 // we return an unroutable address as their address. This is to prevent 2039 // leaking the tor proxy address. 2040 if p.cfg.Proxy != "" { 2041 proxyaddress, _, err := net.SplitHostPort(p.cfg.Proxy) 2042 // invalid proxy means poorly configured, be on the safe side. 2043 if err != nil || p.na.IP.String() == proxyaddress { 2044 theirNA = wire.NewNetAddressIPPort(net.IP([]byte{0, 0, 0, 0}), 0, 2045 theirNA.Services) 2046 } 2047 } 2048 2049 // Create a wire.NetAddress with only the services set to use as the 2050 // "addrme" in the version message. 2051 // 2052 // Older nodes previously added the IP and port information to the 2053 // address manager which proved to be unreliable as an inbound 2054 // connection from a peer didn't necessarily mean the peer itself 2055 // accepted inbound connections. 2056 // 2057 // Also, the timestamp is unused in the version message. 2058 ourNA := &wire.NetAddress{ 2059 Services: p.cfg.Services, 2060 } 2061 2062 // Generate a unique nonce for this peer so self connections can be 2063 // detected. This is accomplished by adding it to a size-limited map of 2064 // recently seen nonces. 2065 nonce := uint64(rand.Int63()) 2066 sentNonces.Add(nonce) 2067 2068 // Version message. 2069 msg := wire.NewMsgVersion(ourNA, theirNA, nonce, blockNum) 2070 msg.AddUserAgent(p.cfg.UserAgentName, p.cfg.UserAgentVersion, 2071 p.cfg.UserAgentComments...) 2072 2073 // Advertise local services. 2074 msg.Services = p.cfg.Services 2075 2076 // Advertise our max supported protocol version. 2077 msg.ProtocolVersion = int32(p.cfg.ProtocolVersion) 2078 2079 // Advertise if inv messages for transactions are desired. 2080 msg.DisableRelayTx = p.cfg.DisableRelayTx 2081 2082 return msg, nil 2083 } 2084 2085 // writeLocalVersionMsg writes our version message to the remote peer. 2086 func (p *Peer) writeLocalVersionMsg() error { 2087 localVerMsg, err := p.localVersionMsg() 2088 if err != nil { 2089 return err 2090 } 2091 2092 return p.writeMessage(localVerMsg, wire.LatestEncoding) 2093 } 2094 2095 // negotiateInboundProtocol performs the negotiation protocol for an inbound 2096 // peer. The events should occur in the following order, otherwise an error is 2097 // returned: 2098 // 2099 // 1. Remote peer sends their version. 2100 // 2. We send our version. 2101 // 3. We send our verack. 2102 // 4. Remote peer sends their verack. 2103 func (p *Peer) negotiateInboundProtocol() error { 2104 if err := p.readRemoteVersionMsg(); err != nil { 2105 return err 2106 } 2107 2108 if err := p.writeLocalVersionMsg(); err != nil { 2109 return err 2110 } 2111 2112 err := p.writeMessage(wire.NewMsgVerAck(), wire.LatestEncoding) 2113 if err != nil { 2114 return err 2115 } 2116 2117 return p.readRemoteVerAckMsg() 2118 } 2119 2120 // negotiateOutboundProtocol performs the negotiation protocol for an outbound 2121 // peer. The events should occur in the following order, otherwise an error is 2122 // returned: 2123 // 2124 // 1. We send our version. 2125 // 2. Remote peer sends their version. 2126 // 3. Remote peer sends their verack. 2127 // 4. We send our verack. 2128 func (p *Peer) negotiateOutboundProtocol() error { 2129 if err := p.writeLocalVersionMsg(); err != nil { 2130 return err 2131 } 2132 2133 if err := p.readRemoteVersionMsg(); err != nil { 2134 return err 2135 } 2136 2137 if err := p.readRemoteVerAckMsg(); err != nil { 2138 return err 2139 } 2140 2141 return p.writeMessage(wire.NewMsgVerAck(), wire.LatestEncoding) 2142 } 2143 2144 // start begins processing input and output messages. 2145 func (p *Peer) start() error { 2146 log.Tracef("Starting peer %s", p) 2147 2148 negotiateErr := make(chan error, 1) 2149 go func() { 2150 if p.inbound { 2151 negotiateErr <- p.negotiateInboundProtocol() 2152 } else { 2153 negotiateErr <- p.negotiateOutboundProtocol() 2154 } 2155 }() 2156 2157 // Negotiate the protocol within the specified negotiateTimeout. 2158 select { 2159 case err := <-negotiateErr: 2160 if err != nil { 2161 p.Disconnect() 2162 return err 2163 } 2164 case <-time.After(negotiateTimeout): 2165 p.Disconnect() 2166 return errors.New("protocol negotiation timeout") 2167 } 2168 log.Debugf("Connected to %s", p.Addr()) 2169 2170 // The protocol has been negotiated successfully so start processing input 2171 // and output messages. 2172 go p.stallHandler() 2173 go p.inHandler() 2174 go p.queueHandler() 2175 go p.outHandler() 2176 go p.pingHandler() 2177 2178 return nil 2179 } 2180 2181 // AssociateConnection associates the given conn to the peer. Calling this 2182 // function when the peer is already connected will have no effect. 2183 func (p *Peer) AssociateConnection(conn net.Conn) { 2184 // Already connected? 2185 if !atomic.CompareAndSwapInt32(&p.connected, 0, 1) { 2186 return 2187 } 2188 2189 p.conn = conn 2190 p.timeConnected = time.Now() 2191 2192 if p.inbound { 2193 p.addr = p.conn.RemoteAddr().String() 2194 2195 // Set up a NetAddress for the peer to be used with AddrManager. We 2196 // only do this inbound because outbound set this up at connection time 2197 // and no point recomputing. 2198 na, err := newNetAddress(p.conn.RemoteAddr(), p.services) 2199 if err != nil { 2200 log.Errorf("Cannot create remote net address: %v", err) 2201 p.Disconnect() 2202 return 2203 } 2204 p.na = na 2205 } 2206 2207 go func() { 2208 if err := p.start(); err != nil { 2209 log.Debugf("Cannot start peer %v: %v", p, err) 2210 p.Disconnect() 2211 } 2212 }() 2213 } 2214 2215 // WaitForDisconnect waits until the peer has completely disconnected and all 2216 // resources are cleaned up. This will happen if either the local or remote 2217 // side has been disconnected or the peer is forcibly disconnected via 2218 // Disconnect. 2219 func (p *Peer) WaitForDisconnect() { 2220 <-p.quit 2221 } 2222 2223 // newPeerBase returns a new base bitcoin peer based on the inbound flag. This 2224 // is used by the NewInboundPeer and NewOutboundPeer functions to perform base 2225 // setup needed by both types of peers. 2226 func newPeerBase(origCfg *Config, inbound bool) *Peer { 2227 // Default to the max supported protocol version if not specified by the 2228 // caller. 2229 cfg := *origCfg // Copy to avoid mutating caller. 2230 if cfg.ProtocolVersion == 0 { 2231 cfg.ProtocolVersion = MaxProtocolVersion 2232 } 2233 2234 // Set the chain parameters to testnet if the caller did not specify any. 2235 if cfg.ChainParams == nil { 2236 cfg.ChainParams = &chaincfg.TestNet3Params 2237 } 2238 2239 // Set the trickle interval if a non-positive value is specified. 2240 if cfg.TrickleInterval <= 0 { 2241 cfg.TrickleInterval = DefaultTrickleInterval 2242 } 2243 2244 encoding := wire.BaseEncoding 2245 // we think this gets overwritten downstream. If not: 2246 // if cfg.Services&wire.SFNodeWitness > 0 { 2247 // encoding = wire.WitnessEncoding 2248 //} 2249 2250 p := Peer{ 2251 inbound: inbound, 2252 wireEncoding: encoding, 2253 knownInventory: lru.NewCache(maxKnownInventory), 2254 stallControl: make(chan stallControlMsg, 1), // nonblocking sync 2255 outputQueue: make(chan outMsg, outputBufferSize), 2256 sendQueue: make(chan outMsg, 1), // nonblocking sync 2257 sendDoneQueue: make(chan struct{}, 1), // nonblocking sync 2258 outputInvChan: make(chan *wire.InvVect, outputBufferSize), 2259 inQuit: make(chan struct{}), 2260 queueQuit: make(chan struct{}), 2261 outQuit: make(chan struct{}), 2262 quit: make(chan struct{}), 2263 cfg: cfg, // Copy so caller can't mutate. 2264 services: cfg.Services, 2265 protocolVersion: cfg.ProtocolVersion, 2266 } 2267 return &p 2268 } 2269 2270 // NewInboundPeer returns a new inbound bitcoin peer. Use Start to begin 2271 // processing incoming and outgoing messages. 2272 func NewInboundPeer(cfg *Config) *Peer { 2273 return newPeerBase(cfg, true) 2274 } 2275 2276 // NewOutboundPeer returns a new outbound bitcoin peer. 2277 func NewOutboundPeer(cfg *Config, addr string) (*Peer, error) { 2278 p := newPeerBase(cfg, false) 2279 p.addr = addr 2280 2281 host, portStr, err := net.SplitHostPort(addr) 2282 if err != nil { 2283 return nil, err 2284 } 2285 2286 port, err := strconv.ParseUint(portStr, 10, 16) 2287 if err != nil { 2288 return nil, err 2289 } 2290 2291 if cfg.HostToNetAddress != nil { 2292 na, err := cfg.HostToNetAddress(host, uint16(port), 0) 2293 if err != nil { 2294 return nil, err 2295 } 2296 p.na = na 2297 } else { 2298 p.na = wire.NewNetAddressIPPort(net.ParseIP(host), uint16(port), 0) 2299 } 2300 2301 return p, nil 2302 } 2303 2304 func init() { 2305 rand.Seed(time.Now().UnixNano()) 2306 }