github.com/snowblossomcoin/go-ethereum@v1.9.25/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  
    70  	checkpointNumber uint64      // Block number for the sync progress validator to cross reference
    71  	checkpointHash   common.Hash // Block hash for the sync progress validator to cross reference
    72  
    73  	txpool     txPool
    74  	blockchain *core.BlockChain
    75  	chaindb    ethdb.Database
    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) (*ProtocolManager, error) {
   105  	// Create the protocol manager with the base fields
   106  	manager := &ProtocolManager{
   107  		networkID:  networkID,
   108  		forkFilter: forkid.NewFilter(blockchain),
   109  		eventMux:   mux,
   110  		txpool:     txpool,
   111  		blockchain: blockchain,
   112  		chaindb:    chaindb,
   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(false, nil, blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, nil, 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  	forkID := forkid.NewID(pm.blockchain.Config(), pm.blockchain.Genesis().Hash(), pm.blockchain.CurrentHeader().Number.Uint64())
   323  	if err := p.Handshake(pm.networkID, td, hash, genesis.Hash(), forkID, pm.forkFilter); err != nil {
   324  		p.Log().Debug("Ethereum handshake failed", "err", err)
   325  		return err
   326  	}
   327  
   328  	// Register the peer locally
   329  	if err := pm.peers.Register(p, pm.removePeer); err != nil {
   330  		p.Log().Error("Ethereum peer registration failed", "err", err)
   331  		return err
   332  	}
   333  	defer pm.removePeer(p.id)
   334  
   335  	// Register the peer in the downloader. If the downloader considers it banned, we disconnect
   336  	if err := pm.downloader.RegisterPeer(p.id, p.version, p); err != nil {
   337  		return err
   338  	}
   339  	pm.chainSync.handlePeerEvent(p)
   340  
   341  	// Propagate existing transactions. new transactions appearing
   342  	// after this will be sent via broadcasts.
   343  	pm.syncTransactions(p)
   344  
   345  	// If we have a trusted CHT, reject all peers below that (avoid fast sync eclipse)
   346  	if pm.checkpointHash != (common.Hash{}) {
   347  		// Request the peer's checkpoint header for chain height/weight validation
   348  		if err := p.RequestHeadersByNumber(pm.checkpointNumber, 1, 0, false); err != nil {
   349  			return err
   350  		}
   351  		// Start a timer to disconnect if the peer doesn't reply in time
   352  		p.syncDrop = time.AfterFunc(syncChallengeTimeout, func() {
   353  			p.Log().Warn("Checkpoint challenge timed out, dropping", "addr", p.RemoteAddr(), "type", p.Name())
   354  			pm.removePeer(p.id)
   355  		})
   356  		// Make sure it's cleaned up if the peer dies off
   357  		defer func() {
   358  			if p.syncDrop != nil {
   359  				p.syncDrop.Stop()
   360  				p.syncDrop = nil
   361  			}
   362  		}()
   363  	}
   364  	// If we have any explicit whitelist block hashes, request them
   365  	for number := range pm.whitelist {
   366  		if err := p.RequestHeadersByNumber(number, 1, 0, false); err != nil {
   367  			return err
   368  		}
   369  	}
   370  	// Handle incoming messages until the connection is torn down
   371  	for {
   372  		if err := pm.handleMsg(p); err != nil {
   373  			p.Log().Debug("Ethereum message handling failed", "err", err)
   374  			return err
   375  		}
   376  	}
   377  }
   378  
   379  // handleMsg is invoked whenever an inbound message is received from a remote
   380  // peer. The remote connection is torn down upon returning any error.
   381  func (pm *ProtocolManager) handleMsg(p *peer) error {
   382  	// Read the next message from the remote peer, and ensure it's fully consumed
   383  	msg, err := p.rw.ReadMsg()
   384  	if err != nil {
   385  		return err
   386  	}
   387  	if msg.Size > protocolMaxMsgSize {
   388  		return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, protocolMaxMsgSize)
   389  	}
   390  	defer msg.Discard()
   391  
   392  	// Handle the message depending on its contents
   393  	switch {
   394  	case msg.Code == StatusMsg:
   395  		// Status messages should never arrive after the handshake
   396  		return errResp(ErrExtraStatusMsg, "uncontrolled status message")
   397  
   398  	// Block header query, collect the requested headers and reply
   399  	case msg.Code == GetBlockHeadersMsg:
   400  		// Decode the complex header query
   401  		var query getBlockHeadersData
   402  		if err := msg.Decode(&query); err != nil {
   403  			return errResp(ErrDecode, "%v: %v", msg, err)
   404  		}
   405  		hashMode := query.Origin.Hash != (common.Hash{})
   406  		first := true
   407  		maxNonCanonical := uint64(100)
   408  
   409  		// Gather headers until the fetch or network limits is reached
   410  		var (
   411  			bytes   common.StorageSize
   412  			headers []*types.Header
   413  			unknown bool
   414  		)
   415  		for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
   416  			// Retrieve the next header satisfying the query
   417  			var origin *types.Header
   418  			if hashMode {
   419  				if first {
   420  					first = false
   421  					origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash)
   422  					if origin != nil {
   423  						query.Origin.Number = origin.Number.Uint64()
   424  					}
   425  				} else {
   426  					origin = pm.blockchain.GetHeader(query.Origin.Hash, query.Origin.Number)
   427  				}
   428  			} else {
   429  				origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
   430  			}
   431  			if origin == nil {
   432  				break
   433  			}
   434  			headers = append(headers, origin)
   435  			bytes += estHeaderRlpSize
   436  
   437  			// Advance to the next header of the query
   438  			switch {
   439  			case hashMode && query.Reverse:
   440  				// Hash based traversal towards the genesis block
   441  				ancestor := query.Skip + 1
   442  				if ancestor == 0 {
   443  					unknown = true
   444  				} else {
   445  					query.Origin.Hash, query.Origin.Number = pm.blockchain.GetAncestor(query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical)
   446  					unknown = (query.Origin.Hash == common.Hash{})
   447  				}
   448  			case hashMode && !query.Reverse:
   449  				// Hash based traversal towards the leaf block
   450  				var (
   451  					current = origin.Number.Uint64()
   452  					next    = current + query.Skip + 1
   453  				)
   454  				if next <= current {
   455  					infos, _ := json.MarshalIndent(p.Peer.Info(), "", "  ")
   456  					p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos)
   457  					unknown = true
   458  				} else {
   459  					if header := pm.blockchain.GetHeaderByNumber(next); header != nil {
   460  						nextHash := header.Hash()
   461  						expOldHash, _ := pm.blockchain.GetAncestor(nextHash, next, query.Skip+1, &maxNonCanonical)
   462  						if expOldHash == query.Origin.Hash {
   463  							query.Origin.Hash, query.Origin.Number = nextHash, next
   464  						} else {
   465  							unknown = true
   466  						}
   467  					} else {
   468  						unknown = true
   469  					}
   470  				}
   471  			case query.Reverse:
   472  				// Number based traversal towards the genesis block
   473  				if query.Origin.Number >= query.Skip+1 {
   474  					query.Origin.Number -= query.Skip + 1
   475  				} else {
   476  					unknown = true
   477  				}
   478  
   479  			case !query.Reverse:
   480  				// Number based traversal towards the leaf block
   481  				query.Origin.Number += query.Skip + 1
   482  			}
   483  		}
   484  		return p.SendBlockHeaders(headers)
   485  
   486  	case msg.Code == BlockHeadersMsg:
   487  		// A batch of headers arrived to one of our previous requests
   488  		var headers []*types.Header
   489  		if err := msg.Decode(&headers); err != nil {
   490  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   491  		}
   492  		// If no headers were received, but we're expencting a checkpoint header, consider it that
   493  		if len(headers) == 0 && p.syncDrop != nil {
   494  			// Stop the timer either way, decide later to drop or not
   495  			p.syncDrop.Stop()
   496  			p.syncDrop = nil
   497  
   498  			// If we're doing a fast sync, we must enforce the checkpoint block to avoid
   499  			// eclipse attacks. Unsynced nodes are welcome to connect after we're done
   500  			// joining the network
   501  			if atomic.LoadUint32(&pm.fastSync) == 1 {
   502  				p.Log().Warn("Dropping unsynced node during fast sync", "addr", p.RemoteAddr(), "type", p.Name())
   503  				return errors.New("unsynced node cannot serve fast sync")
   504  			}
   505  		}
   506  		// Filter out any explicitly requested headers, deliver the rest to the downloader
   507  		filter := len(headers) == 1
   508  		if filter {
   509  			// If it's a potential sync progress check, validate the content and advertised chain weight
   510  			if p.syncDrop != nil && headers[0].Number.Uint64() == pm.checkpointNumber {
   511  				// Disable the sync drop timer
   512  				p.syncDrop.Stop()
   513  				p.syncDrop = nil
   514  
   515  				// Validate the header and either drop the peer or continue
   516  				if headers[0].Hash() != pm.checkpointHash {
   517  					return errors.New("checkpoint hash mismatch")
   518  				}
   519  				return nil
   520  			}
   521  			// Otherwise if it's a whitelisted block, validate against the set
   522  			if want, ok := pm.whitelist[headers[0].Number.Uint64()]; ok {
   523  				if hash := headers[0].Hash(); want != hash {
   524  					p.Log().Info("Whitelist mismatch, dropping peer", "number", headers[0].Number.Uint64(), "hash", hash, "want", want)
   525  					return errors.New("whitelist block mismatch")
   526  				}
   527  				p.Log().Debug("Whitelist block verified", "number", headers[0].Number.Uint64(), "hash", want)
   528  			}
   529  			// Irrelevant of the fork checks, send the header to the fetcher just in case
   530  			headers = pm.blockFetcher.FilterHeaders(p.id, headers, time.Now())
   531  		}
   532  		if len(headers) > 0 || !filter {
   533  			err := pm.downloader.DeliverHeaders(p.id, headers)
   534  			if err != nil {
   535  				log.Debug("Failed to deliver headers", "err", err)
   536  			}
   537  		}
   538  
   539  	case msg.Code == GetBlockBodiesMsg:
   540  		// Decode the retrieval message
   541  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   542  		if _, err := msgStream.List(); err != nil {
   543  			return err
   544  		}
   545  		// Gather blocks until the fetch or network limits is reached
   546  		var (
   547  			hash   common.Hash
   548  			bytes  int
   549  			bodies []rlp.RawValue
   550  		)
   551  		for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
   552  			// Retrieve the hash of the next block
   553  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   554  				break
   555  			} else if err != nil {
   556  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   557  			}
   558  			// Retrieve the requested block body, stopping if enough was found
   559  			if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
   560  				bodies = append(bodies, data)
   561  				bytes += len(data)
   562  			}
   563  		}
   564  		return p.SendBlockBodiesRLP(bodies)
   565  
   566  	case msg.Code == BlockBodiesMsg:
   567  		// A batch of block bodies arrived to one of our previous requests
   568  		var request blockBodiesData
   569  		if err := msg.Decode(&request); err != nil {
   570  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   571  		}
   572  		// Deliver them all to the downloader for queuing
   573  		transactions := make([][]*types.Transaction, len(request))
   574  		uncles := make([][]*types.Header, len(request))
   575  
   576  		for i, body := range request {
   577  			transactions[i] = body.Transactions
   578  			uncles[i] = body.Uncles
   579  		}
   580  		// Filter out any explicitly requested bodies, deliver the rest to the downloader
   581  		filter := len(transactions) > 0 || len(uncles) > 0
   582  		if filter {
   583  			transactions, uncles = pm.blockFetcher.FilterBodies(p.id, transactions, uncles, time.Now())
   584  		}
   585  		if len(transactions) > 0 || len(uncles) > 0 || !filter {
   586  			err := pm.downloader.DeliverBodies(p.id, transactions, uncles)
   587  			if err != nil {
   588  				log.Debug("Failed to deliver bodies", "err", err)
   589  			}
   590  		}
   591  
   592  	case p.version >= eth63 && msg.Code == GetNodeDataMsg:
   593  		// Decode the retrieval message
   594  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   595  		if _, err := msgStream.List(); err != nil {
   596  			return err
   597  		}
   598  		// Gather state data until the fetch or network limits is reached
   599  		var (
   600  			hash  common.Hash
   601  			bytes int
   602  			data  [][]byte
   603  		)
   604  		for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
   605  			// Retrieve the hash of the next state entry
   606  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   607  				break
   608  			} else if err != nil {
   609  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   610  			}
   611  			// Retrieve the requested state entry, stopping if enough was found
   612  			// todo now the code and trienode is mixed in the protocol level,
   613  			// separate these two types.
   614  			if !pm.downloader.SyncBloomContains(hash[:]) {
   615  				// Only lookup the trie node if there's chance that we actually have it
   616  				continue
   617  			}
   618  			entry, err := pm.blockchain.TrieNode(hash)
   619  			if len(entry) == 0 || err != nil {
   620  				// Read the contract code with prefix only to save unnecessary lookups.
   621  				entry, err = pm.blockchain.ContractCodeWithPrefix(hash)
   622  			}
   623  			if err == nil && len(entry) > 0 {
   624  				data = append(data, entry)
   625  				bytes += len(entry)
   626  			}
   627  		}
   628  		return p.SendNodeData(data)
   629  
   630  	case p.version >= eth63 && msg.Code == NodeDataMsg:
   631  		// A batch of node state data arrived to one of our previous requests
   632  		var data [][]byte
   633  		if err := msg.Decode(&data); err != nil {
   634  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   635  		}
   636  		// Deliver all to the downloader
   637  		if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
   638  			log.Debug("Failed to deliver node state data", "err", err)
   639  		}
   640  
   641  	case p.version >= eth63 && msg.Code == GetReceiptsMsg:
   642  		// Decode the retrieval message
   643  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   644  		if _, err := msgStream.List(); err != nil {
   645  			return err
   646  		}
   647  		// Gather state data until the fetch or network limits is reached
   648  		var (
   649  			hash     common.Hash
   650  			bytes    int
   651  			receipts []rlp.RawValue
   652  		)
   653  		for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
   654  			// Retrieve the hash of the next block
   655  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   656  				break
   657  			} else if err != nil {
   658  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   659  			}
   660  			// Retrieve the requested block's receipts, skipping if unknown to us
   661  			results := pm.blockchain.GetReceiptsByHash(hash)
   662  			if results == nil {
   663  				if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
   664  					continue
   665  				}
   666  			}
   667  			// If known, encode and queue for response packet
   668  			if encoded, err := rlp.EncodeToBytes(results); err != nil {
   669  				log.Error("Failed to encode receipt", "err", err)
   670  			} else {
   671  				receipts = append(receipts, encoded)
   672  				bytes += len(encoded)
   673  			}
   674  		}
   675  		return p.SendReceiptsRLP(receipts)
   676  
   677  	case p.version >= eth63 && msg.Code == ReceiptsMsg:
   678  		// A batch of receipts arrived to one of our previous requests
   679  		var receipts [][]*types.Receipt
   680  		if err := msg.Decode(&receipts); err != nil {
   681  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   682  		}
   683  		// Deliver all to the downloader
   684  		if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
   685  			log.Debug("Failed to deliver receipts", "err", err)
   686  		}
   687  
   688  	case msg.Code == NewBlockHashesMsg:
   689  		var announces newBlockHashesData
   690  		if err := msg.Decode(&announces); err != nil {
   691  			return errResp(ErrDecode, "%v: %v", msg, err)
   692  		}
   693  		// Mark the hashes as present at the remote node
   694  		for _, block := range announces {
   695  			p.MarkBlock(block.Hash)
   696  		}
   697  		// Schedule all the unknown hashes for retrieval
   698  		unknown := make(newBlockHashesData, 0, len(announces))
   699  		for _, block := range announces {
   700  			if !pm.blockchain.HasBlock(block.Hash, block.Number) {
   701  				unknown = append(unknown, block)
   702  			}
   703  		}
   704  		for _, block := range unknown {
   705  			pm.blockFetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies)
   706  		}
   707  
   708  	case msg.Code == NewBlockMsg:
   709  		// Retrieve and decode the propagated block
   710  		var request newBlockData
   711  		if err := msg.Decode(&request); err != nil {
   712  			return errResp(ErrDecode, "%v: %v", msg, err)
   713  		}
   714  		if hash := types.CalcUncleHash(request.Block.Uncles()); hash != request.Block.UncleHash() {
   715  			log.Warn("Propagated block has invalid uncles", "have", hash, "exp", request.Block.UncleHash())
   716  			break // TODO(karalabe): return error eventually, but wait a few releases
   717  		}
   718  		if hash := types.DeriveSha(request.Block.Transactions(), trie.NewStackTrie(nil)); hash != request.Block.TxHash() {
   719  			log.Warn("Propagated block has invalid body", "have", hash, "exp", request.Block.TxHash())
   720  			break // TODO(karalabe): return error eventually, but wait a few releases
   721  		}
   722  		if err := request.sanityCheck(); err != nil {
   723  			return err
   724  		}
   725  		request.Block.ReceivedAt = msg.ReceivedAt
   726  		request.Block.ReceivedFrom = p
   727  
   728  		// Mark the peer as owning the block and schedule it for import
   729  		p.MarkBlock(request.Block.Hash())
   730  		pm.blockFetcher.Enqueue(p.id, request.Block)
   731  
   732  		// Assuming the block is importable by the peer, but possibly not yet done so,
   733  		// calculate the head hash and TD that the peer truly must have.
   734  		var (
   735  			trueHead = request.Block.ParentHash()
   736  			trueTD   = new(big.Int).Sub(request.TD, request.Block.Difficulty())
   737  		)
   738  		// Update the peer's total difficulty if better than the previous
   739  		if _, td := p.Head(); trueTD.Cmp(td) > 0 {
   740  			p.SetHead(trueHead, trueTD)
   741  			pm.chainSync.handlePeerEvent(p)
   742  		}
   743  
   744  	case msg.Code == NewPooledTransactionHashesMsg && p.version >= eth65:
   745  		// New transaction announcement arrived, make sure we have
   746  		// a valid and fresh chain to handle them
   747  		if atomic.LoadUint32(&pm.acceptTxs) == 0 {
   748  			break
   749  		}
   750  		var hashes []common.Hash
   751  		if err := msg.Decode(&hashes); err != nil {
   752  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   753  		}
   754  		// Schedule all the unknown hashes for retrieval
   755  		for _, hash := range hashes {
   756  			p.MarkTransaction(hash)
   757  		}
   758  		pm.txFetcher.Notify(p.id, hashes)
   759  
   760  	case msg.Code == GetPooledTransactionsMsg && p.version >= eth65:
   761  		// Decode the retrieval message
   762  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   763  		if _, err := msgStream.List(); err != nil {
   764  			return err
   765  		}
   766  		// Gather transactions until the fetch or network limits is reached
   767  		var (
   768  			hash   common.Hash
   769  			bytes  int
   770  			hashes []common.Hash
   771  			txs    []rlp.RawValue
   772  		)
   773  		for bytes < softResponseLimit {
   774  			// Retrieve the hash of the next block
   775  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   776  				break
   777  			} else if err != nil {
   778  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   779  			}
   780  			// Retrieve the requested transaction, skipping if unknown to us
   781  			tx := pm.txpool.Get(hash)
   782  			if tx == nil {
   783  				continue
   784  			}
   785  			// If known, encode and queue for response packet
   786  			if encoded, err := rlp.EncodeToBytes(tx); err != nil {
   787  				log.Error("Failed to encode transaction", "err", err)
   788  			} else {
   789  				hashes = append(hashes, hash)
   790  				txs = append(txs, encoded)
   791  				bytes += len(encoded)
   792  			}
   793  		}
   794  		return p.SendPooledTransactionsRLP(hashes, txs)
   795  
   796  	case msg.Code == TransactionMsg || (msg.Code == PooledTransactionsMsg && p.version >= eth65):
   797  		// Transactions arrived, make sure we have a valid and fresh chain to handle them
   798  		if atomic.LoadUint32(&pm.acceptTxs) == 0 {
   799  			break
   800  		}
   801  		// Transactions can be processed, parse all of them and deliver to the pool
   802  		var txs []*types.Transaction
   803  		if err := msg.Decode(&txs); err != nil {
   804  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   805  		}
   806  		for i, tx := range txs {
   807  			// Validate and mark the remote transaction
   808  			if tx == nil {
   809  				return errResp(ErrDecode, "transaction %d is nil", i)
   810  			}
   811  			p.MarkTransaction(tx.Hash())
   812  		}
   813  		pm.txFetcher.Enqueue(p.id, txs, msg.Code == PooledTransactionsMsg)
   814  
   815  	default:
   816  		return errResp(ErrInvalidMsgCode, "%v", msg.Code)
   817  	}
   818  	return nil
   819  }
   820  
   821  // BroadcastBlock will either propagate a block to a subset of its peers, or
   822  // will only announce its availability (depending what's requested).
   823  func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
   824  	hash := block.Hash()
   825  	peers := pm.peers.PeersWithoutBlock(hash)
   826  
   827  	// If propagation is requested, send to a subset of the peer
   828  	if propagate {
   829  		// Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
   830  		var td *big.Int
   831  		if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
   832  			td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
   833  		} else {
   834  			log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
   835  			return
   836  		}
   837  		// Send the block to a subset of our peers
   838  		transfer := peers[:int(math.Sqrt(float64(len(peers))))]
   839  		for _, peer := range transfer {
   840  			peer.AsyncSendNewBlock(block, td)
   841  		}
   842  		log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   843  		return
   844  	}
   845  	// Otherwise if the block is indeed in out own chain, announce it
   846  	if pm.blockchain.HasBlock(hash, block.NumberU64()) {
   847  		for _, peer := range peers {
   848  			peer.AsyncSendNewBlockHash(block)
   849  		}
   850  		log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   851  	}
   852  }
   853  
   854  // BroadcastTransactions will propagate a batch of transactions to all peers which are not known to
   855  // already have the given transaction.
   856  func (pm *ProtocolManager) BroadcastTransactions(txs types.Transactions, propagate bool) {
   857  	var (
   858  		txset = make(map[*peer][]common.Hash)
   859  		annos = make(map[*peer][]common.Hash)
   860  	)
   861  	// Broadcast transactions to a batch of peers not knowing about it
   862  	if propagate {
   863  		for _, tx := range txs {
   864  			peers := pm.peers.PeersWithoutTx(tx.Hash())
   865  
   866  			// Send the block to a subset of our peers
   867  			transfer := peers[:int(math.Sqrt(float64(len(peers))))]
   868  			for _, peer := range transfer {
   869  				txset[peer] = append(txset[peer], tx.Hash())
   870  			}
   871  			log.Trace("Broadcast transaction", "hash", tx.Hash(), "recipients", len(peers))
   872  		}
   873  		for peer, hashes := range txset {
   874  			peer.AsyncSendTransactions(hashes)
   875  		}
   876  		return
   877  	}
   878  	// Otherwise only broadcast the announcement to peers
   879  	for _, tx := range txs {
   880  		peers := pm.peers.PeersWithoutTx(tx.Hash())
   881  		for _, peer := range peers {
   882  			annos[peer] = append(annos[peer], tx.Hash())
   883  		}
   884  	}
   885  	for peer, hashes := range annos {
   886  		if peer.version >= eth65 {
   887  			peer.AsyncSendPooledTransactionHashes(hashes)
   888  		} else {
   889  			peer.AsyncSendTransactions(hashes)
   890  		}
   891  	}
   892  }
   893  
   894  // minedBroadcastLoop sends mined blocks to connected peers.
   895  func (pm *ProtocolManager) minedBroadcastLoop() {
   896  	defer pm.wg.Done()
   897  
   898  	for obj := range pm.minedBlockSub.Chan() {
   899  		if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
   900  			pm.BroadcastBlock(ev.Block, true)  // First propagate block to peers
   901  			pm.BroadcastBlock(ev.Block, false) // Only then announce to the rest
   902  		}
   903  	}
   904  }
   905  
   906  // txBroadcastLoop announces new transactions to connected peers.
   907  func (pm *ProtocolManager) txBroadcastLoop() {
   908  	defer pm.wg.Done()
   909  
   910  	for {
   911  		select {
   912  		case event := <-pm.txsCh:
   913  			// For testing purpose only, disable propagation
   914  			if pm.broadcastTxAnnouncesOnly {
   915  				pm.BroadcastTransactions(event.Txs, false)
   916  				continue
   917  			}
   918  			pm.BroadcastTransactions(event.Txs, true)  // First propagate transactions to peers
   919  			pm.BroadcastTransactions(event.Txs, false) // Only then announce to the rest
   920  
   921  		case <-pm.txsSub.Err():
   922  			return
   923  		}
   924  	}
   925  }
   926  
   927  // NodeInfo represents a short summary of the Ethereum sub-protocol metadata
   928  // known about the host peer.
   929  type NodeInfo struct {
   930  	Network    uint64              `json:"network"`    // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3, Rinkeby=4)
   931  	Difficulty *big.Int            `json:"difficulty"` // Total difficulty of the host's blockchain
   932  	Genesis    common.Hash         `json:"genesis"`    // SHA3 hash of the host's genesis block
   933  	Config     *params.ChainConfig `json:"config"`     // Chain configuration for the fork rules
   934  	Head       common.Hash         `json:"head"`       // SHA3 hash of the host's best owned block
   935  }
   936  
   937  // NodeInfo retrieves some protocol metadata about the running host node.
   938  func (pm *ProtocolManager) NodeInfo() *NodeInfo {
   939  	currentBlock := pm.blockchain.CurrentBlock()
   940  	return &NodeInfo{
   941  		Network:    pm.networkID,
   942  		Difficulty: pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
   943  		Genesis:    pm.blockchain.Genesis().Hash(),
   944  		Config:     pm.blockchain.Config(),
   945  		Head:       currentBlock.Hash(),
   946  	}
   947  }