github.com/tdcblockchain/tdcblockchain@v0.0.0-20191111034745-805c65ade158/les/server_handler.go (about)

     1  // Copyright 2019 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  	"encoding/binary"
    21  	"encoding/json"
    22  	"errors"
    23  	"sync"
    24  	"sync/atomic"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/common/mclock"
    29  	"github.com/ethereum/go-ethereum/core"
    30  	"github.com/ethereum/go-ethereum/core/rawdb"
    31  	"github.com/ethereum/go-ethereum/core/state"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/ethdb"
    34  	"github.com/ethereum/go-ethereum/light"
    35  	"github.com/ethereum/go-ethereum/log"
    36  	"github.com/ethereum/go-ethereum/metrics"
    37  	"github.com/ethereum/go-ethereum/p2p"
    38  	"github.com/ethereum/go-ethereum/rlp"
    39  	"github.com/ethereum/go-ethereum/trie"
    40  )
    41  
    42  const (
    43  	softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data.
    44  	estHeaderRlpSize  = 500             // Approximate size of an RLP encoded block header
    45  	ethVersion        = 63              // equivalent eth version for the downloader
    46  
    47  	MaxHeaderFetch           = 192 // Amount of block headers to be fetched per retrieval request
    48  	MaxBodyFetch             = 32  // Amount of block bodies to be fetched per retrieval request
    49  	MaxReceiptFetch          = 128 // Amount of transaction receipts to allow fetching per request
    50  	MaxCodeFetch             = 64  // Amount of contract codes to allow fetching per request
    51  	MaxProofsFetch           = 64  // Amount of merkle proofs to be fetched per retrieval request
    52  	MaxHelperTrieProofsFetch = 64  // Amount of helper tries to be fetched per retrieval request
    53  	MaxTxSend                = 64  // Amount of transactions to be send per request
    54  	MaxTxStatus              = 256 // Amount of transactions to queried per request
    55  )
    56  
    57  var (
    58  	errTooManyInvalidRequest = errors.New("too many invalid requests made")
    59  	errFullClientPool        = errors.New("client pool is full")
    60  )
    61  
    62  // serverHandler is responsible for serving light client and process
    63  // all incoming light requests.
    64  type serverHandler struct {
    65  	blockchain *core.BlockChain
    66  	chainDb    ethdb.Database
    67  	txpool     *core.TxPool
    68  	server     *LesServer
    69  
    70  	closeCh chan struct{}  // Channel used to exit all background routines of handler.
    71  	wg      sync.WaitGroup // WaitGroup used to track all background routines of handler.
    72  	synced  func() bool    // Callback function used to determine whether local node is synced.
    73  
    74  	// Testing fields
    75  	addTxsSync bool
    76  }
    77  
    78  func newServerHandler(server *LesServer, blockchain *core.BlockChain, chainDb ethdb.Database, txpool *core.TxPool, synced func() bool) *serverHandler {
    79  	handler := &serverHandler{
    80  		server:     server,
    81  		blockchain: blockchain,
    82  		chainDb:    chainDb,
    83  		txpool:     txpool,
    84  		closeCh:    make(chan struct{}),
    85  		synced:     synced,
    86  	}
    87  	return handler
    88  }
    89  
    90  // start starts the server handler.
    91  func (h *serverHandler) start() {
    92  	h.wg.Add(1)
    93  	go h.broadcastHeaders()
    94  }
    95  
    96  // stop stops the server handler.
    97  func (h *serverHandler) stop() {
    98  	close(h.closeCh)
    99  	h.wg.Wait()
   100  }
   101  
   102  // runPeer is the p2p protocol run function for the given version.
   103  func (h *serverHandler) runPeer(version uint, p *p2p.Peer, rw p2p.MsgReadWriter) error {
   104  	peer := newPeer(int(version), h.server.config.NetworkId, false, p, newMeteredMsgWriter(rw, int(version)))
   105  	h.wg.Add(1)
   106  	defer h.wg.Done()
   107  	return h.handle(peer)
   108  }
   109  
   110  func (h *serverHandler) handle(p *peer) error {
   111  	// Reject light clients if server is not synced.
   112  	if !h.synced() {
   113  		return p2p.DiscRequested
   114  	}
   115  	p.Log().Debug("Light Ethereum peer connected", "name", p.Name())
   116  
   117  	// Execute the LES handshake
   118  	var (
   119  		head   = h.blockchain.CurrentHeader()
   120  		hash   = head.Hash()
   121  		number = head.Number.Uint64()
   122  		td     = h.blockchain.GetTd(hash, number)
   123  	)
   124  	if err := p.Handshake(td, hash, number, h.blockchain.Genesis().Hash(), h.server); err != nil {
   125  		p.Log().Debug("Light Ethereum handshake failed", "err", err)
   126  		return err
   127  	}
   128  	defer p.fcClient.Disconnect()
   129  
   130  	// Disconnect the inbound peer if it's rejected by clientPool
   131  	if !h.server.clientPool.connect(p, 0) {
   132  		p.Log().Debug("Light Ethereum peer registration failed", "err", errFullClientPool)
   133  		return errFullClientPool
   134  	}
   135  	// Register the peer locally
   136  	if err := h.server.peers.Register(p); err != nil {
   137  		h.server.clientPool.disconnect(p)
   138  		p.Log().Error("Light Ethereum peer registration failed", "err", err)
   139  		return err
   140  	}
   141  	clientConnectionGauge.Update(int64(h.server.peers.Len()))
   142  
   143  	var wg sync.WaitGroup // Wait group used to track all in-flight task routines.
   144  
   145  	connectedAt := mclock.Now()
   146  	defer func() {
   147  		wg.Wait() // Ensure all background task routines have exited.
   148  		h.server.peers.Unregister(p.id)
   149  		h.server.clientPool.disconnect(p)
   150  		clientConnectionGauge.Update(int64(h.server.peers.Len()))
   151  		connectionTimer.Update(time.Duration(mclock.Now() - connectedAt))
   152  	}()
   153  
   154  	// Spawn a main loop to handle all incoming messages.
   155  	for {
   156  		select {
   157  		case err := <-p.errCh:
   158  			p.Log().Debug("Failed to send light ethereum response", "err", err)
   159  			return err
   160  		default:
   161  		}
   162  		if err := h.handleMsg(p, &wg); err != nil {
   163  			p.Log().Debug("Light Ethereum message handling failed", "err", err)
   164  			return err
   165  		}
   166  	}
   167  }
   168  
   169  // handleMsg is invoked whenever an inbound message is received from a remote
   170  // peer. The remote connection is torn down upon returning any error.
   171  func (h *serverHandler) handleMsg(p *peer, wg *sync.WaitGroup) error {
   172  	// Read the next message from the remote peer, and ensure it's fully consumed
   173  	msg, err := p.rw.ReadMsg()
   174  	if err != nil {
   175  		return err
   176  	}
   177  	p.Log().Trace("Light Ethereum message arrived", "code", msg.Code, "bytes", msg.Size)
   178  
   179  	// Discard large message which exceeds the limitation.
   180  	if msg.Size > ProtocolMaxMsgSize {
   181  		clientErrorMeter.Mark(1)
   182  		return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
   183  	}
   184  	defer msg.Discard()
   185  
   186  	var (
   187  		maxCost uint64
   188  		task    *servingTask
   189  	)
   190  	p.responseCount++
   191  	responseCount := p.responseCount
   192  	// accept returns an indicator whether the request can be served.
   193  	// If so, deduct the max cost from the flow control buffer.
   194  	accept := func(reqID, reqCnt, maxCnt uint64) bool {
   195  		// Short circuit if the peer is already frozen or the request is invalid.
   196  		inSizeCost := h.server.costTracker.realCost(0, msg.Size, 0)
   197  		if p.isFrozen() || reqCnt == 0 || reqCnt > maxCnt {
   198  			p.fcClient.OneTimeCost(inSizeCost)
   199  			return false
   200  		}
   201  		// Prepaid max cost units before request been serving.
   202  		maxCost = p.fcCosts.getMaxCost(msg.Code, reqCnt)
   203  		accepted, bufShort, priority := p.fcClient.AcceptRequest(reqID, responseCount, maxCost)
   204  		if !accepted {
   205  			p.freezeClient()
   206  			p.Log().Error("Request came too early", "remaining", common.PrettyDuration(time.Duration(bufShort*1000000/p.fcParams.MinRecharge)))
   207  			p.fcClient.OneTimeCost(inSizeCost)
   208  			return false
   209  		}
   210  		// Create a multi-stage task, estimate the time it takes for the task to
   211  		// execute, and cache it in the request service queue.
   212  		factor := h.server.costTracker.globalFactor()
   213  		if factor < 0.001 {
   214  			factor = 1
   215  			p.Log().Error("Invalid global cost factor", "factor", factor)
   216  		}
   217  		maxTime := uint64(float64(maxCost) / factor)
   218  		task = h.server.servingQueue.newTask(p, maxTime, priority)
   219  		if task.start() {
   220  			return true
   221  		}
   222  		p.fcClient.RequestProcessed(reqID, responseCount, maxCost, inSizeCost)
   223  		return false
   224  	}
   225  	// sendResponse sends back the response and updates the flow control statistic.
   226  	sendResponse := func(reqID, amount uint64, reply *reply, servingTime uint64) {
   227  		p.responseLock.Lock()
   228  		defer p.responseLock.Unlock()
   229  
   230  		// Short circuit if the client is already frozen.
   231  		if p.isFrozen() {
   232  			realCost := h.server.costTracker.realCost(servingTime, msg.Size, 0)
   233  			p.fcClient.RequestProcessed(reqID, responseCount, maxCost, realCost)
   234  			return
   235  		}
   236  		// Positive correction buffer value with real cost.
   237  		var replySize uint32
   238  		if reply != nil {
   239  			replySize = reply.size()
   240  		}
   241  		var realCost uint64
   242  		if h.server.costTracker.testing {
   243  			realCost = maxCost // Assign a fake cost for testing purpose
   244  		} else {
   245  			realCost = h.server.costTracker.realCost(servingTime, msg.Size, replySize)
   246  		}
   247  		bv := p.fcClient.RequestProcessed(reqID, responseCount, maxCost, realCost)
   248  		if amount != 0 {
   249  			// Feed cost tracker request serving statistic.
   250  			h.server.costTracker.updateStats(msg.Code, amount, servingTime, realCost)
   251  			// Reduce priority "balance" for the specific peer.
   252  			h.server.clientPool.requestCost(p, realCost)
   253  		}
   254  		if reply != nil {
   255  			p.queueSend(func() {
   256  				if err := reply.send(bv); err != nil {
   257  					select {
   258  					case p.errCh <- err:
   259  					default:
   260  					}
   261  				}
   262  			})
   263  		}
   264  	}
   265  	switch msg.Code {
   266  	case GetBlockHeadersMsg:
   267  		p.Log().Trace("Received block header request")
   268  		if metrics.EnabledExpensive {
   269  			miscInHeaderPacketsMeter.Mark(1)
   270  			miscInHeaderTrafficMeter.Mark(int64(msg.Size))
   271  		}
   272  		var req struct {
   273  			ReqID uint64
   274  			Query getBlockHeadersData
   275  		}
   276  		if err := msg.Decode(&req); err != nil {
   277  			clientErrorMeter.Mark(1)
   278  			return errResp(ErrDecode, "%v: %v", msg, err)
   279  		}
   280  		query := req.Query
   281  		if accept(req.ReqID, query.Amount, MaxHeaderFetch) {
   282  			wg.Add(1)
   283  			go func() {
   284  				defer wg.Done()
   285  				hashMode := query.Origin.Hash != (common.Hash{})
   286  				first := true
   287  				maxNonCanonical := uint64(100)
   288  
   289  				// Gather headers until the fetch or network limits is reached
   290  				var (
   291  					bytes   common.StorageSize
   292  					headers []*types.Header
   293  					unknown bool
   294  				)
   295  				for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit {
   296  					if !first && !task.waitOrStop() {
   297  						sendResponse(req.ReqID, 0, nil, task.servingTime)
   298  						return
   299  					}
   300  					// Retrieve the next header satisfying the query
   301  					var origin *types.Header
   302  					if hashMode {
   303  						if first {
   304  							origin = h.blockchain.GetHeaderByHash(query.Origin.Hash)
   305  							if origin != nil {
   306  								query.Origin.Number = origin.Number.Uint64()
   307  							}
   308  						} else {
   309  							origin = h.blockchain.GetHeader(query.Origin.Hash, query.Origin.Number)
   310  						}
   311  					} else {
   312  						origin = h.blockchain.GetHeaderByNumber(query.Origin.Number)
   313  					}
   314  					if origin == nil {
   315  						atomic.AddUint32(&p.invalidCount, 1)
   316  						break
   317  					}
   318  					headers = append(headers, origin)
   319  					bytes += estHeaderRlpSize
   320  
   321  					// Advance to the next header of the query
   322  					switch {
   323  					case hashMode && query.Reverse:
   324  						// Hash based traversal towards the genesis block
   325  						ancestor := query.Skip + 1
   326  						if ancestor == 0 {
   327  							unknown = true
   328  						} else {
   329  							query.Origin.Hash, query.Origin.Number = h.blockchain.GetAncestor(query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical)
   330  							unknown = query.Origin.Hash == common.Hash{}
   331  						}
   332  					case hashMode && !query.Reverse:
   333  						// Hash based traversal towards the leaf block
   334  						var (
   335  							current = origin.Number.Uint64()
   336  							next    = current + query.Skip + 1
   337  						)
   338  						if next <= current {
   339  							infos, _ := json.MarshalIndent(p.Peer.Info(), "", "  ")
   340  							p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos)
   341  							unknown = true
   342  						} else {
   343  							if header := h.blockchain.GetHeaderByNumber(next); header != nil {
   344  								nextHash := header.Hash()
   345  								expOldHash, _ := h.blockchain.GetAncestor(nextHash, next, query.Skip+1, &maxNonCanonical)
   346  								if expOldHash == query.Origin.Hash {
   347  									query.Origin.Hash, query.Origin.Number = nextHash, next
   348  								} else {
   349  									unknown = true
   350  								}
   351  							} else {
   352  								unknown = true
   353  							}
   354  						}
   355  					case query.Reverse:
   356  						// Number based traversal towards the genesis block
   357  						if query.Origin.Number >= query.Skip+1 {
   358  							query.Origin.Number -= query.Skip + 1
   359  						} else {
   360  							unknown = true
   361  						}
   362  
   363  					case !query.Reverse:
   364  						// Number based traversal towards the leaf block
   365  						query.Origin.Number += query.Skip + 1
   366  					}
   367  					first = false
   368  				}
   369  				reply := p.ReplyBlockHeaders(req.ReqID, headers)
   370  				sendResponse(req.ReqID, query.Amount, p.ReplyBlockHeaders(req.ReqID, headers), task.done())
   371  				if metrics.EnabledExpensive {
   372  					miscOutHeaderPacketsMeter.Mark(1)
   373  					miscOutHeaderTrafficMeter.Mark(int64(reply.size()))
   374  				}
   375  			}()
   376  		}
   377  
   378  	case GetBlockBodiesMsg:
   379  		p.Log().Trace("Received block bodies request")
   380  		if metrics.EnabledExpensive {
   381  			miscInBodyPacketsMeter.Mark(1)
   382  			miscInBodyTrafficMeter.Mark(int64(msg.Size))
   383  		}
   384  		var req struct {
   385  			ReqID  uint64
   386  			Hashes []common.Hash
   387  		}
   388  		if err := msg.Decode(&req); err != nil {
   389  			clientErrorMeter.Mark(1)
   390  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   391  		}
   392  		var (
   393  			bytes  int
   394  			bodies []rlp.RawValue
   395  		)
   396  		reqCnt := len(req.Hashes)
   397  		if accept(req.ReqID, uint64(reqCnt), MaxBodyFetch) {
   398  			wg.Add(1)
   399  			go func() {
   400  				defer wg.Done()
   401  				for i, hash := range req.Hashes {
   402  					if i != 0 && !task.waitOrStop() {
   403  						sendResponse(req.ReqID, 0, nil, task.servingTime)
   404  						return
   405  					}
   406  					if bytes >= softResponseLimit {
   407  						break
   408  					}
   409  					body := h.blockchain.GetBodyRLP(hash)
   410  					if body == nil {
   411  						atomic.AddUint32(&p.invalidCount, 1)
   412  						continue
   413  					}
   414  					bodies = append(bodies, body)
   415  					bytes += len(body)
   416  				}
   417  				reply := p.ReplyBlockBodiesRLP(req.ReqID, bodies)
   418  				sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
   419  				if metrics.EnabledExpensive {
   420  					miscOutBodyPacketsMeter.Mark(1)
   421  					miscOutBodyTrafficMeter.Mark(int64(reply.size()))
   422  				}
   423  			}()
   424  		}
   425  
   426  	case GetCodeMsg:
   427  		p.Log().Trace("Received code request")
   428  		if metrics.EnabledExpensive {
   429  			miscInCodePacketsMeter.Mark(1)
   430  			miscInCodeTrafficMeter.Mark(int64(msg.Size))
   431  		}
   432  		var req struct {
   433  			ReqID uint64
   434  			Reqs  []CodeReq
   435  		}
   436  		if err := msg.Decode(&req); err != nil {
   437  			clientErrorMeter.Mark(1)
   438  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   439  		}
   440  		var (
   441  			bytes int
   442  			data  [][]byte
   443  		)
   444  		reqCnt := len(req.Reqs)
   445  		if accept(req.ReqID, uint64(reqCnt), MaxCodeFetch) {
   446  			wg.Add(1)
   447  			go func() {
   448  				defer wg.Done()
   449  				for i, request := range req.Reqs {
   450  					if i != 0 && !task.waitOrStop() {
   451  						sendResponse(req.ReqID, 0, nil, task.servingTime)
   452  						return
   453  					}
   454  					// Look up the root hash belonging to the request
   455  					header := h.blockchain.GetHeaderByHash(request.BHash)
   456  					if header == nil {
   457  						p.Log().Warn("Failed to retrieve associate header for code", "hash", request.BHash)
   458  						atomic.AddUint32(&p.invalidCount, 1)
   459  						continue
   460  					}
   461  					// Refuse to search stale state data in the database since looking for
   462  					// a non-exist key is kind of expensive.
   463  					local := h.blockchain.CurrentHeader().Number.Uint64()
   464  					if !h.server.archiveMode && header.Number.Uint64()+core.TriesInMemory <= local {
   465  						p.Log().Debug("Reject stale code request", "number", header.Number.Uint64(), "head", local)
   466  						atomic.AddUint32(&p.invalidCount, 1)
   467  						continue
   468  					}
   469  					triedb := h.blockchain.StateCache().TrieDB()
   470  
   471  					account, err := h.getAccount(triedb, header.Root, common.BytesToHash(request.AccKey))
   472  					if err != nil {
   473  						p.Log().Warn("Failed to retrieve account for code", "block", header.Number, "hash", header.Hash(), "account", common.BytesToHash(request.AccKey), "err", err)
   474  						atomic.AddUint32(&p.invalidCount, 1)
   475  						continue
   476  					}
   477  					code, err := triedb.Node(common.BytesToHash(account.CodeHash))
   478  					if err != nil {
   479  						p.Log().Warn("Failed to retrieve account code", "block", header.Number, "hash", header.Hash(), "account", common.BytesToHash(request.AccKey), "codehash", common.BytesToHash(account.CodeHash), "err", err)
   480  						continue
   481  					}
   482  					// Accumulate the code and abort if enough data was retrieved
   483  					data = append(data, code)
   484  					if bytes += len(code); bytes >= softResponseLimit {
   485  						break
   486  					}
   487  				}
   488  				reply := p.ReplyCode(req.ReqID, data)
   489  				sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
   490  				if metrics.EnabledExpensive {
   491  					miscOutCodePacketsMeter.Mark(1)
   492  					miscOutCodeTrafficMeter.Mark(int64(reply.size()))
   493  				}
   494  			}()
   495  		}
   496  
   497  	case GetReceiptsMsg:
   498  		p.Log().Trace("Received receipts request")
   499  		if metrics.EnabledExpensive {
   500  			miscInReceiptPacketsMeter.Mark(1)
   501  			miscInReceiptTrafficMeter.Mark(int64(msg.Size))
   502  		}
   503  		var req struct {
   504  			ReqID  uint64
   505  			Hashes []common.Hash
   506  		}
   507  		if err := msg.Decode(&req); err != nil {
   508  			clientErrorMeter.Mark(1)
   509  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   510  		}
   511  		var (
   512  			bytes    int
   513  			receipts []rlp.RawValue
   514  		)
   515  		reqCnt := len(req.Hashes)
   516  		if accept(req.ReqID, uint64(reqCnt), MaxReceiptFetch) {
   517  			wg.Add(1)
   518  			go func() {
   519  				defer wg.Done()
   520  				for i, hash := range req.Hashes {
   521  					if i != 0 && !task.waitOrStop() {
   522  						sendResponse(req.ReqID, 0, nil, task.servingTime)
   523  						return
   524  					}
   525  					if bytes >= softResponseLimit {
   526  						break
   527  					}
   528  					// Retrieve the requested block's receipts, skipping if unknown to us
   529  					results := h.blockchain.GetReceiptsByHash(hash)
   530  					if results == nil {
   531  						if header := h.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
   532  							atomic.AddUint32(&p.invalidCount, 1)
   533  							continue
   534  						}
   535  					}
   536  					// If known, encode and queue for response packet
   537  					if encoded, err := rlp.EncodeToBytes(results); err != nil {
   538  						log.Error("Failed to encode receipt", "err", err)
   539  					} else {
   540  						receipts = append(receipts, encoded)
   541  						bytes += len(encoded)
   542  					}
   543  				}
   544  				reply := p.ReplyReceiptsRLP(req.ReqID, receipts)
   545  				sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
   546  				if metrics.EnabledExpensive {
   547  					miscOutReceiptPacketsMeter.Mark(1)
   548  					miscOutReceiptTrafficMeter.Mark(int64(reply.size()))
   549  				}
   550  			}()
   551  		}
   552  
   553  	case GetProofsV2Msg:
   554  		p.Log().Trace("Received les/2 proofs request")
   555  		if metrics.EnabledExpensive {
   556  			miscInTrieProofPacketsMeter.Mark(1)
   557  			miscInTrieProofTrafficMeter.Mark(int64(msg.Size))
   558  		}
   559  		var req struct {
   560  			ReqID uint64
   561  			Reqs  []ProofReq
   562  		}
   563  		if err := msg.Decode(&req); err != nil {
   564  			clientErrorMeter.Mark(1)
   565  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   566  		}
   567  		// Gather state data until the fetch or network limits is reached
   568  		var (
   569  			lastBHash common.Hash
   570  			root      common.Hash
   571  		)
   572  		reqCnt := len(req.Reqs)
   573  		if accept(req.ReqID, uint64(reqCnt), MaxProofsFetch) {
   574  			wg.Add(1)
   575  			go func() {
   576  				defer wg.Done()
   577  				nodes := light.NewNodeSet()
   578  
   579  				for i, request := range req.Reqs {
   580  					if i != 0 && !task.waitOrStop() {
   581  						sendResponse(req.ReqID, 0, nil, task.servingTime)
   582  						return
   583  					}
   584  					// Look up the root hash belonging to the request
   585  					var (
   586  						header *types.Header
   587  						trie   state.Trie
   588  					)
   589  					if request.BHash != lastBHash {
   590  						root, lastBHash = common.Hash{}, request.BHash
   591  
   592  						if header = h.blockchain.GetHeaderByHash(request.BHash); header == nil {
   593  							p.Log().Warn("Failed to retrieve header for proof", "hash", request.BHash)
   594  							atomic.AddUint32(&p.invalidCount, 1)
   595  							continue
   596  						}
   597  						// Refuse to search stale state data in the database since looking for
   598  						// a non-exist key is kind of expensive.
   599  						local := h.blockchain.CurrentHeader().Number.Uint64()
   600  						if !h.server.archiveMode && header.Number.Uint64()+core.TriesInMemory <= local {
   601  							p.Log().Debug("Reject stale trie request", "number", header.Number.Uint64(), "head", local)
   602  							atomic.AddUint32(&p.invalidCount, 1)
   603  							continue
   604  						}
   605  						root = header.Root
   606  					}
   607  					// If a header lookup failed (non existent), ignore subsequent requests for the same header
   608  					if root == (common.Hash{}) {
   609  						atomic.AddUint32(&p.invalidCount, 1)
   610  						continue
   611  					}
   612  					// Open the account or storage trie for the request
   613  					statedb := h.blockchain.StateCache()
   614  
   615  					switch len(request.AccKey) {
   616  					case 0:
   617  						// No account key specified, open an account trie
   618  						trie, err = statedb.OpenTrie(root)
   619  						if trie == nil || err != nil {
   620  							p.Log().Warn("Failed to open storage trie for proof", "block", header.Number, "hash", header.Hash(), "root", root, "err", err)
   621  							continue
   622  						}
   623  					default:
   624  						// Account key specified, open a storage trie
   625  						account, err := h.getAccount(statedb.TrieDB(), root, common.BytesToHash(request.AccKey))
   626  						if err != nil {
   627  							p.Log().Warn("Failed to retrieve account for proof", "block", header.Number, "hash", header.Hash(), "account", common.BytesToHash(request.AccKey), "err", err)
   628  							atomic.AddUint32(&p.invalidCount, 1)
   629  							continue
   630  						}
   631  						trie, err = statedb.OpenStorageTrie(common.BytesToHash(request.AccKey), account.Root)
   632  						if trie == nil || err != nil {
   633  							p.Log().Warn("Failed to open storage trie for proof", "block", header.Number, "hash", header.Hash(), "account", common.BytesToHash(request.AccKey), "root", account.Root, "err", err)
   634  							continue
   635  						}
   636  					}
   637  					// Prove the user's request from the account or stroage trie
   638  					if err := trie.Prove(request.Key, request.FromLevel, nodes); err != nil {
   639  						p.Log().Warn("Failed to prove state request", "block", header.Number, "hash", header.Hash(), "err", err)
   640  						continue
   641  					}
   642  					if nodes.DataSize() >= softResponseLimit {
   643  						break
   644  					}
   645  				}
   646  				reply := p.ReplyProofsV2(req.ReqID, nodes.NodeList())
   647  				sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
   648  				if metrics.EnabledExpensive {
   649  					miscOutTrieProofPacketsMeter.Mark(1)
   650  					miscOutTrieProofTrafficMeter.Mark(int64(reply.size()))
   651  				}
   652  			}()
   653  		}
   654  
   655  	case GetHelperTrieProofsMsg:
   656  		p.Log().Trace("Received helper trie proof request")
   657  		if metrics.EnabledExpensive {
   658  			miscInHelperTriePacketsMeter.Mark(1)
   659  			miscInHelperTrieTrafficMeter.Mark(int64(msg.Size))
   660  		}
   661  		var req struct {
   662  			ReqID uint64
   663  			Reqs  []HelperTrieReq
   664  		}
   665  		if err := msg.Decode(&req); err != nil {
   666  			clientErrorMeter.Mark(1)
   667  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   668  		}
   669  		// Gather state data until the fetch or network limits is reached
   670  		var (
   671  			auxBytes int
   672  			auxData  [][]byte
   673  		)
   674  		reqCnt := len(req.Reqs)
   675  		if accept(req.ReqID, uint64(reqCnt), MaxHelperTrieProofsFetch) {
   676  			wg.Add(1)
   677  			go func() {
   678  				defer wg.Done()
   679  				var (
   680  					lastIdx  uint64
   681  					lastType uint
   682  					root     common.Hash
   683  					auxTrie  *trie.Trie
   684  				)
   685  				nodes := light.NewNodeSet()
   686  				for i, request := range req.Reqs {
   687  					if i != 0 && !task.waitOrStop() {
   688  						sendResponse(req.ReqID, 0, nil, task.servingTime)
   689  						return
   690  					}
   691  					if auxTrie == nil || request.Type != lastType || request.TrieIdx != lastIdx {
   692  						auxTrie, lastType, lastIdx = nil, request.Type, request.TrieIdx
   693  
   694  						var prefix string
   695  						if root, prefix = h.getHelperTrie(request.Type, request.TrieIdx); root != (common.Hash{}) {
   696  							auxTrie, _ = trie.New(root, trie.NewDatabase(rawdb.NewTable(h.chainDb, prefix)))
   697  						}
   698  					}
   699  					if request.AuxReq == auxRoot {
   700  						var data []byte
   701  						if root != (common.Hash{}) {
   702  							data = root[:]
   703  						}
   704  						auxData = append(auxData, data)
   705  						auxBytes += len(data)
   706  					} else {
   707  						if auxTrie != nil {
   708  							auxTrie.Prove(request.Key, request.FromLevel, nodes)
   709  						}
   710  						if request.AuxReq != 0 {
   711  							data := h.getAuxiliaryHeaders(request)
   712  							auxData = append(auxData, data)
   713  							auxBytes += len(data)
   714  						}
   715  					}
   716  					if nodes.DataSize()+auxBytes >= softResponseLimit {
   717  						break
   718  					}
   719  				}
   720  				reply := p.ReplyHelperTrieProofs(req.ReqID, HelperTrieResps{Proofs: nodes.NodeList(), AuxData: auxData})
   721  				sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
   722  				if metrics.EnabledExpensive {
   723  					miscOutHelperTriePacketsMeter.Mark(1)
   724  					miscOutHelperTrieTrafficMeter.Mark(int64(reply.size()))
   725  				}
   726  			}()
   727  		}
   728  
   729  	case SendTxV2Msg:
   730  		p.Log().Trace("Received new transactions")
   731  		if metrics.EnabledExpensive {
   732  			miscInTxsPacketsMeter.Mark(1)
   733  			miscInTxsTrafficMeter.Mark(int64(msg.Size))
   734  		}
   735  		var req struct {
   736  			ReqID uint64
   737  			Txs   []*types.Transaction
   738  		}
   739  		if err := msg.Decode(&req); err != nil {
   740  			clientErrorMeter.Mark(1)
   741  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   742  		}
   743  		reqCnt := len(req.Txs)
   744  		if accept(req.ReqID, uint64(reqCnt), MaxTxSend) {
   745  			wg.Add(1)
   746  			go func() {
   747  				defer wg.Done()
   748  				stats := make([]light.TxStatus, len(req.Txs))
   749  				for i, tx := range req.Txs {
   750  					if i != 0 && !task.waitOrStop() {
   751  						return
   752  					}
   753  					hash := tx.Hash()
   754  					stats[i] = h.txStatus(hash)
   755  					if stats[i].Status == core.TxStatusUnknown {
   756  						addFn := h.txpool.AddRemotes
   757  						// Add txs synchronously for testing purpose
   758  						if h.addTxsSync {
   759  							addFn = h.txpool.AddRemotesSync
   760  						}
   761  						if errs := addFn([]*types.Transaction{tx}); errs[0] != nil {
   762  							stats[i].Error = errs[0].Error()
   763  							continue
   764  						}
   765  						stats[i] = h.txStatus(hash)
   766  					}
   767  				}
   768  				reply := p.ReplyTxStatus(req.ReqID, stats)
   769  				sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
   770  				if metrics.EnabledExpensive {
   771  					miscOutTxsPacketsMeter.Mark(1)
   772  					miscOutTxsTrafficMeter.Mark(int64(reply.size()))
   773  				}
   774  			}()
   775  		}
   776  
   777  	case GetTxStatusMsg:
   778  		p.Log().Trace("Received transaction status query request")
   779  		if metrics.EnabledExpensive {
   780  			miscInTxStatusPacketsMeter.Mark(1)
   781  			miscInTxStatusTrafficMeter.Mark(int64(msg.Size))
   782  		}
   783  		var req struct {
   784  			ReqID  uint64
   785  			Hashes []common.Hash
   786  		}
   787  		if err := msg.Decode(&req); err != nil {
   788  			clientErrorMeter.Mark(1)
   789  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   790  		}
   791  		reqCnt := len(req.Hashes)
   792  		if accept(req.ReqID, uint64(reqCnt), MaxTxStatus) {
   793  			wg.Add(1)
   794  			go func() {
   795  				defer wg.Done()
   796  				stats := make([]light.TxStatus, len(req.Hashes))
   797  				for i, hash := range req.Hashes {
   798  					if i != 0 && !task.waitOrStop() {
   799  						sendResponse(req.ReqID, 0, nil, task.servingTime)
   800  						return
   801  					}
   802  					stats[i] = h.txStatus(hash)
   803  				}
   804  				reply := p.ReplyTxStatus(req.ReqID, stats)
   805  				sendResponse(req.ReqID, uint64(reqCnt), reply, task.done())
   806  				if metrics.EnabledExpensive {
   807  					miscOutTxStatusPacketsMeter.Mark(1)
   808  					miscOutTxStatusTrafficMeter.Mark(int64(reply.size()))
   809  				}
   810  			}()
   811  		}
   812  
   813  	default:
   814  		p.Log().Trace("Received invalid message", "code", msg.Code)
   815  		clientErrorMeter.Mark(1)
   816  		return errResp(ErrInvalidMsgCode, "%v", msg.Code)
   817  	}
   818  	// If the client has made too much invalid request(e.g. request a non-exist data),
   819  	// reject them to prevent SPAM attack.
   820  	if atomic.LoadUint32(&p.invalidCount) > maxRequestErrors {
   821  		clientErrorMeter.Mark(1)
   822  		return errTooManyInvalidRequest
   823  	}
   824  	return nil
   825  }
   826  
   827  // getAccount retrieves an account from the state based on root.
   828  func (h *serverHandler) getAccount(triedb *trie.Database, root, hash common.Hash) (state.Account, error) {
   829  	trie, err := trie.New(root, triedb)
   830  	if err != nil {
   831  		return state.Account{}, err
   832  	}
   833  	blob, err := trie.TryGet(hash[:])
   834  	if err != nil {
   835  		return state.Account{}, err
   836  	}
   837  	var account state.Account
   838  	if err = rlp.DecodeBytes(blob, &account); err != nil {
   839  		return state.Account{}, err
   840  	}
   841  	return account, nil
   842  }
   843  
   844  // getHelperTrie returns the post-processed trie root for the given trie ID and section index
   845  func (h *serverHandler) getHelperTrie(typ uint, index uint64) (common.Hash, string) {
   846  	switch typ {
   847  	case htCanonical:
   848  		sectionHead := rawdb.ReadCanonicalHash(h.chainDb, (index+1)*h.server.iConfig.ChtSize-1)
   849  		return light.GetChtRoot(h.chainDb, index, sectionHead), light.ChtTablePrefix
   850  	case htBloomBits:
   851  		sectionHead := rawdb.ReadCanonicalHash(h.chainDb, (index+1)*h.server.iConfig.BloomTrieSize-1)
   852  		return light.GetBloomTrieRoot(h.chainDb, index, sectionHead), light.BloomTrieTablePrefix
   853  	}
   854  	return common.Hash{}, ""
   855  }
   856  
   857  // getAuxiliaryHeaders returns requested auxiliary headers for the CHT request.
   858  func (h *serverHandler) getAuxiliaryHeaders(req HelperTrieReq) []byte {
   859  	if req.Type == htCanonical && req.AuxReq == auxHeader && len(req.Key) == 8 {
   860  		blockNum := binary.BigEndian.Uint64(req.Key)
   861  		hash := rawdb.ReadCanonicalHash(h.chainDb, blockNum)
   862  		return rawdb.ReadHeaderRLP(h.chainDb, hash, blockNum)
   863  	}
   864  	return nil
   865  }
   866  
   867  // txStatus returns the status of a specified transaction.
   868  func (h *serverHandler) txStatus(hash common.Hash) light.TxStatus {
   869  	var stat light.TxStatus
   870  	// Looking the transaction in txpool first.
   871  	stat.Status = h.txpool.Status([]common.Hash{hash})[0]
   872  
   873  	// If the transaction is unknown to the pool, try looking it up locally.
   874  	if stat.Status == core.TxStatusUnknown {
   875  		lookup := h.blockchain.GetTransactionLookup(hash)
   876  		if lookup != nil {
   877  			stat.Status = core.TxStatusIncluded
   878  			stat.Lookup = lookup
   879  		}
   880  	}
   881  	return stat
   882  }
   883  
   884  // broadcastHeaders broadcasts new block information to all connected light
   885  // clients. According to the agreement between client and server, server should
   886  // only broadcast new announcement if the total difficulty is higher than the
   887  // last one. Besides server will add the signature if client requires.
   888  func (h *serverHandler) broadcastHeaders() {
   889  	defer h.wg.Done()
   890  
   891  	headCh := make(chan core.ChainHeadEvent, 10)
   892  	headSub := h.blockchain.SubscribeChainHeadEvent(headCh)
   893  	defer headSub.Unsubscribe()
   894  
   895  	var (
   896  		lastHead *types.Header
   897  		lastTd   = common.Big0
   898  	)
   899  	for {
   900  		select {
   901  		case ev := <-headCh:
   902  			peers := h.server.peers.AllPeers()
   903  			if len(peers) == 0 {
   904  				continue
   905  			}
   906  			header := ev.Block.Header()
   907  			hash, number := header.Hash(), header.Number.Uint64()
   908  			td := h.blockchain.GetTd(hash, number)
   909  			if td == nil || td.Cmp(lastTd) <= 0 {
   910  				continue
   911  			}
   912  			var reorg uint64
   913  			if lastHead != nil {
   914  				reorg = lastHead.Number.Uint64() - rawdb.FindCommonAncestor(h.chainDb, header, lastHead).Number.Uint64()
   915  			}
   916  			lastHead, lastTd = header, td
   917  
   918  			log.Debug("Announcing block to peers", "number", number, "hash", hash, "td", td, "reorg", reorg)
   919  			var (
   920  				signed         bool
   921  				signedAnnounce announceData
   922  			)
   923  			announce := announceData{Hash: hash, Number: number, Td: td, ReorgDepth: reorg}
   924  			for _, p := range peers {
   925  				p := p
   926  				switch p.announceType {
   927  				case announceTypeSimple:
   928  					p.queueSend(func() { p.SendAnnounce(announce) })
   929  				case announceTypeSigned:
   930  					if !signed {
   931  						signedAnnounce = announce
   932  						signedAnnounce.sign(h.server.privateKey)
   933  						signed = true
   934  					}
   935  					p.queueSend(func() { p.SendAnnounce(signedAnnounce) })
   936  				}
   937  			}
   938  		case <-h.closeCh:
   939  			return
   940  		}
   941  	}
   942  }