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