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