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