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