2015-07-06 19:54:22 -05:00
|
|
|
// Copyright 2015 The go-ethereum Authors
|
2015-07-22 11:48:40 -05:00
|
|
|
// This file is part of the go-ethereum library.
|
2015-07-06 19:54:22 -05:00
|
|
|
//
|
2015-07-23 11:35:11 -05:00
|
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
2015-07-06 19:54:22 -05:00
|
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
2015-07-22 11:48:40 -05:00
|
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
2015-07-06 19:54:22 -05:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
2015-07-22 11:48:40 -05:00
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
2015-07-06 19:54:22 -05:00
|
|
|
// GNU Lesser General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Lesser General Public License
|
2015-07-22 11:48:40 -05:00
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
2015-07-06 19:54:22 -05:00
|
|
|
|
2015-04-17 18:11:09 -05:00
|
|
|
package eth
|
|
|
|
|
|
|
|
import (
|
2015-09-01 09:35:14 -05:00
|
|
|
"errors"
|
2015-06-04 10:46:07 -05:00
|
|
|
"math"
|
2015-07-09 05:55:06 -05:00
|
|
|
"math/big"
|
2015-04-17 18:11:09 -05:00
|
|
|
"sync"
|
2016-05-17 06:17:20 -05:00
|
|
|
"sync/atomic"
|
2015-04-24 07:40:32 -05:00
|
|
|
"time"
|
2015-04-17 18:11:09 -05:00
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
2015-04-17 19:21:07 -05:00
|
|
|
"github.com/ethereum/go-ethereum/core"
|
2019-09-30 13:28:50 -05:00
|
|
|
"github.com/ethereum/go-ethereum/core/forkid"
|
2015-04-17 18:11:09 -05:00
|
|
|
"github.com/ethereum/go-ethereum/core/types"
|
|
|
|
"github.com/ethereum/go-ethereum/eth/downloader"
|
2015-06-17 08:53:28 -05:00
|
|
|
"github.com/ethereum/go-ethereum/eth/fetcher"
|
2020-12-14 03:27:15 -06:00
|
|
|
"github.com/ethereum/go-ethereum/eth/protocols/eth"
|
|
|
|
"github.com/ethereum/go-ethereum/eth/protocols/snap"
|
2015-09-14 02:35:57 -05:00
|
|
|
"github.com/ethereum/go-ethereum/ethdb"
|
2015-04-22 10:56:06 -05:00
|
|
|
"github.com/ethereum/go-ethereum/event"
|
2017-02-22 06:10:07 -06:00
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2015-04-17 18:11:09 -05:00
|
|
|
"github.com/ethereum/go-ethereum/p2p"
|
2016-10-20 06:36:29 -05:00
|
|
|
"github.com/ethereum/go-ethereum/params"
|
2019-05-13 07:28:01 -05:00
|
|
|
"github.com/ethereum/go-ethereum/trie"
|
2015-04-17 18:11:09 -05:00
|
|
|
)
|
|
|
|
|
2015-09-07 12:43:01 -05:00
|
|
|
const (
|
2018-05-18 03:45:52 -05:00
|
|
|
// txChanSize is the size of channel listening to NewTxsEvent.
|
2017-08-18 05:58:36 -05:00
|
|
|
// The number is referenced from the size of tx pool.
|
|
|
|
txChanSize = 4096
|
2015-09-07 12:43:01 -05:00
|
|
|
)
|
2015-06-09 05:00:41 -05:00
|
|
|
|
2016-07-08 12:59:11 -05:00
|
|
|
var (
|
2019-04-16 05:20:38 -05:00
|
|
|
syncChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the sync progress challenge
|
2016-07-08 12:59:11 -05:00
|
|
|
)
|
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
// txPool defines the methods needed from a transaction pool implementation to
|
|
|
|
// support all the operations needed by the Ethereum chain protocols.
|
|
|
|
type txPool interface {
|
|
|
|
// Has returns an indicator whether txpool has a transaction
|
|
|
|
// cached with the given hash.
|
|
|
|
Has(hash common.Hash) bool
|
|
|
|
|
|
|
|
// Get retrieves the transaction from local txpool with given
|
|
|
|
// tx hash.
|
|
|
|
Get(hash common.Hash) *types.Transaction
|
|
|
|
|
|
|
|
// AddRemotes should add the given transactions to the pool.
|
|
|
|
AddRemotes([]*types.Transaction) []error
|
|
|
|
|
|
|
|
// Pending should return pending transactions.
|
|
|
|
// The slice should be modifiable by the caller.
|
2021-10-13 16:00:45 -05:00
|
|
|
Pending(enforceTips bool) map[common.Address]types.Transactions
|
2020-12-14 03:27:15 -06:00
|
|
|
|
|
|
|
// SubscribeNewTxsEvent should return an event subscription of
|
|
|
|
// NewTxsEvent and send events to the given channel.
|
|
|
|
SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription
|
2015-04-17 18:11:09 -05:00
|
|
|
}
|
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
// handlerConfig is the collection of initialization parameters to create a full
|
|
|
|
// node network handler.
|
|
|
|
type handlerConfig struct {
|
|
|
|
Database ethdb.Database // Database for direct sync insertions
|
|
|
|
Chain *core.BlockChain // Blockchain to serve data from
|
|
|
|
TxPool txPool // Transaction pool to propagate from
|
|
|
|
Network uint64 // Network identifier to adfvertise
|
|
|
|
Sync downloader.SyncMode // Whether to fast or full sync
|
|
|
|
BloomCache uint64 // Megabytes to alloc for fast sync bloom
|
|
|
|
EventMux *event.TypeMux // Legacy event mux, deprecate for `feed`
|
|
|
|
Checkpoint *params.TrustedCheckpoint // Hard coded checkpoint for sync challenges
|
|
|
|
Whitelist map[uint64]common.Hash // Hard coded whitelist for sync challenged
|
|
|
|
}
|
|
|
|
|
|
|
|
type handler struct {
|
2019-09-30 13:28:50 -05:00
|
|
|
networkID uint64
|
|
|
|
forkFilter forkid.Filter // Fork ID filter, constant across the lifetime of the node
|
2015-10-27 08:10:30 -05:00
|
|
|
|
2017-04-10 03:43:01 -05:00
|
|
|
fastSync uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
|
2020-12-14 03:27:15 -06:00
|
|
|
snapSync uint32 // Flag whether fast sync should operate on top of the snap protocol
|
2017-04-10 03:43:01 -05:00
|
|
|
acceptTxs uint32 // Flag whether we're considered synchronised (enables transaction processing)
|
2016-06-02 07:54:07 -05:00
|
|
|
|
2019-04-16 05:20:38 -05:00
|
|
|
checkpointNumber uint64 // Block number for the sync progress validator to cross reference
|
|
|
|
checkpointHash common.Hash // Block hash for the sync progress validator to cross reference
|
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
database ethdb.Database
|
|
|
|
txpool txPool
|
|
|
|
chain *core.BlockChain
|
|
|
|
maxPeers int
|
2015-07-02 11:55:18 -05:00
|
|
|
|
2019-10-28 06:59:07 -05:00
|
|
|
downloader *downloader.Downloader
|
2020-12-14 03:27:15 -06:00
|
|
|
stateBloom *trie.SyncBloom
|
2019-10-28 06:59:07 -05:00
|
|
|
blockFetcher *fetcher.BlockFetcher
|
|
|
|
txFetcher *fetcher.TxFetcher
|
|
|
|
peers *peerSet
|
2015-04-17 19:21:07 -05:00
|
|
|
|
2015-04-22 10:56:06 -05:00
|
|
|
eventMux *event.TypeMux
|
2018-05-18 03:45:52 -05:00
|
|
|
txsCh chan core.NewTxsEvent
|
2018-05-10 02:04:45 -05:00
|
|
|
txsSub event.Subscription
|
2016-12-10 12:02:14 -06:00
|
|
|
minedBlockSub *event.TypeMuxSubscription
|
2015-04-24 07:40:32 -05:00
|
|
|
|
2018-11-02 15:26:45 -05:00
|
|
|
whitelist map[uint64]common.Hash
|
|
|
|
|
2015-06-09 05:03:14 -05:00
|
|
|
// channels for fetcher, syncer, txsyncLoop
|
2020-03-27 08:03:20 -05:00
|
|
|
quitSync chan struct{}
|
2015-06-08 12:38:39 -05:00
|
|
|
|
2020-03-27 08:03:20 -05:00
|
|
|
chainSync *chainSyncer
|
|
|
|
wg sync.WaitGroup
|
|
|
|
peerWG sync.WaitGroup
|
2015-04-17 18:11:09 -05:00
|
|
|
}
|
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
// newHandler returns a handler for all Ethereum chain management protocol.
|
|
|
|
func newHandler(config *handlerConfig) (*handler, error) {
|
2015-06-26 08:54:27 -05:00
|
|
|
// Create the protocol manager with the base fields
|
2020-12-14 03:27:15 -06:00
|
|
|
if config.EventMux == nil {
|
|
|
|
config.EventMux = new(event.TypeMux) // Nicety initialization for tests
|
|
|
|
}
|
|
|
|
h := &handler{
|
|
|
|
networkID: config.Network,
|
|
|
|
forkFilter: forkid.NewFilter(config.Chain),
|
|
|
|
eventMux: config.EventMux,
|
|
|
|
database: config.Database,
|
|
|
|
txpool: config.TxPool,
|
|
|
|
chain: config.Chain,
|
2020-03-27 08:03:20 -05:00
|
|
|
peers: newPeerSet(),
|
2020-12-14 03:27:15 -06:00
|
|
|
whitelist: config.Whitelist,
|
2020-03-27 08:03:20 -05:00
|
|
|
quitSync: make(chan struct{}),
|
2015-04-17 18:11:09 -05:00
|
|
|
}
|
2020-12-14 03:27:15 -06:00
|
|
|
if config.Sync == downloader.FullSync {
|
2019-06-26 03:00:21 -05:00
|
|
|
// The database seems empty as the current block is the genesis. Yet the fast
|
|
|
|
// block is ahead, so fast sync was enabled for this node at a certain point.
|
|
|
|
// The scenarios where this can happen is
|
|
|
|
// * if the user manually (or via a bad block) rolled back a fast sync node
|
|
|
|
// below the sync point.
|
|
|
|
// * the last fast sync is not finished while user specifies a full sync this
|
|
|
|
// time. But we don't have any recent state for full sync.
|
|
|
|
// In these cases however it's safe to reenable fast sync.
|
2020-12-14 03:27:15 -06:00
|
|
|
fullBlock, fastBlock := h.chain.CurrentBlock(), h.chain.CurrentFastBlock()
|
2019-06-26 03:00:21 -05:00
|
|
|
if fullBlock.NumberU64() == 0 && fastBlock.NumberU64() > 0 {
|
2020-12-14 03:27:15 -06:00
|
|
|
h.fastSync = uint32(1)
|
2019-06-26 03:00:21 -05:00
|
|
|
log.Warn("Switch sync mode from full sync to fast sync")
|
|
|
|
}
|
|
|
|
} else {
|
2020-12-14 03:27:15 -06:00
|
|
|
if h.chain.CurrentBlock().NumberU64() > 0 {
|
2019-06-26 03:00:21 -05:00
|
|
|
// Print warning log if database is not empty to run fast sync.
|
|
|
|
log.Warn("Switch sync mode from fast sync to full sync")
|
|
|
|
} else {
|
|
|
|
// If fast sync was requested and our database is empty, grant it
|
2020-12-14 03:27:15 -06:00
|
|
|
h.fastSync = uint32(1)
|
|
|
|
if config.Sync == downloader.SnapSync {
|
|
|
|
h.snapSync = uint32(1)
|
|
|
|
}
|
2019-06-26 03:00:21 -05:00
|
|
|
}
|
2016-05-17 06:17:20 -05:00
|
|
|
}
|
2019-04-16 05:20:38 -05:00
|
|
|
// If we have trusted checkpoints, enforce them on the chain
|
2020-12-14 03:27:15 -06:00
|
|
|
if config.Checkpoint != nil {
|
|
|
|
h.checkpointNumber = (config.Checkpoint.SectionIndex+1)*params.CHTFrequency - 1
|
|
|
|
h.checkpointHash = config.Checkpoint.SectionHead
|
2019-04-16 05:20:38 -05:00
|
|
|
}
|
2019-05-13 07:28:01 -05:00
|
|
|
// Construct the downloader (long sync) and its backing state bloom if fast
|
|
|
|
// sync is requested. The downloader is responsible for deallocating the state
|
|
|
|
// bloom when it's done.
|
2021-03-17 03:36:34 -05:00
|
|
|
// Note: we don't enable it if snap-sync is performed, since it's very heavy
|
|
|
|
// and the heal-portion of the snap sync is much lighter than fast. What we particularly
|
|
|
|
// want to avoid, is a 90%-finished (but restarted) snap-sync to begin
|
|
|
|
// indexing the entire trie
|
|
|
|
if atomic.LoadUint32(&h.fastSync) == 1 && atomic.LoadUint32(&h.snapSync) == 0 {
|
2020-12-14 03:27:15 -06:00
|
|
|
h.stateBloom = trie.NewSyncBloom(config.BloomCache, config.Database)
|
2019-05-13 07:28:01 -05:00
|
|
|
}
|
2020-12-14 03:27:15 -06:00
|
|
|
h.downloader = downloader.New(h.checkpointNumber, config.Database, h.stateBloom, h.eventMux, h.chain, nil, h.removePeer)
|
2015-06-16 03:58:32 -05:00
|
|
|
|
2019-05-13 07:28:01 -05:00
|
|
|
// Construct the fetcher (short sync)
|
2017-04-04 17:16:29 -05:00
|
|
|
validator := func(header *types.Header) error {
|
2020-12-14 03:27:15 -06:00
|
|
|
return h.chain.Engine().VerifyHeader(h.chain, header, true)
|
2015-06-18 10:00:19 -05:00
|
|
|
}
|
2015-06-16 09:39:04 -05:00
|
|
|
heighter := func() uint64 {
|
2020-12-14 03:27:15 -06:00
|
|
|
return h.chain.CurrentBlock().NumberU64()
|
2015-06-16 09:39:04 -05:00
|
|
|
}
|
2016-06-02 07:54:07 -05:00
|
|
|
inserter := func(blocks types.Blocks) (int, error) {
|
2019-04-26 04:11:22 -05:00
|
|
|
// If sync hasn't reached the checkpoint yet, deny importing weird blocks.
|
|
|
|
//
|
|
|
|
// Ideally we would also compare the head block's timestamp and similarly reject
|
|
|
|
// the propagated block if the head is too old. Unfortunately there is a corner
|
|
|
|
// case when starting new networks, where the genesis might be ancient (0 unix)
|
|
|
|
// which would prevent full nodes from accepting it.
|
2020-12-14 03:27:15 -06:00
|
|
|
if h.chain.CurrentBlock().NumberU64() < h.checkpointNumber {
|
2019-04-26 04:11:22 -05:00
|
|
|
log.Warn("Unsynced yet, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
|
|
|
|
return 0, nil
|
|
|
|
}
|
|
|
|
// If fast sync is running, deny importing weird blocks. This is a problematic
|
|
|
|
// clause when starting up a new network, because fast-syncing miners might not
|
|
|
|
// accept each others' blocks until a restart. Unfortunately we haven't figured
|
|
|
|
// out a way yet where nodes can decide unilaterally whether the network is new
|
|
|
|
// or not. This should be fixed if we figure out a solution.
|
2020-12-14 03:27:15 -06:00
|
|
|
if atomic.LoadUint32(&h.fastSync) == 1 {
|
2019-04-26 04:11:22 -05:00
|
|
|
log.Warn("Fast syncing, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash())
|
2017-05-26 08:04:12 -05:00
|
|
|
return 0, nil
|
|
|
|
}
|
2020-12-14 03:27:15 -06:00
|
|
|
n, err := h.chain.InsertChain(blocks)
|
2019-04-26 04:11:22 -05:00
|
|
|
if err == nil {
|
2020-12-14 03:27:15 -06:00
|
|
|
atomic.StoreUint32(&h.acceptTxs, 1) // Mark initial sync done on any fetcher import
|
2019-04-26 04:11:22 -05:00
|
|
|
}
|
|
|
|
return n, err
|
2016-06-02 07:54:07 -05:00
|
|
|
}
|
2020-12-14 03:27:15 -06:00
|
|
|
h.blockFetcher = fetcher.NewBlockFetcher(false, nil, h.chain.GetBlockByHash, validator, h.BroadcastBlock, heighter, nil, inserter, h.removePeer)
|
2020-01-22 08:39:43 -06:00
|
|
|
|
|
|
|
fetchTx := func(peer string, hashes []common.Hash) error {
|
2021-02-02 02:44:36 -06:00
|
|
|
p := h.peers.peer(peer)
|
2020-01-22 08:39:43 -06:00
|
|
|
if p == nil {
|
|
|
|
return errors.New("unknown peer")
|
|
|
|
}
|
|
|
|
return p.RequestTxs(hashes)
|
|
|
|
}
|
2020-12-14 03:27:15 -06:00
|
|
|
h.txFetcher = fetcher.NewTxFetcher(h.txpool.Has, h.txpool.AddRemotes, fetchTx)
|
|
|
|
h.chainSync = newChainSyncer(h)
|
|
|
|
return h, nil
|
2019-07-08 10:53:47 -05:00
|
|
|
}
|
|
|
|
|
2021-02-02 02:44:36 -06:00
|
|
|
// runEthPeer registers an eth peer into the joint eth/snap peerset, adds it to
|
|
|
|
// various subsistems and starts handling messages.
|
2020-12-14 03:27:15 -06:00
|
|
|
func (h *handler) runEthPeer(peer *eth.Peer, handler eth.Handler) error {
|
2021-02-02 02:44:36 -06:00
|
|
|
// If the peer has a `snap` extension, wait for it to connect so we can have
|
|
|
|
// a uniform initialization/teardown mechanism
|
|
|
|
snap, err := h.peers.waitSnapExtension(peer)
|
|
|
|
if err != nil {
|
|
|
|
peer.Log().Error("Snapshot extension barrier failed", "err", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// TODO(karalabe): Not sure why this is needed
|
2020-12-14 03:27:15 -06:00
|
|
|
if !h.chainSync.handlePeerEvent(peer) {
|
2020-03-27 08:03:20 -05:00
|
|
|
return p2p.DiscQuitting
|
|
|
|
}
|
2020-12-14 03:27:15 -06:00
|
|
|
h.peerWG.Add(1)
|
|
|
|
defer h.peerWG.Done()
|
2015-06-26 12:42:27 -05:00
|
|
|
|
|
|
|
// Execute the Ethereum handshake
|
2018-01-30 10:39:32 -06:00
|
|
|
var (
|
2020-12-14 03:27:15 -06:00
|
|
|
genesis = h.chain.Genesis()
|
|
|
|
head = h.chain.CurrentHeader()
|
2018-01-30 10:39:32 -06:00
|
|
|
hash = head.Hash()
|
|
|
|
number = head.Number.Uint64()
|
2020-12-14 03:27:15 -06:00
|
|
|
td = h.chain.GetTd(hash, number)
|
2018-01-30 10:39:32 -06:00
|
|
|
)
|
2020-12-14 03:27:15 -06:00
|
|
|
forkID := forkid.NewID(h.chain.Config(), h.chain.Genesis().Hash(), h.chain.CurrentHeader().Number.Uint64())
|
|
|
|
if err := peer.Handshake(h.networkID, td, hash, genesis.Hash(), forkID, h.forkFilter); err != nil {
|
|
|
|
peer.Log().Debug("Ethereum handshake failed", "err", err)
|
2015-04-17 18:11:09 -05:00
|
|
|
return err
|
|
|
|
}
|
2021-01-25 12:06:52 -06:00
|
|
|
reject := false // reserved peer slots
|
2021-02-02 02:44:36 -06:00
|
|
|
if atomic.LoadUint32(&h.snapSync) == 1 {
|
|
|
|
if snap == nil {
|
|
|
|
// If we are running snap-sync, we want to reserve roughly half the peer
|
|
|
|
// slots for peers supporting the snap protocol.
|
|
|
|
// The logic here is; we only allow up to 5 more non-snap peers than snap-peers.
|
|
|
|
if all, snp := h.peers.len(), h.peers.snapLen(); all-snp > snp+5 {
|
|
|
|
reject = true
|
|
|
|
}
|
2021-01-25 12:06:52 -06:00
|
|
|
}
|
|
|
|
}
|
2020-12-14 03:27:15 -06:00
|
|
|
// Ignore maxPeers if this is a trusted peer
|
2021-01-25 12:06:52 -06:00
|
|
|
if !peer.Peer.Info().Network.Trusted {
|
2021-02-02 02:44:36 -06:00
|
|
|
if reject || h.peers.len() >= h.maxPeers {
|
2021-01-25 12:06:52 -06:00
|
|
|
return p2p.DiscTooManyPeers
|
|
|
|
}
|
2020-12-14 03:27:15 -06:00
|
|
|
}
|
|
|
|
peer.Log().Debug("Ethereum peer connected", "name", peer.Name())
|
2020-03-27 08:03:20 -05:00
|
|
|
|
2015-06-26 12:42:27 -05:00
|
|
|
// Register the peer locally
|
2021-02-02 02:44:36 -06:00
|
|
|
if err := h.peers.registerPeer(peer, snap); err != nil {
|
2020-12-14 03:27:15 -06:00
|
|
|
peer.Log().Error("Ethereum peer registration failed", "err", err)
|
2015-05-18 13:33:37 -05:00
|
|
|
return err
|
|
|
|
}
|
2021-05-25 15:20:36 -05:00
|
|
|
defer h.unregisterPeer(peer.ID())
|
2015-04-17 18:11:09 -05:00
|
|
|
|
2021-02-02 02:44:36 -06:00
|
|
|
p := h.peers.peer(peer.ID())
|
2020-12-14 03:27:15 -06:00
|
|
|
if p == nil {
|
|
|
|
return errors.New("peer dropped during handling")
|
|
|
|
}
|
2015-06-26 12:42:27 -05:00
|
|
|
// Register the peer in the downloader. If the downloader considers it banned, we disconnect
|
2020-12-14 03:27:15 -06:00
|
|
|
if err := h.downloader.RegisterPeer(peer.ID(), peer.Version(), peer); err != nil {
|
2021-02-02 02:44:36 -06:00
|
|
|
peer.Log().Error("Failed to register peer in eth syncer", "err", err)
|
2015-05-18 13:33:37 -05:00
|
|
|
return err
|
|
|
|
}
|
2021-02-02 02:44:36 -06:00
|
|
|
if snap != nil {
|
|
|
|
if err := h.downloader.SnapSyncer.Register(snap); err != nil {
|
|
|
|
peer.Log().Error("Failed to register peer in snap syncer", "err", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2020-12-14 03:27:15 -06:00
|
|
|
h.chainSync.handlePeerEvent(peer)
|
2020-03-27 08:03:20 -05:00
|
|
|
|
2015-06-09 05:03:14 -05:00
|
|
|
// Propagate existing transactions. new transactions appearing
|
2015-04-17 18:11:09 -05:00
|
|
|
// after this will be sent via broadcasts.
|
2020-12-14 03:27:15 -06:00
|
|
|
h.syncTransactions(peer)
|
2015-06-09 05:03:14 -05:00
|
|
|
|
2019-04-16 05:20:38 -05:00
|
|
|
// If we have a trusted CHT, reject all peers below that (avoid fast sync eclipse)
|
2020-12-14 03:27:15 -06:00
|
|
|
if h.checkpointHash != (common.Hash{}) {
|
2019-04-16 05:20:38 -05:00
|
|
|
// Request the peer's checkpoint header for chain height/weight validation
|
2020-12-14 03:27:15 -06:00
|
|
|
if err := peer.RequestHeadersByNumber(h.checkpointNumber, 1, 0, false); err != nil {
|
2016-07-08 12:59:11 -05:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Start a timer to disconnect if the peer doesn't reply in time
|
2019-04-16 05:20:38 -05:00
|
|
|
p.syncDrop = time.AfterFunc(syncChallengeTimeout, func() {
|
2020-12-14 03:27:15 -06:00
|
|
|
peer.Log().Warn("Checkpoint challenge timed out, dropping", "addr", peer.RemoteAddr(), "type", peer.Name())
|
|
|
|
h.removePeer(peer.ID())
|
2016-07-08 12:59:11 -05:00
|
|
|
})
|
2016-07-19 04:00:09 -05:00
|
|
|
// Make sure it's cleaned up if the peer dies off
|
|
|
|
defer func() {
|
2019-04-16 05:20:38 -05:00
|
|
|
if p.syncDrop != nil {
|
|
|
|
p.syncDrop.Stop()
|
|
|
|
p.syncDrop = nil
|
2016-07-19 04:00:09 -05:00
|
|
|
}
|
|
|
|
}()
|
2016-07-08 12:59:11 -05:00
|
|
|
}
|
2018-11-02 15:26:45 -05:00
|
|
|
// If we have any explicit whitelist block hashes, request them
|
2020-12-14 03:27:15 -06:00
|
|
|
for number := range h.whitelist {
|
|
|
|
if err := peer.RequestHeadersByNumber(number, 1, 0, false); err != nil {
|
2018-11-02 15:26:45 -05:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2018-12-10 06:47:01 -06:00
|
|
|
// Handle incoming messages until the connection is torn down
|
2020-12-14 03:27:15 -06:00
|
|
|
return handler(peer)
|
2015-04-17 18:11:09 -05:00
|
|
|
}
|
|
|
|
|
2021-02-02 02:44:36 -06:00
|
|
|
// runSnapExtension registers a `snap` peer into the joint eth/snap peerset and
|
|
|
|
// starts handling inbound messages. As `snap` is only a satellite protocol to
|
|
|
|
// `eth`, all subsystem registrations and lifecycle management will be done by
|
|
|
|
// the main `eth` handler to prevent strange races.
|
|
|
|
func (h *handler) runSnapExtension(peer *snap.Peer, handler snap.Handler) error {
|
2020-12-14 03:27:15 -06:00
|
|
|
h.peerWG.Add(1)
|
|
|
|
defer h.peerWG.Done()
|
|
|
|
|
2021-02-02 02:44:36 -06:00
|
|
|
if err := h.peers.registerSnapExtension(peer); err != nil {
|
|
|
|
peer.Log().Error("Snapshot extension registration failed", "err", err)
|
2020-12-14 03:27:15 -06:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return handler(peer)
|
|
|
|
}
|
2015-09-30 11:23:31 -05:00
|
|
|
|
2021-05-25 15:20:36 -05:00
|
|
|
// removePeer requests disconnection of a peer.
|
2020-12-14 03:27:15 -06:00
|
|
|
func (h *handler) removePeer(id string) {
|
2021-05-25 15:20:36 -05:00
|
|
|
peer := h.peers.peer(id)
|
|
|
|
if peer != nil {
|
|
|
|
peer.Peer.Disconnect(p2p.DiscUselessPeer)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// unregisterPeer removes a peer from the downloader, fetchers and main peer set.
|
|
|
|
func (h *handler) unregisterPeer(id string) {
|
2021-01-25 00:17:05 -06:00
|
|
|
// Create a custom logger to avoid printing the entire id
|
|
|
|
var logger log.Logger
|
|
|
|
if len(id) < 16 {
|
|
|
|
// Tests use short IDs, don't choke on them
|
|
|
|
logger = log.New("peer", id)
|
|
|
|
} else {
|
|
|
|
logger = log.New("peer", id[:8])
|
|
|
|
}
|
2021-02-02 02:44:36 -06:00
|
|
|
// Abort if the peer does not exist
|
|
|
|
peer := h.peers.peer(id)
|
|
|
|
if peer == nil {
|
|
|
|
logger.Error("Ethereum peer removal failed", "err", errPeerNotRegistered)
|
|
|
|
return
|
2020-12-14 03:27:15 -06:00
|
|
|
}
|
2021-02-02 02:44:36 -06:00
|
|
|
// Remove the `eth` peer if it exists
|
|
|
|
logger.Debug("Removing Ethereum peer", "snap", peer.snapExt != nil)
|
|
|
|
|
|
|
|
// Remove the `snap` extension if it exists
|
|
|
|
if peer.snapExt != nil {
|
2020-12-14 03:27:15 -06:00
|
|
|
h.downloader.SnapSyncer.Unregister(id)
|
|
|
|
}
|
2021-02-02 02:44:36 -06:00
|
|
|
h.downloader.UnregisterPeer(id)
|
|
|
|
h.txFetcher.Drop(id)
|
|
|
|
|
|
|
|
if err := h.peers.unregisterPeer(id); err != nil {
|
|
|
|
logger.Error("Ethereum peer removal failed", "err", err)
|
2020-12-14 03:27:15 -06:00
|
|
|
}
|
|
|
|
}
|
2015-10-05 11:37:56 -05:00
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
func (h *handler) Start(maxPeers int) {
|
|
|
|
h.maxPeers = maxPeers
|
2015-07-02 11:55:18 -05:00
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
// broadcast transactions
|
|
|
|
h.wg.Add(1)
|
|
|
|
h.txsCh = make(chan core.NewTxsEvent, txChanSize)
|
|
|
|
h.txsSub = h.txpool.SubscribeNewTxsEvent(h.txsCh)
|
|
|
|
go h.txBroadcastLoop()
|
2015-09-30 11:23:31 -05:00
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
// broadcast mined blocks
|
|
|
|
h.wg.Add(1)
|
|
|
|
h.minedBlockSub = h.eventMux.Subscribe(core.NewMinedBlockEvent{})
|
|
|
|
go h.minedBroadcastLoop()
|
2015-04-17 18:11:09 -05:00
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
// start sync handlers
|
2021-08-24 13:52:58 -05:00
|
|
|
h.wg.Add(1)
|
2020-12-14 03:27:15 -06:00
|
|
|
go h.chainSync.loop()
|
|
|
|
}
|
2015-04-17 19:24:24 -05:00
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
func (h *handler) Stop() {
|
|
|
|
h.txsSub.Unsubscribe() // quits txBroadcastLoop
|
|
|
|
h.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
|
2019-10-28 06:59:07 -05:00
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
// Quit chainSync and txsync64.
|
|
|
|
// After this is done, no new peers will be accepted.
|
|
|
|
close(h.quitSync)
|
|
|
|
h.wg.Wait()
|
2019-10-28 06:59:07 -05:00
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
// Disconnect existing sessions.
|
|
|
|
// This also closes the gate for any new registrations on the peer set.
|
|
|
|
// sessions which are already established but not added to h.peers yet
|
|
|
|
// will exit when they try to register.
|
|
|
|
h.peers.close()
|
|
|
|
h.peerWG.Wait()
|
2015-06-30 11:05:06 -05:00
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
log.Info("Ethereum protocol stopped")
|
2015-04-17 18:11:09 -05:00
|
|
|
}
|
2015-04-17 19:21:07 -05:00
|
|
|
|
2020-01-23 09:08:06 -06:00
|
|
|
// BroadcastBlock will either propagate a block to a subset of its peers, or
|
|
|
|
// will only announce its availability (depending what's requested).
|
2020-12-14 03:27:15 -06:00
|
|
|
func (h *handler) BroadcastBlock(block *types.Block, propagate bool) {
|
2015-06-18 08:09:34 -05:00
|
|
|
hash := block.Hash()
|
2021-02-02 02:44:36 -06:00
|
|
|
peers := h.peers.peersWithoutBlock(hash)
|
2015-06-04 10:46:07 -05:00
|
|
|
|
2015-06-18 10:00:19 -05:00
|
|
|
// If propagation is requested, send to a subset of the peer
|
|
|
|
if propagate {
|
2015-07-09 05:55:06 -05:00
|
|
|
// Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
|
|
|
|
var td *big.Int
|
2020-12-14 03:27:15 -06:00
|
|
|
if parent := h.chain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
|
|
|
|
td = new(big.Int).Add(block.Difficulty(), h.chain.GetTd(block.ParentHash(), block.NumberU64()-1))
|
2015-07-09 05:55:06 -05:00
|
|
|
} else {
|
2017-03-02 07:06:16 -06:00
|
|
|
log.Error("Propagating dangling block", "number", block.Number(), "hash", hash)
|
2015-07-09 05:55:06 -05:00
|
|
|
return
|
|
|
|
}
|
|
|
|
// Send the block to a subset of our peers
|
2020-02-17 04:01:03 -06:00
|
|
|
transfer := peers[:int(math.Sqrt(float64(len(peers))))]
|
2015-06-18 10:00:19 -05:00
|
|
|
for _, peer := range transfer {
|
2018-05-21 03:32:42 -05:00
|
|
|
peer.AsyncSendNewBlock(block, td)
|
2015-06-18 10:00:19 -05:00
|
|
|
}
|
2017-03-02 07:06:16 -06:00
|
|
|
log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
|
2017-08-18 00:52:16 -05:00
|
|
|
return
|
2015-06-04 10:46:07 -05:00
|
|
|
}
|
2015-06-18 10:00:19 -05:00
|
|
|
// Otherwise if the block is indeed in out own chain, announce it
|
2020-12-14 03:27:15 -06:00
|
|
|
if h.chain.HasBlock(hash, block.NumberU64()) {
|
2015-06-18 10:00:19 -05:00
|
|
|
for _, peer := range peers {
|
2018-05-21 03:32:42 -05:00
|
|
|
peer.AsyncSendNewBlockHash(block)
|
2015-06-18 10:00:19 -05:00
|
|
|
}
|
2017-03-02 07:06:16 -06:00
|
|
|
log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt)))
|
2015-04-17 19:21:07 -05:00
|
|
|
}
|
|
|
|
}
|
2015-04-22 10:56:06 -05:00
|
|
|
|
2021-02-17 07:59:00 -06:00
|
|
|
// BroadcastTransactions will propagate a batch of transactions
|
|
|
|
// - To a square root of all peers
|
|
|
|
// - And, separately, as announcements to all peers which are not known to
|
2015-06-26 12:42:27 -05:00
|
|
|
// already have the given transaction.
|
2021-02-17 07:59:00 -06:00
|
|
|
func (h *handler) BroadcastTransactions(txs types.Transactions) {
|
2019-10-28 06:59:07 -05:00
|
|
|
var (
|
2021-02-17 07:59:00 -06:00
|
|
|
annoCount int // Count of announcements made
|
|
|
|
annoPeers int
|
|
|
|
directCount int // Count of the txs sent directly to peers
|
|
|
|
directPeers int // Count of the peers that were sent transactions directly
|
|
|
|
|
|
|
|
txset = make(map[*ethPeer][]common.Hash) // Set peer->hash to transfer directly
|
|
|
|
annos = make(map[*ethPeer][]common.Hash) // Set peer->hash to announce
|
|
|
|
|
2019-10-28 06:59:07 -05:00
|
|
|
)
|
2018-05-10 02:04:45 -05:00
|
|
|
// Broadcast transactions to a batch of peers not knowing about it
|
|
|
|
for _, tx := range txs {
|
2021-02-02 02:44:36 -06:00
|
|
|
peers := h.peers.peersWithoutTransaction(tx.Hash())
|
2021-02-17 07:59:00 -06:00
|
|
|
// Send the tx unconditionally to a subset of our peers
|
|
|
|
numDirect := int(math.Sqrt(float64(len(peers))))
|
|
|
|
for _, peer := range peers[:numDirect] {
|
|
|
|
txset[peer] = append(txset[peer], tx.Hash())
|
|
|
|
}
|
|
|
|
// For the remaining peers, send announcement only
|
|
|
|
for _, peer := range peers[numDirect:] {
|
2019-10-28 06:59:07 -05:00
|
|
|
annos[peer] = append(annos[peer], tx.Hash())
|
2018-05-10 02:04:45 -05:00
|
|
|
}
|
|
|
|
}
|
2021-02-17 07:59:00 -06:00
|
|
|
for peer, hashes := range txset {
|
|
|
|
directPeers++
|
|
|
|
directCount += len(hashes)
|
|
|
|
peer.AsyncSendTransactions(hashes)
|
|
|
|
}
|
2019-10-28 06:59:07 -05:00
|
|
|
for peer, hashes := range annos {
|
2021-02-17 07:59:00 -06:00
|
|
|
annoPeers++
|
|
|
|
annoCount += len(hashes)
|
2021-04-08 10:06:03 -05:00
|
|
|
peer.AsyncSendPooledTransactionHashes(hashes)
|
2015-04-22 10:56:06 -05:00
|
|
|
}
|
2021-02-17 07:59:00 -06:00
|
|
|
log.Debug("Transaction broadcast", "txs", len(txs),
|
|
|
|
"announce packs", annoPeers, "announced hashes", annoCount,
|
|
|
|
"tx packs", directPeers, "broadcast txs", directCount)
|
2015-04-22 10:56:06 -05:00
|
|
|
}
|
|
|
|
|
2020-03-27 08:03:20 -05:00
|
|
|
// minedBroadcastLoop sends mined blocks to connected peers.
|
2020-12-14 03:27:15 -06:00
|
|
|
func (h *handler) minedBroadcastLoop() {
|
|
|
|
defer h.wg.Done()
|
2020-03-27 08:03:20 -05:00
|
|
|
|
2020-12-14 03:27:15 -06:00
|
|
|
for obj := range h.minedBlockSub.Chan() {
|
2018-07-30 04:30:09 -05:00
|
|
|
if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok {
|
2020-12-14 03:27:15 -06:00
|
|
|
h.BroadcastBlock(ev.Block, true) // First propagate block to peers
|
|
|
|
h.BroadcastBlock(ev.Block, false) // Only then announce to the rest
|
2015-04-22 10:56:06 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-27 08:03:20 -05:00
|
|
|
// txBroadcastLoop announces new transactions to connected peers.
|
2020-12-14 03:27:15 -06:00
|
|
|
func (h *handler) txBroadcastLoop() {
|
|
|
|
defer h.wg.Done()
|
2017-08-18 05:58:36 -05:00
|
|
|
for {
|
|
|
|
select {
|
2020-12-14 03:27:15 -06:00
|
|
|
case event := <-h.txsCh:
|
2021-02-17 07:59:00 -06:00
|
|
|
h.BroadcastTransactions(event.Txs)
|
2020-12-14 03:27:15 -06:00
|
|
|
case <-h.txsSub.Err():
|
2017-08-18 05:58:36 -05:00
|
|
|
return
|
|
|
|
}
|
2015-04-22 10:56:06 -05:00
|
|
|
}
|
|
|
|
}
|