github.com/halybang/go-ethereum@v1.0.5-0.20180325041310-3b262bc1367c/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/wanchain/go-wanchain/common"
    30  	"github.com/wanchain/go-wanchain/consensus"
    31  	"github.com/wanchain/go-wanchain/core"
    32  	"github.com/wanchain/go-wanchain/core/types"
    33  	"github.com/wanchain/go-wanchain/eth/downloader"
    34  	"github.com/wanchain/go-wanchain/eth/fetcher"
    35  	"github.com/wanchain/go-wanchain/ethdb"
    36  	"github.com/wanchain/go-wanchain/event"
    37  	"github.com/wanchain/go-wanchain/log"
    38  	"github.com/wanchain/go-wanchain/p2p"
    39  	"github.com/wanchain/go-wanchain/p2p/discover"
    40  	"github.com/wanchain/go-wanchain/params"
    41  	"github.com/wanchain/go-wanchain/rlp"
    42  )
    43  
    44  const (
    45  	softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data.
    46  	estHeaderRlpSize  = 500             // Approximate size of an RLP encoded block header
    47  
    48  	// txChanSize is the size of channel listening to TxPreEvent.
    49  	// The number is referenced from the size of tx pool.
    50  	txChanSize = 4096
    51  )
    52  
    53  var (
    54  	daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge
    55  )
    56  
    57  // errIncompatibleConfig is returned if the requested protocols and configs are
    58  // not compatible (low protocol version restrictions and high requirements).
    59  var errIncompatibleConfig = errors.New("incompatible configuration")
    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  	txpool      txPool
    72  	blockchain  *core.BlockChain
    73  	chaindb     ethdb.Database
    74  	chainconfig *params.ChainConfig
    75  	maxPeers    int
    76  
    77  	downloader *downloader.Downloader
    78  	fetcher    *fetcher.Fetcher
    79  	peers      *peerSet
    80  
    81  	SubProtocols []p2p.Protocol
    82  
    83  	eventMux      *event.TypeMux
    84  	txCh          chan core.TxPreEvent
    85  	txSub         event.Subscription
    86  	minedBlockSub *event.TypeMuxSubscription
    87  
    88  	// channels for fetcher, syncer, txsyncLoop
    89  	newPeerCh   chan *peer
    90  	txsyncCh    chan *txsync
    91  	quitSync    chan struct{}
    92  	noMorePeers chan struct{}
    93  
    94  	// wait group is used for graceful shutdowns during downloading
    95  	// and processing
    96  	wg sync.WaitGroup
    97  }
    98  
    99  // NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
   100  // with the ethereum network.
   101  func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, networkId uint64, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database) (*ProtocolManager, error) {
   102  	// Create the protocol manager with the base fields
   103  	manager := &ProtocolManager{
   104  		networkId:   networkId,
   105  		eventMux:    mux,
   106  		txpool:      txpool,
   107  		blockchain:  blockchain,
   108  		chaindb:     chaindb,
   109  		chainconfig: config,
   110  		peers:       newPeerSet(),
   111  		newPeerCh:   make(chan *peer),
   112  		noMorePeers: make(chan struct{}),
   113  		txsyncCh:    make(chan *txsync),
   114  		quitSync:    make(chan struct{}),
   115  	}
   116  	// Figure out whether to allow fast sync or not
   117  	if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 {
   118  		log.Warn("Blockchain not empty, fast sync disabled")
   119  		mode = downloader.FullSync
   120  	}
   121  	if mode == downloader.FastSync {
   122  		manager.fastSync = uint32(1)
   123  	}
   124  	// Initiate a sub-protocol for every implemented version we can handle
   125  	manager.SubProtocols = make([]p2p.Protocol, 0, len(ProtocolVersions))
   126  	for i, version := range ProtocolVersions {
   127  		// Skip protocol version if incompatible with the mode of operation
   128  		if mode == downloader.FastSync && version < eth63 {
   129  			continue
   130  		}
   131  		// Compatible; initialise the sub-protocol
   132  		version := version // Closure for the run
   133  		manager.SubProtocols = append(manager.SubProtocols, p2p.Protocol{
   134  			Name:    ProtocolName,
   135  			Version: version,
   136  			Length:  ProtocolLengths[i],
   137  			Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
   138  				peer := manager.newPeer(int(version), p, rw)
   139  				select {
   140  				case manager.newPeerCh <- peer:
   141  					manager.wg.Add(1)
   142  					defer manager.wg.Done()
   143  					return manager.handle(peer)
   144  				case <-manager.quitSync:
   145  					return p2p.DiscQuitting
   146  				}
   147  			},
   148  			NodeInfo: func() interface{} {
   149  				return manager.NodeInfo()
   150  			},
   151  			PeerInfo: func(id discover.NodeID) interface{} {
   152  				if p := manager.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil {
   153  					return p.Info()
   154  				}
   155  				return nil
   156  			},
   157  		})
   158  	}
   159  	if len(manager.SubProtocols) == 0 {
   160  		return nil, errIncompatibleConfig
   161  	}
   162  	// Construct the different synchronisation mechanisms
   163  	manager.downloader = downloader.New(mode, chaindb, manager.eventMux, blockchain, nil, manager.removePeer)
   164  
   165  	validator := func(header *types.Header) error {
   166  		return engine.VerifyHeader(blockchain, header, true)
   167  	}
   168  	heighter := func() uint64 {
   169  		return blockchain.CurrentBlock().NumberU64()
   170  	}
   171  	inserter := func(blocks types.Blocks) (int, error) {
   172  		// If fast sync is running, deny importing weird blocks
   173  		if atomic.LoadUint32(&manager.fastSync) == 1 {
   174  			log.Warn("Discarded bad propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
   175  			return 0, nil
   176  		}
   177  		atomic.StoreUint32(&manager.acceptTxs, 1) // Mark initial sync done on any fetcher import
   178  		return manager.blockchain.InsertChain(blocks)
   179  	}
   180  	manager.fetcher = fetcher.New(blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, inserter, manager.removePeer)
   181  
   182  	return manager, nil
   183  }
   184  
   185  func (pm *ProtocolManager) removePeer(id string) {
   186  	// Short circuit if the peer was already removed
   187  	peer := pm.peers.Peer(id)
   188  	if peer == nil {
   189  		return
   190  	}
   191  	log.Debug("Removing Wanchain peer", "peer", id)
   192  
   193  	// Unregister the peer from the downloader and Ethereum peer set
   194  	pm.downloader.UnregisterPeer(id)
   195  	if err := pm.peers.Unregister(id); err != nil {
   196  		log.Error("Peer removal failed", "peer", id, "err", err)
   197  	}
   198  	// Hard disconnect at the networking layer
   199  	if peer != nil {
   200  		peer.Peer.Disconnect(p2p.DiscUselessPeer)
   201  	}
   202  }
   203  
   204  func (pm *ProtocolManager) Start(maxPeers int) {
   205  	pm.maxPeers = maxPeers
   206  
   207  	// broadcast transactions
   208  	pm.txCh = make(chan core.TxPreEvent, txChanSize)
   209  	pm.txSub = pm.txpool.SubscribeTxPreEvent(pm.txCh)
   210  	go pm.txBroadcastLoop()
   211  
   212  	// broadcast mined blocks
   213  	pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
   214  	go pm.minedBroadcastLoop()
   215  
   216  	// start sync handlers
   217  	go pm.syncer()
   218  	go pm.txsyncLoop()
   219  }
   220  
   221  func (pm *ProtocolManager) Stop() {
   222  	log.Info("Stopping Wanchain protocol")
   223  
   224  	pm.txSub.Unsubscribe()         // quits txBroadcastLoop
   225  	pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
   226  
   227  	// Quit the sync loop.
   228  	// After this send has completed, no new peers will be accepted.
   229  	pm.noMorePeers <- struct{}{}
   230  
   231  	// Quit fetcher, txsyncLoop.
   232  	close(pm.quitSync)
   233  
   234  	// Disconnect existing sessions.
   235  	// This also closes the gate for any new registrations on the peer set.
   236  	// sessions which are already established but not added to pm.peers yet
   237  	// will exit when they try to register.
   238  	pm.peers.Close()
   239  
   240  	// Wait for all peer handler goroutines and the loops to come down.
   241  	pm.wg.Wait()
   242  
   243  	log.Info("Wanchain protocol stopped")
   244  }
   245  
   246  func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
   247  	return newPeer(pv, p, newMeteredMsgWriter(rw))
   248  }
   249  
   250  // handle is the callback invoked to manage the life cycle of an eth peer. When
   251  // this function terminates, the peer is disconnected.
   252  func (pm *ProtocolManager) handle(p *peer) error {
   253  	if pm.peers.Len() >= pm.maxPeers {
   254  		return p2p.DiscTooManyPeers
   255  	}
   256  	p.Log().Debug("Wanchain peer connected", "name", p.Name())
   257  
   258  	// Execute the Ethereum handshake
   259  	td, head, genesis := pm.blockchain.Status()
   260  	if err := p.Handshake(pm.networkId, td, head, genesis); err != nil {
   261  		p.Log().Debug("Wanchain handshake failed", "err", err)
   262  		return err
   263  	}
   264  	if rw, ok := p.rw.(*meteredMsgReadWriter); ok {
   265  		rw.Init(p.version)
   266  	}
   267  	// Register the peer locally
   268  	if err := pm.peers.Register(p); err != nil {
   269  		p.Log().Error("Wanchain peer registration failed", "err", err)
   270  		return err
   271  	}
   272  	defer pm.removePeer(p.id)
   273  
   274  	// Register the peer in the downloader. If the downloader considers it banned, we disconnect
   275  	if err := pm.downloader.RegisterPeer(p.id, p.version, p); err != nil {
   276  		return err
   277  	}
   278  	// Propagate existing transactions. new transactions appearing
   279  	// after this will be sent via broadcasts.
   280  	pm.syncTransactions(p)
   281  
   282  	// If we're DAO hard-fork aware, validate any remote peer with regard to the hard-fork
   283  	//if daoBlock := pm.chainconfig.DAOForkBlock; daoBlock != nil {
   284  	//	// Request the peer's DAO fork header for extra-data validation
   285  	//	if err := p.RequestHeadersByNumber(daoBlock.Uint64(), 1, 0, false); err != nil {
   286  	//		return err
   287  	//	}
   288  	//	// Start a timer to disconnect if the peer doesn't reply in time
   289  	//	p.forkDrop = time.AfterFunc(daoChallengeTimeout, func() {
   290  	//		p.Log().Debug("Timed out DAO fork-check, dropping")
   291  	//		pm.removePeer(p.id)
   292  	//	})
   293  	//	// Make sure it's cleaned up if the peer dies off
   294  	//	defer func() {
   295  	//		if p.forkDrop != nil {
   296  	//			p.forkDrop.Stop()
   297  	//			p.forkDrop = nil
   298  	//		}
   299  	//	}()
   300  	//}
   301  	// main loop. handle incoming messages.
   302  	for {
   303  		if err := pm.handleMsg(p); err != nil {
   304  			p.Log().Debug("Wanchain message handling failed", "err", err)
   305  			return err
   306  		}
   307  	}
   308  }
   309  
   310  // handleMsg is invoked whenever an inbound message is received from a remote
   311  // peer. The remote connection is torn down upon returning any error.
   312  func (pm *ProtocolManager) handleMsg(p *peer) error {
   313  	// Read the next message from the remote peer, and ensure it's fully consumed
   314  	msg, err := p.rw.ReadMsg()
   315  	if err != nil {
   316  		return err
   317  	}
   318  	if msg.Size > ProtocolMaxMsgSize {
   319  		return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
   320  	}
   321  	defer msg.Discard()
   322  
   323  	// Handle the message depending on its contents
   324  	switch {
   325  	case msg.Code == StatusMsg:
   326  		// Status messages should never arrive after the handshake
   327  		return errResp(ErrExtraStatusMsg, "uncontrolled status message")
   328  
   329  	// Block header query, collect the requested headers and reply
   330  	case msg.Code == GetBlockHeadersMsg:
   331  		// Decode the complex header query
   332  		var query getBlockHeadersData
   333  		if err := msg.Decode(&query); err != nil {
   334  			return errResp(ErrDecode, "%v: %v", msg, err)
   335  		}
   336  		hashMode := query.Origin.Hash != (common.Hash{})
   337  
   338  		// Gather headers until the fetch or network limits is reached
   339  		var (
   340  			bytes   common.StorageSize
   341  			headers []*types.Header
   342  			unknown bool
   343  		)
   344  		for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch {
   345  			// Retrieve the next header satisfying the query
   346  			var origin *types.Header
   347  			if hashMode {
   348  				origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash)
   349  			} else {
   350  				origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
   351  			}
   352  			if origin == nil {
   353  				break
   354  			}
   355  			number := origin.Number.Uint64()
   356  			headers = append(headers, origin)
   357  			bytes += estHeaderRlpSize
   358  
   359  			// Advance to the next header of the query
   360  			switch {
   361  			case query.Origin.Hash != (common.Hash{}) && query.Reverse:
   362  				// Hash based traversal towards the genesis block
   363  				for i := 0; i < int(query.Skip)+1; i++ {
   364  					if header := pm.blockchain.GetHeader(query.Origin.Hash, number); header != nil {
   365  						query.Origin.Hash = header.ParentHash
   366  						number--
   367  					} else {
   368  						unknown = true
   369  						break
   370  					}
   371  				}
   372  			case query.Origin.Hash != (common.Hash{}) && !query.Reverse:
   373  				// Hash based traversal towards the leaf block
   374  				var (
   375  					current = origin.Number.Uint64()
   376  					next    = current + query.Skip + 1
   377  				)
   378  				if next <= current {
   379  					infos, _ := json.MarshalIndent(p.Peer.Info(), "", "  ")
   380  					p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos)
   381  					unknown = true
   382  				} else {
   383  					if header := pm.blockchain.GetHeaderByNumber(next); header != nil {
   384  						if pm.blockchain.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash {
   385  							query.Origin.Hash = header.Hash()
   386  						} else {
   387  							unknown = true
   388  						}
   389  					} else {
   390  						unknown = true
   391  					}
   392  				}
   393  			case query.Reverse:
   394  				// Number based traversal towards the genesis block
   395  				if query.Origin.Number >= query.Skip+1 {
   396  					query.Origin.Number -= (query.Skip + 1)
   397  				} else {
   398  					unknown = true
   399  				}
   400  
   401  			case !query.Reverse:
   402  				// Number based traversal towards the leaf block
   403  				query.Origin.Number += (query.Skip + 1)
   404  			}
   405  		}
   406  		return p.SendBlockHeaders(headers)
   407  
   408  	case msg.Code == BlockHeadersMsg:
   409  		// A batch of headers arrived to one of our previous requests
   410  		var headers []*types.Header
   411  		if err := msg.Decode(&headers); err != nil {
   412  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   413  		}
   414  
   415  		// If no headers were received, but we're expending a DAO fork check, maybe it's that
   416  		//if len(headers) == 0 && p.forkDrop != nil {
   417  		//	// Possibly an empty reply to the fork header checks, sanity check TDs
   418  		//	verifyDAO := true
   419  		//
   420  		//	// If we already have a DAO header, we can check the peer's TD against it. If
   421  		//	// the peer's ahead of this, it too must have a reply to the DAO check
   422  		//	//if daoHeader := pm.blockchain.GetHeaderByNumber(pm.chainconfig.DAOForkBlock.Uint64()); daoHeader != nil {
   423  		//	//	if _, td := p.Head(); td.Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 {
   424  		//	//		verifyDAO = false
   425  		//	//	}
   426  		//	//}
   427  		//	// If we're seemingly on the same chain, disable the drop timer
   428  		//	if verifyDAO {
   429  		//		p.Log().Debug("Seems to be on the same side of the DAO fork")
   430  		//		p.forkDrop.Stop()
   431  		//		p.forkDrop = nil
   432  		//		return nil
   433  		//	}
   434  		//}
   435  		// Filter out any explicitly requested headers, deliver the rest to the downloader
   436  		filter := len(headers) == 1
   437  		if filter {
   438  			// If it's a potential DAO fork check, validate against the rules
   439  			//if p.forkDrop != nil && pm.chainconfig.DAOForkBlock.Cmp(headers[0].Number) == 0 {
   440  			//	// Disable the fork drop timer
   441  			//	p.forkDrop.Stop()
   442  			//	p.forkDrop = nil
   443  			//
   444  			//	// Validate the header and either drop the peer or continue
   445  			//	if err := misc.VerifyDAOHeaderExtraData(pm.chainconfig, headers[0]); err != nil {
   446  			//		p.Log().Debug("Verified to be on the other side of the DAO fork, dropping")
   447  			//		return err
   448  			//	}
   449  			//	p.Log().Debug("Verified to be on the same side of the DAO fork")
   450  			//	return nil
   451  			//}
   452  			// Irrelevant of the fork checks, send the header to the fetcher just in case
   453  			headers = pm.fetcher.FilterHeaders(p.id, headers, time.Now())
   454  		}
   455  
   456  		if len(headers) > 0 || !filter {
   457  			err := pm.downloader.DeliverHeaders(p.id, headers)
   458  			if err != nil {
   459  				log.Debug("Failed to deliver headers", "err", err)
   460  			}
   461  		}
   462  
   463  	case msg.Code == GetBlockBodiesMsg:
   464  		// Decode the retrieval message
   465  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   466  		if _, err := msgStream.List(); err != nil {
   467  			return err
   468  		}
   469  		// Gather blocks until the fetch or network limits is reached
   470  		var (
   471  			hash   common.Hash
   472  			bytes  int
   473  			bodies []rlp.RawValue
   474  		)
   475  		for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch {
   476  			// Retrieve the hash of the next block
   477  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   478  				break
   479  			} else if err != nil {
   480  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   481  			}
   482  			// Retrieve the requested block body, stopping if enough was found
   483  			if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
   484  				bodies = append(bodies, data)
   485  				bytes += len(data)
   486  			}
   487  		}
   488  		return p.SendBlockBodiesRLP(bodies)
   489  
   490  	case msg.Code == BlockBodiesMsg:
   491  		// A batch of block bodies arrived to one of our previous requests
   492  		var request blockBodiesData
   493  		if err := msg.Decode(&request); err != nil {
   494  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   495  		}
   496  		// Deliver them all to the downloader for queuing
   497  		trasactions := make([][]*types.Transaction, len(request))
   498  		uncles := make([][]*types.Header, len(request))
   499  
   500  		for i, body := range request {
   501  			trasactions[i] = body.Transactions
   502  			uncles[i] = body.Uncles
   503  		}
   504  		// Filter out any explicitly requested bodies, deliver the rest to the downloader
   505  		filter := len(trasactions) > 0 || len(uncles) > 0
   506  		if filter {
   507  			trasactions, uncles = pm.fetcher.FilterBodies(p.id, trasactions, uncles, time.Now())
   508  		}
   509  		if len(trasactions) > 0 || len(uncles) > 0 || !filter {
   510  			err := pm.downloader.DeliverBodies(p.id, trasactions, uncles)
   511  			if err != nil {
   512  				log.Debug("Failed to deliver bodies", "err", err)
   513  			}
   514  		}
   515  
   516  	case p.version >= eth63 && msg.Code == GetNodeDataMsg:
   517  		// Decode the retrieval message
   518  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   519  		if _, err := msgStream.List(); err != nil {
   520  			return err
   521  		}
   522  		// Gather state data until the fetch or network limits is reached
   523  		var (
   524  			hash  common.Hash
   525  			bytes int
   526  			data  [][]byte
   527  		)
   528  		for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch {
   529  			// Retrieve the hash of the next state entry
   530  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   531  				break
   532  			} else if err != nil {
   533  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   534  			}
   535  			// Retrieve the requested state entry, stopping if enough was found
   536  			if entry, err := pm.chaindb.Get(hash.Bytes()); err == nil {
   537  				data = append(data, entry)
   538  				bytes += len(entry)
   539  			}
   540  		}
   541  		return p.SendNodeData(data)
   542  
   543  	case p.version >= eth63 && msg.Code == NodeDataMsg:
   544  		// A batch of node state data arrived to one of our previous requests
   545  		var data [][]byte
   546  		if err := msg.Decode(&data); err != nil {
   547  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   548  		}
   549  		// Deliver all to the downloader
   550  		if err := pm.downloader.DeliverNodeData(p.id, data); err != nil {
   551  			log.Debug("Failed to deliver node state data", "err", err)
   552  		}
   553  
   554  	case p.version >= eth63 && msg.Code == GetReceiptsMsg:
   555  		// Decode the retrieval message
   556  		msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size))
   557  		if _, err := msgStream.List(); err != nil {
   558  			return err
   559  		}
   560  		// Gather state data until the fetch or network limits is reached
   561  		var (
   562  			hash     common.Hash
   563  			bytes    int
   564  			receipts []rlp.RawValue
   565  		)
   566  		for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch {
   567  			// Retrieve the hash of the next block
   568  			if err := msgStream.Decode(&hash); err == rlp.EOL {
   569  				break
   570  			} else if err != nil {
   571  				return errResp(ErrDecode, "msg %v: %v", msg, err)
   572  			}
   573  			// Retrieve the requested block's receipts, skipping if unknown to us
   574  			results := core.GetBlockReceipts(pm.chaindb, hash, core.GetBlockNumber(pm.chaindb, hash))
   575  			if results == nil {
   576  				if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash {
   577  					continue
   578  				}
   579  			}
   580  			// If known, encode and queue for response packet
   581  			if encoded, err := rlp.EncodeToBytes(results); err != nil {
   582  				log.Error("Failed to encode receipt", "err", err)
   583  			} else {
   584  				receipts = append(receipts, encoded)
   585  				bytes += len(encoded)
   586  			}
   587  		}
   588  		return p.SendReceiptsRLP(receipts)
   589  
   590  	case p.version >= eth63 && msg.Code == ReceiptsMsg:
   591  		// A batch of receipts arrived to one of our previous requests
   592  		var receipts [][]*types.Receipt
   593  		if err := msg.Decode(&receipts); err != nil {
   594  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   595  		}
   596  		// Deliver all to the downloader
   597  		if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil {
   598  			log.Debug("Failed to deliver receipts", "err", err)
   599  		}
   600  
   601  	case msg.Code == NewBlockHashesMsg:
   602  		var announces newBlockHashesData
   603  		if err := msg.Decode(&announces); err != nil {
   604  			return errResp(ErrDecode, "%v: %v", msg, err)
   605  		}
   606  		// Mark the hashes as present at the remote node
   607  		for _, block := range announces {
   608  			p.MarkBlock(block.Hash)
   609  		}
   610  		// Schedule all the unknown hashes for retrieval
   611  		unknown := make(newBlockHashesData, 0, len(announces))
   612  		for _, block := range announces {
   613  			if !pm.blockchain.HasBlock(block.Hash, block.Number) {
   614  				unknown = append(unknown, block)
   615  			}
   616  		}
   617  		for _, block := range unknown {
   618  			pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies)
   619  		}
   620  
   621  	case msg.Code == NewBlockMsg:
   622  		// Retrieve and decode the propagated block
   623  		var request newBlockData
   624  		if err := msg.Decode(&request); err != nil {
   625  			return errResp(ErrDecode, "%v: %v", msg, err)
   626  		}
   627  		request.Block.ReceivedAt = msg.ReceivedAt
   628  		request.Block.ReceivedFrom = p
   629  
   630  		// Mark the peer as owning the block and schedule it for import
   631  		p.MarkBlock(request.Block.Hash())
   632  		pm.fetcher.Enqueue(p.id, request.Block)
   633  
   634  		// Assuming the block is importable by the peer, but possibly not yet done so,
   635  		// calculate the head hash and TD that the peer truly must have.
   636  		var (
   637  			trueHead = request.Block.ParentHash()
   638  			trueTD   = new(big.Int).Sub(request.TD, request.Block.Difficulty())
   639  		)
   640  		// Update the peers total difficulty if better than the previous
   641  		if _, td := p.Head(); trueTD.Cmp(td) > 0 {
   642  			p.SetHead(trueHead, trueTD)
   643  
   644  			// Schedule a sync if above ours. Note, this will not fire a sync for a gap of
   645  			// a singe block (as the true TD is below the propagated block), however this
   646  			// scenario should easily be covered by the fetcher.
   647  			currentBlock := pm.blockchain.CurrentBlock()
   648  			if trueTD.Cmp(pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())) > 0 {
   649  				go pm.synchronise(p)
   650  			}
   651  		}
   652  
   653  	case msg.Code == TxMsg:
   654  		// Transactions arrived, make sure we have a valid and fresh chain to handle them
   655  		if atomic.LoadUint32(&pm.acceptTxs) == 0 {
   656  			break
   657  		}
   658  		// Transactions can be processed, parse all of them and deliver to the pool
   659  		var txs []*types.Transaction
   660  		if err := msg.Decode(&txs); err != nil {
   661  			return errResp(ErrDecode, "msg %v: %v", msg, err)
   662  		}
   663  		for i, tx := range txs {
   664  			// Validate and mark the remote transaction
   665  			if tx == nil {
   666  				return errResp(ErrDecode, "transaction %d is nil", i)
   667  			}
   668  			p.MarkTransaction(tx.Hash())
   669  		}
   670  		pm.txpool.AddRemotes(txs)
   671  
   672  	default:
   673  		return errResp(ErrInvalidMsgCode, "%v", msg.Code)
   674  	}
   675  	return nil
   676  }
   677  
   678  // BroadcastBlock will either propagate a block to a subset of it's peers, or
   679  // will only announce it's availability (depending what's requested).
   680  func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
   681  	hash := block.Hash()
   682  	peers := pm.peers.PeersWithoutBlock(hash)
   683  
   684  	// If propagation is requested, send to a subset of the peer
   685  	if propagate {
   686  		// Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
   687  		var td *big.Int
   688  		if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
   689  			td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
   690  		} else {
   691  			log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
   692  			return
   693  		}
   694  		// Send the block to a subset of our peers
   695  		transfer := peers[:int(math.Sqrt(float64(len(peers))))]
   696  		for _, peer := range transfer {
   697  			peer.SendNewBlock(block, td)
   698  		}
   699  		log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   700  		return
   701  	}
   702  	// Otherwise if the block is indeed in out own chain, announce it
   703  	if pm.blockchain.HasBlock(hash, block.NumberU64()) {
   704  		for _, peer := range peers {
   705  			peer.SendNewBlockHashes([]common.Hash{hash}, []uint64{block.NumberU64()})
   706  		}
   707  		log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
   708  	}
   709  }
   710  
   711  // BroadcastTx will propagate a transaction to all peers which are not known to
   712  // already have the given transaction.
   713  func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) {
   714  	// Broadcast transaction to a batch of peers not knowing about it
   715  	peers := pm.peers.PeersWithoutTx(hash)
   716  	//FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))]
   717  	for _, peer := range peers {
   718  		peer.SendTransactions(types.Transactions{tx})
   719  	}
   720  	log.Trace("Broadcast transaction", "hash", hash, "recipients", len(peers))
   721  }
   722  
   723  // Mined broadcast loop
   724  func (self *ProtocolManager) minedBroadcastLoop() {
   725  	// automatically stops if unsubscribe
   726  	for obj := range self.minedBlockSub.Chan() {
   727  		switch ev := obj.Data.(type) {
   728  		case core.NewMinedBlockEvent:
   729  			self.BroadcastBlock(ev.Block, true)  // First propagate block to peers
   730  			self.BroadcastBlock(ev.Block, false) // Only then announce to the rest
   731  		}
   732  	}
   733  }
   734  
   735  func (self *ProtocolManager) txBroadcastLoop() {
   736  	for {
   737  		select {
   738  		case event := <-self.txCh:
   739  			self.BroadcastTx(event.Tx.Hash(), event.Tx)
   740  
   741  		// Err() channel will be closed when unsubscribing.
   742  		case <-self.txSub.Err():
   743  			return
   744  		}
   745  	}
   746  }
   747  
   748  // EthNodeInfo represents a short summary of the Ethereum sub-protocol metadata known
   749  // about the host peer.
   750  type EthNodeInfo struct {
   751  	Network    uint64      `json:"network"`    // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3)
   752  	Difficulty *big.Int    `json:"difficulty"` // Total difficulty of the host's blockchain
   753  	Genesis    common.Hash `json:"genesis"`    // SHA3 hash of the host's genesis block
   754  	Head       common.Hash `json:"head"`       // SHA3 hash of the host's best owned block
   755  }
   756  
   757  // NodeInfo retrieves some protocol metadata about the running host node.
   758  func (self *ProtocolManager) NodeInfo() *EthNodeInfo {
   759  	currentBlock := self.blockchain.CurrentBlock()
   760  	return &EthNodeInfo{
   761  		Network:    self.networkId,
   762  		Difficulty: self.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()),
   763  		Genesis:    self.blockchain.Genesis().Hash(),
   764  		Head:       currentBlock.Hash(),
   765  	}
   766  }