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