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