github.com/ethereum/go-ethereum@v1.10.9/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 "errors" 21 "math" 22 "math/big" 23 "sync" 24 "sync/atomic" 25 "time" 26 27 "github.com/ethereum/go-ethereum/common" 28 "github.com/ethereum/go-ethereum/core" 29 "github.com/ethereum/go-ethereum/core/forkid" 30 "github.com/ethereum/go-ethereum/core/types" 31 "github.com/ethereum/go-ethereum/eth/downloader" 32 "github.com/ethereum/go-ethereum/eth/fetcher" 33 "github.com/ethereum/go-ethereum/eth/protocols/eth" 34 "github.com/ethereum/go-ethereum/eth/protocols/snap" 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/params" 40 "github.com/ethereum/go-ethereum/trie" 41 ) 42 43 const ( 44 // txChanSize is the size of channel listening to NewTxsEvent. 45 // The number is referenced from the size of tx pool. 46 txChanSize = 4096 47 ) 48 49 var ( 50 syncChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the sync progress challenge 51 ) 52 53 // txPool defines the methods needed from a transaction pool implementation to 54 // support all the operations needed by the Ethereum chain protocols. 55 type txPool interface { 56 // Has returns an indicator whether txpool has a transaction 57 // cached with the given hash. 58 Has(hash common.Hash) bool 59 60 // Get retrieves the transaction from local txpool with given 61 // tx hash. 62 Get(hash common.Hash) *types.Transaction 63 64 // AddRemotes should add the given transactions to the pool. 65 AddRemotes([]*types.Transaction) []error 66 67 // Pending should return pending transactions. 68 // The slice should be modifiable by the caller. 69 Pending(enforceTips bool) (map[common.Address]types.Transactions, error) 70 71 // SubscribeNewTxsEvent should return an event subscription of 72 // NewTxsEvent and send events to the given channel. 73 SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription 74 } 75 76 // handlerConfig is the collection of initialization parameters to create a full 77 // node network handler. 78 type handlerConfig struct { 79 Database ethdb.Database // Database for direct sync insertions 80 Chain *core.BlockChain // Blockchain to serve data from 81 TxPool txPool // Transaction pool to propagate from 82 Network uint64 // Network identifier to adfvertise 83 Sync downloader.SyncMode // Whether to fast or full sync 84 BloomCache uint64 // Megabytes to alloc for fast sync bloom 85 EventMux *event.TypeMux // Legacy event mux, deprecate for `feed` 86 Checkpoint *params.TrustedCheckpoint // Hard coded checkpoint for sync challenges 87 Whitelist map[uint64]common.Hash // Hard coded whitelist for sync challenged 88 } 89 90 type handler struct { 91 networkID uint64 92 forkFilter forkid.Filter // Fork ID filter, constant across the lifetime of the node 93 94 fastSync uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks) 95 snapSync uint32 // Flag whether fast sync should operate on top of the snap protocol 96 acceptTxs uint32 // Flag whether we're considered synchronised (enables transaction processing) 97 98 checkpointNumber uint64 // Block number for the sync progress validator to cross reference 99 checkpointHash common.Hash // Block hash for the sync progress validator to cross reference 100 101 database ethdb.Database 102 txpool txPool 103 chain *core.BlockChain 104 maxPeers int 105 106 downloader *downloader.Downloader 107 stateBloom *trie.SyncBloom 108 blockFetcher *fetcher.BlockFetcher 109 txFetcher *fetcher.TxFetcher 110 peers *peerSet 111 112 eventMux *event.TypeMux 113 txsCh chan core.NewTxsEvent 114 txsSub event.Subscription 115 minedBlockSub *event.TypeMuxSubscription 116 117 whitelist map[uint64]common.Hash 118 119 // channels for fetcher, syncer, txsyncLoop 120 quitSync chan struct{} 121 122 chainSync *chainSyncer 123 wg sync.WaitGroup 124 peerWG sync.WaitGroup 125 } 126 127 // newHandler returns a handler for all Ethereum chain management protocol. 128 func newHandler(config *handlerConfig) (*handler, error) { 129 // Create the protocol manager with the base fields 130 if config.EventMux == nil { 131 config.EventMux = new(event.TypeMux) // Nicety initialization for tests 132 } 133 h := &handler{ 134 networkID: config.Network, 135 forkFilter: forkid.NewFilter(config.Chain), 136 eventMux: config.EventMux, 137 database: config.Database, 138 txpool: config.TxPool, 139 chain: config.Chain, 140 peers: newPeerSet(), 141 whitelist: config.Whitelist, 142 quitSync: make(chan struct{}), 143 } 144 if config.Sync == downloader.FullSync { 145 // The database seems empty as the current block is the genesis. Yet the fast 146 // block is ahead, so fast sync was enabled for this node at a certain point. 147 // The scenarios where this can happen is 148 // * if the user manually (or via a bad block) rolled back a fast sync node 149 // below the sync point. 150 // * the last fast sync is not finished while user specifies a full sync this 151 // time. But we don't have any recent state for full sync. 152 // In these cases however it's safe to reenable fast sync. 153 fullBlock, fastBlock := h.chain.CurrentBlock(), h.chain.CurrentFastBlock() 154 if fullBlock.NumberU64() == 0 && fastBlock.NumberU64() > 0 { 155 h.fastSync = uint32(1) 156 log.Warn("Switch sync mode from full sync to fast sync") 157 } 158 } else { 159 if h.chain.CurrentBlock().NumberU64() > 0 { 160 // Print warning log if database is not empty to run fast sync. 161 log.Warn("Switch sync mode from fast sync to full sync") 162 } else { 163 // If fast sync was requested and our database is empty, grant it 164 h.fastSync = uint32(1) 165 if config.Sync == downloader.SnapSync { 166 h.snapSync = uint32(1) 167 } 168 } 169 } 170 // If we have trusted checkpoints, enforce them on the chain 171 if config.Checkpoint != nil { 172 h.checkpointNumber = (config.Checkpoint.SectionIndex+1)*params.CHTFrequency - 1 173 h.checkpointHash = config.Checkpoint.SectionHead 174 } 175 // Construct the downloader (long sync) and its backing state bloom if fast 176 // sync is requested. The downloader is responsible for deallocating the state 177 // bloom when it's done. 178 // Note: we don't enable it if snap-sync is performed, since it's very heavy 179 // and the heal-portion of the snap sync is much lighter than fast. What we particularly 180 // want to avoid, is a 90%-finished (but restarted) snap-sync to begin 181 // indexing the entire trie 182 if atomic.LoadUint32(&h.fastSync) == 1 && atomic.LoadUint32(&h.snapSync) == 0 { 183 h.stateBloom = trie.NewSyncBloom(config.BloomCache, config.Database) 184 } 185 h.downloader = downloader.New(h.checkpointNumber, config.Database, h.stateBloom, h.eventMux, h.chain, nil, h.removePeer) 186 187 // Construct the fetcher (short sync) 188 validator := func(header *types.Header) error { 189 return h.chain.Engine().VerifyHeader(h.chain, header, true) 190 } 191 heighter := func() uint64 { 192 return h.chain.CurrentBlock().NumberU64() 193 } 194 inserter := func(blocks types.Blocks) (int, error) { 195 // If sync hasn't reached the checkpoint yet, deny importing weird blocks. 196 // 197 // Ideally we would also compare the head block's timestamp and similarly reject 198 // the propagated block if the head is too old. Unfortunately there is a corner 199 // case when starting new networks, where the genesis might be ancient (0 unix) 200 // which would prevent full nodes from accepting it. 201 if h.chain.CurrentBlock().NumberU64() < h.checkpointNumber { 202 log.Warn("Unsynced yet, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash()) 203 return 0, nil 204 } 205 // If fast sync is running, deny importing weird blocks. This is a problematic 206 // clause when starting up a new network, because fast-syncing miners might not 207 // accept each others' blocks until a restart. Unfortunately we haven't figured 208 // out a way yet where nodes can decide unilaterally whether the network is new 209 // or not. This should be fixed if we figure out a solution. 210 if atomic.LoadUint32(&h.fastSync) == 1 { 211 log.Warn("Fast syncing, discarded propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash()) 212 return 0, nil 213 } 214 n, err := h.chain.InsertChain(blocks) 215 if err == nil { 216 atomic.StoreUint32(&h.acceptTxs, 1) // Mark initial sync done on any fetcher import 217 } 218 return n, err 219 } 220 h.blockFetcher = fetcher.NewBlockFetcher(false, nil, h.chain.GetBlockByHash, validator, h.BroadcastBlock, heighter, nil, inserter, h.removePeer) 221 222 fetchTx := func(peer string, hashes []common.Hash) error { 223 p := h.peers.peer(peer) 224 if p == nil { 225 return errors.New("unknown peer") 226 } 227 return p.RequestTxs(hashes) 228 } 229 h.txFetcher = fetcher.NewTxFetcher(h.txpool.Has, h.txpool.AddRemotes, fetchTx) 230 h.chainSync = newChainSyncer(h) 231 return h, nil 232 } 233 234 // runEthPeer registers an eth peer into the joint eth/snap peerset, adds it to 235 // various subsistems and starts handling messages. 236 func (h *handler) runEthPeer(peer *eth.Peer, handler eth.Handler) error { 237 // If the peer has a `snap` extension, wait for it to connect so we can have 238 // a uniform initialization/teardown mechanism 239 snap, err := h.peers.waitSnapExtension(peer) 240 if err != nil { 241 peer.Log().Error("Snapshot extension barrier failed", "err", err) 242 return err 243 } 244 // TODO(karalabe): Not sure why this is needed 245 if !h.chainSync.handlePeerEvent(peer) { 246 return p2p.DiscQuitting 247 } 248 h.peerWG.Add(1) 249 defer h.peerWG.Done() 250 251 // Execute the Ethereum handshake 252 var ( 253 genesis = h.chain.Genesis() 254 head = h.chain.CurrentHeader() 255 hash = head.Hash() 256 number = head.Number.Uint64() 257 td = h.chain.GetTd(hash, number) 258 ) 259 forkID := forkid.NewID(h.chain.Config(), h.chain.Genesis().Hash(), h.chain.CurrentHeader().Number.Uint64()) 260 if err := peer.Handshake(h.networkID, td, hash, genesis.Hash(), forkID, h.forkFilter); err != nil { 261 peer.Log().Debug("Ethereum handshake failed", "err", err) 262 return err 263 } 264 reject := false // reserved peer slots 265 if atomic.LoadUint32(&h.snapSync) == 1 { 266 if snap == nil { 267 // If we are running snap-sync, we want to reserve roughly half the peer 268 // slots for peers supporting the snap protocol. 269 // The logic here is; we only allow up to 5 more non-snap peers than snap-peers. 270 if all, snp := h.peers.len(), h.peers.snapLen(); all-snp > snp+5 { 271 reject = true 272 } 273 } 274 } 275 // Ignore maxPeers if this is a trusted peer 276 if !peer.Peer.Info().Network.Trusted { 277 if reject || h.peers.len() >= h.maxPeers { 278 return p2p.DiscTooManyPeers 279 } 280 } 281 peer.Log().Debug("Ethereum peer connected", "name", peer.Name()) 282 283 // Register the peer locally 284 if err := h.peers.registerPeer(peer, snap); err != nil { 285 peer.Log().Error("Ethereum peer registration failed", "err", err) 286 return err 287 } 288 defer h.unregisterPeer(peer.ID()) 289 290 p := h.peers.peer(peer.ID()) 291 if p == nil { 292 return errors.New("peer dropped during handling") 293 } 294 // Register the peer in the downloader. If the downloader considers it banned, we disconnect 295 if err := h.downloader.RegisterPeer(peer.ID(), peer.Version(), peer); err != nil { 296 peer.Log().Error("Failed to register peer in eth syncer", "err", err) 297 return err 298 } 299 if snap != nil { 300 if err := h.downloader.SnapSyncer.Register(snap); err != nil { 301 peer.Log().Error("Failed to register peer in snap syncer", "err", err) 302 return err 303 } 304 } 305 h.chainSync.handlePeerEvent(peer) 306 307 // Propagate existing transactions. new transactions appearing 308 // after this will be sent via broadcasts. 309 h.syncTransactions(peer) 310 311 // If we have a trusted CHT, reject all peers below that (avoid fast sync eclipse) 312 if h.checkpointHash != (common.Hash{}) { 313 // Request the peer's checkpoint header for chain height/weight validation 314 if err := peer.RequestHeadersByNumber(h.checkpointNumber, 1, 0, false); err != nil { 315 return err 316 } 317 // Start a timer to disconnect if the peer doesn't reply in time 318 p.syncDrop = time.AfterFunc(syncChallengeTimeout, func() { 319 peer.Log().Warn("Checkpoint challenge timed out, dropping", "addr", peer.RemoteAddr(), "type", peer.Name()) 320 h.removePeer(peer.ID()) 321 }) 322 // Make sure it's cleaned up if the peer dies off 323 defer func() { 324 if p.syncDrop != nil { 325 p.syncDrop.Stop() 326 p.syncDrop = nil 327 } 328 }() 329 } 330 // If we have any explicit whitelist block hashes, request them 331 for number := range h.whitelist { 332 if err := peer.RequestHeadersByNumber(number, 1, 0, false); err != nil { 333 return err 334 } 335 } 336 // Handle incoming messages until the connection is torn down 337 return handler(peer) 338 } 339 340 // runSnapExtension registers a `snap` peer into the joint eth/snap peerset and 341 // starts handling inbound messages. As `snap` is only a satellite protocol to 342 // `eth`, all subsystem registrations and lifecycle management will be done by 343 // the main `eth` handler to prevent strange races. 344 func (h *handler) runSnapExtension(peer *snap.Peer, handler snap.Handler) error { 345 h.peerWG.Add(1) 346 defer h.peerWG.Done() 347 348 if err := h.peers.registerSnapExtension(peer); err != nil { 349 peer.Log().Error("Snapshot extension registration failed", "err", err) 350 return err 351 } 352 return handler(peer) 353 } 354 355 // removePeer requests disconnection of a peer. 356 func (h *handler) removePeer(id string) { 357 peer := h.peers.peer(id) 358 if peer != nil { 359 peer.Peer.Disconnect(p2p.DiscUselessPeer) 360 } 361 } 362 363 // unregisterPeer removes a peer from the downloader, fetchers and main peer set. 364 func (h *handler) unregisterPeer(id string) { 365 // Create a custom logger to avoid printing the entire id 366 var logger log.Logger 367 if len(id) < 16 { 368 // Tests use short IDs, don't choke on them 369 logger = log.New("peer", id) 370 } else { 371 logger = log.New("peer", id[:8]) 372 } 373 // Abort if the peer does not exist 374 peer := h.peers.peer(id) 375 if peer == nil { 376 logger.Error("Ethereum peer removal failed", "err", errPeerNotRegistered) 377 return 378 } 379 // Remove the `eth` peer if it exists 380 logger.Debug("Removing Ethereum peer", "snap", peer.snapExt != nil) 381 382 // Remove the `snap` extension if it exists 383 if peer.snapExt != nil { 384 h.downloader.SnapSyncer.Unregister(id) 385 } 386 h.downloader.UnregisterPeer(id) 387 h.txFetcher.Drop(id) 388 389 if err := h.peers.unregisterPeer(id); err != nil { 390 logger.Error("Ethereum peer removal failed", "err", err) 391 } 392 } 393 394 func (h *handler) Start(maxPeers int) { 395 h.maxPeers = maxPeers 396 397 // broadcast transactions 398 h.wg.Add(1) 399 h.txsCh = make(chan core.NewTxsEvent, txChanSize) 400 h.txsSub = h.txpool.SubscribeNewTxsEvent(h.txsCh) 401 go h.txBroadcastLoop() 402 403 // broadcast mined blocks 404 h.wg.Add(1) 405 h.minedBlockSub = h.eventMux.Subscribe(core.NewMinedBlockEvent{}) 406 go h.minedBroadcastLoop() 407 408 // start sync handlers 409 h.wg.Add(1) 410 go h.chainSync.loop() 411 } 412 413 func (h *handler) Stop() { 414 h.txsSub.Unsubscribe() // quits txBroadcastLoop 415 h.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop 416 417 // Quit chainSync and txsync64. 418 // After this is done, no new peers will be accepted. 419 close(h.quitSync) 420 h.wg.Wait() 421 422 // Disconnect existing sessions. 423 // This also closes the gate for any new registrations on the peer set. 424 // sessions which are already established but not added to h.peers yet 425 // will exit when they try to register. 426 h.peers.close() 427 h.peerWG.Wait() 428 429 log.Info("Ethereum protocol stopped") 430 } 431 432 // BroadcastBlock will either propagate a block to a subset of its peers, or 433 // will only announce its availability (depending what's requested). 434 func (h *handler) BroadcastBlock(block *types.Block, propagate bool) { 435 hash := block.Hash() 436 peers := h.peers.peersWithoutBlock(hash) 437 438 // If propagation is requested, send to a subset of the peer 439 if propagate { 440 // Calculate the TD of the block (it's not imported yet, so block.Td is not valid) 441 var td *big.Int 442 if parent := h.chain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil { 443 td = new(big.Int).Add(block.Difficulty(), h.chain.GetTd(block.ParentHash(), block.NumberU64()-1)) 444 } else { 445 log.Error("Propagating dangling block", "number", block.Number(), "hash", hash) 446 return 447 } 448 // Send the block to a subset of our peers 449 transfer := peers[:int(math.Sqrt(float64(len(peers))))] 450 for _, peer := range transfer { 451 peer.AsyncSendNewBlock(block, td) 452 } 453 log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt))) 454 return 455 } 456 // Otherwise if the block is indeed in out own chain, announce it 457 if h.chain.HasBlock(hash, block.NumberU64()) { 458 for _, peer := range peers { 459 peer.AsyncSendNewBlockHash(block) 460 } 461 log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt))) 462 } 463 } 464 465 // BroadcastTransactions will propagate a batch of transactions 466 // - To a square root of all peers 467 // - And, separately, as announcements to all peers which are not known to 468 // already have the given transaction. 469 func (h *handler) BroadcastTransactions(txs types.Transactions) { 470 var ( 471 annoCount int // Count of announcements made 472 annoPeers int 473 directCount int // Count of the txs sent directly to peers 474 directPeers int // Count of the peers that were sent transactions directly 475 476 txset = make(map[*ethPeer][]common.Hash) // Set peer->hash to transfer directly 477 annos = make(map[*ethPeer][]common.Hash) // Set peer->hash to announce 478 479 ) 480 // Broadcast transactions to a batch of peers not knowing about it 481 for _, tx := range txs { 482 peers := h.peers.peersWithoutTransaction(tx.Hash()) 483 // Send the tx unconditionally to a subset of our peers 484 numDirect := int(math.Sqrt(float64(len(peers)))) 485 for _, peer := range peers[:numDirect] { 486 txset[peer] = append(txset[peer], tx.Hash()) 487 } 488 // For the remaining peers, send announcement only 489 for _, peer := range peers[numDirect:] { 490 annos[peer] = append(annos[peer], tx.Hash()) 491 } 492 } 493 for peer, hashes := range txset { 494 directPeers++ 495 directCount += len(hashes) 496 peer.AsyncSendTransactions(hashes) 497 } 498 for peer, hashes := range annos { 499 annoPeers++ 500 annoCount += len(hashes) 501 peer.AsyncSendPooledTransactionHashes(hashes) 502 } 503 log.Debug("Transaction broadcast", "txs", len(txs), 504 "announce packs", annoPeers, "announced hashes", annoCount, 505 "tx packs", directPeers, "broadcast txs", directCount) 506 } 507 508 // minedBroadcastLoop sends mined blocks to connected peers. 509 func (h *handler) minedBroadcastLoop() { 510 defer h.wg.Done() 511 512 for obj := range h.minedBlockSub.Chan() { 513 if ev, ok := obj.Data.(core.NewMinedBlockEvent); ok { 514 h.BroadcastBlock(ev.Block, true) // First propagate block to peers 515 h.BroadcastBlock(ev.Block, false) // Only then announce to the rest 516 } 517 } 518 } 519 520 // txBroadcastLoop announces new transactions to connected peers. 521 func (h *handler) txBroadcastLoop() { 522 defer h.wg.Done() 523 for { 524 select { 525 case event := <-h.txsCh: 526 h.BroadcastTransactions(event.Txs) 527 case <-h.txsSub.Err(): 528 return 529 } 530 } 531 }