github.com/BlockABC/godash@v0.0.0-20191112120524-f4aa3a32c566/peer/peer.go (about)

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