github.com/coltonfike/e2c@v21.1.0+incompatible/eth/sync.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  	"math/rand"
    21  	"sync/atomic"
    22  	"time"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/core/types"
    26  	"github.com/ethereum/go-ethereum/eth/downloader"
    27  	"github.com/ethereum/go-ethereum/log"
    28  	"github.com/ethereum/go-ethereum/p2p/enode"
    29  	"github.com/ethereum/go-ethereum/permission/core"
    30  )
    31  
    32  const (
    33  	forceSyncCycle      = 10 * time.Second // Time interval to force syncs, even if few peers are available
    34  	minDesiredPeerCount = 5                // Amount of peers desired to start syncing
    35  
    36  	// This is the target size for the packs of transactions sent by txsyncLoop.
    37  	// A pack can get larger than this if a single transactions exceeds this size.
    38  	txsyncPackSize = 100 * 1024
    39  )
    40  
    41  type txsync struct {
    42  	p   *peer
    43  	txs []*types.Transaction
    44  }
    45  
    46  // syncTransactions starts sending all currently pending transactions to the given peer.
    47  func (pm *ProtocolManager) syncTransactions(p *peer) {
    48  	var txs types.Transactions
    49  	pending, _ := pm.txpool.Pending()
    50  	for _, batch := range pending {
    51  		txs = append(txs, batch...)
    52  	}
    53  	if len(txs) == 0 {
    54  		return
    55  	}
    56  	select {
    57  	case pm.txsyncCh <- &txsync{p, txs}:
    58  	case <-pm.quitSync:
    59  	}
    60  }
    61  
    62  // txsyncLoop takes care of the initial transaction sync for each new
    63  // connection. When a new peer appears, we relay all currently pending
    64  // transactions. In order to minimise egress bandwidth usage, we send
    65  // the transactions in small packs to one peer at a time.
    66  func (pm *ProtocolManager) txsyncLoop() {
    67  	var (
    68  		pending = make(map[enode.ID]*txsync)
    69  		sending = false               // whether a send is active
    70  		pack    = new(txsync)         // the pack that is being sent
    71  		done    = make(chan error, 1) // result of the send
    72  	)
    73  
    74  	// send starts a sending a pack of transactions from the sync.
    75  	send := func(s *txsync) {
    76  		// Fill pack with transactions up to the target size.
    77  		size := common.StorageSize(0)
    78  		pack.p = s.p
    79  		pack.txs = pack.txs[:0]
    80  		for i := 0; i < len(s.txs) && size < txsyncPackSize; i++ {
    81  			pack.txs = append(pack.txs, s.txs[i])
    82  			size += s.txs[i].Size()
    83  		}
    84  		// Remove the transactions that will be sent.
    85  		s.txs = s.txs[:copy(s.txs, s.txs[len(pack.txs):])]
    86  		if len(s.txs) == 0 {
    87  			delete(pending, s.p.ID())
    88  		}
    89  		// Send the pack in the background.
    90  		s.p.Log().Trace("Sending batch of transactions", "count", len(pack.txs), "bytes", size)
    91  		sending = true
    92  		go func() { done <- pack.p.SendTransactions(pack.txs) }()
    93  	}
    94  
    95  	// pick chooses the next pending sync.
    96  	pick := func() *txsync {
    97  		if len(pending) == 0 {
    98  			return nil
    99  		}
   100  		n := rand.Intn(len(pending)) + 1
   101  		for _, s := range pending {
   102  			if n--; n == 0 {
   103  				return s
   104  			}
   105  		}
   106  		return nil
   107  	}
   108  
   109  	for {
   110  		select {
   111  		case s := <-pm.txsyncCh:
   112  			pending[s.p.ID()] = s
   113  			if !sending {
   114  				send(s)
   115  			}
   116  		case err := <-done:
   117  			sending = false
   118  			// Stop tracking peers that cause send failures.
   119  			if err != nil {
   120  				pack.p.Log().Debug("Transaction send failed", "err", err)
   121  				delete(pending, pack.p.ID())
   122  			}
   123  			// Schedule the next send.
   124  			if s := pick(); s != nil {
   125  				send(s)
   126  			}
   127  		case <-pm.quitSync:
   128  			return
   129  		}
   130  	}
   131  }
   132  
   133  // syncer is responsible for periodically synchronising with the network, both
   134  // downloading hashes and blocks as well as handling the announcement handler.
   135  func (pm *ProtocolManager) syncer() {
   136  	// Start and ensure cleanup of sync mechanisms
   137  	pm.fetcher.Start()
   138  	defer pm.fetcher.Stop()
   139  	defer pm.downloader.Terminate()
   140  
   141  	// Wait for different events to fire synchronisation operations
   142  	forceSync := time.NewTicker(forceSyncCycle)
   143  	defer forceSync.Stop()
   144  
   145  	for {
   146  		select {
   147  		case <-pm.newPeerCh:
   148  			// Make sure we have peers to select from, then sync
   149  			if pm.peers.Len() < minDesiredPeerCount {
   150  				break
   151  			}
   152  			if !pm.raftMode {
   153  				go pm.synchronise(pm.peers.BestPeer())
   154  			}
   155  
   156  		case <-forceSync.C:
   157  			if !pm.raftMode {
   158  				// Force a sync even if not enough peers are present
   159  				go pm.synchronise(pm.peers.BestPeer())
   160  			}
   161  
   162  		case <-pm.noMorePeers:
   163  			return
   164  		}
   165  	}
   166  }
   167  
   168  // synchronise tries to sync up our local block chain with a remote peer.
   169  func (pm *ProtocolManager) synchronise(peer *peer) {
   170  	// Short circuit if no peers are available
   171  	if peer == nil {
   172  		return
   173  	}
   174  	// Make sure the peer's TD is higher than our own
   175  	currentBlock := pm.blockchain.CurrentBlock()
   176  	td := pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
   177  
   178  	pHead, pTd := peer.Head()
   179  	if pTd.Cmp(td) <= 0 {
   180  		// Quorum
   181  		// added for permissions changes to indicate node sync up has started
   182  		// if peer's TD is smaller than ours, no sync will happen
   183  		core.SetSyncStatus()
   184  		return
   185  	}
   186  	// Otherwise try to sync with the downloader
   187  	mode := downloader.FullSync
   188  	if atomic.LoadUint32(&pm.fastSync) == 1 {
   189  		// Fast sync was explicitly requested, and explicitly granted
   190  		mode = downloader.FastSync
   191  	}
   192  	if mode == downloader.FastSync {
   193  		// Make sure the peer's total difficulty we are synchronizing is higher.
   194  		if pm.blockchain.GetTdByHash(pm.blockchain.CurrentFastBlock().Hash()).Cmp(pTd) >= 0 {
   195  			// Quorum never use FastSync, no need to execute SetSyncStatus
   196  			return
   197  		}
   198  	}
   199  	// Run the sync cycle, and disable fast sync if we've went past the pivot block
   200  	if err := pm.downloader.Synchronise(peer.id, pHead, pTd, mode); err != nil {
   201  		return
   202  	}
   203  	if atomic.LoadUint32(&pm.fastSync) == 1 {
   204  		log.Info("Fast sync complete, auto disabling")
   205  		atomic.StoreUint32(&pm.fastSync, 0)
   206  	}
   207  	// If we've successfully finished a sync cycle and passed any required checkpoint,
   208  	// enable accepting transactions from the network.
   209  	head := pm.blockchain.CurrentBlock()
   210  	if head.NumberU64() >= pm.checkpointNumber {
   211  		// Checkpoint passed, sanity check the timestamp to have a fallback mechanism
   212  		// for non-checkpointed (number = 0) private networks.
   213  		if head.Time() >= uint64(time.Now().AddDate(0, -1, 0).Unix()) {
   214  			atomic.StoreUint32(&pm.acceptTxs, 1)
   215  		}
   216  	}
   217  	if head.NumberU64() > 0 {
   218  		// We've completed a sync cycle, notify all peers of new state. This path is
   219  		// essential in star-topology networks where a gateway node needs to notify
   220  		// all its out-of-date peers of the availability of a new block. This failure
   221  		// scenario will most often crop up in private and hackathon networks with
   222  		// degenerate connectivity, but it should be healthy for the mainnet too to
   223  		// more reliably update peers or the local TD state.
   224  		go pm.BroadcastBlock(head, false)
   225  	}
   226  }