github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/eth/fetcher/fetcher.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 fetcher contains the block announcement based synchronisation. 18 package fetcher 19 20 import ( 21 "errors" 22 "math/rand" 23 "time" 24 25 "github.com/ethereum/go-ethereum/common" 26 "github.com/ethereum/go-ethereum/common/prque" 27 "github.com/ethereum/go-ethereum/consensus" 28 "github.com/ethereum/go-ethereum/core/types" 29 "github.com/ethereum/go-ethereum/log" 30 ) 31 32 const ( 33 arriveTimeout = 500 * time.Millisecond // Time allowance before an announced block is explicitly requested 34 gatherSlack = 100 * time.Millisecond // Interval used to collate almost-expired announces with fetches 35 fetchTimeout = 5 * time.Second // Maximum allotted time to return an explicitly requested block 36 maxUncleDist = 7 // Maximum allowed backward distance from the chain head 37 maxQueueDist = 32 // Maximum allowed distance from the chain head to queue 38 hashLimit = 256 // Maximum number of unique blocks a peer may have announced 39 blockLimit = 64 // Maximum number of unique blocks a peer may have delivered 40 ) 41 42 var ( 43 errTerminated = errors.New("terminated") 44 ) 45 46 // blockRetrievalFn is a callback type for retrieving a block from the local chain. 47 type blockRetrievalFn func(common.Hash) *types.Block 48 49 // headerRequesterFn is a callback type for sending a header retrieval request. 50 type headerRequesterFn func(common.Hash) error 51 52 // bodyRequesterFn is a callback type for sending a body retrieval request. 53 type bodyRequesterFn func([]common.Hash) error 54 55 // headerVerifierFn is a callback type to verify a block's header for fast propagation. 56 type headerVerifierFn func(header *types.Header) error 57 58 // blockBroadcasterFn is a callback type for broadcasting a block to connected peers. 59 type blockBroadcasterFn func(block *types.Block, propagate bool) 60 61 // chainHeightFn is a callback type to retrieve the current chain height. 62 type chainHeightFn func() uint64 63 64 // chainInsertFn is a callback type to insert a batch of blocks into the local chain. 65 type chainInsertFn func(types.Blocks) (int, error) 66 67 // peerDropFn is a callback type for dropping a peer detected as malicious. 68 type peerDropFn func(id string) 69 70 // announce is the hash notification of the availability of a new block in the 71 // network. 72 type announce struct { 73 hash common.Hash // Hash of the block being announced 74 number uint64 // Number of the block being announced (0 = unknown | old protocol) 75 header *types.Header // Header of the block partially reassembled (new protocol) 76 time time.Time // Timestamp of the announcement 77 78 origin string // Identifier of the peer originating the notification 79 80 fetchHeader headerRequesterFn // Fetcher function to retrieve the header of an announced block 81 fetchBodies bodyRequesterFn // Fetcher function to retrieve the body of an announced block 82 } 83 84 // headerFilterTask represents a batch of headers needing fetcher filtering. 85 type headerFilterTask struct { 86 peer string // The source peer of block headers 87 headers []*types.Header // Collection of headers to filter 88 time time.Time // Arrival time of the headers 89 } 90 91 // bodyFilterTask represents a batch of block bodies (transactions and uncles) 92 // needing fetcher filtering. 93 type bodyFilterTask struct { 94 peer string // The source peer of block bodies 95 transactions [][]*types.Transaction // Collection of transactions per block bodies 96 uncles [][]*types.Header // Collection of uncles per block bodies 97 randomness []*types.Randomness 98 epochSnarkData []*types.EpochSnarkData 99 time time.Time // Arrival time of the blocks' contents 100 } 101 102 // inject represents a schedules import operation. 103 type inject struct { 104 origin string 105 block *types.Block 106 } 107 108 // Fetcher is responsible for accumulating block announcements from various peers 109 // and scheduling them for retrieval. 110 type Fetcher struct { 111 // Various event channels 112 notify chan *announce 113 inject chan *inject 114 115 blockFilter chan chan []*types.Block 116 headerFilter chan chan *headerFilterTask 117 bodyFilter chan chan *bodyFilterTask 118 119 done chan common.Hash 120 quit chan struct{} 121 122 // Announce states 123 announces map[string]int // Per peer announce counts to prevent memory exhaustion 124 announced map[common.Hash][]*announce // Announced blocks, scheduled for fetching 125 fetching map[common.Hash]*announce // Announced blocks, currently fetching 126 fetched map[common.Hash][]*announce // Blocks with headers fetched, scheduled for body retrieval 127 completing map[common.Hash]*announce // Blocks with headers, currently body-completing 128 129 // Block cache 130 queue *prque.Prque // Queue containing the import operations (block number sorted) 131 queues map[string]int // Per peer block counts to prevent memory exhaustion 132 queued map[common.Hash]*inject // Set of already queued blocks (to dedupe imports) 133 134 // Callbacks 135 getBlock blockRetrievalFn // Retrieves a block from the local chain 136 verifyHeader headerVerifierFn // Checks if a block's headers have a valid proof of work 137 broadcastBlock blockBroadcasterFn // Broadcasts a block to connected peers 138 chainHeight chainHeightFn // Retrieves the current chain's height 139 insertChain chainInsertFn // Injects a batch of blocks into the chain 140 dropPeer peerDropFn // Drops a peer for misbehaving 141 142 // Testing hooks 143 announceChangeHook func(common.Hash, bool) // Method to call upon adding or deleting a hash from the announce list 144 queueChangeHook func(common.Hash, bool) // Method to call upon adding or deleting a block from the import queue 145 fetchingHook func([]common.Hash) // Method to call upon starting a block (eth/61) or header (eth/62) fetch 146 completingHook func([]common.Hash) // Method to call upon starting a block body fetch (eth/62) 147 importedHook func(*types.Block) // Method to call upon successful block import (both eth/61 and eth/62) 148 } 149 150 // New creates a block fetcher to retrieve blocks based on hash announcements. 151 func New(getBlock blockRetrievalFn, verifyHeader headerVerifierFn, broadcastBlock blockBroadcasterFn, chainHeight chainHeightFn, insertChain chainInsertFn, dropPeer peerDropFn) *Fetcher { 152 return &Fetcher{ 153 notify: make(chan *announce), 154 inject: make(chan *inject), 155 blockFilter: make(chan chan []*types.Block), 156 headerFilter: make(chan chan *headerFilterTask), 157 bodyFilter: make(chan chan *bodyFilterTask), 158 done: make(chan common.Hash), 159 quit: make(chan struct{}), 160 announces: make(map[string]int), 161 announced: make(map[common.Hash][]*announce), 162 fetching: make(map[common.Hash]*announce), 163 fetched: make(map[common.Hash][]*announce), 164 completing: make(map[common.Hash]*announce), 165 queue: prque.New(nil), 166 queues: make(map[string]int), 167 queued: make(map[common.Hash]*inject), 168 getBlock: getBlock, 169 verifyHeader: verifyHeader, 170 broadcastBlock: broadcastBlock, 171 chainHeight: chainHeight, 172 insertChain: insertChain, 173 dropPeer: dropPeer, 174 } 175 } 176 177 // Start boots up the announcement based synchroniser, accepting and processing 178 // hash notifications and block fetches until termination requested. 179 func (f *Fetcher) Start() { 180 go f.loop() 181 } 182 183 // Stop terminates the announcement based synchroniser, canceling all pending 184 // operations. 185 func (f *Fetcher) Stop() { 186 close(f.quit) 187 } 188 189 // Notify announces the fetcher of the potential availability of a new block in 190 // the network. 191 func (f *Fetcher) Notify(peer string, hash common.Hash, number uint64, time time.Time, 192 headerFetcher headerRequesterFn, bodyFetcher bodyRequesterFn) error { 193 block := &announce{ 194 hash: hash, 195 number: number, 196 time: time, 197 origin: peer, 198 fetchHeader: headerFetcher, 199 fetchBodies: bodyFetcher, 200 } 201 select { 202 case f.notify <- block: 203 return nil 204 case <-f.quit: 205 return errTerminated 206 } 207 } 208 209 // Enqueue tries to fill gaps the fetcher's future import queue. 210 func (f *Fetcher) Enqueue(peer string, block *types.Block) error { 211 op := &inject{ 212 origin: peer, 213 block: block, 214 } 215 select { 216 case f.inject <- op: 217 return nil 218 case <-f.quit: 219 return errTerminated 220 } 221 } 222 223 // FilterHeaders extracts all the headers that were explicitly requested by the fetcher, 224 // returning those that should be handled differently. 225 func (f *Fetcher) FilterHeaders(peer string, headers []*types.Header, time time.Time) []*types.Header { 226 log.Trace("Filtering headers", "peer", peer, "headers", len(headers)) 227 228 // Send the filter channel to the fetcher 229 filter := make(chan *headerFilterTask) 230 231 select { 232 case f.headerFilter <- filter: 233 case <-f.quit: 234 return nil 235 } 236 // Request the filtering of the header list 237 select { 238 case filter <- &headerFilterTask{peer: peer, headers: headers, time: time}: 239 case <-f.quit: 240 return nil 241 } 242 // Retrieve the headers remaining after filtering 243 select { 244 case task := <-filter: 245 return task.headers 246 case <-f.quit: 247 return nil 248 } 249 } 250 251 // FilterBodies extracts all the block bodies that were explicitly requested by 252 // the fetcher, returning those that should be handled differently. 253 func (f *Fetcher) FilterBodies(peer string, transactions [][]*types.Transaction, uncles [][]*types.Header, randomness []*types.Randomness, epochSnarkData []*types.EpochSnarkData, time time.Time) ([][]*types.Transaction, [][]*types.Header, []*types.Randomness, []*types.EpochSnarkData) { 254 log.Trace("Filtering bodies", "peer", peer, "txs", len(transactions), "uncles", len(uncles)) 255 256 // Send the filter channel to the fetcher 257 filter := make(chan *bodyFilterTask) 258 259 select { 260 case f.bodyFilter <- filter: 261 case <-f.quit: 262 return nil, nil, nil, nil 263 } 264 // Request the filtering of the body list 265 select { 266 case filter <- &bodyFilterTask{peer: peer, transactions: transactions, uncles: uncles, randomness: randomness, epochSnarkData: epochSnarkData, time: time}: 267 case <-f.quit: 268 return nil, nil, nil, nil 269 } 270 // Retrieve the bodies remaining after filtering 271 select { 272 case task := <-filter: 273 return task.transactions, task.uncles, task.randomness, task.epochSnarkData 274 case <-f.quit: 275 return nil, nil, nil, nil 276 } 277 } 278 279 // Loop is the main fetcher loop, checking and processing various notification 280 // events. 281 func (f *Fetcher) loop() { 282 // Iterate the block fetching until a quit is requested 283 fetchTimer := time.NewTimer(0) 284 completeTimer := time.NewTimer(0) 285 286 for { 287 // Clean up any expired block fetches 288 for hash, announce := range f.fetching { 289 if time.Since(announce.time) > fetchTimeout { 290 f.forgetHash(hash) 291 } 292 } 293 // Import any queued blocks that could potentially fit 294 height := f.chainHeight() 295 for !f.queue.Empty() { 296 op := f.queue.PopItem().(*inject) 297 hash := op.block.Hash() 298 if f.queueChangeHook != nil { 299 f.queueChangeHook(hash, false) 300 } 301 // If too high up the chain or phase, continue later 302 number := op.block.NumberU64() 303 if number > height+1 { 304 f.queue.Push(op, -int64(number)) 305 if f.queueChangeHook != nil { 306 f.queueChangeHook(hash, true) 307 } 308 break 309 } 310 // Otherwise if fresh and still unknown, try and import 311 if number+maxUncleDist < height || f.getBlock(hash) != nil { 312 f.forgetBlock(hash) 313 continue 314 } 315 f.insert(op.origin, op.block) 316 } 317 // Wait for an outside event to occur 318 select { 319 case <-f.quit: 320 // Fetcher terminating, abort all operations 321 return 322 323 case notification := <-f.notify: 324 // A block was announced, make sure the peer isn't DOSing us 325 propAnnounceInMeter.Mark(1) 326 327 count := f.announces[notification.origin] + 1 328 if count > hashLimit { 329 log.Debug("Peer exceeded outstanding announces", "peer", notification.origin, "limit", hashLimit) 330 propAnnounceDOSMeter.Mark(1) 331 break 332 } 333 // If we have a valid block number, check that it's potentially useful 334 if notification.number > 0 { 335 if dist := int64(notification.number) - int64(f.chainHeight()); dist < -maxUncleDist || dist > maxQueueDist { 336 log.Debug("Peer discarded announcement", "peer", notification.origin, "number", notification.number, "hash", notification.hash, "distance", dist) 337 propAnnounceDropMeter.Mark(1) 338 break 339 } 340 } 341 // All is well, schedule the announce if block's not yet downloading 342 if _, ok := f.fetching[notification.hash]; ok { 343 break 344 } 345 if _, ok := f.completing[notification.hash]; ok { 346 break 347 } 348 f.announces[notification.origin] = count 349 f.announced[notification.hash] = append(f.announced[notification.hash], notification) 350 if f.announceChangeHook != nil && len(f.announced[notification.hash]) == 1 { 351 f.announceChangeHook(notification.hash, true) 352 } 353 if len(f.announced) == 1 { 354 f.rescheduleFetch(fetchTimer) 355 } 356 357 case op := <-f.inject: 358 // A direct block insertion was requested, try and fill any pending gaps 359 propBroadcastInMeter.Mark(1) 360 f.enqueue(op.origin, op.block) 361 362 case hash := <-f.done: 363 // A pending import finished, remove all traces of the notification 364 f.forgetHash(hash) 365 f.forgetBlock(hash) 366 367 case <-fetchTimer.C: 368 // At least one block's timer ran out, check for needing retrieval 369 request := make(map[string][]common.Hash) 370 371 for hash, announces := range f.announced { 372 if time.Since(announces[0].time) > arriveTimeout-gatherSlack { 373 // Pick a random peer to retrieve from, reset all others 374 announce := announces[rand.Intn(len(announces))] 375 f.forgetHash(hash) 376 377 // If the block still didn't arrive, queue for fetching 378 if f.getBlock(hash) == nil { 379 request[announce.origin] = append(request[announce.origin], hash) 380 f.fetching[hash] = announce 381 } 382 } 383 } 384 // Send out all block header requests 385 for peer, hashes := range request { 386 log.Trace("Fetching scheduled headers", "peer", peer, "list", hashes) 387 388 // Create a closure of the fetch and schedule in on a new thread 389 fetchHeader, hashes := f.fetching[hashes[0]].fetchHeader, hashes 390 go func() { 391 if f.fetchingHook != nil { 392 f.fetchingHook(hashes) 393 } 394 for _, hash := range hashes { 395 headerFetchMeter.Mark(1) 396 fetchHeader(hash) // Suboptimal, but protocol doesn't allow batch header retrievals 397 } 398 }() 399 } 400 // Schedule the next fetch if blocks are still pending 401 f.rescheduleFetch(fetchTimer) 402 403 case <-completeTimer.C: 404 // At least one header's timer ran out, retrieve everything 405 request := make(map[string][]common.Hash) 406 407 for hash, announces := range f.fetched { 408 // Pick a random peer to retrieve from, reset all others 409 announce := announces[rand.Intn(len(announces))] 410 f.forgetHash(hash) 411 412 // If the block still didn't arrive, queue for completion 413 if f.getBlock(hash) == nil { 414 request[announce.origin] = append(request[announce.origin], hash) 415 f.completing[hash] = announce 416 } 417 } 418 // Send out all block body requests 419 for peer, hashes := range request { 420 log.Trace("Fetching scheduled bodies", "peer", peer, "list", hashes) 421 422 // Create a closure of the fetch and schedule in on a new thread 423 if f.completingHook != nil { 424 f.completingHook(hashes) 425 } 426 bodyFetchMeter.Mark(int64(len(hashes))) 427 go f.completing[hashes[0]].fetchBodies(hashes) 428 } 429 // Schedule the next fetch if blocks are still pending 430 f.rescheduleComplete(completeTimer) 431 432 case filter := <-f.headerFilter: 433 // Headers arrived from a remote peer. Extract those that were explicitly 434 // requested by the fetcher, and return everything else so it's delivered 435 // to other parts of the system. 436 var task *headerFilterTask 437 select { 438 case task = <-filter: 439 case <-f.quit: 440 return 441 } 442 headerFilterInMeter.Mark(int64(len(task.headers))) 443 444 // Split the batch of headers into unknown ones (to return to the caller), 445 // known incomplete ones (requiring body retrievals) and completed blocks. 446 unknown, incomplete, complete := []*types.Header{}, []*announce{}, []*types.Block{} 447 for _, header := range task.headers { 448 hash := header.Hash() 449 450 // Filter fetcher-requested headers from other synchronisation algorithms 451 if announce := f.fetching[hash]; announce != nil && announce.origin == task.peer && f.fetched[hash] == nil && f.completing[hash] == nil && f.queued[hash] == nil { 452 // If the delivered header does not match the promised number, drop the announcer 453 if header.Number.Uint64() != announce.number { 454 log.Trace("Invalid block number fetched", "peer", announce.origin, "hash", header.Hash(), "announced", announce.number, "provided", header.Number) 455 f.dropPeer(announce.origin) 456 f.forgetHash(hash) 457 continue 458 } 459 // Only keep if not imported by other means 460 if f.getBlock(hash) == nil { 461 announce.header = header 462 announce.time = task.time 463 464 // Otherwise add to the list of blocks needing completion 465 incomplete = append(incomplete, announce) 466 } else { 467 log.Trace("Block already imported, discarding header", "peer", announce.origin, "number", header.Number, "hash", header.Hash()) 468 f.forgetHash(hash) 469 } 470 } else { 471 // Fetcher doesn't know about it, add to the return list 472 unknown = append(unknown, header) 473 } 474 } 475 headerFilterOutMeter.Mark(int64(len(unknown))) 476 select { 477 case filter <- &headerFilterTask{headers: unknown, time: task.time}: 478 case <-f.quit: 479 return 480 } 481 // Schedule the retrieved headers for body completion 482 for _, announce := range incomplete { 483 hash := announce.header.Hash() 484 if _, ok := f.completing[hash]; ok { 485 continue 486 } 487 f.fetched[hash] = append(f.fetched[hash], announce) 488 if len(f.fetched) == 1 { 489 f.rescheduleComplete(completeTimer) 490 } 491 } 492 // Schedule the header-only blocks for import 493 for _, block := range complete { 494 if announce := f.completing[block.Hash()]; announce != nil { 495 f.enqueue(announce.origin, block) 496 } 497 } 498 499 case filter := <-f.bodyFilter: 500 // Block bodies arrived, extract any explicitly requested blocks, return the rest 501 var task *bodyFilterTask 502 select { 503 case task = <-filter: 504 case <-f.quit: 505 return 506 } 507 bodyFilterInMeter.Mark(int64(len(task.transactions))) 508 509 blocks := []*types.Block{} 510 for i := 0; i < len(task.transactions) && i < len(task.uncles) && i < len(task.randomness) && i < len(task.epochSnarkData); i++ { 511 // Match up a body to any possible completion request 512 matched := false 513 514 for hash, announce := range f.completing { 515 if f.queued[hash] == nil { 516 txnHash := types.DeriveSha(types.Transactions(task.transactions[i])) 517 uncleHash := types.CalcUncleHash(task.uncles[i]) 518 519 if txnHash == announce.header.TxHash && uncleHash == announce.header.UncleHash && announce.origin == task.peer { 520 // Mark the body matched, reassemble if still unknown 521 matched = true 522 523 if f.getBlock(hash) == nil { 524 block := types.NewBlockWithHeader(announce.header).WithBody(task.transactions[i], task.uncles[i], task.randomness[i], task.epochSnarkData[i]) 525 block.ReceivedAt = task.time 526 527 blocks = append(blocks, block) 528 } else { 529 f.forgetHash(hash) 530 } 531 } 532 } 533 } 534 if matched { 535 task.transactions = append(task.transactions[:i], task.transactions[i+1:]...) 536 task.uncles = append(task.uncles[:i], task.uncles[i+1:]...) 537 task.randomness = append(task.randomness[:i], task.randomness[i+1:]...) 538 task.epochSnarkData = append(task.epochSnarkData[:i], task.epochSnarkData[i+1:]...) 539 i-- 540 continue 541 } 542 } 543 544 bodyFilterOutMeter.Mark(int64(len(task.transactions))) 545 select { 546 case filter <- task: 547 case <-f.quit: 548 return 549 } 550 // Schedule the retrieved blocks for ordered import 551 for _, block := range blocks { 552 if announce := f.completing[block.Hash()]; announce != nil { 553 f.enqueue(announce.origin, block) 554 } 555 } 556 } 557 } 558 } 559 560 // rescheduleFetch resets the specified fetch timer to the next announce timeout. 561 func (f *Fetcher) rescheduleFetch(fetch *time.Timer) { 562 // Short circuit if no blocks are announced 563 if len(f.announced) == 0 { 564 return 565 } 566 // Otherwise find the earliest expiring announcement 567 earliest := time.Now() 568 for _, announces := range f.announced { 569 if earliest.After(announces[0].time) { 570 earliest = announces[0].time 571 } 572 } 573 fetch.Reset(arriveTimeout - time.Since(earliest)) 574 } 575 576 // rescheduleComplete resets the specified completion timer to the next fetch timeout. 577 func (f *Fetcher) rescheduleComplete(complete *time.Timer) { 578 // Short circuit if no headers are fetched 579 if len(f.fetched) == 0 { 580 return 581 } 582 // Otherwise find the earliest expiring announcement 583 earliest := time.Now() 584 for _, announces := range f.fetched { 585 if earliest.After(announces[0].time) { 586 earliest = announces[0].time 587 } 588 } 589 complete.Reset(gatherSlack - time.Since(earliest)) 590 } 591 592 // enqueue schedules a new future import operation, if the block to be imported 593 // has not yet been seen. 594 func (f *Fetcher) enqueue(peer string, block *types.Block) { 595 hash := block.Hash() 596 597 // Ensure the peer isn't DOSing us 598 count := f.queues[peer] + 1 599 if count > blockLimit { 600 log.Debug("Discarded propagated block, exceeded allowance", "peer", peer, "number", block.Number(), "hash", hash, "limit", blockLimit) 601 propBroadcastDOSMeter.Mark(1) 602 f.forgetHash(hash) 603 return 604 } 605 // Discard any past or too distant blocks 606 if dist := int64(block.NumberU64()) - int64(f.chainHeight()); dist < -maxUncleDist || dist > maxQueueDist { 607 log.Debug("Discarded propagated block, too far away", "peer", peer, "number", block.Number(), "hash", hash, "distance", dist) 608 propBroadcastDropMeter.Mark(1) 609 f.forgetHash(hash) 610 return 611 } 612 // Schedule the block for future importing 613 if _, ok := f.queued[hash]; !ok { 614 op := &inject{ 615 origin: peer, 616 block: block, 617 } 618 f.queues[peer] = count 619 f.queued[hash] = op 620 f.queue.Push(op, -int64(block.NumberU64())) 621 if f.queueChangeHook != nil { 622 f.queueChangeHook(op.block.Hash(), true) 623 } 624 log.Debug("Queued propagated block", "peer", peer, "number", block.Number(), "hash", hash, "queued", f.queue.Size()) 625 } 626 } 627 628 // insert spawns a new goroutine to run a block insertion into the chain. If the 629 // block's number is at the same height as the current import phase, it updates 630 // the phase states accordingly. 631 func (f *Fetcher) insert(peer string, block *types.Block) { 632 hash := block.Hash() 633 634 // Run the import on a new thread 635 log.Debug("Importing propagated block", "peer", peer, "number", block.Number(), "hash", hash) 636 go func() { 637 defer func() { f.done <- hash }() 638 639 // If the parent's unknown, abort insertion 640 parent := f.getBlock(block.ParentHash()) 641 if parent == nil { 642 log.Debug("Unknown parent of propagated block", "peer", peer, "number", block.Number(), "hash", hash, "parent", block.ParentHash()) 643 return 644 } 645 // Quickly validate the header and propagate the block if it passes 646 switch err := f.verifyHeader(block.Header()); err { 647 case nil: 648 // All ok, quickly propagate to our peers 649 propBroadcastOutTimer.UpdateSince(block.ReceivedAt) 650 go f.broadcastBlock(block, true) 651 652 case consensus.ErrFutureBlock: 653 // Weird future block, don't fail, but neither propagate 654 655 default: 656 // Something went very wrong, drop the peer 657 log.Debug("Propagated block verification failed", "peer", peer, "number", block.Number(), "hash", hash, "err", err) 658 f.dropPeer(peer) 659 return 660 } 661 // Run the actual import and log any issues 662 if _, err := f.insertChain(types.Blocks{block}); err != nil { 663 log.Debug("Propagated block import failed", "peer", peer, "number", block.Number(), "hash", hash, "err", err) 664 return 665 } 666 // If import succeeded, broadcast the block 667 propAnnounceOutTimer.UpdateSince(block.ReceivedAt) 668 go f.broadcastBlock(block, false) 669 670 // Invoke the testing hook if needed 671 if f.importedHook != nil { 672 f.importedHook(block) 673 } 674 }() 675 } 676 677 // forgetHash removes all traces of a block announcement from the fetcher's 678 // internal state. 679 func (f *Fetcher) forgetHash(hash common.Hash) { 680 // Remove all pending announces and decrement DOS counters 681 for _, announce := range f.announced[hash] { 682 f.announces[announce.origin]-- 683 if f.announces[announce.origin] == 0 { 684 delete(f.announces, announce.origin) 685 } 686 } 687 delete(f.announced, hash) 688 if f.announceChangeHook != nil { 689 f.announceChangeHook(hash, false) 690 } 691 // Remove any pending fetches and decrement the DOS counters 692 if announce := f.fetching[hash]; announce != nil { 693 f.announces[announce.origin]-- 694 if f.announces[announce.origin] == 0 { 695 delete(f.announces, announce.origin) 696 } 697 delete(f.fetching, hash) 698 } 699 700 // Remove any pending completion requests and decrement the DOS counters 701 for _, announce := range f.fetched[hash] { 702 f.announces[announce.origin]-- 703 if f.announces[announce.origin] == 0 { 704 delete(f.announces, announce.origin) 705 } 706 } 707 delete(f.fetched, hash) 708 709 // Remove any pending completions and decrement the DOS counters 710 if announce := f.completing[hash]; announce != nil { 711 f.announces[announce.origin]-- 712 if f.announces[announce.origin] == 0 { 713 delete(f.announces, announce.origin) 714 } 715 delete(f.completing, hash) 716 } 717 } 718 719 // forgetBlock removes all traces of a queued block from the fetcher's internal 720 // state. 721 func (f *Fetcher) forgetBlock(hash common.Hash) { 722 if insert := f.queued[hash]; insert != nil { 723 f.queues[insert.origin]-- 724 if f.queues[insert.origin] == 0 { 725 delete(f.queues, insert.origin) 726 } 727 delete(f.queued, hash) 728 } 729 }