github.com/codingfuture/orig-energi3@v0.8.4/eth/handler.go (about)

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