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