github.com/btcsuite/btcd@v0.24.0/server.go (about)

     1  // Copyright (c) 2013-2017 The btcsuite developers
     2  // Copyright (c) 2015-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 main
     7  
     8  import (
     9  	"bytes"
    10  	"crypto/rand"
    11  	"crypto/tls"
    12  	"encoding/binary"
    13  	"errors"
    14  	"fmt"
    15  	"math"
    16  	"net"
    17  	"runtime"
    18  	"sort"
    19  	"strconv"
    20  	"strings"
    21  	"sync"
    22  	"sync/atomic"
    23  	"time"
    24  
    25  	"github.com/btcsuite/btcd/addrmgr"
    26  	"github.com/btcsuite/btcd/blockchain"
    27  	"github.com/btcsuite/btcd/blockchain/indexers"
    28  	"github.com/btcsuite/btcd/btcutil"
    29  	"github.com/btcsuite/btcd/btcutil/bloom"
    30  	"github.com/btcsuite/btcd/chaincfg"
    31  	"github.com/btcsuite/btcd/chaincfg/chainhash"
    32  	"github.com/btcsuite/btcd/connmgr"
    33  	"github.com/btcsuite/btcd/database"
    34  	"github.com/btcsuite/btcd/mempool"
    35  	"github.com/btcsuite/btcd/mining"
    36  	"github.com/btcsuite/btcd/mining/cpuminer"
    37  	"github.com/btcsuite/btcd/netsync"
    38  	"github.com/btcsuite/btcd/peer"
    39  	"github.com/btcsuite/btcd/txscript"
    40  	"github.com/btcsuite/btcd/wire"
    41  	"github.com/decred/dcrd/lru"
    42  )
    43  
    44  const (
    45  	// defaultServices describes the default services that are supported by
    46  	// the server.
    47  	defaultServices = wire.SFNodeNetwork | wire.SFNodeNetworkLimited |
    48  		wire.SFNodeBloom | wire.SFNodeWitness | wire.SFNodeCF
    49  
    50  	// defaultRequiredServices describes the default services that are
    51  	// required to be supported by outbound peers.
    52  	defaultRequiredServices = wire.SFNodeNetwork
    53  
    54  	// defaultTargetOutbound is the default number of outbound peers to target.
    55  	defaultTargetOutbound = 8
    56  
    57  	// connectionRetryInterval is the base amount of time to wait in between
    58  	// retries when connecting to persistent peers.  It is adjusted by the
    59  	// number of retries such that there is a retry backoff.
    60  	connectionRetryInterval = time.Second * 5
    61  )
    62  
    63  var (
    64  	// userAgentName is the user agent name and is used to help identify
    65  	// ourselves to other bitcoin peers.
    66  	userAgentName = "btcd"
    67  
    68  	// userAgentVersion is the user agent version and is used to help
    69  	// identify ourselves to other bitcoin peers.
    70  	userAgentVersion = fmt.Sprintf("%d.%d.%d", appMajor, appMinor, appPatch)
    71  )
    72  
    73  // zeroHash is the zero value hash (all zeros).  It is defined as a convenience.
    74  var zeroHash chainhash.Hash
    75  
    76  // onionAddr implements the net.Addr interface and represents a tor address.
    77  type onionAddr struct {
    78  	addr string
    79  }
    80  
    81  // String returns the onion address.
    82  //
    83  // This is part of the net.Addr interface.
    84  func (oa *onionAddr) String() string {
    85  	return oa.addr
    86  }
    87  
    88  // Network returns "onion".
    89  //
    90  // This is part of the net.Addr interface.
    91  func (oa *onionAddr) Network() string {
    92  	return "onion"
    93  }
    94  
    95  // Ensure onionAddr implements the net.Addr interface.
    96  var _ net.Addr = (*onionAddr)(nil)
    97  
    98  // simpleAddr implements the net.Addr interface with two struct fields
    99  type simpleAddr struct {
   100  	net, addr string
   101  }
   102  
   103  // String returns the address.
   104  //
   105  // This is part of the net.Addr interface.
   106  func (a simpleAddr) String() string {
   107  	return a.addr
   108  }
   109  
   110  // Network returns the network.
   111  //
   112  // This is part of the net.Addr interface.
   113  func (a simpleAddr) Network() string {
   114  	return a.net
   115  }
   116  
   117  // Ensure simpleAddr implements the net.Addr interface.
   118  var _ net.Addr = simpleAddr{}
   119  
   120  // broadcastMsg provides the ability to house a bitcoin message to be broadcast
   121  // to all connected peers except specified excluded peers.
   122  type broadcastMsg struct {
   123  	message      wire.Message
   124  	excludePeers []*serverPeer
   125  }
   126  
   127  // broadcastInventoryAdd is a type used to declare that the InvVect it contains
   128  // needs to be added to the rebroadcast map
   129  type broadcastInventoryAdd relayMsg
   130  
   131  // broadcastInventoryDel is a type used to declare that the InvVect it contains
   132  // needs to be removed from the rebroadcast map
   133  type broadcastInventoryDel *wire.InvVect
   134  
   135  // relayMsg packages an inventory vector along with the newly discovered
   136  // inventory so the relay has access to that information.
   137  type relayMsg struct {
   138  	invVect *wire.InvVect
   139  	data    interface{}
   140  }
   141  
   142  // updatePeerHeightsMsg is a message sent from the blockmanager to the server
   143  // after a new block has been accepted. The purpose of the message is to update
   144  // the heights of peers that were known to announce the block before we
   145  // connected it to the main chain or recognized it as an orphan. With these
   146  // updates, peer heights will be kept up to date, allowing for fresh data when
   147  // selecting sync peer candidacy.
   148  type updatePeerHeightsMsg struct {
   149  	newHash    *chainhash.Hash
   150  	newHeight  int32
   151  	originPeer *peer.Peer
   152  }
   153  
   154  // peerState maintains state of inbound, persistent, outbound peers as well
   155  // as banned peers and outbound groups.
   156  type peerState struct {
   157  	inboundPeers    map[int32]*serverPeer
   158  	outboundPeers   map[int32]*serverPeer
   159  	persistentPeers map[int32]*serverPeer
   160  	banned          map[string]time.Time
   161  	outboundGroups  map[string]int
   162  }
   163  
   164  // Count returns the count of all known peers.
   165  func (ps *peerState) Count() int {
   166  	return len(ps.inboundPeers) + len(ps.outboundPeers) +
   167  		len(ps.persistentPeers)
   168  }
   169  
   170  // forAllOutboundPeers is a helper function that runs closure on all outbound
   171  // peers known to peerState.
   172  func (ps *peerState) forAllOutboundPeers(closure func(sp *serverPeer)) {
   173  	for _, e := range ps.outboundPeers {
   174  		closure(e)
   175  	}
   176  	for _, e := range ps.persistentPeers {
   177  		closure(e)
   178  	}
   179  }
   180  
   181  // forAllPeers is a helper function that runs closure on all peers known to
   182  // peerState.
   183  func (ps *peerState) forAllPeers(closure func(sp *serverPeer)) {
   184  	for _, e := range ps.inboundPeers {
   185  		closure(e)
   186  	}
   187  	ps.forAllOutboundPeers(closure)
   188  }
   189  
   190  // cfHeaderKV is a tuple of a filter header and its associated block hash. The
   191  // struct is used to cache cfcheckpt responses.
   192  type cfHeaderKV struct {
   193  	blockHash    chainhash.Hash
   194  	filterHeader chainhash.Hash
   195  }
   196  
   197  // server provides a bitcoin server for handling communications to and from
   198  // bitcoin peers.
   199  type server struct {
   200  	// The following variables must only be used atomically.
   201  	// Putting the uint64s first makes them 64-bit aligned for 32-bit systems.
   202  	bytesReceived uint64 // Total bytes received from all peers since start.
   203  	bytesSent     uint64 // Total bytes sent by all peers since start.
   204  	started       int32
   205  	shutdown      int32
   206  	shutdownSched int32
   207  	startupTime   int64
   208  
   209  	chainParams          *chaincfg.Params
   210  	addrManager          *addrmgr.AddrManager
   211  	connManager          *connmgr.ConnManager
   212  	sigCache             *txscript.SigCache
   213  	hashCache            *txscript.HashCache
   214  	rpcServer            *rpcServer
   215  	syncManager          *netsync.SyncManager
   216  	chain                *blockchain.BlockChain
   217  	txMemPool            *mempool.TxPool
   218  	cpuMiner             *cpuminer.CPUMiner
   219  	modifyRebroadcastInv chan interface{}
   220  	newPeers             chan *serverPeer
   221  	donePeers            chan *serverPeer
   222  	banPeers             chan *serverPeer
   223  	query                chan interface{}
   224  	relayInv             chan relayMsg
   225  	broadcast            chan broadcastMsg
   226  	peerHeightsUpdate    chan updatePeerHeightsMsg
   227  	wg                   sync.WaitGroup
   228  	quit                 chan struct{}
   229  	nat                  NAT
   230  	db                   database.DB
   231  	timeSource           blockchain.MedianTimeSource
   232  	services             wire.ServiceFlag
   233  
   234  	// The following fields are used for optional indexes.  They will be nil
   235  	// if the associated index is not enabled.  These fields are set during
   236  	// initial creation of the server and never changed afterwards, so they
   237  	// do not need to be protected for concurrent access.
   238  	txIndex   *indexers.TxIndex
   239  	addrIndex *indexers.AddrIndex
   240  	cfIndex   *indexers.CfIndex
   241  
   242  	// The fee estimator keeps track of how long transactions are left in
   243  	// the mempool before they are mined into blocks.
   244  	feeEstimator *mempool.FeeEstimator
   245  
   246  	// cfCheckptCaches stores a cached slice of filter headers for cfcheckpt
   247  	// messages for each filter type.
   248  	cfCheckptCaches    map[wire.FilterType][]cfHeaderKV
   249  	cfCheckptCachesMtx sync.RWMutex
   250  
   251  	// agentBlacklist is a list of blacklisted substrings by which to filter
   252  	// user agents.
   253  	agentBlacklist []string
   254  
   255  	// agentWhitelist is a list of whitelisted user agent substrings, no
   256  	// whitelisting will be applied if the list is empty or nil.
   257  	agentWhitelist []string
   258  }
   259  
   260  // serverPeer extends the peer to maintain state shared by the server and
   261  // the blockmanager.
   262  type serverPeer struct {
   263  	// The following variables must only be used atomically
   264  	feeFilter int64
   265  
   266  	*peer.Peer
   267  
   268  	connReq        *connmgr.ConnReq
   269  	server         *server
   270  	persistent     bool
   271  	continueHash   *chainhash.Hash
   272  	relayMtx       sync.Mutex
   273  	disableRelayTx bool
   274  	sentAddrs      bool
   275  	isWhitelisted  bool
   276  	filter         *bloom.Filter
   277  	addressesMtx   sync.RWMutex
   278  	knownAddresses lru.Cache
   279  	banScore       connmgr.DynamicBanScore
   280  	quit           chan struct{}
   281  	// The following chans are used to sync blockmanager and server.
   282  	txProcessed    chan struct{}
   283  	blockProcessed chan struct{}
   284  }
   285  
   286  // newServerPeer returns a new serverPeer instance. The peer needs to be set by
   287  // the caller.
   288  func newServerPeer(s *server, isPersistent bool) *serverPeer {
   289  	return &serverPeer{
   290  		server:         s,
   291  		persistent:     isPersistent,
   292  		filter:         bloom.LoadFilter(nil),
   293  		knownAddresses: lru.NewCache(5000),
   294  		quit:           make(chan struct{}),
   295  		txProcessed:    make(chan struct{}, 1),
   296  		blockProcessed: make(chan struct{}, 1),
   297  	}
   298  }
   299  
   300  // newestBlock returns the current best block hash and height using the format
   301  // required by the configuration for the peer package.
   302  func (sp *serverPeer) newestBlock() (*chainhash.Hash, int32, error) {
   303  	best := sp.server.chain.BestSnapshot()
   304  	return &best.Hash, best.Height, nil
   305  }
   306  
   307  // addKnownAddresses adds the given addresses to the set of known addresses to
   308  // the peer to prevent sending duplicate addresses.
   309  func (sp *serverPeer) addKnownAddresses(addresses []*wire.NetAddressV2) {
   310  	sp.addressesMtx.Lock()
   311  	for _, na := range addresses {
   312  		sp.knownAddresses.Add(addrmgr.NetAddressKey(na))
   313  	}
   314  	sp.addressesMtx.Unlock()
   315  }
   316  
   317  // addressKnown true if the given address is already known to the peer.
   318  func (sp *serverPeer) addressKnown(na *wire.NetAddressV2) bool {
   319  	sp.addressesMtx.RLock()
   320  	exists := sp.knownAddresses.Contains(addrmgr.NetAddressKey(na))
   321  	sp.addressesMtx.RUnlock()
   322  	return exists
   323  }
   324  
   325  // setDisableRelayTx toggles relaying of transactions for the given peer.
   326  // It is safe for concurrent access.
   327  func (sp *serverPeer) setDisableRelayTx(disable bool) {
   328  	sp.relayMtx.Lock()
   329  	sp.disableRelayTx = disable
   330  	sp.relayMtx.Unlock()
   331  }
   332  
   333  // relayTxDisabled returns whether or not relaying of transactions for the given
   334  // peer is disabled.
   335  // It is safe for concurrent access.
   336  func (sp *serverPeer) relayTxDisabled() bool {
   337  	sp.relayMtx.Lock()
   338  	isDisabled := sp.disableRelayTx
   339  	sp.relayMtx.Unlock()
   340  
   341  	return isDisabled
   342  }
   343  
   344  // pushAddrMsg sends a legacy addr message to the connected peer using the
   345  // provided addresses.
   346  func (sp *serverPeer) pushAddrMsg(addresses []*wire.NetAddressV2) {
   347  	if sp.WantsAddrV2() {
   348  		// If the peer supports addrv2, we'll be pushing an addrv2
   349  		// message instead. The logic is otherwise identical to the
   350  		// addr case below.
   351  		addrs := make([]*wire.NetAddressV2, 0, len(addresses))
   352  		for _, addr := range addresses {
   353  			// Filter addresses already known to the peer.
   354  			if sp.addressKnown(addr) {
   355  				continue
   356  			}
   357  
   358  			addrs = append(addrs, addr)
   359  		}
   360  
   361  		known, err := sp.PushAddrV2Msg(addrs)
   362  		if err != nil {
   363  			peerLog.Errorf("Can't push addrv2 message to %s: %v",
   364  				sp.Peer, err)
   365  			sp.Disconnect()
   366  			return
   367  		}
   368  
   369  		// Add the final set of addresses sent to the set the peer
   370  		// knows of.
   371  		sp.addKnownAddresses(known)
   372  		return
   373  	}
   374  
   375  	addrs := make([]*wire.NetAddress, 0, len(addresses))
   376  	for _, addr := range addresses {
   377  		// Filter addresses already known to the peer.
   378  		if sp.addressKnown(addr) {
   379  			continue
   380  		}
   381  
   382  		// Must skip the V3 addresses for legacy ADDR messages.
   383  		if addr.IsTorV3() {
   384  			continue
   385  		}
   386  
   387  		// Convert the NetAddressV2 to a legacy address.
   388  		addrs = append(addrs, addr.ToLegacy())
   389  	}
   390  
   391  	known, err := sp.PushAddrMsg(addrs)
   392  	if err != nil {
   393  		peerLog.Errorf(
   394  			"Can't push address message to %s: %v", sp.Peer, err,
   395  		)
   396  		sp.Disconnect()
   397  		return
   398  	}
   399  
   400  	// Convert all of the known addresses to NetAddressV2 to add them to
   401  	// the set of known addresses.
   402  	knownAddrs := make([]*wire.NetAddressV2, 0, len(known))
   403  	for _, knownAddr := range known {
   404  		currentKna := wire.NetAddressV2FromBytes(
   405  			knownAddr.Timestamp, knownAddr.Services,
   406  			knownAddr.IP, knownAddr.Port,
   407  		)
   408  		knownAddrs = append(knownAddrs, currentKna)
   409  	}
   410  	sp.addKnownAddresses(knownAddrs)
   411  }
   412  
   413  // addBanScore increases the persistent and decaying ban score fields by the
   414  // values passed as parameters. If the resulting score exceeds half of the ban
   415  // threshold, a warning is logged including the reason provided. Further, if
   416  // the score is above the ban threshold, the peer will be banned and
   417  // disconnected.
   418  func (sp *serverPeer) addBanScore(persistent, transient uint32, reason string) bool {
   419  	// No warning is logged and no score is calculated if banning is disabled.
   420  	if cfg.DisableBanning {
   421  		return false
   422  	}
   423  	if sp.isWhitelisted {
   424  		peerLog.Debugf("Misbehaving whitelisted peer %s: %s", sp, reason)
   425  		return false
   426  	}
   427  
   428  	warnThreshold := cfg.BanThreshold >> 1
   429  	if transient == 0 && persistent == 0 {
   430  		// The score is not being increased, but a warning message is still
   431  		// logged if the score is above the warn threshold.
   432  		score := sp.banScore.Int()
   433  		if score > warnThreshold {
   434  			peerLog.Warnf("Misbehaving peer %s: %s -- ban score is %d, "+
   435  				"it was not increased this time", sp, reason, score)
   436  		}
   437  		return false
   438  	}
   439  	score := sp.banScore.Increase(persistent, transient)
   440  	if score > warnThreshold {
   441  		peerLog.Warnf("Misbehaving peer %s: %s -- ban score increased to %d",
   442  			sp, reason, score)
   443  		if score > cfg.BanThreshold {
   444  			peerLog.Warnf("Misbehaving peer %s -- banning and disconnecting",
   445  				sp)
   446  			sp.server.BanPeer(sp)
   447  			sp.Disconnect()
   448  			return true
   449  		}
   450  	}
   451  	return false
   452  }
   453  
   454  // hasServices returns whether or not the provided advertised service flags have
   455  // all of the provided desired service flags set.
   456  func hasServices(advertised, desired wire.ServiceFlag) bool {
   457  	return advertised&desired == desired
   458  }
   459  
   460  // OnVersion is invoked when a peer receives a version bitcoin message
   461  // and is used to negotiate the protocol version details as well as kick start
   462  // the communications.
   463  func (sp *serverPeer) OnVersion(_ *peer.Peer, msg *wire.MsgVersion) *wire.MsgReject {
   464  	// Update the address manager with the advertised services for outbound
   465  	// connections in case they have changed.  This is not done for inbound
   466  	// connections to help prevent malicious behavior and is skipped when
   467  	// running on the simulation test network since it is only intended to
   468  	// connect to specified peers and actively avoids advertising and
   469  	// connecting to discovered peers.
   470  	//
   471  	// NOTE: This is done before rejecting peers that are too old to ensure
   472  	// it is updated regardless in the case a new minimum protocol version is
   473  	// enforced and the remote node has not upgraded yet.
   474  	isInbound := sp.Inbound()
   475  	remoteAddr := sp.NA()
   476  	addrManager := sp.server.addrManager
   477  	if !cfg.SimNet && !isInbound {
   478  		addrManager.SetServices(remoteAddr, msg.Services)
   479  	}
   480  
   481  	// Ignore peers that have a protcol version that is too old.  The peer
   482  	// negotiation logic will disconnect it after this callback returns.
   483  	if msg.ProtocolVersion < int32(peer.MinAcceptableProtocolVersion) {
   484  		return nil
   485  	}
   486  
   487  	// Reject outbound peers that are not full nodes.
   488  	wantServices := wire.SFNodeNetwork
   489  	if !isInbound && !hasServices(msg.Services, wantServices) {
   490  		missingServices := wantServices & ^msg.Services
   491  		srvrLog.Debugf("Rejecting peer %s with services %v due to not "+
   492  			"providing desired services %v", sp.Peer, msg.Services,
   493  			missingServices)
   494  		reason := fmt.Sprintf("required services %#x not offered",
   495  			uint64(missingServices))
   496  		return wire.NewMsgReject(msg.Command(), wire.RejectNonstandard, reason)
   497  	}
   498  
   499  	if !cfg.SimNet && !isInbound {
   500  		// After soft-fork activation, only make outbound
   501  		// connection to peers if they flag that they're segwit
   502  		// enabled.
   503  		chain := sp.server.chain
   504  		segwitActive, err := chain.IsDeploymentActive(chaincfg.DeploymentSegwit)
   505  		if err != nil {
   506  			peerLog.Errorf("Unable to query for segwit soft-fork state: %v",
   507  				err)
   508  			return nil
   509  		}
   510  
   511  		if segwitActive && !sp.IsWitnessEnabled() {
   512  			peerLog.Infof("Disconnecting non-segwit peer %v, isn't segwit "+
   513  				"enabled and we need more segwit enabled peers", sp)
   514  			sp.Disconnect()
   515  			return nil
   516  		}
   517  	}
   518  
   519  	// Add the remote peer time as a sample for creating an offset against
   520  	// the local clock to keep the network time in sync.
   521  	sp.server.timeSource.AddTimeSample(sp.Addr(), msg.Timestamp)
   522  
   523  	// Choose whether or not to relay transactions before a filter command
   524  	// is received.
   525  	sp.setDisableRelayTx(msg.DisableRelayTx)
   526  
   527  	return nil
   528  }
   529  
   530  // OnVerAck is invoked when a peer receives a verack bitcoin message and is used
   531  // to kick start communication with them.
   532  func (sp *serverPeer) OnVerAck(_ *peer.Peer, _ *wire.MsgVerAck) {
   533  	sp.server.AddPeer(sp)
   534  }
   535  
   536  // OnMemPool is invoked when a peer receives a mempool bitcoin message.
   537  // It creates and sends an inventory message with the contents of the memory
   538  // pool up to the maximum inventory allowed per message.  When the peer has a
   539  // bloom filter loaded, the contents are filtered accordingly.
   540  func (sp *serverPeer) OnMemPool(_ *peer.Peer, msg *wire.MsgMemPool) {
   541  	// Only allow mempool requests if the server has bloom filtering
   542  	// enabled.
   543  	if sp.server.services&wire.SFNodeBloom != wire.SFNodeBloom {
   544  		peerLog.Debugf("peer %v sent mempool request with bloom "+
   545  			"filtering disabled -- disconnecting", sp)
   546  		sp.Disconnect()
   547  		return
   548  	}
   549  
   550  	// A decaying ban score increase is applied to prevent flooding.
   551  	// The ban score accumulates and passes the ban threshold if a burst of
   552  	// mempool messages comes from a peer. The score decays each minute to
   553  	// half of its value.
   554  	if sp.addBanScore(0, 33, "mempool") {
   555  		return
   556  	}
   557  
   558  	// Generate inventory message with the available transactions in the
   559  	// transaction memory pool.  Limit it to the max allowed inventory
   560  	// per message.  The NewMsgInvSizeHint function automatically limits
   561  	// the passed hint to the maximum allowed, so it's safe to pass it
   562  	// without double checking it here.
   563  	txMemPool := sp.server.txMemPool
   564  	txDescs := txMemPool.TxDescs()
   565  	invMsg := wire.NewMsgInvSizeHint(uint(len(txDescs)))
   566  
   567  	for _, txDesc := range txDescs {
   568  		// Either add all transactions when there is no bloom filter,
   569  		// or only the transactions that match the filter when there is
   570  		// one.
   571  		if !sp.filter.IsLoaded() || sp.filter.MatchTxAndUpdate(txDesc.Tx) {
   572  			iv := wire.NewInvVect(wire.InvTypeTx, txDesc.Tx.Hash())
   573  			invMsg.AddInvVect(iv)
   574  			if len(invMsg.InvList)+1 > wire.MaxInvPerMsg {
   575  				break
   576  			}
   577  		}
   578  	}
   579  
   580  	// Send the inventory message if there is anything to send.
   581  	if len(invMsg.InvList) > 0 {
   582  		sp.QueueMessage(invMsg, nil)
   583  	}
   584  }
   585  
   586  // OnTx is invoked when a peer receives a tx bitcoin message.  It blocks
   587  // until the bitcoin transaction has been fully processed.  Unlock the block
   588  // handler this does not serialize all transactions through a single thread
   589  // transactions don't rely on the previous one in a linear fashion like blocks.
   590  func (sp *serverPeer) OnTx(_ *peer.Peer, msg *wire.MsgTx) {
   591  	if cfg.BlocksOnly {
   592  		peerLog.Tracef("Ignoring tx %v from %v - blocksonly enabled",
   593  			msg.TxHash(), sp)
   594  		return
   595  	}
   596  
   597  	// Add the transaction to the known inventory for the peer.
   598  	// Convert the raw MsgTx to a btcutil.Tx which provides some convenience
   599  	// methods and things such as hash caching.
   600  	tx := btcutil.NewTx(msg)
   601  	iv := wire.NewInvVect(wire.InvTypeTx, tx.Hash())
   602  	sp.AddKnownInventory(iv)
   603  
   604  	// Queue the transaction up to be handled by the sync manager and
   605  	// intentionally block further receives until the transaction is fully
   606  	// processed and known good or bad.  This helps prevent a malicious peer
   607  	// from queuing up a bunch of bad transactions before disconnecting (or
   608  	// being disconnected) and wasting memory.
   609  	sp.server.syncManager.QueueTx(tx, sp.Peer, sp.txProcessed)
   610  	<-sp.txProcessed
   611  }
   612  
   613  // OnBlock is invoked when a peer receives a block bitcoin message.  It
   614  // blocks until the bitcoin block has been fully processed.
   615  func (sp *serverPeer) OnBlock(_ *peer.Peer, msg *wire.MsgBlock, buf []byte) {
   616  	// Convert the raw MsgBlock to a btcutil.Block which provides some
   617  	// convenience methods and things such as hash caching.
   618  	block := btcutil.NewBlockFromBlockAndBytes(msg, buf)
   619  
   620  	// Add the block to the known inventory for the peer.
   621  	iv := wire.NewInvVect(wire.InvTypeBlock, block.Hash())
   622  	sp.AddKnownInventory(iv)
   623  
   624  	// Queue the block up to be handled by the block
   625  	// manager and intentionally block further receives
   626  	// until the bitcoin block is fully processed and known
   627  	// good or bad.  This helps prevent a malicious peer
   628  	// from queuing up a bunch of bad blocks before
   629  	// disconnecting (or being disconnected) and wasting
   630  	// memory.  Additionally, this behavior is depended on
   631  	// by at least the block acceptance test tool as the
   632  	// reference implementation processes blocks in the same
   633  	// thread and therefore blocks further messages until
   634  	// the bitcoin block has been fully processed.
   635  	sp.server.syncManager.QueueBlock(block, sp.Peer, sp.blockProcessed)
   636  	<-sp.blockProcessed
   637  }
   638  
   639  // OnInv is invoked when a peer receives an inv bitcoin message and is
   640  // used to examine the inventory being advertised by the remote peer and react
   641  // accordingly.  We pass the message down to blockmanager which will call
   642  // QueueMessage with any appropriate responses.
   643  func (sp *serverPeer) OnInv(_ *peer.Peer, msg *wire.MsgInv) {
   644  	if !cfg.BlocksOnly {
   645  		if len(msg.InvList) > 0 {
   646  			sp.server.syncManager.QueueInv(msg, sp.Peer)
   647  		}
   648  		return
   649  	}
   650  
   651  	newInv := wire.NewMsgInvSizeHint(uint(len(msg.InvList)))
   652  	for _, invVect := range msg.InvList {
   653  		if invVect.Type == wire.InvTypeTx {
   654  			peerLog.Tracef("Ignoring tx %v in inv from %v -- "+
   655  				"blocksonly enabled", invVect.Hash, sp)
   656  			if sp.ProtocolVersion() >= wire.BIP0037Version {
   657  				peerLog.Infof("Peer %v is announcing "+
   658  					"transactions -- disconnecting", sp)
   659  				sp.Disconnect()
   660  				return
   661  			}
   662  			continue
   663  		}
   664  		err := newInv.AddInvVect(invVect)
   665  		if err != nil {
   666  			peerLog.Errorf("Failed to add inventory vector: %v", err)
   667  			break
   668  		}
   669  	}
   670  
   671  	if len(newInv.InvList) > 0 {
   672  		sp.server.syncManager.QueueInv(newInv, sp.Peer)
   673  	}
   674  }
   675  
   676  // OnHeaders is invoked when a peer receives a headers bitcoin
   677  // message.  The message is passed down to the sync manager.
   678  func (sp *serverPeer) OnHeaders(_ *peer.Peer, msg *wire.MsgHeaders) {
   679  	sp.server.syncManager.QueueHeaders(msg, sp.Peer)
   680  }
   681  
   682  // handleGetData is invoked when a peer receives a getdata bitcoin message and
   683  // is used to deliver block and transaction information.
   684  func (sp *serverPeer) OnGetData(_ *peer.Peer, msg *wire.MsgGetData) {
   685  	numAdded := 0
   686  	notFound := wire.NewMsgNotFound()
   687  
   688  	length := len(msg.InvList)
   689  	// A decaying ban score increase is applied to prevent exhausting resources
   690  	// with unusually large inventory queries.
   691  	// Requesting more than the maximum inventory vector length within a short
   692  	// period of time yields a score above the default ban threshold. Sustained
   693  	// bursts of small requests are not penalized as that would potentially ban
   694  	// peers performing IBD.
   695  	// This incremental score decays each minute to half of its value.
   696  	if sp.addBanScore(0, uint32(length)*99/wire.MaxInvPerMsg, "getdata") {
   697  		return
   698  	}
   699  
   700  	// We wait on this wait channel periodically to prevent queuing
   701  	// far more data than we can send in a reasonable time, wasting memory.
   702  	// The waiting occurs after the database fetch for the next one to
   703  	// provide a little pipelining.
   704  	var waitChan chan struct{}
   705  	doneChan := make(chan struct{}, 1)
   706  
   707  	for i, iv := range msg.InvList {
   708  		var c chan struct{}
   709  		// If this will be the last message we send.
   710  		if i == length-1 && len(notFound.InvList) == 0 {
   711  			c = doneChan
   712  		} else if (i+1)%3 == 0 {
   713  			// Buffered so as to not make the send goroutine block.
   714  			c = make(chan struct{}, 1)
   715  		}
   716  		var err error
   717  		switch iv.Type {
   718  		case wire.InvTypeWitnessTx:
   719  			err = sp.server.pushTxMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
   720  		case wire.InvTypeTx:
   721  			err = sp.server.pushTxMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
   722  		case wire.InvTypeWitnessBlock:
   723  			err = sp.server.pushBlockMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
   724  		case wire.InvTypeBlock:
   725  			err = sp.server.pushBlockMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
   726  		case wire.InvTypeFilteredWitnessBlock:
   727  			err = sp.server.pushMerkleBlockMsg(sp, &iv.Hash, c, waitChan, wire.WitnessEncoding)
   728  		case wire.InvTypeFilteredBlock:
   729  			err = sp.server.pushMerkleBlockMsg(sp, &iv.Hash, c, waitChan, wire.BaseEncoding)
   730  		default:
   731  			peerLog.Warnf("Unknown type in inventory request %d",
   732  				iv.Type)
   733  			continue
   734  		}
   735  		if err != nil {
   736  			notFound.AddInvVect(iv)
   737  
   738  			// When there is a failure fetching the final entry
   739  			// and the done channel was sent in due to there
   740  			// being no outstanding not found inventory, consume
   741  			// it here because there is now not found inventory
   742  			// that will use the channel momentarily.
   743  			if i == len(msg.InvList)-1 && c != nil {
   744  				<-c
   745  			}
   746  		}
   747  		numAdded++
   748  		waitChan = c
   749  	}
   750  	if len(notFound.InvList) != 0 {
   751  		sp.QueueMessage(notFound, doneChan)
   752  	}
   753  
   754  	// Wait for messages to be sent. We can send quite a lot of data at this
   755  	// point and this will keep the peer busy for a decent amount of time.
   756  	// We don't process anything else by them in this time so that we
   757  	// have an idea of when we should hear back from them - else the idle
   758  	// timeout could fire when we were only half done sending the blocks.
   759  	if numAdded > 0 {
   760  		<-doneChan
   761  	}
   762  }
   763  
   764  // OnGetBlocks is invoked when a peer receives a getblocks bitcoin
   765  // message.
   766  func (sp *serverPeer) OnGetBlocks(_ *peer.Peer, msg *wire.MsgGetBlocks) {
   767  	// Find the most recent known block in the best chain based on the block
   768  	// locator and fetch all of the block hashes after it until either
   769  	// wire.MaxBlocksPerMsg have been fetched or the provided stop hash is
   770  	// encountered.
   771  	//
   772  	// Use the block after the genesis block if no other blocks in the
   773  	// provided locator are known.  This does mean the client will start
   774  	// over with the genesis block if unknown block locators are provided.
   775  	//
   776  	// This mirrors the behavior in the reference implementation.
   777  	chain := sp.server.chain
   778  	hashList := chain.LocateBlocks(msg.BlockLocatorHashes, &msg.HashStop,
   779  		wire.MaxBlocksPerMsg)
   780  
   781  	// Generate inventory message.
   782  	invMsg := wire.NewMsgInv()
   783  	for i := range hashList {
   784  		iv := wire.NewInvVect(wire.InvTypeBlock, &hashList[i])
   785  		invMsg.AddInvVect(iv)
   786  	}
   787  
   788  	// Send the inventory message if there is anything to send.
   789  	if len(invMsg.InvList) > 0 {
   790  		invListLen := len(invMsg.InvList)
   791  		if invListLen == wire.MaxBlocksPerMsg {
   792  			// Intentionally use a copy of the final hash so there
   793  			// is not a reference into the inventory slice which
   794  			// would prevent the entire slice from being eligible
   795  			// for GC as soon as it's sent.
   796  			continueHash := invMsg.InvList[invListLen-1].Hash
   797  			sp.continueHash = &continueHash
   798  		}
   799  		sp.QueueMessage(invMsg, nil)
   800  	}
   801  }
   802  
   803  // OnGetHeaders is invoked when a peer receives a getheaders bitcoin
   804  // message.
   805  func (sp *serverPeer) OnGetHeaders(_ *peer.Peer, msg *wire.MsgGetHeaders) {
   806  	// Ignore getheaders requests if not in sync.
   807  	if !sp.server.syncManager.IsCurrent() {
   808  		return
   809  	}
   810  
   811  	// Find the most recent known block in the best chain based on the block
   812  	// locator and fetch all of the headers after it until either
   813  	// wire.MaxBlockHeadersPerMsg have been fetched or the provided stop
   814  	// hash is encountered.
   815  	//
   816  	// Use the block after the genesis block if no other blocks in the
   817  	// provided locator are known.  This does mean the client will start
   818  	// over with the genesis block if unknown block locators are provided.
   819  	//
   820  	// This mirrors the behavior in the reference implementation.
   821  	chain := sp.server.chain
   822  	headers := chain.LocateHeaders(msg.BlockLocatorHashes, &msg.HashStop)
   823  
   824  	// Send found headers to the requesting peer.
   825  	blockHeaders := make([]*wire.BlockHeader, len(headers))
   826  	for i := range headers {
   827  		blockHeaders[i] = &headers[i]
   828  	}
   829  	sp.QueueMessage(&wire.MsgHeaders{Headers: blockHeaders}, nil)
   830  }
   831  
   832  // OnGetCFilters is invoked when a peer receives a getcfilters bitcoin message.
   833  func (sp *serverPeer) OnGetCFilters(_ *peer.Peer, msg *wire.MsgGetCFilters) {
   834  	// Ignore getcfilters requests if not in sync.
   835  	if !sp.server.syncManager.IsCurrent() {
   836  		return
   837  	}
   838  
   839  	// We'll also ensure that the remote party is requesting a set of
   840  	// filters that we actually currently maintain.
   841  	switch msg.FilterType {
   842  	case wire.GCSFilterRegular:
   843  		break
   844  
   845  	default:
   846  		peerLog.Debug("Filter request for unknown filter: %v",
   847  			msg.FilterType)
   848  		return
   849  	}
   850  
   851  	hashes, err := sp.server.chain.HeightToHashRange(
   852  		int32(msg.StartHeight), &msg.StopHash, wire.MaxGetCFiltersReqRange,
   853  	)
   854  	if err != nil {
   855  		peerLog.Debugf("Invalid getcfilters request: %v", err)
   856  		return
   857  	}
   858  
   859  	// Create []*chainhash.Hash from []chainhash.Hash to pass to
   860  	// FiltersByBlockHashes.
   861  	hashPtrs := make([]*chainhash.Hash, len(hashes))
   862  	for i := range hashes {
   863  		hashPtrs[i] = &hashes[i]
   864  	}
   865  
   866  	filters, err := sp.server.cfIndex.FiltersByBlockHashes(
   867  		hashPtrs, msg.FilterType,
   868  	)
   869  	if err != nil {
   870  		peerLog.Errorf("Error retrieving cfilters: %v", err)
   871  		return
   872  	}
   873  
   874  	for i, filterBytes := range filters {
   875  		if len(filterBytes) == 0 {
   876  			peerLog.Warnf("Could not obtain cfilter for %v",
   877  				hashes[i])
   878  			return
   879  		}
   880  
   881  		filterMsg := wire.NewMsgCFilter(
   882  			msg.FilterType, &hashes[i], filterBytes,
   883  		)
   884  		sp.QueueMessage(filterMsg, nil)
   885  	}
   886  }
   887  
   888  // OnGetCFHeaders is invoked when a peer receives a getcfheader bitcoin message.
   889  func (sp *serverPeer) OnGetCFHeaders(_ *peer.Peer, msg *wire.MsgGetCFHeaders) {
   890  	// Ignore getcfilterheader requests if not in sync.
   891  	if !sp.server.syncManager.IsCurrent() {
   892  		return
   893  	}
   894  
   895  	// We'll also ensure that the remote party is requesting a set of
   896  	// headers for filters that we actually currently maintain.
   897  	switch msg.FilterType {
   898  	case wire.GCSFilterRegular:
   899  		break
   900  
   901  	default:
   902  		peerLog.Debug("Filter request for unknown headers for "+
   903  			"filter: %v", msg.FilterType)
   904  		return
   905  	}
   906  
   907  	startHeight := int32(msg.StartHeight)
   908  	maxResults := wire.MaxCFHeadersPerMsg
   909  
   910  	// If StartHeight is positive, fetch the predecessor block hash so we
   911  	// can populate the PrevFilterHeader field.
   912  	if msg.StartHeight > 0 {
   913  		startHeight--
   914  		maxResults++
   915  	}
   916  
   917  	// Fetch the hashes from the block index.
   918  	hashList, err := sp.server.chain.HeightToHashRange(
   919  		startHeight, &msg.StopHash, maxResults,
   920  	)
   921  	if err != nil {
   922  		peerLog.Debugf("Invalid getcfheaders request: %v", err)
   923  	}
   924  
   925  	// This is possible if StartHeight is one greater that the height of
   926  	// StopHash, and we pull a valid range of hashes including the previous
   927  	// filter header.
   928  	if len(hashList) == 0 || (msg.StartHeight > 0 && len(hashList) == 1) {
   929  		peerLog.Debug("No results for getcfheaders request")
   930  		return
   931  	}
   932  
   933  	// Create []*chainhash.Hash from []chainhash.Hash to pass to
   934  	// FilterHeadersByBlockHashes.
   935  	hashPtrs := make([]*chainhash.Hash, len(hashList))
   936  	for i := range hashList {
   937  		hashPtrs[i] = &hashList[i]
   938  	}
   939  
   940  	// Fetch the raw filter hash bytes from the database for all blocks.
   941  	filterHashes, err := sp.server.cfIndex.FilterHashesByBlockHashes(
   942  		hashPtrs, msg.FilterType,
   943  	)
   944  	if err != nil {
   945  		peerLog.Errorf("Error retrieving cfilter hashes: %v", err)
   946  		return
   947  	}
   948  
   949  	// Generate cfheaders message and send it.
   950  	headersMsg := wire.NewMsgCFHeaders()
   951  
   952  	// Populate the PrevFilterHeader field.
   953  	if msg.StartHeight > 0 {
   954  		prevBlockHash := &hashList[0]
   955  
   956  		// Fetch the raw committed filter header bytes from the
   957  		// database.
   958  		headerBytes, err := sp.server.cfIndex.FilterHeaderByBlockHash(
   959  			prevBlockHash, msg.FilterType)
   960  		if err != nil {
   961  			peerLog.Errorf("Error retrieving CF header: %v", err)
   962  			return
   963  		}
   964  		if len(headerBytes) == 0 {
   965  			peerLog.Warnf("Could not obtain CF header for %v", prevBlockHash)
   966  			return
   967  		}
   968  
   969  		// Deserialize the hash into PrevFilterHeader.
   970  		err = headersMsg.PrevFilterHeader.SetBytes(headerBytes)
   971  		if err != nil {
   972  			peerLog.Warnf("Committed filter header deserialize "+
   973  				"failed: %v", err)
   974  			return
   975  		}
   976  
   977  		hashList = hashList[1:]
   978  		filterHashes = filterHashes[1:]
   979  	}
   980  
   981  	// Populate HeaderHashes.
   982  	for i, hashBytes := range filterHashes {
   983  		if len(hashBytes) == 0 {
   984  			peerLog.Warnf("Could not obtain CF hash for %v", hashList[i])
   985  			return
   986  		}
   987  
   988  		// Deserialize the hash.
   989  		filterHash, err := chainhash.NewHash(hashBytes)
   990  		if err != nil {
   991  			peerLog.Warnf("Committed filter hash deserialize "+
   992  				"failed: %v", err)
   993  			return
   994  		}
   995  
   996  		headersMsg.AddCFHash(filterHash)
   997  	}
   998  
   999  	headersMsg.FilterType = msg.FilterType
  1000  	headersMsg.StopHash = msg.StopHash
  1001  
  1002  	sp.QueueMessage(headersMsg, nil)
  1003  }
  1004  
  1005  // OnGetCFCheckpt is invoked when a peer receives a getcfcheckpt bitcoin message.
  1006  func (sp *serverPeer) OnGetCFCheckpt(_ *peer.Peer, msg *wire.MsgGetCFCheckpt) {
  1007  	// Ignore getcfcheckpt requests if not in sync.
  1008  	if !sp.server.syncManager.IsCurrent() {
  1009  		return
  1010  	}
  1011  
  1012  	// We'll also ensure that the remote party is requesting a set of
  1013  	// checkpoints for filters that we actually currently maintain.
  1014  	switch msg.FilterType {
  1015  	case wire.GCSFilterRegular:
  1016  		break
  1017  
  1018  	default:
  1019  		peerLog.Debug("Filter request for unknown checkpoints for "+
  1020  			"filter: %v", msg.FilterType)
  1021  		return
  1022  	}
  1023  
  1024  	// Now that we know the client is fetching a filter that we know of,
  1025  	// we'll fetch the block hashes et each check point interval so we can
  1026  	// compare against our cache, and create new check points if necessary.
  1027  	blockHashes, err := sp.server.chain.IntervalBlockHashes(
  1028  		&msg.StopHash, wire.CFCheckptInterval,
  1029  	)
  1030  	if err != nil {
  1031  		peerLog.Debugf("Invalid getcfilters request: %v", err)
  1032  		return
  1033  	}
  1034  
  1035  	checkptMsg := wire.NewMsgCFCheckpt(
  1036  		msg.FilterType, &msg.StopHash, len(blockHashes),
  1037  	)
  1038  
  1039  	// Fetch the current existing cache so we can decide if we need to
  1040  	// extend it or if its adequate as is.
  1041  	sp.server.cfCheckptCachesMtx.RLock()
  1042  	checkptCache := sp.server.cfCheckptCaches[msg.FilterType]
  1043  
  1044  	// If the set of block hashes is beyond the current size of the cache,
  1045  	// then we'll expand the size of the cache and also retain the write
  1046  	// lock.
  1047  	var updateCache bool
  1048  	if len(blockHashes) > len(checkptCache) {
  1049  		// Now that we know we'll need to modify the size of the cache,
  1050  		// we'll release the read lock and grab the write lock to
  1051  		// possibly expand the cache size.
  1052  		sp.server.cfCheckptCachesMtx.RUnlock()
  1053  
  1054  		sp.server.cfCheckptCachesMtx.Lock()
  1055  		defer sp.server.cfCheckptCachesMtx.Unlock()
  1056  
  1057  		// Now that we have the write lock, we'll check again as it's
  1058  		// possible that the cache has already been expanded.
  1059  		checkptCache = sp.server.cfCheckptCaches[msg.FilterType]
  1060  
  1061  		// If we still need to expand the cache, then We'll mark that
  1062  		// we need to update the cache for below and also expand the
  1063  		// size of the cache in place.
  1064  		if len(blockHashes) > len(checkptCache) {
  1065  			updateCache = true
  1066  
  1067  			additionalLength := len(blockHashes) - len(checkptCache)
  1068  			newEntries := make([]cfHeaderKV, additionalLength)
  1069  
  1070  			peerLog.Infof("Growing size of checkpoint cache from %v to %v "+
  1071  				"block hashes", len(checkptCache), len(blockHashes))
  1072  
  1073  			checkptCache = append(
  1074  				sp.server.cfCheckptCaches[msg.FilterType],
  1075  				newEntries...,
  1076  			)
  1077  		}
  1078  	} else {
  1079  		// Otherwise, we'll hold onto the read lock for the remainder
  1080  		// of this method.
  1081  		defer sp.server.cfCheckptCachesMtx.RUnlock()
  1082  
  1083  		peerLog.Tracef("Serving stale cache of size %v",
  1084  			len(checkptCache))
  1085  	}
  1086  
  1087  	// Now that we know the cache is of an appropriate size, we'll iterate
  1088  	// backwards until the find the block hash. We do this as it's possible
  1089  	// a re-org has occurred so items in the db are now in the main china
  1090  	// while the cache has been partially invalidated.
  1091  	var forkIdx int
  1092  	for forkIdx = len(blockHashes); forkIdx > 0; forkIdx-- {
  1093  		if checkptCache[forkIdx-1].blockHash == blockHashes[forkIdx-1] {
  1094  			break
  1095  		}
  1096  	}
  1097  
  1098  	// Now that we know the how much of the cache is relevant for this
  1099  	// query, we'll populate our check point message with the cache as is.
  1100  	// Shortly below, we'll populate the new elements of the cache.
  1101  	for i := 0; i < forkIdx; i++ {
  1102  		checkptMsg.AddCFHeader(&checkptCache[i].filterHeader)
  1103  	}
  1104  
  1105  	// We'll now collect the set of hashes that are beyond our cache so we
  1106  	// can look up the filter headers to populate the final cache.
  1107  	blockHashPtrs := make([]*chainhash.Hash, 0, len(blockHashes)-forkIdx)
  1108  	for i := forkIdx; i < len(blockHashes); i++ {
  1109  		blockHashPtrs = append(blockHashPtrs, &blockHashes[i])
  1110  	}
  1111  	filterHeaders, err := sp.server.cfIndex.FilterHeadersByBlockHashes(
  1112  		blockHashPtrs, msg.FilterType,
  1113  	)
  1114  	if err != nil {
  1115  		peerLog.Errorf("Error retrieving cfilter headers: %v", err)
  1116  		return
  1117  	}
  1118  
  1119  	// Now that we have the full set of filter headers, we'll add them to
  1120  	// the checkpoint message, and also update our cache in line.
  1121  	for i, filterHeaderBytes := range filterHeaders {
  1122  		if len(filterHeaderBytes) == 0 {
  1123  			peerLog.Warnf("Could not obtain CF header for %v",
  1124  				blockHashPtrs[i])
  1125  			return
  1126  		}
  1127  
  1128  		filterHeader, err := chainhash.NewHash(filterHeaderBytes)
  1129  		if err != nil {
  1130  			peerLog.Warnf("Committed filter header deserialize "+
  1131  				"failed: %v", err)
  1132  			return
  1133  		}
  1134  
  1135  		checkptMsg.AddCFHeader(filterHeader)
  1136  
  1137  		// If the new main chain is longer than what's in the cache,
  1138  		// then we'll override it beyond the fork point.
  1139  		if updateCache {
  1140  			checkptCache[forkIdx+i] = cfHeaderKV{
  1141  				blockHash:    blockHashes[forkIdx+i],
  1142  				filterHeader: *filterHeader,
  1143  			}
  1144  		}
  1145  	}
  1146  
  1147  	// Finally, we'll update the cache if we need to, and send the final
  1148  	// message back to the requesting peer.
  1149  	if updateCache {
  1150  		sp.server.cfCheckptCaches[msg.FilterType] = checkptCache
  1151  	}
  1152  
  1153  	sp.QueueMessage(checkptMsg, nil)
  1154  }
  1155  
  1156  // enforceNodeBloomFlag disconnects the peer if the server is not configured to
  1157  // allow bloom filters.  Additionally, if the peer has negotiated to a protocol
  1158  // version  that is high enough to observe the bloom filter service support bit,
  1159  // it will be banned since it is intentionally violating the protocol.
  1160  func (sp *serverPeer) enforceNodeBloomFlag(cmd string) bool {
  1161  	if sp.server.services&wire.SFNodeBloom != wire.SFNodeBloom {
  1162  		// Ban the peer if the protocol version is high enough that the
  1163  		// peer is knowingly violating the protocol and banning is
  1164  		// enabled.
  1165  		//
  1166  		// NOTE: Even though the addBanScore function already examines
  1167  		// whether or not banning is enabled, it is checked here as well
  1168  		// to ensure the violation is logged and the peer is
  1169  		// disconnected regardless.
  1170  		if sp.ProtocolVersion() >= wire.BIP0111Version &&
  1171  			!cfg.DisableBanning {
  1172  
  1173  			// Disconnect the peer regardless of whether it was
  1174  			// banned.
  1175  			sp.addBanScore(100, 0, cmd)
  1176  			sp.Disconnect()
  1177  			return false
  1178  		}
  1179  
  1180  		// Disconnect the peer regardless of protocol version or banning
  1181  		// state.
  1182  		peerLog.Debugf("%s sent an unsupported %s request -- "+
  1183  			"disconnecting", sp, cmd)
  1184  		sp.Disconnect()
  1185  		return false
  1186  	}
  1187  
  1188  	return true
  1189  }
  1190  
  1191  // OnFeeFilter is invoked when a peer receives a feefilter bitcoin message and
  1192  // is used by remote peers to request that no transactions which have a fee rate
  1193  // lower than provided value are inventoried to them.  The peer will be
  1194  // disconnected if an invalid fee filter value is provided.
  1195  func (sp *serverPeer) OnFeeFilter(_ *peer.Peer, msg *wire.MsgFeeFilter) {
  1196  	// Check that the passed minimum fee is a valid amount.
  1197  	if msg.MinFee < 0 || msg.MinFee > btcutil.MaxSatoshi {
  1198  		peerLog.Debugf("Peer %v sent an invalid feefilter '%v' -- "+
  1199  			"disconnecting", sp, btcutil.Amount(msg.MinFee))
  1200  		sp.Disconnect()
  1201  		return
  1202  	}
  1203  
  1204  	atomic.StoreInt64(&sp.feeFilter, msg.MinFee)
  1205  }
  1206  
  1207  // OnFilterAdd is invoked when a peer receives a filteradd bitcoin
  1208  // message and is used by remote peers to add data to an already loaded bloom
  1209  // filter.  The peer will be disconnected if a filter is not loaded when this
  1210  // message is received or the server is not configured to allow bloom filters.
  1211  func (sp *serverPeer) OnFilterAdd(_ *peer.Peer, msg *wire.MsgFilterAdd) {
  1212  	// Disconnect and/or ban depending on the node bloom services flag and
  1213  	// negotiated protocol version.
  1214  	if !sp.enforceNodeBloomFlag(msg.Command()) {
  1215  		return
  1216  	}
  1217  
  1218  	if !sp.filter.IsLoaded() {
  1219  		peerLog.Debugf("%s sent a filteradd request with no filter "+
  1220  			"loaded -- disconnecting", sp)
  1221  		sp.Disconnect()
  1222  		return
  1223  	}
  1224  
  1225  	sp.filter.Add(msg.Data)
  1226  }
  1227  
  1228  // OnFilterClear is invoked when a peer receives a filterclear bitcoin
  1229  // message and is used by remote peers to clear an already loaded bloom filter.
  1230  // The peer will be disconnected if a filter is not loaded when this message is
  1231  // received  or the server is not configured to allow bloom filters.
  1232  func (sp *serverPeer) OnFilterClear(_ *peer.Peer, msg *wire.MsgFilterClear) {
  1233  	// Disconnect and/or ban depending on the node bloom services flag and
  1234  	// negotiated protocol version.
  1235  	if !sp.enforceNodeBloomFlag(msg.Command()) {
  1236  		return
  1237  	}
  1238  
  1239  	if !sp.filter.IsLoaded() {
  1240  		peerLog.Debugf("%s sent a filterclear request with no "+
  1241  			"filter loaded -- disconnecting", sp)
  1242  		sp.Disconnect()
  1243  		return
  1244  	}
  1245  
  1246  	sp.filter.Unload()
  1247  }
  1248  
  1249  // OnFilterLoad is invoked when a peer receives a filterload bitcoin
  1250  // message and it used to load a bloom filter that should be used for
  1251  // delivering merkle blocks and associated transactions that match the filter.
  1252  // The peer will be disconnected if the server is not configured to allow bloom
  1253  // filters.
  1254  func (sp *serverPeer) OnFilterLoad(_ *peer.Peer, msg *wire.MsgFilterLoad) {
  1255  	// Disconnect and/or ban depending on the node bloom services flag and
  1256  	// negotiated protocol version.
  1257  	if !sp.enforceNodeBloomFlag(msg.Command()) {
  1258  		return
  1259  	}
  1260  
  1261  	sp.setDisableRelayTx(false)
  1262  
  1263  	sp.filter.Reload(msg)
  1264  }
  1265  
  1266  // OnGetAddr is invoked when a peer receives a getaddr bitcoin message
  1267  // and is used to provide the peer with known addresses from the address
  1268  // manager.
  1269  func (sp *serverPeer) OnGetAddr(_ *peer.Peer, msg *wire.MsgGetAddr) {
  1270  	// Don't return any addresses when running on the simulation test
  1271  	// network.  This helps prevent the network from becoming another
  1272  	// public test network since it will not be able to learn about other
  1273  	// peers that have not specifically been provided.
  1274  	if cfg.SimNet {
  1275  		return
  1276  	}
  1277  
  1278  	// Do not accept getaddr requests from outbound peers.  This reduces
  1279  	// fingerprinting attacks.
  1280  	if !sp.Inbound() {
  1281  		peerLog.Debugf("Ignoring getaddr request from outbound peer "+
  1282  			"%v", sp)
  1283  		return
  1284  	}
  1285  
  1286  	// Only allow one getaddr request per connection to discourage
  1287  	// address stamping of inv announcements.
  1288  	if sp.sentAddrs {
  1289  		peerLog.Debugf("Ignoring repeated getaddr request from peer "+
  1290  			"%v", sp)
  1291  		return
  1292  	}
  1293  	sp.sentAddrs = true
  1294  
  1295  	// Get the current known addresses from the address manager.
  1296  	addrCache := sp.server.addrManager.AddressCache()
  1297  
  1298  	// Push the addresses.
  1299  	sp.pushAddrMsg(addrCache)
  1300  }
  1301  
  1302  // OnAddr is invoked when a peer receives an addr bitcoin message and is
  1303  // used to notify the server about advertised addresses.
  1304  func (sp *serverPeer) OnAddr(_ *peer.Peer, msg *wire.MsgAddr) {
  1305  	// Ignore addresses when running on the simulation test network.  This
  1306  	// helps prevent the network from becoming another public test network
  1307  	// since it will not be able to learn about other peers that have not
  1308  	// specifically been provided.
  1309  	if cfg.SimNet {
  1310  		return
  1311  	}
  1312  
  1313  	// Ignore old style addresses which don't include a timestamp.
  1314  	if sp.ProtocolVersion() < wire.NetAddressTimeVersion {
  1315  		return
  1316  	}
  1317  
  1318  	// A message that has no addresses is invalid.
  1319  	if len(msg.AddrList) == 0 {
  1320  		peerLog.Errorf("Command [%s] from %s does not contain any addresses",
  1321  			msg.Command(), sp.Peer)
  1322  		sp.Disconnect()
  1323  		return
  1324  	}
  1325  
  1326  	addrs := make([]*wire.NetAddressV2, 0, len(msg.AddrList))
  1327  	for _, na := range msg.AddrList {
  1328  		// Don't add more address if we're disconnecting.
  1329  		if !sp.Connected() {
  1330  			return
  1331  		}
  1332  
  1333  		// Set the timestamp to 5 days ago if it's more than 24 hours
  1334  		// in the future so this address is one of the first to be
  1335  		// removed when space is needed.
  1336  		now := time.Now()
  1337  		if na.Timestamp.After(now.Add(time.Minute * 10)) {
  1338  			na.Timestamp = now.Add(-1 * time.Hour * 24 * 5)
  1339  		}
  1340  
  1341  		// Add address to known addresses for this peer. This is
  1342  		// converted to NetAddressV2 since that's what the address
  1343  		// manager uses.
  1344  		currentNa := wire.NetAddressV2FromBytes(
  1345  			na.Timestamp, na.Services, na.IP, na.Port,
  1346  		)
  1347  		addrs = append(addrs, currentNa)
  1348  		sp.addKnownAddresses([]*wire.NetAddressV2{currentNa})
  1349  	}
  1350  
  1351  	// Add addresses to server address manager.  The address manager handles
  1352  	// the details of things such as preventing duplicate addresses, max
  1353  	// addresses, and last seen updates.
  1354  	// XXX bitcoind gives a 2 hour time penalty here, do we want to do the
  1355  	// same?
  1356  	sp.server.addrManager.AddAddresses(addrs, sp.NA())
  1357  }
  1358  
  1359  // OnAddrV2 is invoked when a peer receives an addrv2 bitcoin message and is
  1360  // used to notify the server about advertised addresses.
  1361  func (sp *serverPeer) OnAddrV2(_ *peer.Peer, msg *wire.MsgAddrV2) {
  1362  	// Ignore if simnet for the same reasons as the regular addr message.
  1363  	if cfg.SimNet {
  1364  		return
  1365  	}
  1366  
  1367  	// An empty AddrV2 message is invalid.
  1368  	if len(msg.AddrList) == 0 {
  1369  		peerLog.Errorf("Command [%s] from %s does not contain any "+
  1370  			"addresses", msg.Command(), sp.Peer)
  1371  		sp.Disconnect()
  1372  		return
  1373  	}
  1374  
  1375  	for _, na := range msg.AddrList {
  1376  		// Don't add more to the set of known addresses if we're
  1377  		// disconnecting.
  1378  		if !sp.Connected() {
  1379  			return
  1380  		}
  1381  
  1382  		// Set the timestamp to 5 days ago if the timestamp received is
  1383  		// more than 10 minutes in the future so this address is one of
  1384  		// the first to be removed.
  1385  		now := time.Now()
  1386  		if na.Timestamp.After(now.Add(time.Minute * 10)) {
  1387  			na.Timestamp = now.Add(-1 * time.Hour * 24 * 5)
  1388  		}
  1389  
  1390  		// Add to the set of known addresses.
  1391  		sp.addKnownAddresses([]*wire.NetAddressV2{na})
  1392  	}
  1393  
  1394  	// Add the addresses to the addrmanager.
  1395  	sp.server.addrManager.AddAddresses(msg.AddrList, sp.NA())
  1396  }
  1397  
  1398  // OnRead is invoked when a peer receives a message and it is used to update
  1399  // the bytes received by the server.
  1400  func (sp *serverPeer) OnRead(_ *peer.Peer, bytesRead int, msg wire.Message, err error) {
  1401  	sp.server.AddBytesReceived(uint64(bytesRead))
  1402  }
  1403  
  1404  // OnWrite is invoked when a peer sends a message and it is used to update
  1405  // the bytes sent by the server.
  1406  func (sp *serverPeer) OnWrite(_ *peer.Peer, bytesWritten int, msg wire.Message, err error) {
  1407  	sp.server.AddBytesSent(uint64(bytesWritten))
  1408  }
  1409  
  1410  // OnNotFound is invoked when a peer sends a notfound message.
  1411  func (sp *serverPeer) OnNotFound(p *peer.Peer, msg *wire.MsgNotFound) {
  1412  	if !sp.Connected() {
  1413  		return
  1414  	}
  1415  
  1416  	var numBlocks, numTxns uint32
  1417  	for _, inv := range msg.InvList {
  1418  		switch inv.Type {
  1419  		case wire.InvTypeBlock:
  1420  			numBlocks++
  1421  		case wire.InvTypeWitnessBlock:
  1422  			numBlocks++
  1423  		case wire.InvTypeTx:
  1424  			numTxns++
  1425  		case wire.InvTypeWitnessTx:
  1426  			numTxns++
  1427  		default:
  1428  			peerLog.Debugf("Invalid inv type '%d' in notfound message from %s",
  1429  				inv.Type, sp)
  1430  			sp.Disconnect()
  1431  			return
  1432  		}
  1433  	}
  1434  	if numBlocks > 0 {
  1435  		blockStr := pickNoun(uint64(numBlocks), "block", "blocks")
  1436  		reason := fmt.Sprintf("%d %v not found", numBlocks, blockStr)
  1437  		if sp.addBanScore(20*numBlocks, 0, reason) {
  1438  			return
  1439  		}
  1440  	}
  1441  	if numTxns > 0 {
  1442  		txStr := pickNoun(uint64(numTxns), "transaction", "transactions")
  1443  		reason := fmt.Sprintf("%d %v not found", numTxns, txStr)
  1444  		if sp.addBanScore(0, 10*numTxns, reason) {
  1445  			return
  1446  		}
  1447  	}
  1448  
  1449  	sp.server.syncManager.QueueNotFound(msg, p)
  1450  }
  1451  
  1452  // randomUint16Number returns a random uint16 in a specified input range.  Note
  1453  // that the range is in zeroth ordering; if you pass it 1800, you will get
  1454  // values from 0 to 1800.
  1455  func randomUint16Number(max uint16) uint16 {
  1456  	// In order to avoid modulo bias and ensure every possible outcome in
  1457  	// [0, max) has equal probability, the random number must be sampled
  1458  	// from a random source that has a range limited to a multiple of the
  1459  	// modulus.
  1460  	var randomNumber uint16
  1461  	var limitRange = (math.MaxUint16 / max) * max
  1462  	for {
  1463  		binary.Read(rand.Reader, binary.LittleEndian, &randomNumber)
  1464  		if randomNumber < limitRange {
  1465  			return (randomNumber % max)
  1466  		}
  1467  	}
  1468  }
  1469  
  1470  // AddRebroadcastInventory adds 'iv' to the list of inventories to be
  1471  // rebroadcasted at random intervals until they show up in a block.
  1472  func (s *server) AddRebroadcastInventory(iv *wire.InvVect, data interface{}) {
  1473  	// Ignore if shutting down.
  1474  	if atomic.LoadInt32(&s.shutdown) != 0 {
  1475  		return
  1476  	}
  1477  
  1478  	s.modifyRebroadcastInv <- broadcastInventoryAdd{invVect: iv, data: data}
  1479  }
  1480  
  1481  // RemoveRebroadcastInventory removes 'iv' from the list of items to be
  1482  // rebroadcasted if present.
  1483  func (s *server) RemoveRebroadcastInventory(iv *wire.InvVect) {
  1484  	// Ignore if shutting down.
  1485  	if atomic.LoadInt32(&s.shutdown) != 0 {
  1486  		return
  1487  	}
  1488  
  1489  	s.modifyRebroadcastInv <- broadcastInventoryDel(iv)
  1490  }
  1491  
  1492  // relayTransactions generates and relays inventory vectors for all of the
  1493  // passed transactions to all connected peers.
  1494  func (s *server) relayTransactions(txns []*mempool.TxDesc) {
  1495  	for _, txD := range txns {
  1496  		iv := wire.NewInvVect(wire.InvTypeTx, txD.Tx.Hash())
  1497  		s.RelayInventory(iv, txD)
  1498  	}
  1499  }
  1500  
  1501  // AnnounceNewTransactions generates and relays inventory vectors and notifies
  1502  // both websocket and getblocktemplate long poll clients of the passed
  1503  // transactions.  This function should be called whenever new transactions
  1504  // are added to the mempool.
  1505  func (s *server) AnnounceNewTransactions(txns []*mempool.TxDesc) {
  1506  	// Generate and relay inventory vectors for all newly accepted
  1507  	// transactions.
  1508  	s.relayTransactions(txns)
  1509  
  1510  	// Notify both websocket and getblocktemplate long poll clients of all
  1511  	// newly accepted transactions.
  1512  	if s.rpcServer != nil {
  1513  		s.rpcServer.NotifyNewTransactions(txns)
  1514  	}
  1515  }
  1516  
  1517  // Transaction has one confirmation on the main chain. Now we can mark it as no
  1518  // longer needing rebroadcasting.
  1519  func (s *server) TransactionConfirmed(tx *btcutil.Tx) {
  1520  	// Rebroadcasting is only necessary when the RPC server is active.
  1521  	if s.rpcServer == nil {
  1522  		return
  1523  	}
  1524  
  1525  	iv := wire.NewInvVect(wire.InvTypeTx, tx.Hash())
  1526  	s.RemoveRebroadcastInventory(iv)
  1527  }
  1528  
  1529  // pushTxMsg sends a tx message for the provided transaction hash to the
  1530  // connected peer.  An error is returned if the transaction hash is not known.
  1531  func (s *server) pushTxMsg(sp *serverPeer, hash *chainhash.Hash, doneChan chan<- struct{},
  1532  	waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
  1533  
  1534  	// Attempt to fetch the requested transaction from the pool.  A
  1535  	// call could be made to check for existence first, but simply trying
  1536  	// to fetch a missing transaction results in the same behavior.
  1537  	tx, err := s.txMemPool.FetchTransaction(hash)
  1538  	if err != nil {
  1539  		peerLog.Tracef("Unable to fetch tx %v from transaction "+
  1540  			"pool: %v", hash, err)
  1541  
  1542  		if doneChan != nil {
  1543  			doneChan <- struct{}{}
  1544  		}
  1545  		return err
  1546  	}
  1547  
  1548  	// Once we have fetched data wait for any previous operation to finish.
  1549  	if waitChan != nil {
  1550  		<-waitChan
  1551  	}
  1552  
  1553  	sp.QueueMessageWithEncoding(tx.MsgTx(), doneChan, encoding)
  1554  
  1555  	return nil
  1556  }
  1557  
  1558  // pushBlockMsg sends a block message for the provided block hash to the
  1559  // connected peer.  An error is returned if the block hash is not known.
  1560  func (s *server) pushBlockMsg(sp *serverPeer, hash *chainhash.Hash, doneChan chan<- struct{},
  1561  	waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
  1562  
  1563  	// Fetch the raw block bytes from the database.
  1564  	var blockBytes []byte
  1565  	err := sp.server.db.View(func(dbTx database.Tx) error {
  1566  		var err error
  1567  		blockBytes, err = dbTx.FetchBlock(hash)
  1568  		return err
  1569  	})
  1570  	if err != nil {
  1571  		peerLog.Tracef("Unable to fetch requested block hash %v: %v",
  1572  			hash, err)
  1573  
  1574  		if doneChan != nil {
  1575  			doneChan <- struct{}{}
  1576  		}
  1577  		return err
  1578  	}
  1579  
  1580  	// Deserialize the block.
  1581  	var msgBlock wire.MsgBlock
  1582  	err = msgBlock.Deserialize(bytes.NewReader(blockBytes))
  1583  	if err != nil {
  1584  		peerLog.Tracef("Unable to deserialize requested block hash "+
  1585  			"%v: %v", hash, err)
  1586  
  1587  		if doneChan != nil {
  1588  			doneChan <- struct{}{}
  1589  		}
  1590  		return err
  1591  	}
  1592  
  1593  	// Once we have fetched data wait for any previous operation to finish.
  1594  	if waitChan != nil {
  1595  		<-waitChan
  1596  	}
  1597  
  1598  	// We only send the channel for this message if we aren't sending
  1599  	// an inv straight after.
  1600  	var dc chan<- struct{}
  1601  	continueHash := sp.continueHash
  1602  	sendInv := continueHash != nil && continueHash.IsEqual(hash)
  1603  	if !sendInv {
  1604  		dc = doneChan
  1605  	}
  1606  	sp.QueueMessageWithEncoding(&msgBlock, dc, encoding)
  1607  
  1608  	// When the peer requests the final block that was advertised in
  1609  	// response to a getblocks message which requested more blocks than
  1610  	// would fit into a single message, send it a new inventory message
  1611  	// to trigger it to issue another getblocks message for the next
  1612  	// batch of inventory.
  1613  	if sendInv {
  1614  		best := sp.server.chain.BestSnapshot()
  1615  		invMsg := wire.NewMsgInvSizeHint(1)
  1616  		iv := wire.NewInvVect(wire.InvTypeBlock, &best.Hash)
  1617  		invMsg.AddInvVect(iv)
  1618  		sp.QueueMessage(invMsg, doneChan)
  1619  		sp.continueHash = nil
  1620  	}
  1621  	return nil
  1622  }
  1623  
  1624  // pushMerkleBlockMsg sends a merkleblock message for the provided block hash to
  1625  // the connected peer.  Since a merkle block requires the peer to have a filter
  1626  // loaded, this call will simply be ignored if there is no filter loaded.  An
  1627  // error is returned if the block hash is not known.
  1628  func (s *server) pushMerkleBlockMsg(sp *serverPeer, hash *chainhash.Hash,
  1629  	doneChan chan<- struct{}, waitChan <-chan struct{}, encoding wire.MessageEncoding) error {
  1630  
  1631  	// Do not send a response if the peer doesn't have a filter loaded.
  1632  	if !sp.filter.IsLoaded() {
  1633  		if doneChan != nil {
  1634  			doneChan <- struct{}{}
  1635  		}
  1636  		return nil
  1637  	}
  1638  
  1639  	// Fetch the raw block bytes from the database.
  1640  	blk, err := sp.server.chain.BlockByHash(hash)
  1641  	if err != nil {
  1642  		peerLog.Tracef("Unable to fetch requested block hash %v: %v",
  1643  			hash, err)
  1644  
  1645  		if doneChan != nil {
  1646  			doneChan <- struct{}{}
  1647  		}
  1648  		return err
  1649  	}
  1650  
  1651  	// Generate a merkle block by filtering the requested block according
  1652  	// to the filter for the peer.
  1653  	merkle, matchedTxIndices := bloom.NewMerkleBlock(blk, sp.filter)
  1654  
  1655  	// Once we have fetched data wait for any previous operation to finish.
  1656  	if waitChan != nil {
  1657  		<-waitChan
  1658  	}
  1659  
  1660  	// Send the merkleblock.  Only send the done channel with this message
  1661  	// if no transactions will be sent afterwards.
  1662  	var dc chan<- struct{}
  1663  	if len(matchedTxIndices) == 0 {
  1664  		dc = doneChan
  1665  	}
  1666  	sp.QueueMessage(merkle, dc)
  1667  
  1668  	// Finally, send any matched transactions.
  1669  	blkTransactions := blk.MsgBlock().Transactions
  1670  	for i, txIndex := range matchedTxIndices {
  1671  		// Only send the done channel on the final transaction.
  1672  		var dc chan<- struct{}
  1673  		if i == len(matchedTxIndices)-1 {
  1674  			dc = doneChan
  1675  		}
  1676  		if txIndex < uint32(len(blkTransactions)) {
  1677  			sp.QueueMessageWithEncoding(blkTransactions[txIndex], dc,
  1678  				encoding)
  1679  		}
  1680  	}
  1681  
  1682  	return nil
  1683  }
  1684  
  1685  // handleUpdatePeerHeight updates the heights of all peers who were known to
  1686  // announce a block we recently accepted.
  1687  func (s *server) handleUpdatePeerHeights(state *peerState, umsg updatePeerHeightsMsg) {
  1688  	state.forAllPeers(func(sp *serverPeer) {
  1689  		// The origin peer should already have the updated height.
  1690  		if sp.Peer == umsg.originPeer {
  1691  			return
  1692  		}
  1693  
  1694  		// This is a pointer to the underlying memory which doesn't
  1695  		// change.
  1696  		latestBlkHash := sp.LastAnnouncedBlock()
  1697  
  1698  		// Skip this peer if it hasn't recently announced any new blocks.
  1699  		if latestBlkHash == nil {
  1700  			return
  1701  		}
  1702  
  1703  		// If the peer has recently announced a block, and this block
  1704  		// matches our newly accepted block, then update their block
  1705  		// height.
  1706  		if *latestBlkHash == *umsg.newHash {
  1707  			sp.UpdateLastBlockHeight(umsg.newHeight)
  1708  			sp.UpdateLastAnnouncedBlock(nil)
  1709  		}
  1710  	})
  1711  }
  1712  
  1713  // handleAddPeerMsg deals with adding new peers.  It is invoked from the
  1714  // peerHandler goroutine.
  1715  func (s *server) handleAddPeerMsg(state *peerState, sp *serverPeer) bool {
  1716  	if sp == nil || !sp.Connected() {
  1717  		return false
  1718  	}
  1719  
  1720  	// Disconnect peers with unwanted user agents.
  1721  	if sp.HasUndesiredUserAgent(s.agentBlacklist, s.agentWhitelist) {
  1722  		sp.Disconnect()
  1723  		return false
  1724  	}
  1725  
  1726  	// Ignore new peers if we're shutting down.
  1727  	if atomic.LoadInt32(&s.shutdown) != 0 {
  1728  		srvrLog.Infof("New peer %s ignored - server is shutting down", sp)
  1729  		sp.Disconnect()
  1730  		return false
  1731  	}
  1732  
  1733  	// Disconnect banned peers.
  1734  	host, _, err := net.SplitHostPort(sp.Addr())
  1735  	if err != nil {
  1736  		srvrLog.Debugf("can't split hostport %v", err)
  1737  		sp.Disconnect()
  1738  		return false
  1739  	}
  1740  	if banEnd, ok := state.banned[host]; ok {
  1741  		if time.Now().Before(banEnd) {
  1742  			srvrLog.Debugf("Peer %s is banned for another %v - disconnecting",
  1743  				host, time.Until(banEnd))
  1744  			sp.Disconnect()
  1745  			return false
  1746  		}
  1747  
  1748  		srvrLog.Infof("Peer %s is no longer banned", host)
  1749  		delete(state.banned, host)
  1750  	}
  1751  
  1752  	// TODO: Check for max peers from a single IP.
  1753  
  1754  	// Limit max number of total peers.
  1755  	if state.Count() >= cfg.MaxPeers {
  1756  		srvrLog.Infof("Max peers reached [%d] - disconnecting peer %s",
  1757  			cfg.MaxPeers, sp)
  1758  		sp.Disconnect()
  1759  		// TODO: how to handle permanent peers here?
  1760  		// they should be rescheduled.
  1761  		return false
  1762  	}
  1763  
  1764  	// Add the new peer and start it.
  1765  	srvrLog.Debugf("New peer %s", sp)
  1766  	if sp.Inbound() {
  1767  		state.inboundPeers[sp.ID()] = sp
  1768  	} else {
  1769  		state.outboundGroups[addrmgr.GroupKey(sp.NA())]++
  1770  		if sp.persistent {
  1771  			state.persistentPeers[sp.ID()] = sp
  1772  		} else {
  1773  			state.outboundPeers[sp.ID()] = sp
  1774  		}
  1775  	}
  1776  
  1777  	// Update the address' last seen time if the peer has acknowledged
  1778  	// our version and has sent us its version as well.
  1779  	if sp.VerAckReceived() && sp.VersionKnown() && sp.NA() != nil {
  1780  		s.addrManager.Connected(sp.NA())
  1781  	}
  1782  
  1783  	// Signal the sync manager this peer is a new sync candidate.
  1784  	s.syncManager.NewPeer(sp.Peer)
  1785  
  1786  	// Update the address manager and request known addresses from the
  1787  	// remote peer for outbound connections. This is skipped when running on
  1788  	// the simulation test network since it is only intended to connect to
  1789  	// specified peers and actively avoids advertising and connecting to
  1790  	// discovered peers.
  1791  	if !cfg.SimNet && !sp.Inbound() {
  1792  		// Advertise the local address when the server accepts incoming
  1793  		// connections and it believes itself to be close to the best
  1794  		// known tip.
  1795  		if !cfg.DisableListen && s.syncManager.IsCurrent() {
  1796  			// Get address that best matches.
  1797  			lna := s.addrManager.GetBestLocalAddress(sp.NA())
  1798  			if addrmgr.IsRoutable(lna) {
  1799  				// Filter addresses the peer already knows about.
  1800  				addresses := []*wire.NetAddressV2{lna}
  1801  				sp.pushAddrMsg(addresses)
  1802  			}
  1803  		}
  1804  
  1805  		// Request known addresses if the server address manager needs
  1806  		// more and the peer has a protocol version new enough to
  1807  		// include a timestamp with addresses.
  1808  		hasTimestamp := sp.ProtocolVersion() >= wire.NetAddressTimeVersion
  1809  		if s.addrManager.NeedMoreAddresses() && hasTimestamp {
  1810  			sp.QueueMessage(wire.NewMsgGetAddr(), nil)
  1811  		}
  1812  
  1813  		// Mark the address as a known good address.
  1814  		s.addrManager.Good(sp.NA())
  1815  	}
  1816  
  1817  	return true
  1818  }
  1819  
  1820  // handleDonePeerMsg deals with peers that have signalled they are done.  It is
  1821  // invoked from the peerHandler goroutine.
  1822  func (s *server) handleDonePeerMsg(state *peerState, sp *serverPeer) {
  1823  	var list map[int32]*serverPeer
  1824  	if sp.persistent {
  1825  		list = state.persistentPeers
  1826  	} else if sp.Inbound() {
  1827  		list = state.inboundPeers
  1828  	} else {
  1829  		list = state.outboundPeers
  1830  	}
  1831  
  1832  	// Regardless of whether the peer was found in our list, we'll inform
  1833  	// our connection manager about the disconnection. This can happen if we
  1834  	// process a peer's `done` message before its `add`.
  1835  	if !sp.Inbound() {
  1836  		if sp.persistent {
  1837  			s.connManager.Disconnect(sp.connReq.ID())
  1838  		} else {
  1839  			s.connManager.Remove(sp.connReq.ID())
  1840  			go s.connManager.NewConnReq()
  1841  		}
  1842  	}
  1843  
  1844  	if _, ok := list[sp.ID()]; ok {
  1845  		if !sp.Inbound() && sp.VersionKnown() {
  1846  			state.outboundGroups[addrmgr.GroupKey(sp.NA())]--
  1847  		}
  1848  		delete(list, sp.ID())
  1849  		srvrLog.Debugf("Removed peer %s", sp)
  1850  		return
  1851  	}
  1852  }
  1853  
  1854  // handleBanPeerMsg deals with banning peers.  It is invoked from the
  1855  // peerHandler goroutine.
  1856  func (s *server) handleBanPeerMsg(state *peerState, sp *serverPeer) {
  1857  	host, _, err := net.SplitHostPort(sp.Addr())
  1858  	if err != nil {
  1859  		srvrLog.Debugf("can't split ban peer %s %v", sp.Addr(), err)
  1860  		return
  1861  	}
  1862  	direction := directionString(sp.Inbound())
  1863  	srvrLog.Infof("Banned peer %s (%s) for %v", host, direction,
  1864  		cfg.BanDuration)
  1865  	state.banned[host] = time.Now().Add(cfg.BanDuration)
  1866  }
  1867  
  1868  // handleRelayInvMsg deals with relaying inventory to peers that are not already
  1869  // known to have it.  It is invoked from the peerHandler goroutine.
  1870  func (s *server) handleRelayInvMsg(state *peerState, msg relayMsg) {
  1871  	state.forAllPeers(func(sp *serverPeer) {
  1872  		if !sp.Connected() {
  1873  			return
  1874  		}
  1875  
  1876  		// If the inventory is a block and the peer prefers headers,
  1877  		// generate and send a headers message instead of an inventory
  1878  		// message.
  1879  		if msg.invVect.Type == wire.InvTypeBlock && sp.WantsHeaders() {
  1880  			blockHeader, ok := msg.data.(wire.BlockHeader)
  1881  			if !ok {
  1882  				peerLog.Warnf("Underlying data for headers" +
  1883  					" is not a block header")
  1884  				return
  1885  			}
  1886  			msgHeaders := wire.NewMsgHeaders()
  1887  			if err := msgHeaders.AddBlockHeader(&blockHeader); err != nil {
  1888  				peerLog.Errorf("Failed to add block"+
  1889  					" header: %v", err)
  1890  				return
  1891  			}
  1892  			sp.QueueMessage(msgHeaders, nil)
  1893  			return
  1894  		}
  1895  
  1896  		if msg.invVect.Type == wire.InvTypeTx {
  1897  			// Don't relay the transaction to the peer when it has
  1898  			// transaction relaying disabled.
  1899  			if sp.relayTxDisabled() {
  1900  				return
  1901  			}
  1902  
  1903  			txD, ok := msg.data.(*mempool.TxDesc)
  1904  			if !ok {
  1905  				peerLog.Warnf("Underlying data for tx inv "+
  1906  					"relay is not a *mempool.TxDesc: %T",
  1907  					msg.data)
  1908  				return
  1909  			}
  1910  
  1911  			// Don't relay the transaction if the transaction fee-per-kb
  1912  			// is less than the peer's feefilter.
  1913  			feeFilter := atomic.LoadInt64(&sp.feeFilter)
  1914  			if feeFilter > 0 && txD.FeePerKB < feeFilter {
  1915  				return
  1916  			}
  1917  
  1918  			// Don't relay the transaction if there is a bloom
  1919  			// filter loaded and the transaction doesn't match it.
  1920  			if sp.filter.IsLoaded() {
  1921  				if !sp.filter.MatchTxAndUpdate(txD.Tx) {
  1922  					return
  1923  				}
  1924  			}
  1925  		}
  1926  
  1927  		// Queue the inventory to be relayed with the next batch.
  1928  		// It will be ignored if the peer is already known to
  1929  		// have the inventory.
  1930  		sp.QueueInventory(msg.invVect)
  1931  	})
  1932  }
  1933  
  1934  // handleBroadcastMsg deals with broadcasting messages to peers.  It is invoked
  1935  // from the peerHandler goroutine.
  1936  func (s *server) handleBroadcastMsg(state *peerState, bmsg *broadcastMsg) {
  1937  	state.forAllPeers(func(sp *serverPeer) {
  1938  		if !sp.Connected() {
  1939  			return
  1940  		}
  1941  
  1942  		for _, ep := range bmsg.excludePeers {
  1943  			if sp == ep {
  1944  				return
  1945  			}
  1946  		}
  1947  
  1948  		sp.QueueMessage(bmsg.message, nil)
  1949  	})
  1950  }
  1951  
  1952  type getConnCountMsg struct {
  1953  	reply chan int32
  1954  }
  1955  
  1956  type getPeersMsg struct {
  1957  	reply chan []*serverPeer
  1958  }
  1959  
  1960  type getOutboundGroup struct {
  1961  	key   string
  1962  	reply chan int
  1963  }
  1964  
  1965  type getAddedNodesMsg struct {
  1966  	reply chan []*serverPeer
  1967  }
  1968  
  1969  type disconnectNodeMsg struct {
  1970  	cmp   func(*serverPeer) bool
  1971  	reply chan error
  1972  }
  1973  
  1974  type connectNodeMsg struct {
  1975  	addr      string
  1976  	permanent bool
  1977  	reply     chan error
  1978  }
  1979  
  1980  type removeNodeMsg struct {
  1981  	cmp   func(*serverPeer) bool
  1982  	reply chan error
  1983  }
  1984  
  1985  // handleQuery is the central handler for all queries and commands from other
  1986  // goroutines related to peer state.
  1987  func (s *server) handleQuery(state *peerState, querymsg interface{}) {
  1988  	switch msg := querymsg.(type) {
  1989  	case getConnCountMsg:
  1990  		nconnected := int32(0)
  1991  		state.forAllPeers(func(sp *serverPeer) {
  1992  			if sp.Connected() {
  1993  				nconnected++
  1994  			}
  1995  		})
  1996  		msg.reply <- nconnected
  1997  
  1998  	case getPeersMsg:
  1999  		peers := make([]*serverPeer, 0, state.Count())
  2000  		state.forAllPeers(func(sp *serverPeer) {
  2001  			if !sp.Connected() {
  2002  				return
  2003  			}
  2004  			peers = append(peers, sp)
  2005  		})
  2006  		msg.reply <- peers
  2007  
  2008  	case connectNodeMsg:
  2009  		// TODO: duplicate oneshots?
  2010  		// Limit max number of total peers.
  2011  		if state.Count() >= cfg.MaxPeers {
  2012  			msg.reply <- errors.New("max peers reached")
  2013  			return
  2014  		}
  2015  		for _, peer := range state.persistentPeers {
  2016  			if peer.Addr() == msg.addr {
  2017  				if msg.permanent {
  2018  					msg.reply <- errors.New("peer already connected")
  2019  				} else {
  2020  					msg.reply <- errors.New("peer exists as a permanent peer")
  2021  				}
  2022  				return
  2023  			}
  2024  		}
  2025  
  2026  		netAddr, err := addrStringToNetAddr(msg.addr)
  2027  		if err != nil {
  2028  			msg.reply <- err
  2029  			return
  2030  		}
  2031  
  2032  		// TODO: if too many, nuke a non-perm peer.
  2033  		go s.connManager.Connect(&connmgr.ConnReq{
  2034  			Addr:      netAddr,
  2035  			Permanent: msg.permanent,
  2036  		})
  2037  		msg.reply <- nil
  2038  	case removeNodeMsg:
  2039  		found := disconnectPeer(state.persistentPeers, msg.cmp, func(sp *serverPeer) {
  2040  			// Keep group counts ok since we remove from
  2041  			// the list now.
  2042  			state.outboundGroups[addrmgr.GroupKey(sp.NA())]--
  2043  		})
  2044  
  2045  		if found {
  2046  			msg.reply <- nil
  2047  		} else {
  2048  			msg.reply <- errors.New("peer not found")
  2049  		}
  2050  	case getOutboundGroup:
  2051  		count, ok := state.outboundGroups[msg.key]
  2052  		if ok {
  2053  			msg.reply <- count
  2054  		} else {
  2055  			msg.reply <- 0
  2056  		}
  2057  	// Request a list of the persistent (added) peers.
  2058  	case getAddedNodesMsg:
  2059  		// Respond with a slice of the relevant peers.
  2060  		peers := make([]*serverPeer, 0, len(state.persistentPeers))
  2061  		for _, sp := range state.persistentPeers {
  2062  			peers = append(peers, sp)
  2063  		}
  2064  		msg.reply <- peers
  2065  	case disconnectNodeMsg:
  2066  		// Check inbound peers. We pass a nil callback since we don't
  2067  		// require any additional actions on disconnect for inbound peers.
  2068  		found := disconnectPeer(state.inboundPeers, msg.cmp, nil)
  2069  		if found {
  2070  			msg.reply <- nil
  2071  			return
  2072  		}
  2073  
  2074  		// Check outbound peers.
  2075  		found = disconnectPeer(state.outboundPeers, msg.cmp, func(sp *serverPeer) {
  2076  			// Keep group counts ok since we remove from
  2077  			// the list now.
  2078  			state.outboundGroups[addrmgr.GroupKey(sp.NA())]--
  2079  		})
  2080  		if found {
  2081  			// If there are multiple outbound connections to the same
  2082  			// ip:port, continue disconnecting them all until no such
  2083  			// peers are found.
  2084  			for found {
  2085  				found = disconnectPeer(state.outboundPeers, msg.cmp, func(sp *serverPeer) {
  2086  					state.outboundGroups[addrmgr.GroupKey(sp.NA())]--
  2087  				})
  2088  			}
  2089  			msg.reply <- nil
  2090  			return
  2091  		}
  2092  
  2093  		msg.reply <- errors.New("peer not found")
  2094  	}
  2095  }
  2096  
  2097  // disconnectPeer attempts to drop the connection of a targeted peer in the
  2098  // passed peer list. Targets are identified via usage of the passed
  2099  // `compareFunc`, which should return `true` if the passed peer is the target
  2100  // peer. This function returns true on success and false if the peer is unable
  2101  // to be located. If the peer is found, and the passed callback: `whenFound'
  2102  // isn't nil, we call it with the peer as the argument before it is removed
  2103  // from the peerList, and is disconnected from the server.
  2104  func disconnectPeer(peerList map[int32]*serverPeer, compareFunc func(*serverPeer) bool, whenFound func(*serverPeer)) bool {
  2105  	for addr, peer := range peerList {
  2106  		if compareFunc(peer) {
  2107  			if whenFound != nil {
  2108  				whenFound(peer)
  2109  			}
  2110  
  2111  			// This is ok because we are not continuing
  2112  			// to iterate so won't corrupt the loop.
  2113  			delete(peerList, addr)
  2114  			peer.Disconnect()
  2115  			return true
  2116  		}
  2117  	}
  2118  	return false
  2119  }
  2120  
  2121  // newPeerConfig returns the configuration for the given serverPeer.
  2122  func newPeerConfig(sp *serverPeer) *peer.Config {
  2123  	return &peer.Config{
  2124  		Listeners: peer.MessageListeners{
  2125  			OnVersion:      sp.OnVersion,
  2126  			OnVerAck:       sp.OnVerAck,
  2127  			OnMemPool:      sp.OnMemPool,
  2128  			OnTx:           sp.OnTx,
  2129  			OnBlock:        sp.OnBlock,
  2130  			OnInv:          sp.OnInv,
  2131  			OnHeaders:      sp.OnHeaders,
  2132  			OnGetData:      sp.OnGetData,
  2133  			OnGetBlocks:    sp.OnGetBlocks,
  2134  			OnGetHeaders:   sp.OnGetHeaders,
  2135  			OnGetCFilters:  sp.OnGetCFilters,
  2136  			OnGetCFHeaders: sp.OnGetCFHeaders,
  2137  			OnGetCFCheckpt: sp.OnGetCFCheckpt,
  2138  			OnFeeFilter:    sp.OnFeeFilter,
  2139  			OnFilterAdd:    sp.OnFilterAdd,
  2140  			OnFilterClear:  sp.OnFilterClear,
  2141  			OnFilterLoad:   sp.OnFilterLoad,
  2142  			OnGetAddr:      sp.OnGetAddr,
  2143  			OnAddr:         sp.OnAddr,
  2144  			OnAddrV2:       sp.OnAddrV2,
  2145  			OnRead:         sp.OnRead,
  2146  			OnWrite:        sp.OnWrite,
  2147  			OnNotFound:     sp.OnNotFound,
  2148  
  2149  			// Note: The reference client currently bans peers that send alerts
  2150  			// not signed with its key.  We could verify against their key, but
  2151  			// since the reference client is currently unwilling to support
  2152  			// other implementations' alert messages, we will not relay theirs.
  2153  			OnAlert: nil,
  2154  		},
  2155  		NewestBlock:         sp.newestBlock,
  2156  		HostToNetAddress:    sp.server.addrManager.HostToNetAddress,
  2157  		Proxy:               cfg.Proxy,
  2158  		UserAgentName:       userAgentName,
  2159  		UserAgentVersion:    userAgentVersion,
  2160  		UserAgentComments:   cfg.UserAgentComments,
  2161  		ChainParams:         sp.server.chainParams,
  2162  		Services:            sp.server.services,
  2163  		DisableRelayTx:      cfg.BlocksOnly,
  2164  		ProtocolVersion:     peer.MaxProtocolVersion,
  2165  		TrickleInterval:     cfg.TrickleInterval,
  2166  		DisableStallHandler: cfg.DisableStallHandler,
  2167  	}
  2168  }
  2169  
  2170  // inboundPeerConnected is invoked by the connection manager when a new inbound
  2171  // connection is established.  It initializes a new inbound server peer
  2172  // instance, associates it with the connection, and starts a goroutine to wait
  2173  // for disconnection.
  2174  func (s *server) inboundPeerConnected(conn net.Conn) {
  2175  	sp := newServerPeer(s, false)
  2176  	sp.isWhitelisted = isWhitelisted(conn.RemoteAddr())
  2177  	sp.Peer = peer.NewInboundPeer(newPeerConfig(sp))
  2178  	sp.AssociateConnection(conn)
  2179  	go s.peerDoneHandler(sp)
  2180  }
  2181  
  2182  // outboundPeerConnected is invoked by the connection manager when a new
  2183  // outbound connection is established.  It initializes a new outbound server
  2184  // peer instance, associates it with the relevant state such as the connection
  2185  // request instance and the connection itself, and finally notifies the address
  2186  // manager of the attempt.
  2187  func (s *server) outboundPeerConnected(c *connmgr.ConnReq, conn net.Conn) {
  2188  	sp := newServerPeer(s, c.Permanent)
  2189  	p, err := peer.NewOutboundPeer(newPeerConfig(sp), c.Addr.String())
  2190  	if err != nil {
  2191  		srvrLog.Debugf("Cannot create outbound peer %s: %v", c.Addr, err)
  2192  		if c.Permanent {
  2193  			s.connManager.Disconnect(c.ID())
  2194  		} else {
  2195  			s.connManager.Remove(c.ID())
  2196  			go s.connManager.NewConnReq()
  2197  		}
  2198  		return
  2199  	}
  2200  	sp.Peer = p
  2201  	sp.connReq = c
  2202  	sp.isWhitelisted = isWhitelisted(conn.RemoteAddr())
  2203  	sp.AssociateConnection(conn)
  2204  	go s.peerDoneHandler(sp)
  2205  }
  2206  
  2207  // peerDoneHandler handles peer disconnects by notifiying the server that it's
  2208  // done along with other performing other desirable cleanup.
  2209  func (s *server) peerDoneHandler(sp *serverPeer) {
  2210  	sp.WaitForDisconnect()
  2211  	s.donePeers <- sp
  2212  
  2213  	// Only tell sync manager we are gone if we ever told it we existed.
  2214  	if sp.VerAckReceived() {
  2215  		s.syncManager.DonePeer(sp.Peer)
  2216  
  2217  		// Evict any remaining orphans that were sent by the peer.
  2218  		numEvicted := s.txMemPool.RemoveOrphansByTag(mempool.Tag(sp.ID()))
  2219  		if numEvicted > 0 {
  2220  			txmpLog.Debugf("Evicted %d %s from peer %v (id %d)",
  2221  				numEvicted, pickNoun(numEvicted, "orphan",
  2222  					"orphans"), sp, sp.ID())
  2223  		}
  2224  	}
  2225  	close(sp.quit)
  2226  }
  2227  
  2228  // peerHandler is used to handle peer operations such as adding and removing
  2229  // peers to and from the server, banning peers, and broadcasting messages to
  2230  // peers.  It must be run in a goroutine.
  2231  func (s *server) peerHandler() {
  2232  	// Start the address manager and sync manager, both of which are needed
  2233  	// by peers.  This is done here since their lifecycle is closely tied
  2234  	// to this handler and rather than adding more channels to sychronize
  2235  	// things, it's easier and slightly faster to simply start and stop them
  2236  	// in this handler.
  2237  	s.addrManager.Start()
  2238  	s.syncManager.Start()
  2239  
  2240  	srvrLog.Tracef("Starting peer handler")
  2241  
  2242  	state := &peerState{
  2243  		inboundPeers:    make(map[int32]*serverPeer),
  2244  		persistentPeers: make(map[int32]*serverPeer),
  2245  		outboundPeers:   make(map[int32]*serverPeer),
  2246  		banned:          make(map[string]time.Time),
  2247  		outboundGroups:  make(map[string]int),
  2248  	}
  2249  
  2250  	if !cfg.DisableDNSSeed {
  2251  		// Add peers discovered through DNS to the address manager.
  2252  		connmgr.SeedFromDNS(activeNetParams.Params, defaultRequiredServices,
  2253  			btcdLookup, func(addrs []*wire.NetAddressV2) {
  2254  				// Bitcoind uses a lookup of the dns seeder here. This
  2255  				// is rather strange since the values looked up by the
  2256  				// DNS seed lookups will vary quite a lot.
  2257  				// to replicate this behaviour we put all addresses as
  2258  				// having come from the first one.
  2259  				s.addrManager.AddAddresses(addrs, addrs[0])
  2260  			})
  2261  	}
  2262  	go s.connManager.Start()
  2263  
  2264  out:
  2265  	for {
  2266  		select {
  2267  		// New peers connected to the server.
  2268  		case p := <-s.newPeers:
  2269  			s.handleAddPeerMsg(state, p)
  2270  
  2271  		// Disconnected peers.
  2272  		case p := <-s.donePeers:
  2273  			s.handleDonePeerMsg(state, p)
  2274  
  2275  		// Block accepted in mainchain or orphan, update peer height.
  2276  		case umsg := <-s.peerHeightsUpdate:
  2277  			s.handleUpdatePeerHeights(state, umsg)
  2278  
  2279  		// Peer to ban.
  2280  		case p := <-s.banPeers:
  2281  			s.handleBanPeerMsg(state, p)
  2282  
  2283  		// New inventory to potentially be relayed to other peers.
  2284  		case invMsg := <-s.relayInv:
  2285  			s.handleRelayInvMsg(state, invMsg)
  2286  
  2287  		// Message to broadcast to all connected peers except those
  2288  		// which are excluded by the message.
  2289  		case bmsg := <-s.broadcast:
  2290  			s.handleBroadcastMsg(state, &bmsg)
  2291  
  2292  		case qmsg := <-s.query:
  2293  			s.handleQuery(state, qmsg)
  2294  
  2295  		case <-s.quit:
  2296  			// Disconnect all peers on server shutdown.
  2297  			state.forAllPeers(func(sp *serverPeer) {
  2298  				srvrLog.Tracef("Shutdown peer %s", sp)
  2299  				sp.Disconnect()
  2300  			})
  2301  			break out
  2302  		}
  2303  	}
  2304  
  2305  	s.connManager.Stop()
  2306  	s.syncManager.Stop()
  2307  	s.addrManager.Stop()
  2308  
  2309  	// Drain channels before exiting so nothing is left waiting around
  2310  	// to send.
  2311  cleanup:
  2312  	for {
  2313  		select {
  2314  		case <-s.newPeers:
  2315  		case <-s.donePeers:
  2316  		case <-s.peerHeightsUpdate:
  2317  		case <-s.relayInv:
  2318  		case <-s.broadcast:
  2319  		case <-s.query:
  2320  		default:
  2321  			break cleanup
  2322  		}
  2323  	}
  2324  	s.wg.Done()
  2325  	srvrLog.Tracef("Peer handler done")
  2326  }
  2327  
  2328  // AddPeer adds a new peer that has already been connected to the server.
  2329  func (s *server) AddPeer(sp *serverPeer) {
  2330  	s.newPeers <- sp
  2331  }
  2332  
  2333  // BanPeer bans a peer that has already been connected to the server by ip.
  2334  func (s *server) BanPeer(sp *serverPeer) {
  2335  	s.banPeers <- sp
  2336  }
  2337  
  2338  // RelayInventory relays the passed inventory vector to all connected peers
  2339  // that are not already known to have it.
  2340  func (s *server) RelayInventory(invVect *wire.InvVect, data interface{}) {
  2341  	s.relayInv <- relayMsg{invVect: invVect, data: data}
  2342  }
  2343  
  2344  // BroadcastMessage sends msg to all peers currently connected to the server
  2345  // except those in the passed peers to exclude.
  2346  func (s *server) BroadcastMessage(msg wire.Message, exclPeers ...*serverPeer) {
  2347  	// XXX: Need to determine if this is an alert that has already been
  2348  	// broadcast and refrain from broadcasting again.
  2349  	bmsg := broadcastMsg{message: msg, excludePeers: exclPeers}
  2350  	s.broadcast <- bmsg
  2351  }
  2352  
  2353  // ConnectedCount returns the number of currently connected peers.
  2354  func (s *server) ConnectedCount() int32 {
  2355  	replyChan := make(chan int32)
  2356  
  2357  	s.query <- getConnCountMsg{reply: replyChan}
  2358  
  2359  	return <-replyChan
  2360  }
  2361  
  2362  // OutboundGroupCount returns the number of peers connected to the given
  2363  // outbound group key.
  2364  func (s *server) OutboundGroupCount(key string) int {
  2365  	replyChan := make(chan int)
  2366  	s.query <- getOutboundGroup{key: key, reply: replyChan}
  2367  	return <-replyChan
  2368  }
  2369  
  2370  // AddBytesSent adds the passed number of bytes to the total bytes sent counter
  2371  // for the server.  It is safe for concurrent access.
  2372  func (s *server) AddBytesSent(bytesSent uint64) {
  2373  	atomic.AddUint64(&s.bytesSent, bytesSent)
  2374  }
  2375  
  2376  // AddBytesReceived adds the passed number of bytes to the total bytes received
  2377  // counter for the server.  It is safe for concurrent access.
  2378  func (s *server) AddBytesReceived(bytesReceived uint64) {
  2379  	atomic.AddUint64(&s.bytesReceived, bytesReceived)
  2380  }
  2381  
  2382  // NetTotals returns the sum of all bytes received and sent across the network
  2383  // for all peers.  It is safe for concurrent access.
  2384  func (s *server) NetTotals() (uint64, uint64) {
  2385  	return atomic.LoadUint64(&s.bytesReceived),
  2386  		atomic.LoadUint64(&s.bytesSent)
  2387  }
  2388  
  2389  // UpdatePeerHeights updates the heights of all peers who have have announced
  2390  // the latest connected main chain block, or a recognized orphan. These height
  2391  // updates allow us to dynamically refresh peer heights, ensuring sync peer
  2392  // selection has access to the latest block heights for each peer.
  2393  func (s *server) UpdatePeerHeights(latestBlkHash *chainhash.Hash, latestHeight int32, updateSource *peer.Peer) {
  2394  	s.peerHeightsUpdate <- updatePeerHeightsMsg{
  2395  		newHash:    latestBlkHash,
  2396  		newHeight:  latestHeight,
  2397  		originPeer: updateSource,
  2398  	}
  2399  }
  2400  
  2401  // rebroadcastHandler keeps track of user submitted inventories that we have
  2402  // sent out but have not yet made it into a block. We periodically rebroadcast
  2403  // them in case our peers restarted or otherwise lost track of them.
  2404  func (s *server) rebroadcastHandler() {
  2405  	// Wait 5 min before first tx rebroadcast.
  2406  	timer := time.NewTimer(5 * time.Minute)
  2407  	pendingInvs := make(map[wire.InvVect]interface{})
  2408  
  2409  out:
  2410  	for {
  2411  		select {
  2412  		case riv := <-s.modifyRebroadcastInv:
  2413  			switch msg := riv.(type) {
  2414  			// Incoming InvVects are added to our map of RPC txs.
  2415  			case broadcastInventoryAdd:
  2416  				pendingInvs[*msg.invVect] = msg.data
  2417  
  2418  			// When an InvVect has been added to a block, we can
  2419  			// now remove it, if it was present.
  2420  			case broadcastInventoryDel:
  2421  				delete(pendingInvs, *msg)
  2422  			}
  2423  
  2424  		case <-timer.C:
  2425  			// Any inventory we have has not made it into a block
  2426  			// yet. We periodically resubmit them until they have.
  2427  			for iv, data := range pendingInvs {
  2428  				ivCopy := iv
  2429  				s.RelayInventory(&ivCopy, data)
  2430  			}
  2431  
  2432  			// Process at a random time up to 30mins (in seconds)
  2433  			// in the future.
  2434  			timer.Reset(time.Second *
  2435  				time.Duration(randomUint16Number(1800)))
  2436  
  2437  		case <-s.quit:
  2438  			break out
  2439  		}
  2440  	}
  2441  
  2442  	timer.Stop()
  2443  
  2444  	// Drain channels before exiting so nothing is left waiting around
  2445  	// to send.
  2446  cleanup:
  2447  	for {
  2448  		select {
  2449  		case <-s.modifyRebroadcastInv:
  2450  		default:
  2451  			break cleanup
  2452  		}
  2453  	}
  2454  	s.wg.Done()
  2455  }
  2456  
  2457  // Start begins accepting connections from peers.
  2458  func (s *server) Start() {
  2459  	// Already started?
  2460  	if atomic.AddInt32(&s.started, 1) != 1 {
  2461  		return
  2462  	}
  2463  
  2464  	srvrLog.Trace("Starting server")
  2465  
  2466  	// Server startup time. Used for the uptime command for uptime calculation.
  2467  	s.startupTime = time.Now().Unix()
  2468  
  2469  	// Start the peer handler which in turn starts the address and block
  2470  	// managers.
  2471  	s.wg.Add(1)
  2472  	go s.peerHandler()
  2473  
  2474  	if s.nat != nil {
  2475  		s.wg.Add(1)
  2476  		go s.upnpUpdateThread()
  2477  	}
  2478  
  2479  	if !cfg.DisableRPC {
  2480  		s.wg.Add(1)
  2481  
  2482  		// Start the rebroadcastHandler, which ensures user tx received by
  2483  		// the RPC server are rebroadcast until being included in a block.
  2484  		go s.rebroadcastHandler()
  2485  
  2486  		s.rpcServer.Start()
  2487  	}
  2488  
  2489  	// Start the CPU miner if generation is enabled.
  2490  	if cfg.Generate {
  2491  		s.cpuMiner.Start()
  2492  	}
  2493  }
  2494  
  2495  // Stop gracefully shuts down the server by stopping and disconnecting all
  2496  // peers and the main listener.
  2497  func (s *server) Stop() error {
  2498  	// Make sure this only happens once.
  2499  	if atomic.AddInt32(&s.shutdown, 1) != 1 {
  2500  		srvrLog.Infof("Server is already in the process of shutting down")
  2501  		return nil
  2502  	}
  2503  
  2504  	srvrLog.Warnf("Server shutting down")
  2505  
  2506  	// Stop the CPU miner if needed
  2507  	s.cpuMiner.Stop()
  2508  
  2509  	// Shutdown the RPC server if it's not disabled.
  2510  	if !cfg.DisableRPC {
  2511  		s.rpcServer.Stop()
  2512  	}
  2513  
  2514  	// Save fee estimator state in the database.
  2515  	s.db.Update(func(tx database.Tx) error {
  2516  		metadata := tx.Metadata()
  2517  		metadata.Put(mempool.EstimateFeeDatabaseKey, s.feeEstimator.Save())
  2518  
  2519  		return nil
  2520  	})
  2521  
  2522  	// Signal the remaining goroutines to quit.
  2523  	close(s.quit)
  2524  	return nil
  2525  }
  2526  
  2527  // WaitForShutdown blocks until the main listener and peer handlers are stopped.
  2528  func (s *server) WaitForShutdown() {
  2529  	s.wg.Wait()
  2530  }
  2531  
  2532  // ScheduleShutdown schedules a server shutdown after the specified duration.
  2533  // It also dynamically adjusts how often to warn the server is going down based
  2534  // on remaining duration.
  2535  func (s *server) ScheduleShutdown(duration time.Duration) {
  2536  	// Don't schedule shutdown more than once.
  2537  	if atomic.AddInt32(&s.shutdownSched, 1) != 1 {
  2538  		return
  2539  	}
  2540  	srvrLog.Warnf("Server shutdown in %v", duration)
  2541  	go func() {
  2542  		remaining := duration
  2543  		tickDuration := dynamicTickDuration(remaining)
  2544  		done := time.After(remaining)
  2545  		ticker := time.NewTicker(tickDuration)
  2546  	out:
  2547  		for {
  2548  			select {
  2549  			case <-done:
  2550  				ticker.Stop()
  2551  				s.Stop()
  2552  				break out
  2553  			case <-ticker.C:
  2554  				remaining = remaining - tickDuration
  2555  				if remaining < time.Second {
  2556  					continue
  2557  				}
  2558  
  2559  				// Change tick duration dynamically based on remaining time.
  2560  				newDuration := dynamicTickDuration(remaining)
  2561  				if tickDuration != newDuration {
  2562  					tickDuration = newDuration
  2563  					ticker.Stop()
  2564  					ticker = time.NewTicker(tickDuration)
  2565  				}
  2566  				srvrLog.Warnf("Server shutdown in %v", remaining)
  2567  			}
  2568  		}
  2569  	}()
  2570  }
  2571  
  2572  // parseListeners determines whether each listen address is IPv4 and IPv6 and
  2573  // returns a slice of appropriate net.Addrs to listen on with TCP. It also
  2574  // properly detects addresses which apply to "all interfaces" and adds the
  2575  // address as both IPv4 and IPv6.
  2576  func parseListeners(addrs []string) ([]net.Addr, error) {
  2577  	netAddrs := make([]net.Addr, 0, len(addrs)*2)
  2578  	for _, addr := range addrs {
  2579  		host, _, err := net.SplitHostPort(addr)
  2580  		if err != nil {
  2581  			// Shouldn't happen due to already being normalized.
  2582  			return nil, err
  2583  		}
  2584  
  2585  		// Empty host or host of * on plan9 is both IPv4 and IPv6.
  2586  		if host == "" || (host == "*" && runtime.GOOS == "plan9") {
  2587  			netAddrs = append(netAddrs, simpleAddr{net: "tcp4", addr: addr})
  2588  			netAddrs = append(netAddrs, simpleAddr{net: "tcp6", addr: addr})
  2589  			continue
  2590  		}
  2591  
  2592  		// Strip IPv6 zone id if present since net.ParseIP does not
  2593  		// handle it.
  2594  		zoneIndex := strings.LastIndex(host, "%")
  2595  		if zoneIndex > 0 {
  2596  			host = host[:zoneIndex]
  2597  		}
  2598  
  2599  		// Parse the IP.
  2600  		ip := net.ParseIP(host)
  2601  		if ip == nil {
  2602  			return nil, fmt.Errorf("'%s' is not a valid IP address", host)
  2603  		}
  2604  
  2605  		// To4 returns nil when the IP is not an IPv4 address, so use
  2606  		// this determine the address type.
  2607  		if ip.To4() == nil {
  2608  			netAddrs = append(netAddrs, simpleAddr{net: "tcp6", addr: addr})
  2609  		} else {
  2610  			netAddrs = append(netAddrs, simpleAddr{net: "tcp4", addr: addr})
  2611  		}
  2612  	}
  2613  	return netAddrs, nil
  2614  }
  2615  
  2616  func (s *server) upnpUpdateThread() {
  2617  	// Go off immediately to prevent code duplication, thereafter we renew
  2618  	// lease every 15 minutes.
  2619  	timer := time.NewTimer(0 * time.Second)
  2620  	lport, _ := strconv.ParseInt(activeNetParams.DefaultPort, 10, 16)
  2621  	first := true
  2622  out:
  2623  	for {
  2624  		select {
  2625  		case <-timer.C:
  2626  			// TODO: pick external port  more cleverly
  2627  			// TODO: know which ports we are listening to on an external net.
  2628  			// TODO: if specific listen port doesn't work then ask for wildcard
  2629  			// listen port?
  2630  			// XXX this assumes timeout is in seconds.
  2631  			listenPort, err := s.nat.AddPortMapping("tcp", int(lport), int(lport),
  2632  				"btcd listen port", 20*60)
  2633  			if err != nil {
  2634  				srvrLog.Warnf("can't add UPnP port mapping: %v", err)
  2635  			}
  2636  			if first && err == nil {
  2637  				// TODO: look this up periodically to see if upnp domain changed
  2638  				// and so did ip.
  2639  				externalip, err := s.nat.GetExternalAddress()
  2640  				if err != nil {
  2641  					srvrLog.Warnf("UPnP can't get external address: %v", err)
  2642  					continue out
  2643  				}
  2644  				na := wire.NetAddressV2FromBytes(time.Now(), s.services,
  2645  					externalip, uint16(listenPort))
  2646  				err = s.addrManager.AddLocalAddress(na, addrmgr.UpnpPrio)
  2647  				if err != nil {
  2648  					// XXX DeletePortMapping?
  2649  				}
  2650  				srvrLog.Warnf("Successfully bound via UPnP to %s", addrmgr.NetAddressKey(na))
  2651  				first = false
  2652  			}
  2653  			timer.Reset(time.Minute * 15)
  2654  		case <-s.quit:
  2655  			break out
  2656  		}
  2657  	}
  2658  
  2659  	timer.Stop()
  2660  
  2661  	if err := s.nat.DeletePortMapping("tcp", int(lport), int(lport)); err != nil {
  2662  		srvrLog.Warnf("unable to remove UPnP port mapping: %v", err)
  2663  	} else {
  2664  		srvrLog.Debugf("successfully disestablished UPnP port mapping")
  2665  	}
  2666  
  2667  	s.wg.Done()
  2668  }
  2669  
  2670  // setupRPCListeners returns a slice of listeners that are configured for use
  2671  // with the RPC server depending on the configuration settings for listen
  2672  // addresses and TLS.
  2673  func setupRPCListeners() ([]net.Listener, error) {
  2674  	// Setup TLS if not disabled.
  2675  	listenFunc := net.Listen
  2676  	if !cfg.DisableTLS {
  2677  		// Generate the TLS cert and key file if both don't already
  2678  		// exist.
  2679  		if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
  2680  			err := genCertPair(cfg.RPCCert, cfg.RPCKey)
  2681  			if err != nil {
  2682  				return nil, err
  2683  			}
  2684  		}
  2685  		keypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)
  2686  		if err != nil {
  2687  			return nil, err
  2688  		}
  2689  
  2690  		tlsConfig := tls.Config{
  2691  			Certificates: []tls.Certificate{keypair},
  2692  			MinVersion:   tls.VersionTLS12,
  2693  		}
  2694  
  2695  		// Change the standard net.Listen function to the tls one.
  2696  		listenFunc = func(net string, laddr string) (net.Listener, error) {
  2697  			return tls.Listen(net, laddr, &tlsConfig)
  2698  		}
  2699  	}
  2700  
  2701  	netAddrs, err := parseListeners(cfg.RPCListeners)
  2702  	if err != nil {
  2703  		return nil, err
  2704  	}
  2705  
  2706  	listeners := make([]net.Listener, 0, len(netAddrs))
  2707  	for _, addr := range netAddrs {
  2708  		listener, err := listenFunc(addr.Network(), addr.String())
  2709  		if err != nil {
  2710  			rpcsLog.Warnf("Can't listen on %s: %v", addr, err)
  2711  			continue
  2712  		}
  2713  		listeners = append(listeners, listener)
  2714  	}
  2715  
  2716  	return listeners, nil
  2717  }
  2718  
  2719  // newServer returns a new btcd server configured to listen on addr for the
  2720  // bitcoin network type specified by chainParams.  Use start to begin accepting
  2721  // connections from peers.
  2722  func newServer(listenAddrs, agentBlacklist, agentWhitelist []string,
  2723  	db database.DB, chainParams *chaincfg.Params,
  2724  	interrupt <-chan struct{}) (*server, error) {
  2725  
  2726  	services := defaultServices
  2727  	if cfg.NoPeerBloomFilters {
  2728  		services &^= wire.SFNodeBloom
  2729  	}
  2730  	if cfg.NoCFilters {
  2731  		services &^= wire.SFNodeCF
  2732  	}
  2733  	if cfg.Prune != 0 {
  2734  		services &^= wire.SFNodeNetwork
  2735  	}
  2736  
  2737  	amgr := addrmgr.New(cfg.DataDir, btcdLookup)
  2738  
  2739  	var listeners []net.Listener
  2740  	var nat NAT
  2741  	if !cfg.DisableListen {
  2742  		var err error
  2743  		listeners, nat, err = initListeners(amgr, listenAddrs, services)
  2744  		if err != nil {
  2745  			return nil, err
  2746  		}
  2747  		if len(listeners) == 0 {
  2748  			return nil, errors.New("no valid listen address")
  2749  		}
  2750  	}
  2751  
  2752  	if len(agentBlacklist) > 0 {
  2753  		srvrLog.Infof("User-agent blacklist %s", agentBlacklist)
  2754  	}
  2755  	if len(agentWhitelist) > 0 {
  2756  		srvrLog.Infof("User-agent whitelist %s", agentWhitelist)
  2757  	}
  2758  
  2759  	s := server{
  2760  		chainParams:          chainParams,
  2761  		addrManager:          amgr,
  2762  		newPeers:             make(chan *serverPeer, cfg.MaxPeers),
  2763  		donePeers:            make(chan *serverPeer, cfg.MaxPeers),
  2764  		banPeers:             make(chan *serverPeer, cfg.MaxPeers),
  2765  		query:                make(chan interface{}),
  2766  		relayInv:             make(chan relayMsg, cfg.MaxPeers),
  2767  		broadcast:            make(chan broadcastMsg, cfg.MaxPeers),
  2768  		quit:                 make(chan struct{}),
  2769  		modifyRebroadcastInv: make(chan interface{}),
  2770  		peerHeightsUpdate:    make(chan updatePeerHeightsMsg),
  2771  		nat:                  nat,
  2772  		db:                   db,
  2773  		timeSource:           blockchain.NewMedianTime(),
  2774  		services:             services,
  2775  		sigCache:             txscript.NewSigCache(cfg.SigCacheMaxSize),
  2776  		hashCache:            txscript.NewHashCache(cfg.SigCacheMaxSize),
  2777  		cfCheckptCaches:      make(map[wire.FilterType][]cfHeaderKV),
  2778  		agentBlacklist:       agentBlacklist,
  2779  		agentWhitelist:       agentWhitelist,
  2780  	}
  2781  
  2782  	// Create the transaction and address indexes if needed.
  2783  	//
  2784  	// CAUTION: the txindex needs to be first in the indexes array because
  2785  	// the addrindex uses data from the txindex during catchup.  If the
  2786  	// addrindex is run first, it may not have the transactions from the
  2787  	// current block indexed.
  2788  	var indexes []indexers.Indexer
  2789  	if cfg.TxIndex || cfg.AddrIndex {
  2790  		// Enable transaction index if address index is enabled since it
  2791  		// requires it.
  2792  		if !cfg.TxIndex {
  2793  			indxLog.Infof("Transaction index enabled because it " +
  2794  				"is required by the address index")
  2795  			cfg.TxIndex = true
  2796  		} else {
  2797  			indxLog.Info("Transaction index is enabled")
  2798  		}
  2799  
  2800  		s.txIndex = indexers.NewTxIndex(db)
  2801  		indexes = append(indexes, s.txIndex)
  2802  	}
  2803  	if cfg.AddrIndex {
  2804  		indxLog.Info("Address index is enabled")
  2805  		s.addrIndex = indexers.NewAddrIndex(db, chainParams)
  2806  		indexes = append(indexes, s.addrIndex)
  2807  	}
  2808  	if !cfg.NoCFilters {
  2809  		indxLog.Info("Committed filter index is enabled")
  2810  		s.cfIndex = indexers.NewCfIndex(db, chainParams)
  2811  		indexes = append(indexes, s.cfIndex)
  2812  	}
  2813  
  2814  	// Create an index manager if any of the optional indexes are enabled.
  2815  	var indexManager blockchain.IndexManager
  2816  	if len(indexes) > 0 {
  2817  		indexManager = indexers.NewManager(db, indexes)
  2818  	}
  2819  
  2820  	// Merge given checkpoints with the default ones unless they are disabled.
  2821  	var checkpoints []chaincfg.Checkpoint
  2822  	if !cfg.DisableCheckpoints {
  2823  		checkpoints = mergeCheckpoints(s.chainParams.Checkpoints, cfg.addCheckpoints)
  2824  	}
  2825  
  2826  	// Create a new block chain instance with the appropriate configuration.
  2827  	var err error
  2828  	s.chain, err = blockchain.New(&blockchain.Config{
  2829  		DB:               s.db,
  2830  		Interrupt:        interrupt,
  2831  		ChainParams:      s.chainParams,
  2832  		Checkpoints:      checkpoints,
  2833  		TimeSource:       s.timeSource,
  2834  		SigCache:         s.sigCache,
  2835  		IndexManager:     indexManager,
  2836  		HashCache:        s.hashCache,
  2837  		Prune:            cfg.Prune * 1024 * 1024,
  2838  		UtxoCacheMaxSize: uint64(cfg.UtxoCacheMaxSizeMiB) * 1024 * 1024,
  2839  	})
  2840  	if err != nil {
  2841  		return nil, err
  2842  	}
  2843  
  2844  	// Search for a FeeEstimator state in the database. If none can be found
  2845  	// or if it cannot be loaded, create a new one.
  2846  	db.Update(func(tx database.Tx) error {
  2847  		metadata := tx.Metadata()
  2848  		feeEstimationData := metadata.Get(mempool.EstimateFeeDatabaseKey)
  2849  		if feeEstimationData != nil {
  2850  			// delete it from the database so that we don't try to restore the
  2851  			// same thing again somehow.
  2852  			metadata.Delete(mempool.EstimateFeeDatabaseKey)
  2853  
  2854  			// If there is an error, log it and make a new fee estimator.
  2855  			var err error
  2856  			s.feeEstimator, err = mempool.RestoreFeeEstimator(feeEstimationData)
  2857  
  2858  			if err != nil {
  2859  				peerLog.Errorf("Failed to restore fee estimator %v", err)
  2860  			}
  2861  		}
  2862  
  2863  		return nil
  2864  	})
  2865  
  2866  	// If no feeEstimator has been found, or if the one that has been found
  2867  	// is behind somehow, create a new one and start over.
  2868  	if s.feeEstimator == nil || s.feeEstimator.LastKnownHeight() != s.chain.BestSnapshot().Height {
  2869  		s.feeEstimator = mempool.NewFeeEstimator(
  2870  			mempool.DefaultEstimateFeeMaxRollback,
  2871  			mempool.DefaultEstimateFeeMinRegisteredBlocks)
  2872  	}
  2873  
  2874  	txC := mempool.Config{
  2875  		Policy: mempool.Policy{
  2876  			DisableRelayPriority: cfg.NoRelayPriority,
  2877  			AcceptNonStd:         cfg.RelayNonStd,
  2878  			FreeTxRelayLimit:     cfg.FreeTxRelayLimit,
  2879  			MaxOrphanTxs:         cfg.MaxOrphanTxs,
  2880  			MaxOrphanTxSize:      defaultMaxOrphanTxSize,
  2881  			MaxSigOpCostPerTx:    blockchain.MaxBlockSigOpsCost / 4,
  2882  			MinRelayTxFee:        cfg.minRelayTxFee,
  2883  			MaxTxVersion:         2,
  2884  			RejectReplacement:    cfg.RejectReplacement,
  2885  		},
  2886  		ChainParams:    chainParams,
  2887  		FetchUtxoView:  s.chain.FetchUtxoView,
  2888  		BestHeight:     func() int32 { return s.chain.BestSnapshot().Height },
  2889  		MedianTimePast: func() time.Time { return s.chain.BestSnapshot().MedianTime },
  2890  		CalcSequenceLock: func(tx *btcutil.Tx, view *blockchain.UtxoViewpoint) (*blockchain.SequenceLock, error) {
  2891  			return s.chain.CalcSequenceLock(tx, view, true)
  2892  		},
  2893  		IsDeploymentActive: s.chain.IsDeploymentActive,
  2894  		SigCache:           s.sigCache,
  2895  		HashCache:          s.hashCache,
  2896  		AddrIndex:          s.addrIndex,
  2897  		FeeEstimator:       s.feeEstimator,
  2898  	}
  2899  	s.txMemPool = mempool.New(&txC)
  2900  
  2901  	s.syncManager, err = netsync.New(&netsync.Config{
  2902  		PeerNotifier:       &s,
  2903  		Chain:              s.chain,
  2904  		TxMemPool:          s.txMemPool,
  2905  		ChainParams:        s.chainParams,
  2906  		DisableCheckpoints: cfg.DisableCheckpoints,
  2907  		MaxPeers:           cfg.MaxPeers,
  2908  		FeeEstimator:       s.feeEstimator,
  2909  	})
  2910  	if err != nil {
  2911  		return nil, err
  2912  	}
  2913  
  2914  	// Create the mining policy and block template generator based on the
  2915  	// configuration options.
  2916  	//
  2917  	// NOTE: The CPU miner relies on the mempool, so the mempool has to be
  2918  	// created before calling the function to create the CPU miner.
  2919  	policy := mining.Policy{
  2920  		BlockMinWeight:    cfg.BlockMinWeight,
  2921  		BlockMaxWeight:    cfg.BlockMaxWeight,
  2922  		BlockMinSize:      cfg.BlockMinSize,
  2923  		BlockMaxSize:      cfg.BlockMaxSize,
  2924  		BlockPrioritySize: cfg.BlockPrioritySize,
  2925  		TxMinFreeFee:      cfg.minRelayTxFee,
  2926  	}
  2927  	blockTemplateGenerator := mining.NewBlkTmplGenerator(&policy,
  2928  		s.chainParams, s.txMemPool, s.chain, s.timeSource,
  2929  		s.sigCache, s.hashCache)
  2930  	s.cpuMiner = cpuminer.New(&cpuminer.Config{
  2931  		ChainParams:            chainParams,
  2932  		BlockTemplateGenerator: blockTemplateGenerator,
  2933  		MiningAddrs:            cfg.miningAddrs,
  2934  		ProcessBlock:           s.syncManager.ProcessBlock,
  2935  		ConnectedCount:         s.ConnectedCount,
  2936  		IsCurrent:              s.syncManager.IsCurrent,
  2937  	})
  2938  
  2939  	// Only setup a function to return new addresses to connect to when
  2940  	// not running in connect-only mode.  The simulation network is always
  2941  	// in connect-only mode since it is only intended to connect to
  2942  	// specified peers and actively avoid advertising and connecting to
  2943  	// discovered peers in order to prevent it from becoming a public test
  2944  	// network.
  2945  	var newAddressFunc func() (net.Addr, error)
  2946  	if !cfg.SimNet && len(cfg.ConnectPeers) == 0 {
  2947  		newAddressFunc = func() (net.Addr, error) {
  2948  			for tries := 0; tries < 100; tries++ {
  2949  				addr := s.addrManager.GetAddress()
  2950  				if addr == nil {
  2951  					break
  2952  				}
  2953  
  2954  				// Address will not be invalid, local or unroutable
  2955  				// because addrmanager rejects those on addition.
  2956  				// Just check that we don't already have an address
  2957  				// in the same group so that we are not connecting
  2958  				// to the same network segment at the expense of
  2959  				// others.
  2960  				key := addrmgr.GroupKey(addr.NetAddress())
  2961  				if s.OutboundGroupCount(key) != 0 {
  2962  					continue
  2963  				}
  2964  
  2965  				// only allow recent nodes (10mins) after we failed 30
  2966  				// times
  2967  				if tries < 30 && time.Since(addr.LastAttempt()) < 10*time.Minute {
  2968  					continue
  2969  				}
  2970  
  2971  				// allow nondefault ports after 50 failed tries.
  2972  				if tries < 50 && fmt.Sprintf("%d", addr.NetAddress().Port) !=
  2973  					activeNetParams.DefaultPort {
  2974  					continue
  2975  				}
  2976  
  2977  				// Mark an attempt for the valid address.
  2978  				s.addrManager.Attempt(addr.NetAddress())
  2979  
  2980  				addrString := addrmgr.NetAddressKey(addr.NetAddress())
  2981  				return addrStringToNetAddr(addrString)
  2982  			}
  2983  
  2984  			return nil, errors.New("no valid connect address")
  2985  		}
  2986  	}
  2987  
  2988  	// Create a connection manager.
  2989  	targetOutbound := defaultTargetOutbound
  2990  	if cfg.MaxPeers < targetOutbound {
  2991  		targetOutbound = cfg.MaxPeers
  2992  	}
  2993  	cmgr, err := connmgr.New(&connmgr.Config{
  2994  		Listeners:      listeners,
  2995  		OnAccept:       s.inboundPeerConnected,
  2996  		RetryDuration:  connectionRetryInterval,
  2997  		TargetOutbound: uint32(targetOutbound),
  2998  		Dial:           btcdDial,
  2999  		OnConnection:   s.outboundPeerConnected,
  3000  		GetNewAddress:  newAddressFunc,
  3001  	})
  3002  	if err != nil {
  3003  		return nil, err
  3004  	}
  3005  	s.connManager = cmgr
  3006  
  3007  	// Start up persistent peers.
  3008  	permanentPeers := cfg.ConnectPeers
  3009  	if len(permanentPeers) == 0 {
  3010  		permanentPeers = cfg.AddPeers
  3011  	}
  3012  	for _, addr := range permanentPeers {
  3013  		netAddr, err := addrStringToNetAddr(addr)
  3014  		if err != nil {
  3015  			return nil, err
  3016  		}
  3017  
  3018  		go s.connManager.Connect(&connmgr.ConnReq{
  3019  			Addr:      netAddr,
  3020  			Permanent: true,
  3021  		})
  3022  	}
  3023  
  3024  	if !cfg.DisableRPC {
  3025  		// Setup listeners for the configured RPC listen addresses and
  3026  		// TLS settings.
  3027  		rpcListeners, err := setupRPCListeners()
  3028  		if err != nil {
  3029  			return nil, err
  3030  		}
  3031  		if len(rpcListeners) == 0 {
  3032  			return nil, errors.New("RPCS: No valid listen address")
  3033  		}
  3034  
  3035  		s.rpcServer, err = newRPCServer(&rpcserverConfig{
  3036  			Listeners:    rpcListeners,
  3037  			StartupTime:  s.startupTime,
  3038  			ConnMgr:      &rpcConnManager{&s},
  3039  			SyncMgr:      &rpcSyncMgr{&s, s.syncManager},
  3040  			TimeSource:   s.timeSource,
  3041  			Chain:        s.chain,
  3042  			ChainParams:  chainParams,
  3043  			DB:           db,
  3044  			TxMemPool:    s.txMemPool,
  3045  			Generator:    blockTemplateGenerator,
  3046  			CPUMiner:     s.cpuMiner,
  3047  			TxIndex:      s.txIndex,
  3048  			AddrIndex:    s.addrIndex,
  3049  			CfIndex:      s.cfIndex,
  3050  			FeeEstimator: s.feeEstimator,
  3051  		})
  3052  		if err != nil {
  3053  			return nil, err
  3054  		}
  3055  
  3056  		// Signal process shutdown when the RPC server requests it.
  3057  		go func() {
  3058  			<-s.rpcServer.RequestedProcessShutdown()
  3059  			shutdownRequestChannel <- struct{}{}
  3060  		}()
  3061  	}
  3062  
  3063  	return &s, nil
  3064  }
  3065  
  3066  // initListeners initializes the configured net listeners and adds any bound
  3067  // addresses to the address manager. Returns the listeners and a NAT interface,
  3068  // which is non-nil if UPnP is in use.
  3069  func initListeners(amgr *addrmgr.AddrManager, listenAddrs []string, services wire.ServiceFlag) ([]net.Listener, NAT, error) {
  3070  	// Listen for TCP connections at the configured addresses
  3071  	netAddrs, err := parseListeners(listenAddrs)
  3072  	if err != nil {
  3073  		return nil, nil, err
  3074  	}
  3075  
  3076  	listeners := make([]net.Listener, 0, len(netAddrs))
  3077  	for _, addr := range netAddrs {
  3078  		listener, err := net.Listen(addr.Network(), addr.String())
  3079  		if err != nil {
  3080  			srvrLog.Warnf("Can't listen on %s: %v", addr, err)
  3081  			continue
  3082  		}
  3083  		listeners = append(listeners, listener)
  3084  	}
  3085  
  3086  	var nat NAT
  3087  	if len(cfg.ExternalIPs) != 0 {
  3088  		defaultPort, err := strconv.ParseUint(activeNetParams.DefaultPort, 10, 16)
  3089  		if err != nil {
  3090  			srvrLog.Errorf("Can not parse default port %s for active chain: %v",
  3091  				activeNetParams.DefaultPort, err)
  3092  			return nil, nil, err
  3093  		}
  3094  
  3095  		for _, sip := range cfg.ExternalIPs {
  3096  			eport := uint16(defaultPort)
  3097  			host, portstr, err := net.SplitHostPort(sip)
  3098  			if err != nil {
  3099  				// no port, use default.
  3100  				host = sip
  3101  			} else {
  3102  				port, err := strconv.ParseUint(portstr, 10, 16)
  3103  				if err != nil {
  3104  					srvrLog.Warnf("Can not parse port from %s for "+
  3105  						"externalip: %v", sip, err)
  3106  					continue
  3107  				}
  3108  				eport = uint16(port)
  3109  			}
  3110  			na, err := amgr.HostToNetAddress(host, eport, services)
  3111  			if err != nil {
  3112  				srvrLog.Warnf("Not adding %s as externalip: %v", sip, err)
  3113  				continue
  3114  			}
  3115  
  3116  			err = amgr.AddLocalAddress(na, addrmgr.ManualPrio)
  3117  			if err != nil {
  3118  				amgrLog.Warnf("Skipping specified external IP: %v", err)
  3119  			}
  3120  		}
  3121  	} else {
  3122  		if cfg.Upnp {
  3123  			var err error
  3124  			nat, err = Discover()
  3125  			if err != nil {
  3126  				srvrLog.Warnf("Can't discover upnp: %v", err)
  3127  			}
  3128  			// nil nat here is fine, just means no upnp on network.
  3129  		}
  3130  
  3131  		// Add bound addresses to address manager to be advertised to peers.
  3132  		for _, listener := range listeners {
  3133  			addr := listener.Addr().String()
  3134  			err := addLocalAddress(amgr, addr, services)
  3135  			if err != nil {
  3136  				amgrLog.Warnf("Skipping bound address %s: %v", addr, err)
  3137  			}
  3138  		}
  3139  	}
  3140  
  3141  	return listeners, nat, nil
  3142  }
  3143  
  3144  // addrStringToNetAddr takes an address in the form of 'host:port' and returns
  3145  // a net.Addr which maps to the original address with any host names resolved
  3146  // to IP addresses.  It also handles tor addresses properly by returning a
  3147  // net.Addr that encapsulates the address.
  3148  func addrStringToNetAddr(addr string) (net.Addr, error) {
  3149  	host, strPort, err := net.SplitHostPort(addr)
  3150  	if err != nil {
  3151  		return nil, err
  3152  	}
  3153  
  3154  	port, err := strconv.Atoi(strPort)
  3155  	if err != nil {
  3156  		return nil, err
  3157  	}
  3158  
  3159  	// Skip if host is already an IP address.
  3160  	if ip := net.ParseIP(host); ip != nil {
  3161  		return &net.TCPAddr{
  3162  			IP:   ip,
  3163  			Port: port,
  3164  		}, nil
  3165  	}
  3166  
  3167  	// Tor addresses cannot be resolved to an IP, so just return an onion
  3168  	// address instead.
  3169  	if strings.HasSuffix(host, ".onion") {
  3170  		if cfg.NoOnion {
  3171  			return nil, errors.New("tor has been disabled")
  3172  		}
  3173  
  3174  		return &onionAddr{addr: addr}, nil
  3175  	}
  3176  
  3177  	// Attempt to look up an IP address associated with the parsed host.
  3178  	ips, err := btcdLookup(host)
  3179  	if err != nil {
  3180  		return nil, err
  3181  	}
  3182  	if len(ips) == 0 {
  3183  		return nil, fmt.Errorf("no addresses found for %s", host)
  3184  	}
  3185  
  3186  	return &net.TCPAddr{
  3187  		IP:   ips[0],
  3188  		Port: port,
  3189  	}, nil
  3190  }
  3191  
  3192  // addLocalAddress adds an address that this node is listening on to the
  3193  // address manager so that it may be relayed to peers.
  3194  func addLocalAddress(addrMgr *addrmgr.AddrManager, addr string, services wire.ServiceFlag) error {
  3195  	host, portStr, err := net.SplitHostPort(addr)
  3196  	if err != nil {
  3197  		return err
  3198  	}
  3199  	port, err := strconv.ParseUint(portStr, 10, 16)
  3200  	if err != nil {
  3201  		return err
  3202  	}
  3203  
  3204  	if ip := net.ParseIP(host); ip != nil && ip.IsUnspecified() {
  3205  		// If bound to unspecified address, advertise all local interfaces
  3206  		addrs, err := net.InterfaceAddrs()
  3207  		if err != nil {
  3208  			return err
  3209  		}
  3210  
  3211  		for _, addr := range addrs {
  3212  			ifaceIP, _, err := net.ParseCIDR(addr.String())
  3213  			if err != nil {
  3214  				continue
  3215  			}
  3216  
  3217  			// If bound to 0.0.0.0, do not add IPv6 interfaces and if bound to
  3218  			// ::, do not add IPv4 interfaces.
  3219  			if (ip.To4() == nil) != (ifaceIP.To4() == nil) {
  3220  				continue
  3221  			}
  3222  
  3223  			netAddr := wire.NetAddressV2FromBytes(
  3224  				time.Now(), services, ifaceIP, uint16(port),
  3225  			)
  3226  			addrMgr.AddLocalAddress(netAddr, addrmgr.BoundPrio)
  3227  		}
  3228  	} else {
  3229  		netAddr, err := addrMgr.HostToNetAddress(host, uint16(port), services)
  3230  		if err != nil {
  3231  			return err
  3232  		}
  3233  
  3234  		addrMgr.AddLocalAddress(netAddr, addrmgr.BoundPrio)
  3235  	}
  3236  
  3237  	return nil
  3238  }
  3239  
  3240  // dynamicTickDuration is a convenience function used to dynamically choose a
  3241  // tick duration based on remaining time.  It is primarily used during
  3242  // server shutdown to make shutdown warnings more frequent as the shutdown time
  3243  // approaches.
  3244  func dynamicTickDuration(remaining time.Duration) time.Duration {
  3245  	switch {
  3246  	case remaining <= time.Second*5:
  3247  		return time.Second
  3248  	case remaining <= time.Second*15:
  3249  		return time.Second * 5
  3250  	case remaining <= time.Minute:
  3251  		return time.Second * 15
  3252  	case remaining <= time.Minute*5:
  3253  		return time.Minute
  3254  	case remaining <= time.Minute*15:
  3255  		return time.Minute * 5
  3256  	case remaining <= time.Hour:
  3257  		return time.Minute * 15
  3258  	}
  3259  	return time.Hour
  3260  }
  3261  
  3262  // isWhitelisted returns whether the IP address is included in the whitelisted
  3263  // networks and IPs.
  3264  func isWhitelisted(addr net.Addr) bool {
  3265  	if len(cfg.whitelists) == 0 {
  3266  		return false
  3267  	}
  3268  
  3269  	host, _, err := net.SplitHostPort(addr.String())
  3270  	if err != nil {
  3271  		srvrLog.Warnf("Unable to SplitHostPort on '%s': %v", addr, err)
  3272  		return false
  3273  	}
  3274  	ip := net.ParseIP(host)
  3275  	if ip == nil {
  3276  		srvrLog.Warnf("Unable to parse IP '%s'", addr)
  3277  		return false
  3278  	}
  3279  
  3280  	for _, ipnet := range cfg.whitelists {
  3281  		if ipnet.Contains(ip) {
  3282  			return true
  3283  		}
  3284  	}
  3285  	return false
  3286  }
  3287  
  3288  // checkpointSorter implements sort.Interface to allow a slice of checkpoints to
  3289  // be sorted.
  3290  type checkpointSorter []chaincfg.Checkpoint
  3291  
  3292  // Len returns the number of checkpoints in the slice.  It is part of the
  3293  // sort.Interface implementation.
  3294  func (s checkpointSorter) Len() int {
  3295  	return len(s)
  3296  }
  3297  
  3298  // Swap swaps the checkpoints at the passed indices.  It is part of the
  3299  // sort.Interface implementation.
  3300  func (s checkpointSorter) Swap(i, j int) {
  3301  	s[i], s[j] = s[j], s[i]
  3302  }
  3303  
  3304  // Less returns whether the checkpoint with index i should sort before the
  3305  // checkpoint with index j.  It is part of the sort.Interface implementation.
  3306  func (s checkpointSorter) Less(i, j int) bool {
  3307  	return s[i].Height < s[j].Height
  3308  }
  3309  
  3310  // mergeCheckpoints returns two slices of checkpoints merged into one slice
  3311  // such that the checkpoints are sorted by height.  In the case the additional
  3312  // checkpoints contain a checkpoint with the same height as a checkpoint in the
  3313  // default checkpoints, the additional checkpoint will take precedence and
  3314  // overwrite the default one.
  3315  func mergeCheckpoints(defaultCheckpoints, additional []chaincfg.Checkpoint) []chaincfg.Checkpoint {
  3316  	// Create a map of the additional checkpoints to remove duplicates while
  3317  	// leaving the most recently-specified checkpoint.
  3318  	extra := make(map[int32]chaincfg.Checkpoint)
  3319  	for _, checkpoint := range additional {
  3320  		extra[checkpoint.Height] = checkpoint
  3321  	}
  3322  
  3323  	// Add all default checkpoints that do not have an override in the
  3324  	// additional checkpoints.
  3325  	numDefault := len(defaultCheckpoints)
  3326  	checkpoints := make([]chaincfg.Checkpoint, 0, numDefault+len(extra))
  3327  	for _, checkpoint := range defaultCheckpoints {
  3328  		if _, exists := extra[checkpoint.Height]; !exists {
  3329  			checkpoints = append(checkpoints, checkpoint)
  3330  		}
  3331  	}
  3332  
  3333  	// Append the additional checkpoints and return the sorted results.
  3334  	for _, checkpoint := range extra {
  3335  		checkpoints = append(checkpoints, checkpoint)
  3336  	}
  3337  	sort.Sort(checkpointSorter(checkpoints))
  3338  	return checkpoints
  3339  }
  3340  
  3341  // HasUndesiredUserAgent determines whether the server should continue to pursue
  3342  // a connection with this peer based on its advertised user agent. It performs
  3343  // the following steps:
  3344  // 1) Reject the peer if it contains a blacklisted agent.
  3345  // 2) If no whitelist is provided, accept all user agents.
  3346  // 3) Accept the peer if it contains a whitelisted agent.
  3347  // 4) Reject all other peers.
  3348  func (sp *serverPeer) HasUndesiredUserAgent(blacklistedAgents,
  3349  	whitelistedAgents []string) bool {
  3350  
  3351  	agent := sp.UserAgent()
  3352  
  3353  	// First, if peer's user agent contains any blacklisted substring, we
  3354  	// will ignore the connection request.
  3355  	for _, blacklistedAgent := range blacklistedAgents {
  3356  		if strings.Contains(agent, blacklistedAgent) {
  3357  			srvrLog.Debugf("Ignoring peer %s, user agent "+
  3358  				"contains blacklisted user agent: %s", sp,
  3359  				agent)
  3360  			return true
  3361  		}
  3362  	}
  3363  
  3364  	// If no whitelist is provided, we will accept all user agents.
  3365  	if len(whitelistedAgents) == 0 {
  3366  		return false
  3367  	}
  3368  
  3369  	// Peer's user agent passed blacklist. Now check to see if it contains
  3370  	// one of our whitelisted user agents, if so accept.
  3371  	for _, whitelistedAgent := range whitelistedAgents {
  3372  		if strings.Contains(agent, whitelistedAgent) {
  3373  			return false
  3374  		}
  3375  	}
  3376  
  3377  	// Otherwise, the peer's user agent was not included in our whitelist.
  3378  	// Ignore just in case it could stall the initial block download.
  3379  	srvrLog.Debugf("Ignoring peer %s, user agent: %s not found in "+
  3380  		"whitelist", sp, agent)
  3381  
  3382  	return true
  3383  }