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