github.com/dotlike13/wemix30_go@v1.8.23/eth/handler.go (about)

     1  // Copyright 2015 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 eth
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"fmt"
    23  	"math"
    24  	"math/big"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/consensus"
    31  	"github.com/ethereum/go-ethereum/consensus/misc"
    32  	"github.com/ethereum/go-ethereum/core"
    33  	"github.com/ethereum/go-ethereum/core/types"
    34  	"github.com/ethereum/go-ethereum/eth/downloader"
    35  	"github.com/ethereum/go-ethereum/eth/fetcher"
    36  	"github.com/ethereum/go-ethereum/ethdb"
    37  	"github.com/ethereum/go-ethereum/event"
    38  	"github.com/ethereum/go-ethereum/log"
    39  	"github.com/ethereum/go-ethereum/p2p"
    40  	"github.com/ethereum/go-ethereum/p2p/enode"
    41  	"github.com/ethereum/go-ethereum/params"
    42  	"github.com/ethereum/go-ethereum/rlp"
    43  )
    44  
    45  const (
    46  	softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data.
    47  	estHeaderRlpSize  = 500             // Approximate size of an RLP encoded block header
    48  
    49  	// txChanSize is the size of channel listening to NewTxsEvent.
    50  	// The number is referenced from the size of tx pool.
    51  	txChanSize = 4096
    52  
    53  	// minimim number of peers to broadcast new blocks to
    54  	minBroadcastPeers = 4
    55  )
    56  
    57  var (
    58  	daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge
    59  )
    60  
    61  // errIncompatibleConfig is returned if the requested protocols and configs are
    62  // not compatible (low protocol version restrictions and high requirements).
    63  var errIncompatibleConfig = errors.New("incompatible configuration")
    64  
    65  func errResp(code errCode, format string, v ...interface{}) error {
    66  	return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...))
    67  }
    68  
    69  type ProtocolManager struct {
    70  	networkID uint64
    71  
    72  	fastSync  uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
    73  	acceptTxs uint32 // Flag whether we're considered synchronised (enables transaction processing)
    74  
    75  	txpool      txPool
    76  	blockchain  *core.BlockChain
    77  	chainconfig *params.ChainConfig
    78  	maxPeers    int
    79  
    80  	downloader *downloader.Downloader
    81  	fetcher    *fetcher.Fetcher
    82  	peers      *peerSet
    83  
    84  	SubProtocols []p2p.Protocol
    85  
    86  	eventMux      *event.TypeMux
    87  	txsCh         chan core.NewTxsEvent
    88  	txsSub        event.Subscription
    89  	minedBlockSub *event.TypeMuxSubscription
    90  
    91  	whitelist map[uint64]common.Hash
    92  
    93  	// channels for fetcher, syncer, txsyncLoop
    94  	newPeerCh   chan *peer
    95  	txsyncCh    chan *txsync
    96  	quitSync    chan struct{}
    97  	noMorePeers chan struct{}
    98  
    99  	// wait group is used for graceful shutdowns during downloading
   100  	// and processing
   101  	wg sync.WaitGroup
   102  }
   103  
   104  // NewProtocolManager returns a new Ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
   105  // with the Ethereum network.
   106  func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, networkID uint64, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database, whitelist map[uint64]common.Hash) (*ProtocolManager, error) {
   107  	// Create the protocol manager with the base fields
   108  	manager := &ProtocolManager{
   109  		networkID:   networkID,
   110  		eventMux:    mux,
   111  		txpool:      txpool,
   112  		blockchain:  blockchain,
   113  		chainconfig: config,
   114  		peers:       newPeerSet(),
   115  		whitelist:   whitelist,
   116  		newPeerCh:   make(chan *peer),
   117  		noMorePeers: make(chan struct{}),
   118  		txsyncCh:    make(chan *txsync),
   119  		quitSync:    make(chan struct{}),
   120  	}
   121  	// Figure out whether to allow fast sync or not
   122  	if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 {
   123  		log.Warn("Blockchain not empty, fast sync disabled")
   124  		mode = downloader.FullSync
   125  	}
   126  	if mode == downloader.FastSync {
   127  		manager.fastSync = uint32(1)
   128  	}
   129  	// Initiate a sub-protocol for every implemented version we can handle
   130  	manager.SubProtocols = make([]p2p.Protocol, 0, len(ProtocolVersions))
   131  	for i, version := range ProtocolVersions {
   132  		// Skip protocol version if incompatible with the mode of operation
   133  		if mode == downloader.FastSync && version < eth63 {
   134  			continue
   135  		}
   136  		// Compatible; initialise the sub-protocol
   137  		version := version // Closure for the run
   138  		manager.SubProtocols = append(manager.SubProtocols, p2p.Protocol{
   139  			Name:    ProtocolName,
   140  			Version: version,
   141  			Length:  ProtocolLengths[i],
   142  			Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
   143  				peer := manager.newPeer(int(version), p, rw)
   144  				select {
   145  				case manager.newPeerCh <- peer:
   146  					manager.wg.Add(1)
   147  					defer manager.wg.Done()
   148  					return manager.handle(peer)
   149  				case <-manager.quitSync:
   150  					return p2p.DiscQuitting
   151  				}
   152  			},
   153  			NodeInfo: func() interface{} {
   154  				return manager.NodeInfo()
   155  			},
   156  			PeerInfo: func(id enode.ID) interface{} {
   157  				if p := manager.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil {
   158  					return p.Info()
   159  				}
   160  				return nil
   161  			},
   162  		})
   163  	}
   164  	if len(manager.SubProtocols) == 0 {
   165  		return nil, errIncompatibleConfig
   166  	}
   167  	// Construct the different synchronisation mechanisms
   168  	manager.downloader = downloader.New(mode, chaindb, manager.eventMux, blockchain, nil, manager.removePeer)
   169  
   170  	validator := func(header *types.Header) error {
   171  		return engine.VerifyHeader(blockchain, header, true)
   172  	}
   173  	heighter := func() uint64 {
   174  		return blockchain.CurrentBlock().NumberU64()
   175  	}
   176  	inserter := func(blocks types.Blocks) (int, error) {
   177  		// If fast sync is running, deny importing weird blocks
   178  		if atomic.LoadUint32(&manager.fastSync) == 1 {
   179  			log.Warn("Discarded bad propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
   180  			return 0, nil
   181  		}
   182  		atomic.StoreUint32(&manager.acceptTxs, 1) // Mark initial sync done on any fetcher import
   183  		return manager.blockchain.InsertChain(blocks)
   184  	}
   185  	manager.fetcher = fetcher.New(blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, inserter, manager.removePeer)
   186  
   187  	return manager, nil
   188  }
   189  
   190  func (pm *ProtocolManager) removePeer(id string) {
   191  	// Short circuit if the peer was already removed
   192  	peer := pm.peers.Peer(id)
   193  	if peer == nil {
   194  		return
   195  	}
   196  	log.Debug("Removing Ethereum peer", "peer", id)
   197  
   198  	// Unregister the peer from the downloader and Ethereum peer set
   199  	pm.downloader.UnregisterPeer(id)
   200  	if err := pm.peers.Unregister(id); err != nil {
   201  		log.Error("Peer removal failed", "peer", id, "err", err)
   202  	}
   203  	// Hard disconnect at the networking layer
   204  	if peer != nil {
   205  		peer.Peer.Disconnect(p2p.DiscUselessPeer)
   206  	}
   207  }
   208  
   209  func (pm *ProtocolManager) Start(maxPeers int) {
   210  	pm.maxPeers = maxPeers
   211  
   212  	// broadcast transactions
   213  	pm.txsCh = make(chan core.NewTxsEvent, txChanSize)
   214  	pm.txsSub = pm.txpool.SubscribeNewTxsEvent(pm.txsCh)
   215  	go pm.txBroadcastLoop()
   216  
   217  	// broadcast mined blocks
   218  	pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
   219  	go pm.minedBroadcastLoop()
   220  
   221  	// start sync handlers
   222  	go pm.syncer()
   223  	go pm.txsyncLoop()
   224  }
   225  
   226  func (pm *ProtocolManager) Stop() {
   227  	log.Info("Stopping Ethereum protocol")
   228  
   229  	pm.txsSub.Unsubscribe()        // quits txBroadcastLoop
   230  	pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
   231  
   232  	// Quit the sync loop.
   233  	// After this send has completed, no new peers will be accepted.
   234  	pm.noMorePeers <- struct{}{}
   235  
   236  	// Quit fetcher, txsyncLoop.
   237  	close(pm.quitSync)
   238  
   239  	// Disconnect existing sessions.
   240  	// This also closes the gate for any new registrations on the peer set.
   241  	// sessions which are already established but not added to pm.peers yet
   242  	// will exit when they try to register.
   243  	pm.peers.Close()
   244  
   245  	// Wait for all peer handler goroutines and the loops to come down.
   246  	pm.wg.Wait()
   247  
   248  	log.Info("Ethereum protocol stopped")
   249  }
   250  
   251  func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
   252  	return newPeer(pv, p, newMeteredMsgWriter(rw))
   253  }
   254  
   255  // handle is the callback invoked to manage the life cycle of an eth peer. When
   256  // this function terminates, the peer is disconnected.
   257  func (pm *ProtocolManager) handle(p *peer) error {
   258  	// Ignore maxPeers if this is a trusted peer
   259  	if pm.peers.Len() >= pm.maxPeers && !p.Peer.Info().Network.Trusted {
   260  		return p2p.DiscTooManyPeers
   261  	}
   262  	p.Log().Debug("Ethereum peer connected", "name", p.Name())
   263  
   264  	// Execute the Ethereum handshake
   265  	var (
   266  		genesis = pm.blockchain.Genesis()
   267  		head    = pm.blockchain.CurrentHeader()
   268  		hash    = head.Hash()
   269  		number  = head.Number.Uint64()
   270  		td      = pm.blockchain.GetTd(hash, number)
   271  	)
   272  	if err := p.Handshake(pm.networkID, td, hash, genesis.Hash()); err != nil {
   273  		p.Log().Debug("Ethereum handshake failed", "err", err)
   274  		return err
   275  	}
   276  	if rw, ok := p.rw.(*meteredMsgReadWriter); ok {
   277  		rw.Init(p.version)
   278  	}
   279  	// Register the peer locally
   280  	if err := pm.peers.Register(p); err != nil {
   281  		p.Log().Error("Ethereum peer registration failed", "err", err)
   282  		return err
   283  	}
   284  	defer pm.removePeer(p.id)
   285  
   286  	// Register the peer in the downloader. If the downloader considers it banned, we disconnect
   287  	if err := pm.downloader.RegisterPeer(p.id, p.version, p); err != nil {
   288  		return err
   289  	}
   290  	// Propagate existing transactions. new transactions appearing
   291  	// after this will be sent via broadcasts.
   292  	pm.syncTransactions(p)
   293  
   294  	// If we're DAO hard-fork aware, validate any remote peer with regard to the hard-fork
   295  	if daoBlock := pm.chainconfig.DAOForkBlock; daoBlock != nil {
   296  		// Request the peer's DAO fork header for extra-data validation
   297  		if err := p.RequestHeadersByNumber(daoBlock.Uint64(), 1, 0, false); err != nil {
   298  			return err
   299  		}
   300  		// Start a timer to disconnect if the peer doesn't reply in time
   301  		p.forkDrop = time.AfterFunc(daoChallengeTimeout, func() {
   302  			p.Log().Debug("Timed out DAO fork-check, dropping")
   303  			pm.removePeer(p.id)
   304  		})
   305  		// Make sure it's cleaned up if the peer dies off
   306  		defer func() {
   307  			if p.forkDrop != nil {
   308  				p.forkDrop.Stop()
   309  				p.forkDrop = nil
   310  			}
   311  		}()
   312  	}
   313  	// If we have any explicit whitelist block hashes, request them
   314  	for number := range pm.whitelist {
   315  		if err := p.RequestHeadersByNumber(number, 1, 0, false); err != nil {
   316  			return err
   317  		}
   318  	}
   319  	// Handle incoming messages until the connection is torn down
   320  	for {
   321  		if err := pm.handleMsg(p); err != nil {
   322  			p.Log().Debug("Ethereum message handling failed", "err", err)
   323  			return err
   324  		}
   325  	}
   326  }
   327  
   328  // handleMsg is invoked whenever an inbound message is received from a remote
   329  // peer. The remote connection is torn down upon returning any error.
   330  func (pm *ProtocolManager) handleMsg(p *peer) error {
   331  	// Read the next message from the remote peer, and ensure it's fully consumed
   332  	msg, err := p.rw.ReadMsg()
   333  	if err != nil {
   334  		return err
   335  	}
   336  	if msg.Size > ProtocolMaxMsgSize {
   337  		return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
   338  	}
   339  	defer msg.Discard()
   340  
   341  	// Handle the message depending on its contents
   342  	switch {
   343  	case msg.Code == StatusMsg:
   344  		// Status messages should never arrive after the handshake
   345  		return errResp(ErrExtraStatusMsg, "uncontrolled status message")
   346  
   347  	// Block header query, collect the requested headers and reply
   348  	case msg.Code == GetBlockHeadersMsg:
   349  		// Decode the complex header query
   350  		var query getBlockHeadersData
   351  		if err := msg.Decode(&query); err != nil {
   352  			return errResp(ErrDecode, "%v: %v", msg, err)
   353  		}
   354  		hashMode := query.Origin.Hash != (common.Hash{})
   355  		first := true
   356  		maxNonCanonical := uint64(100)
   357  
   358  		// Gather headers until the fetch or network limits is reached
   359  		var (
   360  			bytes   common.StorageSize
   361  			headers []*types.Header
   362  			unknown bool
   363  		)
   364  		for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
   365  			// Retrieve the next header satisfying the query
   366  			var origin *types.Header
   367  			if hashMode {
   368  				if first {
   369  					first = false
   370  					origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash)
   371  					if origin != nil {
   372  						query.Origin.Number = origin.Number.Uint64()
   373  					}
   374  				} else {
   375  					origin = pm.blockchain.GetHeader(query.Origin.Hash, query.Origin.Number)
   376  				}
   377  			} else {
   378  				origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
   379  			}
   380  			if origin == nil {
   381  				break
   382  			}
   383  			headers = append(headers, origin)
   384  			bytes += estHeaderRlpSize
   385  
   386  			// Advance to the next header of the query
   387  			switch {
   388  			case hashMode && query.Reverse:
   389  				// Hash based traversal towards the genesis block
   390  				ancestor := query.Skip + 1
   391  				if ancestor == 0 {
   392  					unknown = true
   393  				} else {
   394  					query.Origin.Hash, query.Origin.Number = pm.blockchain.GetAncestor(query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical)
   395  					unknown = (query.Origin.Hash == common.Hash{})
   396  				}
   397  			case hashMode && !query.Reverse:
   398  				// Hash based traversal towards the leaf block
   399  				var (
   400  					current = origin.Number.Uint64()
   401  					next    = current + query.Skip + 1
   402  				)
   403  				if next <= current {
   404  					infos, _ := json.MarshalIndent(p.Peer.Info(), "", "  ")
   405  					p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos)
   406  					unknown = true
   407  				} else {
   408  					if header := pm.blockchain.GetHeaderByNumber(next); header != nil {
   409  						nextHash := header.Hash()
   410  						expOldHash, _ := pm.blockchain.GetAncestor(nextHash, next, query.Skip+1, &maxNonCanonical)
   411  						if expOldHash == query.Origin.Hash {
   412  							query.Origin.Hash, query.Origin.Number = nextHash, next
   413  						} else {
   414  							unknown = true
   415  						}
   416  					} else {
   417  						unknown = true
   418  					}
   419  				}
   420  			case query.Reverse:
   421  				// Number based traversal towards the genesis block
   422  				if query.Origin.Number >= query.Skip+1 {
   423  					query.Origin.Number -= query.Skip + 1
   424  				} else {
   425  					unknown = true
   426  				}
   427  
   428  			case !query.Reverse:
   429  				// Number based traversal towards the leaf block
   430  				query.Origin.Number += query.Skip + 1
   431  			}
   432  		}
   433  		return p.SendBlockHeaders(headers)
   434  
   435  	case msg.Code == BlockHeadersMsg:
   436  		// A batch of headers arrived to one of our previous requests
   437  		var headers []*types.Header
   438  		if err := msg.Decode(&headers); err != nil {
   439  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   440  		}
   441  		// If no headers were received, but we're expending a DAO fork check, maybe it's that
   442  		if len(headers) == 0 && p.forkDrop != nil {
   443  			// Possibly an empty reply to the fork header checks, sanity check TDs
   444  			verifyDAO := true
   445  
   446  			// If we already have a DAO header, we can check the peer's TD against it. If
   447  			// the peer's ahead of this, it too must have a reply to the DAO check
   448  			if daoHeader := pm.blockchain.GetHeaderByNumber(pm.chainconfig.DAOForkBlock.Uint64()); daoHeader != nil {
   449  				if _, td := p.Head(); td.Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 {
   450  					verifyDAO = false
   451  				}
   452  			}
   453  			// If we're seemingly on the same chain, disable the drop timer
   454  			if verifyDAO {
   455  				p.Log().Debug("Seems to be on the same side of the DAO fork")
   456  				p.forkDrop.Stop()
   457  				p.forkDrop = nil
   458  				return nil
   459  			}
   460  		}
   461  		// Filter out any explicitly requested headers, deliver the rest to the downloader
   462  		filter := len(headers) == 1
   463  		if filter {
   464  			// If it's a potential DAO fork check, validate against the rules
   465  			if p.forkDrop != nil && pm.chainconfig.DAOForkBlock.Cmp(headers[0].Number) == 0 {
   466  				// Disable the fork drop timer
   467  				p.forkDrop.Stop()
   468  				p.forkDrop = nil
   469  
   470  				// Validate the header and either drop the peer or continue
   471  				if err := misc.VerifyDAOHeaderExtraData(pm.chainconfig, headers[0]); err != nil {
   472  					p.Log().Debug("Verified to be on the other side of the DAO fork, dropping")
   473  					return err
   474  				}
   475  				p.Log().Debug("Verified to be on the same side of the DAO fork")
   476  				return nil
   477  			}
   478  			// Otherwise if it's a whitelisted block, validate against the set
   479  			if want, ok := pm.whitelist[headers[0].Number.Uint64()]; ok {
   480  				if hash := headers[0].Hash(); want != hash {
   481  					p.Log().Info("Whitelist mismatch, dropping peer", "number", headers[0].Number.Uint64(), "hash", hash, "want", want)
   482  					return errors.New("whitelist block mismatch")
   483  				}
   484  				p.Log().Debug("Whitelist block verified", "number", headers[0].Number.Uint64(), "hash", want)
   485  			}
   486  			// Irrelevant of the fork checks, send the header to the fetcher just in case
   487  			headers = pm.fetcher.FilterHeaders(p.id, headers, time.Now())
   488  		}
   489  		if len(headers) > 0 || !filter {
   490  			err := pm.downloader.DeliverHeaders(p.id, headers)
   491  			if err != nil {
   492  				log.Debug("Failed to deliver headers", "err", err)
   493  			}
   494  		}
   495  
   496  	case msg.Code == GetBlockBodiesMsg:
   497  		// Decode the retrieval message
   498  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   499  		if _, err := msgStream.List(); err != nil {
   500  			return err
   501  		}
   502  		// Gather blocks until the fetch or network limits is reached
   503  		var (
   504  			hash   common.Hash
   505  			bytes  int
   506  			bodies []rlp.RawValue
   507  		)
   508  		for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
   509  			// Retrieve the hash of the next block
   510  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   511  				break
   512  			} else if err != nil {
   513  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   514  			}
   515  			// Retrieve the requested block body, stopping if enough was found
   516  			if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
   517  				bodies = append(bodies, data)
   518  				bytes += len(data)
   519  			}
   520  		}
   521  		return p.SendBlockBodiesRLP(bodies)
   522  
   523  	case msg.Code == BlockBodiesMsg:
   524  		// A batch of block bodies arrived to one of our previous requests
   525  		var request blockBodiesData
   526  		if err := msg.Decode(&request); err != nil {
   527  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   528  		}
   529  		// Deliver them all to the downloader for queuing
   530  		transactions := make([][]*types.Transaction, len(request))
   531  		uncles := make([][]*types.Header, len(request))
   532  
   533  		for i, body := range request {
   534  			transactions[i] = body.Transactions
   535  			uncles[i] = body.Uncles
   536  		}
   537  		// Filter out any explicitly requested bodies, deliver the rest to the downloader
   538  		filter := len(transactions) > 0 || len(uncles) > 0
   539  		if filter {
   540  			transactions, uncles = pm.fetcher.FilterBodies(p.id, transactions, uncles, time.Now())
   541  		}
   542  		if len(transactions) > 0 || len(uncles) > 0 || !filter {
   543  			err := pm.downloader.DeliverBodies(p.id, transactions, uncles)
   544  			if err != nil {
   545  				log.Debug("Failed to deliver bodies", "err", err)
   546  			}
   547  		}
   548  
   549  	case p.version >= eth63 && msg.Code == GetNodeDataMsg:
   550  		// Decode the retrieval message
   551  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   552  		if _, err := msgStream.List(); err != nil {
   553  			return err
   554  		}
   555  		// Gather state data until the fetch or network limits is reached
   556  		var (
   557  			hash  common.Hash
   558  			bytes int
   559  			data  [][]byte
   560  		)
   561  		for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
   562  			// Retrieve the hash of the next state entry
   563  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   564  				break
   565  			} else if err != nil {
   566  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   567  			}
   568  			// Retrieve the requested state entry, stopping if enough was found
   569  			if entry, err := pm.blockchain.TrieNode(hash); err == nil {
   570  				data = append(data, entry)
   571  				bytes += len(entry)
   572  			}
   573  		}
   574  		return p.SendNodeData(data)
   575  
   576  	case p.version >= eth63 && msg.Code == NodeDataMsg:
   577  		// A batch of node state data arrived to one of our previous requests
   578  		var data [][]byte
   579  		if err := msg.Decode(&data); err != nil {
   580  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   581  		}
   582  		// Deliver all to the downloader
   583  		if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
   584  			log.Debug("Failed to deliver node state data", "err", err)
   585  		}
   586  
   587  	case p.version >= eth63 && msg.Code == GetReceiptsMsg:
   588  		// Decode the retrieval message
   589  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   590  		if _, err := msgStream.List(); err != nil {
   591  			return err
   592  		}
   593  		// Gather state data until the fetch or network limits is reached
   594  		var (
   595  			hash     common.Hash
   596  			bytes    int
   597  			receipts []rlp.RawValue
   598  		)
   599  		for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
   600  			// Retrieve the hash of the next block
   601  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   602  				break
   603  			} else if err != nil {
   604  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   605  			}
   606  			// Retrieve the requested block's receipts, skipping if unknown to us
   607  			results := pm.blockchain.GetReceiptsByHash(hash)
   608  			if results == nil {
   609  				if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
   610  					continue
   611  				}
   612  			}
   613  			// If known, encode and queue for response packet
   614  			if encoded, err := rlp.EncodeToBytes(results); err != nil {
   615  				log.Error("Failed to encode receipt", "err", err)
   616  			} else {
   617  				receipts = append(receipts, encoded)
   618  				bytes += len(encoded)
   619  			}
   620  		}
   621  		return p.SendReceiptsRLP(receipts)
   622  
   623  	case p.version >= eth63 && msg.Code == ReceiptsMsg:
   624  		// A batch of receipts arrived to one of our previous requests
   625  		var receipts [][]*types.Receipt
   626  		if err := msg.Decode(&receipts); err != nil {
   627  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   628  		}
   629  		// Deliver all to the downloader
   630  		if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
   631  			log.Debug("Failed to deliver receipts", "err", err)
   632  		}
   633  
   634  	case msg.Code == NewBlockHashesMsg:
   635  		var announces newBlockHashesData
   636  		if err := msg.Decode(&announces); err != nil {
   637  			return errResp(ErrDecode, "%v: %v", msg, err)
   638  		}
   639  		// Mark the hashes as present at the remote node
   640  		for _, block := range announces {
   641  			p.MarkBlock(block.Hash)
   642  		}
   643  		// Schedule all the unknown hashes for retrieval
   644  		unknown := make(newBlockHashesData, 0, len(announces))
   645  		for _, block := range announces {
   646  			if !pm.blockchain.HasBlock(block.Hash, block.Number) {
   647  				unknown = append(unknown, block)
   648  			}
   649  		}
   650  		for _, block := range unknown {
   651  			pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies)
   652  		}
   653  
   654  	case msg.Code == NewBlockMsg:
   655  		// Retrieve and decode the propagated block
   656  		var request newBlockData
   657  		if err := msg.Decode(&request); err != nil {
   658  			return errResp(ErrDecode, "%v: %v", msg, err)
   659  		}
   660  		request.Block.ReceivedAt = msg.ReceivedAt
   661  		request.Block.ReceivedFrom = p
   662  
   663  		// Mark the peer as owning the block and schedule it for import
   664  		p.MarkBlock(request.Block.Hash())
   665  		pm.fetcher.Enqueue(p.id, request.Block)
   666  
   667  		// Assuming the block is importable by the peer, but possibly not yet done so,
   668  		// calculate the head hash and TD that the peer truly must have.
   669  		var (
   670  			trueHead = request.Block.ParentHash()
   671  			trueTD   = new(big.Int).Sub(request.TD, request.Block.Difficulty())
   672  		)
   673  		// Update the peer's total difficulty if better than the previous
   674  		if _, td := p.Head(); trueTD.Cmp(td) > 0 {
   675  			p.SetHead(trueHead, trueTD)
   676  
   677  			// Schedule a sync if above ours. Note, this will not fire a sync for a gap of
   678  			// a single block (as the true TD is below the propagated block), however this
   679  			// scenario should easily be covered by the fetcher.
   680  			currentBlock := pm.blockchain.CurrentBlock()
   681  			if trueTD.Cmp(pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())) > 0 {
   682  				go pm.synchronise(p)
   683  			}
   684  		}
   685  
   686  	case msg.Code == TxMsg:
   687  		// Transactions arrived, make sure we have a valid and fresh chain to handle them
   688  		if atomic.LoadUint32(&pm.acceptTxs) == 0 {
   689  			break
   690  		}
   691  		// Transactions can be processed, parse all of them and deliver to the pool
   692  		var txs []*types.Transaction
   693  		if err := msg.Decode(&txs); err != nil {
   694  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   695  		}
   696  		for i, tx := range txs {
   697  			// Validate and mark the remote transaction
   698  			if tx == nil {
   699  				return errResp(ErrDecode, "transaction %d is nil", i)
   700  			}
   701  			p.MarkTransaction(tx.Hash())
   702  		}
   703  		pm.txpool.AddRemotes(txs)
   704  
   705  	default:
   706  		return errResp(ErrInvalidMsgCode, "%v", msg.Code)
   707  	}
   708  	return nil
   709  }
   710  
   711  // BroadcastBlock will either propagate a block to a subset of it's peers, or
   712  // will only announce it's availability (depending what's requested).
   713  func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
   714  	hash := block.Hash()
   715  	peers := pm.peers.PeersWithoutBlock(hash)
   716  
   717  	// If propagation is requested, send to a subset of the peer
   718  	if propagate {
   719  		// Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
   720  		var td *big.Int
   721  		if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
   722  			td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
   723  		} else {
   724  			log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
   725  			return
   726  		}
   727  		// Send the block to a subset of our peers
   728  		transferLen := int(math.Sqrt(float64(len(peers))))
   729  		if transferLen < minBroadcastPeers {
   730  			transferLen = minBroadcastPeers
   731  		}
   732  		if transferLen > len(peers) {
   733  			transferLen = len(peers)
   734  		}
   735  		transfer := peers[:transferLen]
   736  		for _, peer := range transfer {
   737  			peer.AsyncSendNewBlock(block, td)
   738  		}
   739  		log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   740  		return
   741  	}
   742  	// Otherwise if the block is indeed in out own chain, announce it
   743  	if pm.blockchain.HasBlock(hash, block.NumberU64()) {
   744  		for _, peer := range peers {
   745  			peer.AsyncSendNewBlockHash(block)
   746  		}
   747  		log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   748  	}
   749  }
   750  
   751  // BroadcastTxs will propagate a batch of transactions to all peers which are not known to
   752  // already have the given transaction.
   753  func (pm *ProtocolManager) BroadcastTxs(txs types.Transactions) {
   754  	var txset = make(map[*peer]types.Transactions)
   755  
   756  	// Broadcast transactions to a batch of peers not knowing about it
   757  	for _, tx := range txs {
   758  		peers := pm.peers.PeersWithoutTx(tx.Hash())
   759  		for _, peer := range peers {
   760  			txset[peer] = append(txset[peer], tx)
   761  		}
   762  		log.Trace("Broadcast transaction", "hash", tx.Hash(), "recipients", len(peers))
   763  	}
   764  	// FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
   765  	for peer, txs := range txset {
   766  		peer.AsyncSendTransactions(txs)
   767  	}
   768  }
   769  
   770  // Mined broadcast loop
   771  func (pm *ProtocolManager) minedBroadcastLoop() {
   772  	// automatically stops if unsubscribe
   773  	for obj := range pm.minedBlockSub.Chan() {
   774  		if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
   775  			pm.BroadcastBlock(ev.Block, true)  // First propagate block to peers
   776  			pm.BroadcastBlock(ev.Block, false) // Only then announce to the rest
   777  		}
   778  	}
   779  }
   780  
   781  func (pm *ProtocolManager) txBroadcastLoop() {
   782  	for {
   783  		select {
   784  		case event := <-pm.txsCh:
   785  			pm.BroadcastTxs(event.Txs)
   786  
   787  		// Err() channel will be closed when unsubscribing.
   788  		case <-pm.txsSub.Err():
   789  			return
   790  		}
   791  	}
   792  }
   793  
   794  // NodeInfo represents a short summary of the Ethereum sub-protocol metadata
   795  // known about the host peer.
   796  type NodeInfo struct {
   797  	Network    uint64              `json:"network"`    // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3, Rinkeby=4)
   798  	Difficulty *big.Int            `json:"difficulty"` // Total difficulty of the host's blockchain
   799  	Genesis    common.Hash         `json:"genesis"`    // SHA3 hash of the host's genesis block
   800  	Config     *params.ChainConfig `json:"config"`     // Chain configuration for the fork rules
   801  	Head       common.Hash         `json:"head"`       // SHA3 hash of the host's best owned block
   802  }
   803  
   804  // NodeInfo retrieves some protocol metadata about the running host node.
   805  func (pm *ProtocolManager) NodeInfo() *NodeInfo {
   806  	currentBlock := pm.blockchain.CurrentBlock()
   807  	return &NodeInfo{
   808  		Network:    pm.networkID,
   809  		Difficulty: pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
   810  		Genesis:    pm.blockchain.Genesis().Hash(),
   811  		Config:     pm.blockchain.Config(),
   812  		Head:       currentBlock.Hash(),
   813  	}
   814  }