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