github.com/juliankolbe/go-ethereum@v1.9.992/les/peer.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package les
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"math/big"
    23  	"math/rand"
    24  	"net"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/juliankolbe/go-ethereum/common"
    30  	"github.com/juliankolbe/go-ethereum/common/mclock"
    31  	"github.com/juliankolbe/go-ethereum/core"
    32  	"github.com/juliankolbe/go-ethereum/core/forkid"
    33  	"github.com/juliankolbe/go-ethereum/core/types"
    34  	"github.com/juliankolbe/go-ethereum/les/flowcontrol"
    35  	"github.com/juliankolbe/go-ethereum/les/utils"
    36  	vfc "github.com/juliankolbe/go-ethereum/les/vflux/client"
    37  	vfs "github.com/juliankolbe/go-ethereum/les/vflux/server"
    38  	"github.com/juliankolbe/go-ethereum/light"
    39  	"github.com/juliankolbe/go-ethereum/p2p"
    40  	"github.com/juliankolbe/go-ethereum/params"
    41  	"github.com/juliankolbe/go-ethereum/rlp"
    42  )
    43  
    44  var (
    45  	errClosed            = errors.New("peer set is closed")
    46  	errAlreadyRegistered = errors.New("peer is already registered")
    47  	errNotRegistered     = errors.New("peer is not registered")
    48  )
    49  
    50  const (
    51  	maxRequestErrors  = 20 // number of invalid requests tolerated (makes the protocol less brittle but still avoids spam)
    52  	maxResponseErrors = 50 // number of invalid responses tolerated (makes the protocol less brittle but still avoids spam)
    53  
    54  	allowedUpdateBytes = 100000                // initial/maximum allowed update size
    55  	allowedUpdateRate  = time.Millisecond * 10 // time constant for recharging one byte of allowance
    56  
    57  	freezeTimeBase    = time.Millisecond * 700 // fixed component of client freeze time
    58  	freezeTimeRandom  = time.Millisecond * 600 // random component of client freeze time
    59  	freezeCheckPeriod = time.Millisecond * 100 // buffer value recheck period after initial freeze time has elapsed
    60  
    61  	// If the total encoded size of a sent transaction batch is over txSizeCostLimit
    62  	// per transaction then the request cost is calculated as proportional to the
    63  	// encoded size instead of the transaction count
    64  	txSizeCostLimit = 0x4000
    65  
    66  	// handshakeTimeout is the timeout LES handshake will be treated as failed.
    67  	handshakeTimeout = 5 * time.Second
    68  )
    69  
    70  const (
    71  	announceTypeNone = iota
    72  	announceTypeSimple
    73  	announceTypeSigned
    74  )
    75  
    76  type keyValueEntry struct {
    77  	Key   string
    78  	Value rlp.RawValue
    79  }
    80  
    81  type keyValueList []keyValueEntry
    82  type keyValueMap map[string]rlp.RawValue
    83  
    84  func (l keyValueList) add(key string, val interface{}) keyValueList {
    85  	var entry keyValueEntry
    86  	entry.Key = key
    87  	if val == nil {
    88  		val = uint64(0)
    89  	}
    90  	enc, err := rlp.EncodeToBytes(val)
    91  	if err == nil {
    92  		entry.Value = enc
    93  	}
    94  	return append(l, entry)
    95  }
    96  
    97  func (l keyValueList) decode() (keyValueMap, uint64) {
    98  	m := make(keyValueMap)
    99  	var size uint64
   100  	for _, entry := range l {
   101  		m[entry.Key] = entry.Value
   102  		size += uint64(len(entry.Key)) + uint64(len(entry.Value)) + 8
   103  	}
   104  	return m, size
   105  }
   106  
   107  func (m keyValueMap) get(key string, val interface{}) error {
   108  	enc, ok := m[key]
   109  	if !ok {
   110  		return errResp(ErrMissingKey, "%s", key)
   111  	}
   112  	if val == nil {
   113  		return nil
   114  	}
   115  	return rlp.DecodeBytes(enc, val)
   116  }
   117  
   118  // peerCommons contains fields needed by both server peer and client peer.
   119  type peerCommons struct {
   120  	*p2p.Peer
   121  	rw p2p.MsgReadWriter
   122  
   123  	id           string    // Peer identity.
   124  	version      int       // Protocol version negotiated.
   125  	network      uint64    // Network ID being on.
   126  	frozen       uint32    // Flag whether the peer is frozen.
   127  	announceType uint64    // New block announcement type.
   128  	serving      uint32    // The status indicates the peer is served.
   129  	headInfo     blockInfo // Last announced block information.
   130  
   131  	// Background task queue for caching peer tasks and executing in order.
   132  	sendQueue *utils.ExecQueue
   133  
   134  	// Flow control agreement.
   135  	fcParams flowcontrol.ServerParams // The config for token bucket.
   136  	fcCosts  requestCostTable         // The Maximum request cost table.
   137  
   138  	closeCh chan struct{}
   139  	lock    sync.RWMutex // Lock used to protect all thread-sensitive fields.
   140  }
   141  
   142  // isFrozen returns true if the client is frozen or the server has put our
   143  // client in frozen state
   144  func (p *peerCommons) isFrozen() bool {
   145  	return atomic.LoadUint32(&p.frozen) != 0
   146  }
   147  
   148  // canQueue returns an indicator whether the peer can queue an operation.
   149  func (p *peerCommons) canQueue() bool {
   150  	return p.sendQueue.CanQueue() && !p.isFrozen()
   151  }
   152  
   153  // queueSend caches a peer operation in the background task queue.
   154  // Please ensure to check `canQueue` before call this function
   155  func (p *peerCommons) queueSend(f func()) bool {
   156  	return p.sendQueue.Queue(f)
   157  }
   158  
   159  // String implements fmt.Stringer.
   160  func (p *peerCommons) String() string {
   161  	return fmt.Sprintf("Peer %s [%s]", p.id, fmt.Sprintf("les/%d", p.version))
   162  }
   163  
   164  // PeerInfo represents a short summary of the `eth` sub-protocol metadata known
   165  // about a connected peer.
   166  type PeerInfo struct {
   167  	Version    int      `json:"version"`    // Ethereum protocol version negotiated
   168  	Difficulty *big.Int `json:"difficulty"` // Total difficulty of the peer's blockchain
   169  	Head       string   `json:"head"`       // SHA3 hash of the peer's best owned block
   170  }
   171  
   172  // Info gathers and returns a collection of metadata known about a peer.
   173  func (p *peerCommons) Info() *PeerInfo {
   174  	return &PeerInfo{
   175  		Version:    p.version,
   176  		Difficulty: p.Td(),
   177  		Head:       fmt.Sprintf("%x", p.Head()),
   178  	}
   179  }
   180  
   181  // Head retrieves a copy of the current head (most recent) hash of the peer.
   182  func (p *peerCommons) Head() (hash common.Hash) {
   183  	p.lock.RLock()
   184  	defer p.lock.RUnlock()
   185  
   186  	return p.headInfo.Hash
   187  }
   188  
   189  // Td retrieves the current total difficulty of a peer.
   190  func (p *peerCommons) Td() *big.Int {
   191  	p.lock.RLock()
   192  	defer p.lock.RUnlock()
   193  
   194  	return new(big.Int).Set(p.headInfo.Td)
   195  }
   196  
   197  // HeadAndTd retrieves the current head hash and total difficulty of a peer.
   198  func (p *peerCommons) HeadAndTd() (hash common.Hash, td *big.Int) {
   199  	p.lock.RLock()
   200  	defer p.lock.RUnlock()
   201  
   202  	return p.headInfo.Hash, new(big.Int).Set(p.headInfo.Td)
   203  }
   204  
   205  // sendReceiveHandshake exchanges handshake packet with remote peer and returns any error
   206  // if failed to send or receive packet.
   207  func (p *peerCommons) sendReceiveHandshake(sendList keyValueList) (keyValueList, error) {
   208  	var (
   209  		errc     = make(chan error, 2)
   210  		recvList keyValueList
   211  	)
   212  	// Send out own handshake in a new thread
   213  	go func() {
   214  		errc <- p2p.Send(p.rw, StatusMsg, sendList)
   215  	}()
   216  	go func() {
   217  		// In the mean time retrieve the remote status message
   218  		msg, err := p.rw.ReadMsg()
   219  		if err != nil {
   220  			errc <- err
   221  			return
   222  		}
   223  		if msg.Code != StatusMsg {
   224  			errc <- errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
   225  			return
   226  		}
   227  		if msg.Size > ProtocolMaxMsgSize {
   228  			errc <- errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
   229  			return
   230  		}
   231  		// Decode the handshake
   232  		if err := msg.Decode(&recvList); err != nil {
   233  			errc <- errResp(ErrDecode, "msg %v: %v", msg, err)
   234  			return
   235  		}
   236  		errc <- nil
   237  	}()
   238  	timeout := time.NewTimer(handshakeTimeout)
   239  	defer timeout.Stop()
   240  	for i := 0; i < 2; i++ {
   241  		select {
   242  		case err := <-errc:
   243  			if err != nil {
   244  				return nil, err
   245  			}
   246  		case <-timeout.C:
   247  			return nil, p2p.DiscReadTimeout
   248  		}
   249  	}
   250  	return recvList, nil
   251  }
   252  
   253  // handshake executes the les protocol handshake, negotiating version number,
   254  // network IDs, difficulties, head and genesis blocks. Besides the basic handshake
   255  // fields, server and client can exchange and resolve some specified fields through
   256  // two callback functions.
   257  func (p *peerCommons) handshake(td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, forkID forkid.ID, forkFilter forkid.Filter, sendCallback func(*keyValueList), recvCallback func(keyValueMap) error) error {
   258  	p.lock.Lock()
   259  	defer p.lock.Unlock()
   260  
   261  	var send keyValueList
   262  
   263  	// Add some basic handshake fields
   264  	send = send.add("protocolVersion", uint64(p.version))
   265  	send = send.add("networkId", p.network)
   266  	// Note: the head info announced at handshake is only used in case of server peers
   267  	// but dummy values are still announced by clients for compatibility with older servers
   268  	send = send.add("headTd", td)
   269  	send = send.add("headHash", head)
   270  	send = send.add("headNum", headNum)
   271  	send = send.add("genesisHash", genesis)
   272  
   273  	// If the protocol version is beyond les4, then pass the forkID
   274  	// as well. Check http://eips.ethereum.org/EIPS/eip-2124 for more
   275  	// spec detail.
   276  	if p.version >= lpv4 {
   277  		send = send.add("forkID", forkID)
   278  	}
   279  	// Add client-specified or server-specified fields
   280  	if sendCallback != nil {
   281  		sendCallback(&send)
   282  	}
   283  	// Exchange the handshake packet and resolve the received one.
   284  	recvList, err := p.sendReceiveHandshake(send)
   285  	if err != nil {
   286  		return err
   287  	}
   288  	recv, size := recvList.decode()
   289  	if size > allowedUpdateBytes {
   290  		return errResp(ErrRequestRejected, "")
   291  	}
   292  	var rGenesis common.Hash
   293  	var rVersion, rNetwork uint64
   294  	if err := recv.get("protocolVersion", &rVersion); err != nil {
   295  		return err
   296  	}
   297  	if err := recv.get("networkId", &rNetwork); err != nil {
   298  		return err
   299  	}
   300  	if err := recv.get("genesisHash", &rGenesis); err != nil {
   301  		return err
   302  	}
   303  	if rGenesis != genesis {
   304  		return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", rGenesis[:8], genesis[:8])
   305  	}
   306  	if rNetwork != p.network {
   307  		return errResp(ErrNetworkIdMismatch, "%d (!= %d)", rNetwork, p.network)
   308  	}
   309  	if int(rVersion) != p.version {
   310  		return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", rVersion, p.version)
   311  	}
   312  	// Check forkID if the protocol version is beyond the les4
   313  	if p.version >= lpv4 {
   314  		var forkID forkid.ID
   315  		if err := recv.get("forkID", &forkID); err != nil {
   316  			return err
   317  		}
   318  		if err := forkFilter(forkID); err != nil {
   319  			return errResp(ErrForkIDRejected, "%v", err)
   320  		}
   321  	}
   322  	if recvCallback != nil {
   323  		return recvCallback(recv)
   324  	}
   325  	return nil
   326  }
   327  
   328  // close closes the channel and notifies all background routines to exit.
   329  func (p *peerCommons) close() {
   330  	close(p.closeCh)
   331  	p.sendQueue.Quit()
   332  }
   333  
   334  // serverPeer represents each node to which the client is connected.
   335  // The node here refers to the les server.
   336  type serverPeer struct {
   337  	peerCommons
   338  
   339  	// Status fields
   340  	trusted                 bool   // The flag whether the server is selected as trusted server.
   341  	onlyAnnounce            bool   // The flag whether the server sends announcement only.
   342  	chainSince, chainRecent uint64 // The range of chain server peer can serve.
   343  	stateSince, stateRecent uint64 // The range of state server peer can serve.
   344  	txHistory               uint64 // The length of available tx history, 0 means all, 1 means disabled
   345  
   346  	// Advertised checkpoint fields
   347  	checkpointNumber uint64                   // The block height which the checkpoint is registered.
   348  	checkpoint       params.TrustedCheckpoint // The advertised checkpoint sent by server.
   349  
   350  	fcServer         *flowcontrol.ServerNode // Client side mirror token bucket.
   351  	vtLock           sync.Mutex
   352  	nodeValueTracker *vfc.NodeValueTracker
   353  	sentReqs         map[uint64]sentReqEntry
   354  
   355  	// Statistics
   356  	errCount    utils.LinearExpiredValue // Counter the invalid responses server has replied
   357  	updateCount uint64
   358  	updateTime  mclock.AbsTime
   359  
   360  	// Test callback hooks
   361  	hasBlockHook func(common.Hash, uint64, bool) bool // Used to determine whether the server has the specified block.
   362  }
   363  
   364  func newServerPeer(version int, network uint64, trusted bool, p *p2p.Peer, rw p2p.MsgReadWriter) *serverPeer {
   365  	return &serverPeer{
   366  		peerCommons: peerCommons{
   367  			Peer:      p,
   368  			rw:        rw,
   369  			id:        p.ID().String(),
   370  			version:   version,
   371  			network:   network,
   372  			sendQueue: utils.NewExecQueue(100),
   373  			closeCh:   make(chan struct{}),
   374  		},
   375  		trusted:  trusted,
   376  		errCount: utils.LinearExpiredValue{Rate: mclock.AbsTime(time.Hour)},
   377  	}
   378  }
   379  
   380  // rejectUpdate returns true if a parameter update has to be rejected because
   381  // the size and/or rate of updates exceed the capacity limitation
   382  func (p *serverPeer) rejectUpdate(size uint64) bool {
   383  	now := mclock.Now()
   384  	if p.updateCount == 0 {
   385  		p.updateTime = now
   386  	} else {
   387  		dt := now - p.updateTime
   388  		p.updateTime = now
   389  
   390  		r := uint64(dt / mclock.AbsTime(allowedUpdateRate))
   391  		if p.updateCount > r {
   392  			p.updateCount -= r
   393  		} else {
   394  			p.updateCount = 0
   395  		}
   396  	}
   397  	p.updateCount += size
   398  	return p.updateCount > allowedUpdateBytes
   399  }
   400  
   401  // freeze processes Stop messages from the given server and set the status as
   402  // frozen.
   403  func (p *serverPeer) freeze() {
   404  	if atomic.CompareAndSwapUint32(&p.frozen, 0, 1) {
   405  		p.sendQueue.Clear()
   406  	}
   407  }
   408  
   409  // unfreeze processes Resume messages from the given server and set the status
   410  // as unfrozen.
   411  func (p *serverPeer) unfreeze() {
   412  	atomic.StoreUint32(&p.frozen, 0)
   413  }
   414  
   415  // sendRequest send a request to the server based on the given message type
   416  // and content.
   417  func sendRequest(w p2p.MsgWriter, msgcode, reqID uint64, data interface{}) error {
   418  	type req struct {
   419  		ReqID uint64
   420  		Data  interface{}
   421  	}
   422  	return p2p.Send(w, msgcode, req{reqID, data})
   423  }
   424  
   425  func (p *serverPeer) sendRequest(msgcode, reqID uint64, data interface{}, amount int) error {
   426  	p.sentRequest(reqID, uint32(msgcode), uint32(amount))
   427  	return sendRequest(p.rw, msgcode, reqID, data)
   428  }
   429  
   430  // requestHeadersByHash fetches a batch of blocks' headers corresponding to the
   431  // specified header query, based on the hash of an origin block.
   432  func (p *serverPeer) requestHeadersByHash(reqID uint64, origin common.Hash, amount int, skip int, reverse bool) error {
   433  	p.Log().Debug("Fetching batch of headers", "count", amount, "fromhash", origin, "skip", skip, "reverse", reverse)
   434  	return p.sendRequest(GetBlockHeadersMsg, reqID, &GetBlockHeadersData{Origin: hashOrNumber{Hash: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse}, amount)
   435  }
   436  
   437  // requestHeadersByNumber fetches a batch of blocks' headers corresponding to the
   438  // specified header query, based on the number of an origin block.
   439  func (p *serverPeer) requestHeadersByNumber(reqID, origin uint64, amount int, skip int, reverse bool) error {
   440  	p.Log().Debug("Fetching batch of headers", "count", amount, "fromnum", origin, "skip", skip, "reverse", reverse)
   441  	return p.sendRequest(GetBlockHeadersMsg, reqID, &GetBlockHeadersData{Origin: hashOrNumber{Number: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse}, amount)
   442  }
   443  
   444  // requestBodies fetches a batch of blocks' bodies corresponding to the hashes
   445  // specified.
   446  func (p *serverPeer) requestBodies(reqID uint64, hashes []common.Hash) error {
   447  	p.Log().Debug("Fetching batch of block bodies", "count", len(hashes))
   448  	return p.sendRequest(GetBlockBodiesMsg, reqID, hashes, len(hashes))
   449  }
   450  
   451  // requestCode fetches a batch of arbitrary data from a node's known state
   452  // data, corresponding to the specified hashes.
   453  func (p *serverPeer) requestCode(reqID uint64, reqs []CodeReq) error {
   454  	p.Log().Debug("Fetching batch of codes", "count", len(reqs))
   455  	return p.sendRequest(GetCodeMsg, reqID, reqs, len(reqs))
   456  }
   457  
   458  // requestReceipts fetches a batch of transaction receipts from a remote node.
   459  func (p *serverPeer) requestReceipts(reqID uint64, hashes []common.Hash) error {
   460  	p.Log().Debug("Fetching batch of receipts", "count", len(hashes))
   461  	return p.sendRequest(GetReceiptsMsg, reqID, hashes, len(hashes))
   462  }
   463  
   464  // requestProofs fetches a batch of merkle proofs from a remote node.
   465  func (p *serverPeer) requestProofs(reqID uint64, reqs []ProofReq) error {
   466  	p.Log().Debug("Fetching batch of proofs", "count", len(reqs))
   467  	return p.sendRequest(GetProofsV2Msg, reqID, reqs, len(reqs))
   468  }
   469  
   470  // requestHelperTrieProofs fetches a batch of HelperTrie merkle proofs from a remote node.
   471  func (p *serverPeer) requestHelperTrieProofs(reqID uint64, reqs []HelperTrieReq) error {
   472  	p.Log().Debug("Fetching batch of HelperTrie proofs", "count", len(reqs))
   473  	return p.sendRequest(GetHelperTrieProofsMsg, reqID, reqs, len(reqs))
   474  }
   475  
   476  // requestTxStatus fetches a batch of transaction status records from a remote node.
   477  func (p *serverPeer) requestTxStatus(reqID uint64, txHashes []common.Hash) error {
   478  	p.Log().Debug("Requesting transaction status", "count", len(txHashes))
   479  	return p.sendRequest(GetTxStatusMsg, reqID, txHashes, len(txHashes))
   480  }
   481  
   482  // sendTxs creates a reply with a batch of transactions to be added to the remote transaction pool.
   483  func (p *serverPeer) sendTxs(reqID uint64, amount int, txs rlp.RawValue) error {
   484  	p.Log().Debug("Sending batch of transactions", "amount", amount, "size", len(txs))
   485  	sizeFactor := (len(txs) + txSizeCostLimit/2) / txSizeCostLimit
   486  	if sizeFactor > amount {
   487  		amount = sizeFactor
   488  	}
   489  	return p.sendRequest(SendTxV2Msg, reqID, txs, amount)
   490  }
   491  
   492  // waitBefore implements distPeer interface
   493  func (p *serverPeer) waitBefore(maxCost uint64) (time.Duration, float64) {
   494  	return p.fcServer.CanSend(maxCost)
   495  }
   496  
   497  // getRequestCost returns an estimated request cost according to the flow control
   498  // rules negotiated between the server and the client.
   499  func (p *serverPeer) getRequestCost(msgcode uint64, amount int) uint64 {
   500  	p.lock.RLock()
   501  	defer p.lock.RUnlock()
   502  
   503  	costs := p.fcCosts[msgcode]
   504  	if costs == nil {
   505  		return 0
   506  	}
   507  	cost := costs.baseCost + costs.reqCost*uint64(amount)
   508  	if cost > p.fcParams.BufLimit {
   509  		cost = p.fcParams.BufLimit
   510  	}
   511  	return cost
   512  }
   513  
   514  // getTxRelayCost returns an estimated relay cost according to the flow control
   515  // rules negotiated between the server and the client.
   516  func (p *serverPeer) getTxRelayCost(amount, size int) uint64 {
   517  	p.lock.RLock()
   518  	defer p.lock.RUnlock()
   519  
   520  	costs := p.fcCosts[SendTxV2Msg]
   521  	if costs == nil {
   522  		return 0
   523  	}
   524  	cost := costs.baseCost + costs.reqCost*uint64(amount)
   525  	sizeCost := costs.baseCost + costs.reqCost*uint64(size)/txSizeCostLimit
   526  	if sizeCost > cost {
   527  		cost = sizeCost
   528  	}
   529  	if cost > p.fcParams.BufLimit {
   530  		cost = p.fcParams.BufLimit
   531  	}
   532  	return cost
   533  }
   534  
   535  // HasBlock checks if the peer has a given block
   536  func (p *serverPeer) HasBlock(hash common.Hash, number uint64, hasState bool) bool {
   537  	p.lock.RLock()
   538  	defer p.lock.RUnlock()
   539  
   540  	if p.hasBlockHook != nil {
   541  		return p.hasBlockHook(hash, number, hasState)
   542  	}
   543  	head := p.headInfo.Number
   544  	var since, recent uint64
   545  	if hasState {
   546  		since = p.stateSince
   547  		recent = p.stateRecent
   548  	} else {
   549  		since = p.chainSince
   550  		recent = p.chainRecent
   551  	}
   552  	return head >= number && number >= since && (recent == 0 || number+recent+4 > head)
   553  }
   554  
   555  // updateFlowControl updates the flow control parameters belonging to the server
   556  // node if the announced key/value set contains relevant fields
   557  func (p *serverPeer) updateFlowControl(update keyValueMap) {
   558  	p.lock.Lock()
   559  	defer p.lock.Unlock()
   560  
   561  	// If any of the flow control params is nil, refuse to update.
   562  	var params flowcontrol.ServerParams
   563  	if update.get("flowControl/BL", &params.BufLimit) == nil && update.get("flowControl/MRR", &params.MinRecharge) == nil {
   564  		// todo can light client set a minimal acceptable flow control params?
   565  		p.fcParams = params
   566  		p.fcServer.UpdateParams(params)
   567  	}
   568  	var MRC RequestCostList
   569  	if update.get("flowControl/MRC", &MRC) == nil {
   570  		costUpdate := MRC.decode(ProtocolLengths[uint(p.version)])
   571  		for code, cost := range costUpdate {
   572  			p.fcCosts[code] = cost
   573  		}
   574  	}
   575  }
   576  
   577  // updateHead updates the head information based on the announcement from
   578  // the peer.
   579  func (p *serverPeer) updateHead(hash common.Hash, number uint64, td *big.Int) {
   580  	p.lock.Lock()
   581  	defer p.lock.Unlock()
   582  
   583  	p.headInfo = blockInfo{Hash: hash, Number: number, Td: td}
   584  }
   585  
   586  // Handshake executes the les protocol handshake, negotiating version number,
   587  // network IDs and genesis blocks.
   588  func (p *serverPeer) Handshake(genesis common.Hash, forkid forkid.ID, forkFilter forkid.Filter) error {
   589  	// Note: there is no need to share local head with a server but older servers still
   590  	// require these fields so we announce zero values.
   591  	return p.handshake(common.Big0, common.Hash{}, 0, genesis, forkid, forkFilter, func(lists *keyValueList) {
   592  		// Add some client-specific handshake fields
   593  		//
   594  		// Enable signed announcement randomly even the server is not trusted.
   595  		p.announceType = announceTypeSimple
   596  		if p.trusted {
   597  			p.announceType = announceTypeSigned
   598  		}
   599  		*lists = (*lists).add("announceType", p.announceType)
   600  	}, func(recv keyValueMap) error {
   601  		var (
   602  			rHash common.Hash
   603  			rNum  uint64
   604  			rTd   *big.Int
   605  		)
   606  		if err := recv.get("headTd", &rTd); err != nil {
   607  			return err
   608  		}
   609  		if err := recv.get("headHash", &rHash); err != nil {
   610  			return err
   611  		}
   612  		if err := recv.get("headNum", &rNum); err != nil {
   613  			return err
   614  		}
   615  		p.headInfo = blockInfo{Hash: rHash, Number: rNum, Td: rTd}
   616  		if recv.get("serveChainSince", &p.chainSince) != nil {
   617  			p.onlyAnnounce = true
   618  		}
   619  		if recv.get("serveRecentChain", &p.chainRecent) != nil {
   620  			p.chainRecent = 0
   621  		}
   622  		if recv.get("serveStateSince", &p.stateSince) != nil {
   623  			p.onlyAnnounce = true
   624  		}
   625  		if recv.get("serveRecentState", &p.stateRecent) != nil {
   626  			p.stateRecent = 0
   627  		}
   628  		if recv.get("txRelay", nil) != nil {
   629  			p.onlyAnnounce = true
   630  		}
   631  		if p.version >= lpv4 {
   632  			var recentTx uint
   633  			if err := recv.get("recentTxLookup", &recentTx); err != nil {
   634  				return err
   635  			}
   636  			p.txHistory = uint64(recentTx)
   637  		} else {
   638  			// The weak assumption is held here that legacy les server(les2,3)
   639  			// has unlimited transaction history. The les serving in these legacy
   640  			// versions is disabled if the transaction is unindexed.
   641  			p.txHistory = txIndexUnlimited
   642  		}
   643  		if p.onlyAnnounce && !p.trusted {
   644  			return errResp(ErrUselessPeer, "peer cannot serve requests")
   645  		}
   646  		// Parse flow control handshake packet.
   647  		var sParams flowcontrol.ServerParams
   648  		if err := recv.get("flowControl/BL", &sParams.BufLimit); err != nil {
   649  			return err
   650  		}
   651  		if err := recv.get("flowControl/MRR", &sParams.MinRecharge); err != nil {
   652  			return err
   653  		}
   654  		var MRC RequestCostList
   655  		if err := recv.get("flowControl/MRC", &MRC); err != nil {
   656  			return err
   657  		}
   658  		p.fcParams = sParams
   659  		p.fcServer = flowcontrol.NewServerNode(sParams, &mclock.System{})
   660  		p.fcCosts = MRC.decode(ProtocolLengths[uint(p.version)])
   661  
   662  		recv.get("checkpoint/value", &p.checkpoint)
   663  		recv.get("checkpoint/registerHeight", &p.checkpointNumber)
   664  
   665  		if !p.onlyAnnounce {
   666  			for msgCode := range reqAvgTimeCost {
   667  				if p.fcCosts[msgCode] == nil {
   668  					return errResp(ErrUselessPeer, "peer does not support message %d", msgCode)
   669  				}
   670  			}
   671  		}
   672  		return nil
   673  	})
   674  }
   675  
   676  // setValueTracker sets the value tracker references for connected servers. Note that the
   677  // references should be removed upon disconnection by setValueTracker(nil, nil).
   678  func (p *serverPeer) setValueTracker(nvt *vfc.NodeValueTracker) {
   679  	p.vtLock.Lock()
   680  	p.nodeValueTracker = nvt
   681  	if nvt != nil {
   682  		p.sentReqs = make(map[uint64]sentReqEntry)
   683  	} else {
   684  		p.sentReqs = nil
   685  	}
   686  	p.vtLock.Unlock()
   687  }
   688  
   689  // updateVtParams updates the server's price table in the value tracker.
   690  func (p *serverPeer) updateVtParams() {
   691  	p.vtLock.Lock()
   692  	defer p.vtLock.Unlock()
   693  
   694  	if p.nodeValueTracker == nil {
   695  		return
   696  	}
   697  	reqCosts := make([]uint64, len(requestList))
   698  	for code, costs := range p.fcCosts {
   699  		if m, ok := requestMapping[uint32(code)]; ok {
   700  			reqCosts[m.first] = costs.baseCost + costs.reqCost
   701  			if m.rest != -1 {
   702  				reqCosts[m.rest] = costs.reqCost
   703  			}
   704  		}
   705  	}
   706  	p.nodeValueTracker.UpdateCosts(reqCosts)
   707  }
   708  
   709  // sentReqEntry remembers sent requests and their sending times
   710  type sentReqEntry struct {
   711  	reqType, amount uint32
   712  	at              mclock.AbsTime
   713  }
   714  
   715  // sentRequest marks a request sent at the current moment to this server.
   716  func (p *serverPeer) sentRequest(id uint64, reqType, amount uint32) {
   717  	p.vtLock.Lock()
   718  	if p.sentReqs != nil {
   719  		p.sentReqs[id] = sentReqEntry{reqType, amount, mclock.Now()}
   720  	}
   721  	p.vtLock.Unlock()
   722  }
   723  
   724  // answeredRequest marks a request answered at the current moment by this server.
   725  func (p *serverPeer) answeredRequest(id uint64) {
   726  	p.vtLock.Lock()
   727  	if p.sentReqs == nil {
   728  		p.vtLock.Unlock()
   729  		return
   730  	}
   731  	e, ok := p.sentReqs[id]
   732  	delete(p.sentReqs, id)
   733  	nvt := p.nodeValueTracker
   734  	p.vtLock.Unlock()
   735  	if !ok {
   736  		return
   737  	}
   738  	var (
   739  		vtReqs   [2]vfc.ServedRequest
   740  		reqCount int
   741  	)
   742  	m := requestMapping[e.reqType]
   743  	if m.rest == -1 || e.amount <= 1 {
   744  		reqCount = 1
   745  		vtReqs[0] = vfc.ServedRequest{ReqType: uint32(m.first), Amount: e.amount}
   746  	} else {
   747  		reqCount = 2
   748  		vtReqs[0] = vfc.ServedRequest{ReqType: uint32(m.first), Amount: 1}
   749  		vtReqs[1] = vfc.ServedRequest{ReqType: uint32(m.rest), Amount: e.amount - 1}
   750  	}
   751  	dt := time.Duration(mclock.Now() - e.at)
   752  	nvt.Served(vtReqs[:reqCount], dt)
   753  }
   754  
   755  // clientPeer represents each node to which the les server is connected.
   756  // The node here refers to the light client.
   757  type clientPeer struct {
   758  	peerCommons
   759  
   760  	// responseLock ensures that responses are queued in the same order as
   761  	// RequestProcessed is called
   762  	responseLock  sync.Mutex
   763  	responseCount uint64 // Counter to generate an unique id for request processing.
   764  
   765  	balance *vfs.NodeBalance
   766  
   767  	// invalidLock is used for protecting invalidCount.
   768  	invalidLock  sync.RWMutex
   769  	invalidCount utils.LinearExpiredValue // Counter the invalid request the client peer has made.
   770  
   771  	server   bool
   772  	errCh    chan error
   773  	fcClient *flowcontrol.ClientNode // Server side mirror token bucket.
   774  }
   775  
   776  func newClientPeer(version int, network uint64, p *p2p.Peer, rw p2p.MsgReadWriter) *clientPeer {
   777  	return &clientPeer{
   778  		peerCommons: peerCommons{
   779  			Peer:      p,
   780  			rw:        rw,
   781  			id:        p.ID().String(),
   782  			version:   version,
   783  			network:   network,
   784  			sendQueue: utils.NewExecQueue(100),
   785  			closeCh:   make(chan struct{}),
   786  		},
   787  		invalidCount: utils.LinearExpiredValue{Rate: mclock.AbsTime(time.Hour)},
   788  		errCh:        make(chan error, 1),
   789  	}
   790  }
   791  
   792  // freeClientId returns a string identifier for the peer. Multiple peers with
   793  // the same identifier can not be connected in free mode simultaneously.
   794  func (p *clientPeer) freeClientId() string {
   795  	if addr, ok := p.RemoteAddr().(*net.TCPAddr); ok {
   796  		if addr.IP.IsLoopback() {
   797  			// using peer id instead of loopback ip address allows multiple free
   798  			// connections from local machine to own server
   799  			return p.id
   800  		} else {
   801  			return addr.IP.String()
   802  		}
   803  	}
   804  	return p.id
   805  }
   806  
   807  // sendStop notifies the client about being in frozen state
   808  func (p *clientPeer) sendStop() error {
   809  	return p2p.Send(p.rw, StopMsg, struct{}{})
   810  }
   811  
   812  // sendResume notifies the client about getting out of frozen state
   813  func (p *clientPeer) sendResume(bv uint64) error {
   814  	return p2p.Send(p.rw, ResumeMsg, bv)
   815  }
   816  
   817  // freeze temporarily puts the client in a frozen state which means all unprocessed
   818  // and subsequent requests are dropped. Unfreezing happens automatically after a short
   819  // time if the client's buffer value is at least in the slightly positive region.
   820  // The client is also notified about being frozen/unfrozen with a Stop/Resume message.
   821  func (p *clientPeer) freeze() {
   822  	if p.version < lpv3 {
   823  		// if Stop/Resume is not supported then just drop the peer after setting
   824  		// its frozen status permanently
   825  		atomic.StoreUint32(&p.frozen, 1)
   826  		p.Peer.Disconnect(p2p.DiscUselessPeer)
   827  		return
   828  	}
   829  	if atomic.SwapUint32(&p.frozen, 1) == 0 {
   830  		go func() {
   831  			p.sendStop()
   832  			time.Sleep(freezeTimeBase + time.Duration(rand.Int63n(int64(freezeTimeRandom))))
   833  			for {
   834  				bufValue, bufLimit := p.fcClient.BufferStatus()
   835  				if bufLimit == 0 {
   836  					return
   837  				}
   838  				if bufValue <= bufLimit/8 {
   839  					time.Sleep(freezeCheckPeriod)
   840  					continue
   841  				}
   842  				atomic.StoreUint32(&p.frozen, 0)
   843  				p.sendResume(bufValue)
   844  				return
   845  			}
   846  		}()
   847  	}
   848  }
   849  
   850  // reply struct represents a reply with the actual data already RLP encoded and
   851  // only the bv (buffer value) missing. This allows the serving mechanism to
   852  // calculate the bv value which depends on the data size before sending the reply.
   853  type reply struct {
   854  	w              p2p.MsgWriter
   855  	msgcode, reqID uint64
   856  	data           rlp.RawValue
   857  }
   858  
   859  // send sends the reply with the calculated buffer value
   860  func (r *reply) send(bv uint64) error {
   861  	type resp struct {
   862  		ReqID, BV uint64
   863  		Data      rlp.RawValue
   864  	}
   865  	return p2p.Send(r.w, r.msgcode, resp{r.reqID, bv, r.data})
   866  }
   867  
   868  // size returns the RLP encoded size of the message data
   869  func (r *reply) size() uint32 {
   870  	return uint32(len(r.data))
   871  }
   872  
   873  // replyBlockHeaders creates a reply with a batch of block headers
   874  func (p *clientPeer) replyBlockHeaders(reqID uint64, headers []*types.Header) *reply {
   875  	data, _ := rlp.EncodeToBytes(headers)
   876  	return &reply{p.rw, BlockHeadersMsg, reqID, data}
   877  }
   878  
   879  // replyBlockBodiesRLP creates a reply with a batch of block contents from
   880  // an already RLP encoded format.
   881  func (p *clientPeer) replyBlockBodiesRLP(reqID uint64, bodies []rlp.RawValue) *reply {
   882  	data, _ := rlp.EncodeToBytes(bodies)
   883  	return &reply{p.rw, BlockBodiesMsg, reqID, data}
   884  }
   885  
   886  // replyCode creates a reply with a batch of arbitrary internal data, corresponding to the
   887  // hashes requested.
   888  func (p *clientPeer) replyCode(reqID uint64, codes [][]byte) *reply {
   889  	data, _ := rlp.EncodeToBytes(codes)
   890  	return &reply{p.rw, CodeMsg, reqID, data}
   891  }
   892  
   893  // replyReceiptsRLP creates a reply with a batch of transaction receipts, corresponding to the
   894  // ones requested from an already RLP encoded format.
   895  func (p *clientPeer) replyReceiptsRLP(reqID uint64, receipts []rlp.RawValue) *reply {
   896  	data, _ := rlp.EncodeToBytes(receipts)
   897  	return &reply{p.rw, ReceiptsMsg, reqID, data}
   898  }
   899  
   900  // replyProofsV2 creates a reply with a batch of merkle proofs, corresponding to the ones requested.
   901  func (p *clientPeer) replyProofsV2(reqID uint64, proofs light.NodeList) *reply {
   902  	data, _ := rlp.EncodeToBytes(proofs)
   903  	return &reply{p.rw, ProofsV2Msg, reqID, data}
   904  }
   905  
   906  // replyHelperTrieProofs creates a reply with a batch of HelperTrie proofs, corresponding to the ones requested.
   907  func (p *clientPeer) replyHelperTrieProofs(reqID uint64, resp HelperTrieResps) *reply {
   908  	data, _ := rlp.EncodeToBytes(resp)
   909  	return &reply{p.rw, HelperTrieProofsMsg, reqID, data}
   910  }
   911  
   912  // replyTxStatus creates a reply with a batch of transaction status records, corresponding to the ones requested.
   913  func (p *clientPeer) replyTxStatus(reqID uint64, stats []light.TxStatus) *reply {
   914  	data, _ := rlp.EncodeToBytes(stats)
   915  	return &reply{p.rw, TxStatusMsg, reqID, data}
   916  }
   917  
   918  // sendAnnounce announces the availability of a number of blocks through
   919  // a hash notification.
   920  func (p *clientPeer) sendAnnounce(request announceData) error {
   921  	return p2p.Send(p.rw, AnnounceMsg, request)
   922  }
   923  
   924  // allowInactive implements clientPoolPeer
   925  func (p *clientPeer) allowInactive() bool {
   926  	return false
   927  }
   928  
   929  // updateCapacity updates the request serving capacity assigned to a given client
   930  // and also sends an announcement about the updated flow control parameters
   931  func (p *clientPeer) updateCapacity(cap uint64) {
   932  	p.lock.Lock()
   933  	defer p.lock.Unlock()
   934  
   935  	if cap != p.fcParams.MinRecharge {
   936  		p.fcParams = flowcontrol.ServerParams{MinRecharge: cap, BufLimit: cap * bufLimitRatio}
   937  		p.fcClient.UpdateParams(p.fcParams)
   938  		var kvList keyValueList
   939  		kvList = kvList.add("flowControl/MRR", cap)
   940  		kvList = kvList.add("flowControl/BL", cap*bufLimitRatio)
   941  		p.queueSend(func() { p.sendAnnounce(announceData{Update: kvList}) })
   942  	}
   943  }
   944  
   945  // freezeClient temporarily puts the client in a frozen state which means all
   946  // unprocessed and subsequent requests are dropped. Unfreezing happens automatically
   947  // after a short time if the client's buffer value is at least in the slightly positive
   948  // region. The client is also notified about being frozen/unfrozen with a Stop/Resume
   949  // message.
   950  func (p *clientPeer) freezeClient() {
   951  	if p.version < lpv3 {
   952  		// if Stop/Resume is not supported then just drop the peer after setting
   953  		// its frozen status permanently
   954  		atomic.StoreUint32(&p.frozen, 1)
   955  		p.Peer.Disconnect(p2p.DiscUselessPeer)
   956  		return
   957  	}
   958  	if atomic.SwapUint32(&p.frozen, 1) == 0 {
   959  		go func() {
   960  			p.sendStop()
   961  			time.Sleep(freezeTimeBase + time.Duration(rand.Int63n(int64(freezeTimeRandom))))
   962  			for {
   963  				bufValue, bufLimit := p.fcClient.BufferStatus()
   964  				if bufLimit == 0 {
   965  					return
   966  				}
   967  				if bufValue <= bufLimit/8 {
   968  					time.Sleep(freezeCheckPeriod)
   969  				} else {
   970  					atomic.StoreUint32(&p.frozen, 0)
   971  					p.sendResume(bufValue)
   972  					break
   973  				}
   974  			}
   975  		}()
   976  	}
   977  }
   978  
   979  // Handshake executes the les protocol handshake, negotiating version number,
   980  // network IDs, difficulties, head and genesis blocks.
   981  func (p *clientPeer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, forkID forkid.ID, forkFilter forkid.Filter, server *LesServer) error {
   982  	recentTx := server.handler.blockchain.TxLookupLimit()
   983  	if recentTx != txIndexUnlimited {
   984  		if recentTx < blockSafetyMargin {
   985  			recentTx = txIndexDisabled
   986  		} else {
   987  			recentTx -= blockSafetyMargin - txIndexRecentOffset
   988  		}
   989  	}
   990  	if server.config.UltraLightOnlyAnnounce {
   991  		recentTx = txIndexDisabled
   992  	}
   993  	if recentTx != txIndexUnlimited && p.version < lpv4 {
   994  		return errors.New("Cannot serve old clients without a complete tx index")
   995  	}
   996  	// Note: clientPeer.headInfo should contain the last head announced to the client by us.
   997  	// The values announced in the handshake are dummy values for compatibility reasons and should be ignored.
   998  	p.headInfo = blockInfo{Hash: head, Number: headNum, Td: td}
   999  	return p.handshake(td, head, headNum, genesis, forkID, forkFilter, func(lists *keyValueList) {
  1000  		// Add some information which services server can offer.
  1001  		if !server.config.UltraLightOnlyAnnounce {
  1002  			*lists = (*lists).add("serveHeaders", nil)
  1003  			*lists = (*lists).add("serveChainSince", uint64(0))
  1004  			*lists = (*lists).add("serveStateSince", uint64(0))
  1005  
  1006  			// If local ethereum node is running in archive mode, advertise ourselves we have
  1007  			// all version state data. Otherwise only recent state is available.
  1008  			stateRecent := uint64(core.TriesInMemory - blockSafetyMargin)
  1009  			if server.archiveMode {
  1010  				stateRecent = 0
  1011  			}
  1012  			*lists = (*lists).add("serveRecentState", stateRecent)
  1013  			*lists = (*lists).add("txRelay", nil)
  1014  		}
  1015  		if p.version >= lpv4 {
  1016  			*lists = (*lists).add("recentTxLookup", recentTx)
  1017  		}
  1018  		*lists = (*lists).add("flowControl/BL", server.defParams.BufLimit)
  1019  		*lists = (*lists).add("flowControl/MRR", server.defParams.MinRecharge)
  1020  
  1021  		var costList RequestCostList
  1022  		if server.costTracker.testCostList != nil {
  1023  			costList = server.costTracker.testCostList
  1024  		} else {
  1025  			costList = server.costTracker.makeCostList(server.costTracker.globalFactor())
  1026  		}
  1027  		*lists = (*lists).add("flowControl/MRC", costList)
  1028  		p.fcCosts = costList.decode(ProtocolLengths[uint(p.version)])
  1029  		p.fcParams = server.defParams
  1030  
  1031  		// Add advertised checkpoint and register block height which
  1032  		// client can verify the checkpoint validity.
  1033  		if server.oracle != nil && server.oracle.IsRunning() {
  1034  			cp, height := server.oracle.StableCheckpoint()
  1035  			if cp != nil {
  1036  				*lists = (*lists).add("checkpoint/value", cp)
  1037  				*lists = (*lists).add("checkpoint/registerHeight", height)
  1038  			}
  1039  		}
  1040  	}, func(recv keyValueMap) error {
  1041  		p.server = recv.get("flowControl/MRR", nil) == nil
  1042  		if p.server {
  1043  			p.announceType = announceTypeNone // connected to another server, send no messages
  1044  		} else {
  1045  			if recv.get("announceType", &p.announceType) != nil {
  1046  				// set default announceType on server side
  1047  				p.announceType = announceTypeSimple
  1048  			}
  1049  			p.fcClient = flowcontrol.NewClientNode(server.fcManager, p.fcParams)
  1050  		}
  1051  		return nil
  1052  	})
  1053  }
  1054  
  1055  func (p *clientPeer) bumpInvalid() {
  1056  	p.invalidLock.Lock()
  1057  	p.invalidCount.Add(1, mclock.Now())
  1058  	p.invalidLock.Unlock()
  1059  }
  1060  
  1061  func (p *clientPeer) getInvalid() uint64 {
  1062  	p.invalidLock.RLock()
  1063  	defer p.invalidLock.RUnlock()
  1064  	return p.invalidCount.Value(mclock.Now())
  1065  }
  1066  
  1067  // serverPeerSubscriber is an interface to notify services about added or
  1068  // removed server peers
  1069  type serverPeerSubscriber interface {
  1070  	registerPeer(*serverPeer)
  1071  	unregisterPeer(*serverPeer)
  1072  }
  1073  
  1074  // serverPeerSet represents the set of active server peers currently
  1075  // participating in the Light Ethereum sub-protocol.
  1076  type serverPeerSet struct {
  1077  	peers map[string]*serverPeer
  1078  	// subscribers is a batch of subscribers and peerset will notify
  1079  	// these subscribers when the peerset changes(new server peer is
  1080  	// added or removed)
  1081  	subscribers []serverPeerSubscriber
  1082  	closed      bool
  1083  	lock        sync.RWMutex
  1084  }
  1085  
  1086  // newServerPeerSet creates a new peer set to track the active server peers.
  1087  func newServerPeerSet() *serverPeerSet {
  1088  	return &serverPeerSet{peers: make(map[string]*serverPeer)}
  1089  }
  1090  
  1091  // subscribe adds a service to be notified about added or removed
  1092  // peers and also register all active peers into the given service.
  1093  func (ps *serverPeerSet) subscribe(sub serverPeerSubscriber) {
  1094  	ps.lock.Lock()
  1095  	defer ps.lock.Unlock()
  1096  
  1097  	ps.subscribers = append(ps.subscribers, sub)
  1098  	for _, p := range ps.peers {
  1099  		sub.registerPeer(p)
  1100  	}
  1101  }
  1102  
  1103  // unSubscribe removes the specified service from the subscriber pool.
  1104  func (ps *serverPeerSet) unSubscribe(sub serverPeerSubscriber) {
  1105  	ps.lock.Lock()
  1106  	defer ps.lock.Unlock()
  1107  
  1108  	for i, s := range ps.subscribers {
  1109  		if s == sub {
  1110  			ps.subscribers = append(ps.subscribers[:i], ps.subscribers[i+1:]...)
  1111  			return
  1112  		}
  1113  	}
  1114  }
  1115  
  1116  // register adds a new server peer into the set, or returns an error if the
  1117  // peer is already known.
  1118  func (ps *serverPeerSet) register(peer *serverPeer) error {
  1119  	ps.lock.Lock()
  1120  	defer ps.lock.Unlock()
  1121  
  1122  	if ps.closed {
  1123  		return errClosed
  1124  	}
  1125  	if _, exist := ps.peers[peer.id]; exist {
  1126  		return errAlreadyRegistered
  1127  	}
  1128  	ps.peers[peer.id] = peer
  1129  	for _, sub := range ps.subscribers {
  1130  		sub.registerPeer(peer)
  1131  	}
  1132  	return nil
  1133  }
  1134  
  1135  // unregister removes a remote peer from the active set, disabling any further
  1136  // actions to/from that particular entity. It also initiates disconnection at
  1137  // the networking layer.
  1138  func (ps *serverPeerSet) unregister(id string) error {
  1139  	ps.lock.Lock()
  1140  	defer ps.lock.Unlock()
  1141  
  1142  	p, ok := ps.peers[id]
  1143  	if !ok {
  1144  		return errNotRegistered
  1145  	}
  1146  	delete(ps.peers, id)
  1147  	for _, sub := range ps.subscribers {
  1148  		sub.unregisterPeer(p)
  1149  	}
  1150  	p.Peer.Disconnect(p2p.DiscRequested)
  1151  	return nil
  1152  }
  1153  
  1154  // ids returns a list of all registered peer IDs
  1155  func (ps *serverPeerSet) ids() []string {
  1156  	ps.lock.RLock()
  1157  	defer ps.lock.RUnlock()
  1158  
  1159  	var ids []string
  1160  	for id := range ps.peers {
  1161  		ids = append(ids, id)
  1162  	}
  1163  	return ids
  1164  }
  1165  
  1166  // peer retrieves the registered peer with the given id.
  1167  func (ps *serverPeerSet) peer(id string) *serverPeer {
  1168  	ps.lock.RLock()
  1169  	defer ps.lock.RUnlock()
  1170  
  1171  	return ps.peers[id]
  1172  }
  1173  
  1174  // len returns if the current number of peers in the set.
  1175  func (ps *serverPeerSet) len() int {
  1176  	ps.lock.RLock()
  1177  	defer ps.lock.RUnlock()
  1178  
  1179  	return len(ps.peers)
  1180  }
  1181  
  1182  // bestPeer retrieves the known peer with the currently highest total difficulty.
  1183  // If the peerset is "client peer set", then nothing meaningful will return. The
  1184  // reason is client peer never send back their latest status to server.
  1185  func (ps *serverPeerSet) bestPeer() *serverPeer {
  1186  	ps.lock.RLock()
  1187  	defer ps.lock.RUnlock()
  1188  
  1189  	var (
  1190  		bestPeer *serverPeer
  1191  		bestTd   *big.Int
  1192  	)
  1193  	for _, p := range ps.peers {
  1194  		if td := p.Td(); bestTd == nil || td.Cmp(bestTd) > 0 {
  1195  			bestPeer, bestTd = p, td
  1196  		}
  1197  	}
  1198  	return bestPeer
  1199  }
  1200  
  1201  // allServerPeers returns all server peers in a list.
  1202  func (ps *serverPeerSet) allPeers() []*serverPeer {
  1203  	ps.lock.RLock()
  1204  	defer ps.lock.RUnlock()
  1205  
  1206  	list := make([]*serverPeer, 0, len(ps.peers))
  1207  	for _, p := range ps.peers {
  1208  		list = append(list, p)
  1209  	}
  1210  	return list
  1211  }
  1212  
  1213  // close disconnects all peers. No new peers can be registered
  1214  // after close has returned.
  1215  func (ps *serverPeerSet) close() {
  1216  	ps.lock.Lock()
  1217  	defer ps.lock.Unlock()
  1218  
  1219  	for _, p := range ps.peers {
  1220  		p.Disconnect(p2p.DiscQuitting)
  1221  	}
  1222  	ps.closed = true
  1223  }