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