github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/eth/fetcher/fetcher_test.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 18 19 import ( 20 "errors" 21 "github.com/PlatONnetwork/PlatON-Go/consensus/cbft" 22 "github.com/PlatONnetwork/PlatON-Go/core/ppos_storage" 23 "math/big" 24 "sync" 25 "sync/atomic" 26 "testing" 27 "time" 28 29 "github.com/PlatONnetwork/PlatON-Go/common" 30 "github.com/PlatONnetwork/PlatON-Go/core" 31 "github.com/PlatONnetwork/PlatON-Go/core/types" 32 "github.com/PlatONnetwork/PlatON-Go/crypto" 33 "github.com/PlatONnetwork/PlatON-Go/ethdb" 34 "github.com/PlatONnetwork/PlatON-Go/params" 35 ) 36 37 var ( 38 testdb = ethdb.NewMemDatabase() 39 testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 40 testAddress = crypto.PubkeyToAddress(testKey.PublicKey) 41 genesis = core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000)) 42 unknownBlock = types.NewBlock(&types.Header{GasLimit: params.GenesisGasLimit}, nil, nil, nil) 43 ) 44 45 // makeChain creates a chain of n blocks starting at and including parent. 46 // the returned hash chain is ordered head->parent. In addition, every 3rd block 47 // contains a transaction and every 5th an uncle to allow testing correct block 48 // reassembly. 49 func makeChain(n int, seed byte, parent *types.Block) ([]common.Hash, map[common.Hash]*types.Block) { 50 db := ethdb.NewMemDatabase() 51 ppos_storage.NewPPosTemp(db) 52 blocks, _ := core.GenerateChain(params.TestChainConfig, parent, cbft.New(params.GrapeChainConfig.Cbft, nil, nil, nil), testdb, n, func(i int, block *core.BlockGen) { 53 block.SetCoinbase(common.Address{seed}) 54 55 // If the block number is multiple of 3, send a bonus transaction to the miner 56 if parent == genesis && i%3 == 0 { 57 signer := types.MakeSigner(params.TestChainConfig, block.Number()) 58 tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, nil, nil), signer, testKey) 59 if err != nil { 60 panic(err) 61 } 62 block.AddTx(tx) 63 } 64 // If the block number is a multiple of 5, add a bonus uncle to the block 65 if i%5 == 0 { 66 block.AddUncle(&types.Header{ParentHash: block.PrevBlock(i - 1).Hash(), Number: big.NewInt(int64(i - 1))}) 67 } 68 }) 69 hashes := make([]common.Hash, n+1) 70 hashes[len(hashes)-1] = parent.Hash() 71 blockm := make(map[common.Hash]*types.Block, n+1) 72 blockm[parent.Hash()] = parent 73 for i, b := range blocks { 74 hashes[len(hashes)-i-2] = b.Hash() 75 b.ConfirmSigns = make([]*common.BlockConfirmSign, 0) 76 blockm[b.Hash()] = b 77 } 78 return hashes, blockm 79 } 80 81 // fetcherTester is a test simulator for mocking out local block chain. 82 type fetcherTester struct { 83 fetcher *Fetcher 84 85 hashes []common.Hash // Hash chain belonging to the tester 86 blocks map[common.Hash]*types.Block // Blocks belonging to the tester 87 drops map[string]bool // Map of peers dropped by the fetcher 88 89 lock sync.RWMutex 90 } 91 92 // newTester creates a new fetcher test mocker. 93 func newTester() *fetcherTester { 94 tester := &fetcherTester{ 95 hashes: []common.Hash{genesis.Hash()}, 96 blocks: map[common.Hash]*types.Block{genesis.Hash(): genesis}, 97 drops: make(map[string]bool), 98 } 99 tester.fetcher = New(tester.getBlock, tester.verifyHeader, tester.broadcastBlock, tester.chainHeight, tester.insertChain, tester.dropPeer) 100 tester.fetcher.Start() 101 102 return tester 103 } 104 105 // getBlock retrieves a block from the tester's block chain. 106 func (f *fetcherTester) getBlock(hash common.Hash) *types.Block { 107 f.lock.RLock() 108 defer f.lock.RUnlock() 109 110 return f.blocks[hash] 111 } 112 113 // verifyHeader is a nop placeholder for the block header verification. 114 func (f *fetcherTester) verifyHeader(header *types.Header) error { 115 return nil 116 } 117 118 // broadcastBlock is a nop placeholder for the block broadcasting. 119 func (f *fetcherTester) broadcastBlock(block *types.Block, propagate bool) { 120 } 121 122 // chainHeight retrieves the current height (block number) of the chain. 123 func (f *fetcherTester) chainHeight() uint64 { 124 f.lock.RLock() 125 defer f.lock.RUnlock() 126 127 return f.blocks[f.hashes[len(f.hashes)-1]].NumberU64() 128 } 129 130 // insertChain injects a new blocks into the simulated chain. 131 func (f *fetcherTester) insertChain(blocks types.Blocks) (int, error) { 132 f.lock.Lock() 133 defer f.lock.Unlock() 134 135 for i, block := range blocks { 136 // Make sure the parent in known 137 if _, ok := f.blocks[block.ParentHash()]; !ok { 138 return i, errors.New("unknown parent") 139 } 140 // Discard any new blocks if the same height already exists 141 if block.NumberU64() <= f.blocks[f.hashes[len(f.hashes)-1]].NumberU64() { 142 return i, nil 143 } 144 // Otherwise build our current chain 145 f.hashes = append(f.hashes, block.Hash()) 146 f.blocks[block.Hash()] = block 147 } 148 return 0, nil 149 } 150 151 // dropPeer is an emulator for the peer removal, simply accumulating the various 152 // peers dropped by the fetcher. 153 func (f *fetcherTester) dropPeer(peer string) { 154 f.lock.Lock() 155 defer f.lock.Unlock() 156 157 f.drops[peer] = true 158 } 159 160 // makeHeaderFetcher retrieves a block header fetcher associated with a simulated peer. 161 func (f *fetcherTester) makeHeaderFetcher(peer string, blocks map[common.Hash]*types.Block, drift time.Duration) headerRequesterFn { 162 closure := make(map[common.Hash]*types.Block) 163 for hash, block := range blocks { 164 closure[hash] = block 165 } 166 // Create a function that return a header from the closure 167 return func(hash common.Hash) error { 168 // Gather the blocks to return 169 headers := make([]*types.Header, 0, 1) 170 if block, ok := closure[hash]; ok { 171 headers = append(headers, block.Header()) 172 } 173 // Return on a new thread 174 go f.fetcher.FilterHeaders(peer, headers, time.Now().Add(drift)) 175 176 return nil 177 } 178 } 179 180 // makeBodyFetcher retrieves a block body fetcher associated with a simulated peer. 181 func (f *fetcherTester) makeBodyFetcher(peer string, blocks map[common.Hash]*types.Block, drift time.Duration) bodyRequesterFn { 182 closure := make(map[common.Hash]*types.Block) 183 for hash, block := range blocks { 184 closure[hash] = block 185 } 186 // Create a function that returns blocks from the closure 187 return func(hashes []common.Hash) error { 188 // Gather the block bodies to return 189 transactions := make([][]*types.Transaction, 0, len(hashes)) 190 uncles := make([][]*types.Header, 0, len(hashes)) 191 192 signs := make([][]*common.BlockConfirmSign, 0, len(hashes)) 193 194 for _, hash := range hashes { 195 if block, ok := closure[hash]; ok { 196 transactions = append(transactions, block.Transactions()) 197 uncles = append(uncles, block.Uncles()) 198 signs = append(signs, block.Signatures()) 199 } 200 } 201 // Return on a new thread 202 go f.fetcher.FilterBodies(peer, transactions, uncles, signs, time.Now().Add(drift)) 203 204 return nil 205 } 206 } 207 208 // verifyFetchingEvent verifies that one single event arrive on a fetching channel. 209 func verifyFetchingEvent(t *testing.T, fetching chan []common.Hash, arrive bool) { 210 if arrive { 211 select { 212 case <-fetching: 213 case <-time.After(time.Second): 214 t.Fatalf("fetching timeout") 215 } 216 } else { 217 select { 218 case <-fetching: 219 t.Fatalf("fetching invoked") 220 case <-time.After(10 * time.Millisecond): 221 } 222 } 223 } 224 225 // verifyCompletingEvent verifies that one single event arrive on an completing channel. 226 func verifyCompletingEvent(t *testing.T, completing chan []common.Hash, arrive bool) { 227 if arrive { 228 select { 229 case <-completing: 230 case <-time.After(time.Second): 231 t.Fatalf("completing timeout") 232 } 233 } else { 234 select { 235 case <-completing: 236 t.Fatalf("completing invoked") 237 case <-time.After(10 * time.Millisecond): 238 } 239 } 240 } 241 242 // verifyImportEvent verifies that one single event arrive on an import channel. 243 func verifyImportEvent(t *testing.T, imported chan *types.Block, arrive bool) { 244 if arrive { 245 select { 246 case <-imported: 247 case <-time.After(time.Second): 248 t.Fatalf("import timeout") 249 } 250 } else { 251 select { 252 case <-imported: 253 t.Fatalf("import invoked") 254 case <-time.After(10 * time.Millisecond): 255 } 256 } 257 } 258 259 // verifyImportCount verifies that exactly count number of events arrive on an 260 // import hook channel. 261 func verifyImportCount(t *testing.T, imported chan *types.Block, count int) { 262 for i := 0; i < count; i++ { 263 select { 264 case <-imported: 265 case <-time.After(time.Second): 266 t.Fatalf("block %d: import timeout", i+1) 267 } 268 } 269 verifyImportDone(t, imported) 270 } 271 272 // verifyImportDone verifies that no more events are arriving on an import channel. 273 func verifyImportDone(t *testing.T, imported chan *types.Block) { 274 select { 275 case <-imported: 276 t.Fatalf("extra block imported") 277 case <-time.After(50 * time.Millisecond): 278 } 279 } 280 281 // Tests that a fetcher accepts block announcements and initiates retrievals for 282 // them, successfully importing into the local chain. 283 func TestSequentialAnnouncements62(t *testing.T) { testSequentialAnnouncements(t, 62) } 284 func TestSequentialAnnouncements63(t *testing.T) { testSequentialAnnouncements(t, 63) } 285 func TestSequentialAnnouncements64(t *testing.T) { testSequentialAnnouncements(t, 64) } 286 287 func testSequentialAnnouncements(t *testing.T, protocol int) { 288 // Create a chain of blocks to import 289 targetBlocks := 4 * hashLimit 290 hashes, blocks := makeChain(targetBlocks, 0, genesis) 291 292 tester := newTester() 293 headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack) 294 bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0) 295 296 // Iteratively announce blocks until all are imported 297 imported := make(chan *types.Block) 298 tester.fetcher.importedHook = func(block *types.Block) { imported <- block } 299 300 for i := len(hashes) - 2; i >= 0; i-- { 301 tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher) 302 verifyImportEvent(t, imported, true) 303 } 304 verifyImportDone(t, imported) 305 } 306 307 // Tests that if blocks are announced by multiple peers (or even the same buggy 308 // peer), they will only get downloaded at most once. 309 func TestConcurrentAnnouncements62(t *testing.T) { testConcurrentAnnouncements(t, 62) } 310 func TestConcurrentAnnouncements63(t *testing.T) { testConcurrentAnnouncements(t, 63) } 311 func TestConcurrentAnnouncements64(t *testing.T) { testConcurrentAnnouncements(t, 64) } 312 313 func testConcurrentAnnouncements(t *testing.T, protocol int) { 314 // Create a chain of blocks to import 315 targetBlocks := 4 * hashLimit 316 hashes, blocks := makeChain(targetBlocks, 0, genesis) 317 318 // Assemble a tester with a built in counter for the requests 319 tester := newTester() 320 firstHeaderFetcher := tester.makeHeaderFetcher("first", blocks, -gatherSlack) 321 firstBodyFetcher := tester.makeBodyFetcher("first", blocks, 0) 322 secondHeaderFetcher := tester.makeHeaderFetcher("second", blocks, -gatherSlack) 323 secondBodyFetcher := tester.makeBodyFetcher("second", blocks, 0) 324 325 counter := uint32(0) 326 firstHeaderWrapper := func(hash common.Hash) error { 327 atomic.AddUint32(&counter, 1) 328 return firstHeaderFetcher(hash) 329 } 330 secondHeaderWrapper := func(hash common.Hash) error { 331 atomic.AddUint32(&counter, 1) 332 return secondHeaderFetcher(hash) 333 } 334 // Iteratively announce blocks until all are imported 335 imported := make(chan *types.Block) 336 tester.fetcher.importedHook = func(block *types.Block) { imported <- block } 337 338 for i := len(hashes) - 2; i >= 0; i-- { 339 tester.fetcher.Notify("first", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), firstHeaderWrapper, firstBodyFetcher) 340 tester.fetcher.Notify("second", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout+time.Millisecond), secondHeaderWrapper, secondBodyFetcher) 341 tester.fetcher.Notify("second", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout-time.Millisecond), secondHeaderWrapper, secondBodyFetcher) 342 verifyImportEvent(t, imported, true) 343 } 344 verifyImportDone(t, imported) 345 346 // Make sure no blocks were retrieved twice 347 if int(counter) != targetBlocks { 348 t.Fatalf("retrieval count mismatch: have %v, want %v", counter, targetBlocks) 349 } 350 } 351 352 // Tests that announcements arriving while a previous is being fetched still 353 // results in a valid import. 354 func TestOverlappingAnnouncements62(t *testing.T) { testOverlappingAnnouncements(t, 62) } 355 func TestOverlappingAnnouncements63(t *testing.T) { testOverlappingAnnouncements(t, 63) } 356 func TestOverlappingAnnouncements64(t *testing.T) { testOverlappingAnnouncements(t, 64) } 357 358 func testOverlappingAnnouncements(t *testing.T, protocol int) { 359 // Create a chain of blocks to import 360 targetBlocks := 4 * hashLimit 361 hashes, blocks := makeChain(targetBlocks, 0, genesis) 362 363 tester := newTester() 364 headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack) 365 bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0) 366 367 // Iteratively announce blocks, but overlap them continuously 368 overlap := 16 369 imported := make(chan *types.Block, len(hashes)-1) 370 for i := 0; i < overlap; i++ { 371 imported <- nil 372 } 373 tester.fetcher.importedHook = func(block *types.Block) { imported <- block } 374 375 for i := len(hashes) - 2; i >= 0; i-- { 376 tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher) 377 select { 378 case <-imported: 379 case <-time.After(time.Second): 380 t.Fatalf("block %d: import timeout", len(hashes)-i) 381 } 382 } 383 // Wait for all the imports to complete and check count 384 verifyImportCount(t, imported, overlap) 385 } 386 387 // Tests that announces already being retrieved will not be duplicated. 388 func TestPendingDeduplication62(t *testing.T) { testPendingDeduplication(t, 62) } 389 func TestPendingDeduplication63(t *testing.T) { testPendingDeduplication(t, 63) } 390 func TestPendingDeduplication64(t *testing.T) { testPendingDeduplication(t, 64) } 391 392 func testPendingDeduplication(t *testing.T, protocol int) { 393 // Create a hash and corresponding block 394 hashes, blocks := makeChain(1, 0, genesis) 395 396 // Assemble a tester with a built in counter and delayed fetcher 397 tester := newTester() 398 headerFetcher := tester.makeHeaderFetcher("repeater", blocks, -gatherSlack) 399 bodyFetcher := tester.makeBodyFetcher("repeater", blocks, 0) 400 401 delay := 50 * time.Millisecond 402 counter := uint32(0) 403 headerWrapper := func(hash common.Hash) error { 404 atomic.AddUint32(&counter, 1) 405 406 // Simulate a long running fetch 407 go func() { 408 time.Sleep(delay) 409 headerFetcher(hash) 410 }() 411 return nil 412 } 413 // Announce the same block many times until it's fetched (wait for any pending ops) 414 for tester.getBlock(hashes[0]) == nil { 415 tester.fetcher.Notify("repeater", hashes[0], 1, time.Now().Add(-arriveTimeout), headerWrapper, bodyFetcher) 416 time.Sleep(time.Millisecond) 417 } 418 time.Sleep(delay) 419 420 // Check that all blocks were imported and none fetched twice 421 if imported := len(tester.blocks); imported != 2 { 422 t.Fatalf("synchronised block mismatch: have %v, want %v", imported, 2) 423 } 424 if int(counter) != 1 { 425 t.Fatalf("retrieval count mismatch: have %v, want %v", counter, 1) 426 } 427 } 428 429 // Tests that announcements retrieved in a random order are cached and eventually 430 // imported when all the gaps are filled in. 431 func TestRandomArrivalImport62(t *testing.T) { testRandomArrivalImport(t, 62) } 432 func TestRandomArrivalImport63(t *testing.T) { testRandomArrivalImport(t, 63) } 433 func TestRandomArrivalImport64(t *testing.T) { testRandomArrivalImport(t, 64) } 434 435 func testRandomArrivalImport(t *testing.T, protocol int) { 436 // Create a chain of blocks to import, and choose one to delay 437 targetBlocks := maxQueueDist 438 hashes, blocks := makeChain(targetBlocks, 0, genesis) 439 skip := targetBlocks / 2 440 441 tester := newTester() 442 headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack) 443 bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0) 444 445 // Iteratively announce blocks, skipping one entry 446 imported := make(chan *types.Block, len(hashes)-1) 447 tester.fetcher.importedHook = func(block *types.Block) { imported <- block } 448 449 for i := len(hashes) - 1; i >= 0; i-- { 450 if i != skip { 451 tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher) 452 time.Sleep(time.Millisecond) 453 } 454 } 455 // Finally announce the skipped entry and check full import 456 tester.fetcher.Notify("valid", hashes[skip], uint64(len(hashes)-skip-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher) 457 verifyImportCount(t, imported, len(hashes)-1) 458 } 459 460 // Tests that direct block enqueues (due to block propagation vs. hash announce) 461 // are correctly schedule, filling and import queue gaps. 462 func TestQueueGapFill62(t *testing.T) { testQueueGapFill(t, 62) } 463 func TestQueueGapFill63(t *testing.T) { testQueueGapFill(t, 63) } 464 func TestQueueGapFill64(t *testing.T) { testQueueGapFill(t, 64) } 465 466 func testQueueGapFill(t *testing.T, protocol int) { 467 // Create a chain of blocks to import, and choose one to not announce at all 468 targetBlocks := maxQueueDist 469 hashes, blocks := makeChain(targetBlocks, 0, genesis) 470 skip := targetBlocks / 2 471 472 tester := newTester() 473 headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack) 474 bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0) 475 476 // Iteratively announce blocks, skipping one entry 477 imported := make(chan *types.Block, len(hashes)-1) 478 tester.fetcher.importedHook = func(block *types.Block) { imported <- block } 479 480 for i := len(hashes) - 1; i >= 0; i-- { 481 if i != skip { 482 tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher) 483 time.Sleep(time.Millisecond) 484 } 485 } 486 // Fill the missing block directly as if propagated 487 tester.fetcher.Enqueue("valid", blocks[hashes[skip]]) 488 verifyImportCount(t, imported, len(hashes)-1) 489 } 490 491 // Tests that blocks arriving from various sources (multiple propagations, hash 492 // announces, etc) do not get scheduled for import multiple times. 493 func TestImportDeduplication62(t *testing.T) { testImportDeduplication(t, 62) } 494 func TestImportDeduplication63(t *testing.T) { testImportDeduplication(t, 63) } 495 func TestImportDeduplication64(t *testing.T) { testImportDeduplication(t, 64) } 496 497 func testImportDeduplication(t *testing.T, protocol int) { 498 // Create two blocks to import (one for duplication, the other for stalling) 499 hashes, blocks := makeChain(2, 0, genesis) 500 501 // Create the tester and wrap the importer with a counter 502 tester := newTester() 503 headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack) 504 bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0) 505 506 counter := uint32(0) 507 tester.fetcher.insertChain = func(blocks types.Blocks) (int, error) { 508 atomic.AddUint32(&counter, uint32(len(blocks))) 509 return tester.insertChain(blocks) 510 } 511 // Instrument the fetching and imported events 512 fetching := make(chan []common.Hash) 513 imported := make(chan *types.Block, len(hashes)-1) 514 tester.fetcher.fetchingHook = func(hashes []common.Hash) { fetching <- hashes } 515 tester.fetcher.importedHook = func(block *types.Block) { imported <- block } 516 517 // Announce the duplicating block, wait for retrieval, and also propagate directly 518 tester.fetcher.Notify("valid", hashes[0], 1, time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher) 519 <-fetching 520 521 tester.fetcher.Enqueue("valid", blocks[hashes[0]]) 522 tester.fetcher.Enqueue("valid", blocks[hashes[0]]) 523 tester.fetcher.Enqueue("valid", blocks[hashes[0]]) 524 525 // Fill the missing block directly as if propagated, and check import uniqueness 526 tester.fetcher.Enqueue("valid", blocks[hashes[1]]) 527 verifyImportCount(t, imported, 2) 528 529 if counter != 2 { 530 t.Fatalf("import invocation count mismatch: have %v, want %v", counter, 2) 531 } 532 } 533 534 // Tests that blocks with numbers much lower or higher than out current head get 535 // discarded to prevent wasting resources on useless blocks from faulty peers. 536 func TestDistantPropagationDiscarding(t *testing.T) { 537 // Create a long chain to import and define the discard boundaries 538 hashes, blocks := makeChain(3*maxQueueDist, 0, genesis) 539 head := hashes[len(hashes)/2] 540 541 low, high := len(hashes)/2+maxUncleDist+1, len(hashes)/2-maxQueueDist-1 542 543 // Create a tester and simulate a head block being the middle of the above chain 544 tester := newTester() 545 546 tester.lock.Lock() 547 tester.hashes = []common.Hash{head} 548 tester.blocks = map[common.Hash]*types.Block{head: blocks[head]} 549 tester.lock.Unlock() 550 551 // Ensure that a block with a lower number than the threshold is discarded 552 tester.fetcher.Enqueue("lower", blocks[hashes[low]]) 553 time.Sleep(10 * time.Millisecond) 554 if !tester.fetcher.queue.Empty() { 555 t.Fatalf("fetcher queued stale block") 556 } 557 // Ensure that a block with a higher number than the threshold is discarded 558 tester.fetcher.Enqueue("higher", blocks[hashes[high]]) 559 time.Sleep(10 * time.Millisecond) 560 if !tester.fetcher.queue.Empty() { 561 t.Fatalf("fetcher queued future block") 562 } 563 } 564 565 // Tests that announcements with numbers much lower or higher than out current 566 // head get discarded to prevent wasting resources on useless blocks from faulty 567 // peers. 568 func TestDistantAnnouncementDiscarding62(t *testing.T) { testDistantAnnouncementDiscarding(t, 62) } 569 func TestDistantAnnouncementDiscarding63(t *testing.T) { testDistantAnnouncementDiscarding(t, 63) } 570 func TestDistantAnnouncementDiscarding64(t *testing.T) { testDistantAnnouncementDiscarding(t, 64) } 571 572 func testDistantAnnouncementDiscarding(t *testing.T, protocol int) { 573 // Create a long chain to import and define the discard boundaries 574 hashes, blocks := makeChain(3*maxQueueDist, 0, genesis) 575 head := hashes[len(hashes)/2] 576 577 low, high := len(hashes)/2+maxUncleDist+1, len(hashes)/2-maxQueueDist-1 578 579 // Create a tester and simulate a head block being the middle of the above chain 580 tester := newTester() 581 582 tester.lock.Lock() 583 tester.hashes = []common.Hash{head} 584 tester.blocks = map[common.Hash]*types.Block{head: blocks[head]} 585 tester.lock.Unlock() 586 587 headerFetcher := tester.makeHeaderFetcher("lower", blocks, -gatherSlack) 588 bodyFetcher := tester.makeBodyFetcher("lower", blocks, 0) 589 590 fetching := make(chan struct{}, 2) 591 tester.fetcher.fetchingHook = func(hashes []common.Hash) { fetching <- struct{}{} } 592 593 // Ensure that a block with a lower number than the threshold is discarded 594 tester.fetcher.Notify("lower", hashes[low], blocks[hashes[low]].NumberU64(), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher) 595 select { 596 case <-time.After(50 * time.Millisecond): 597 case <-fetching: 598 t.Fatalf("fetcher requested stale header") 599 } 600 // Ensure that a block with a higher number than the threshold is discarded 601 tester.fetcher.Notify("higher", hashes[high], blocks[hashes[high]].NumberU64(), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher) 602 select { 603 case <-time.After(50 * time.Millisecond): 604 case <-fetching: 605 t.Fatalf("fetcher requested future header") 606 } 607 } 608 609 // Tests that peers announcing blocks with invalid numbers (i.e. not matching 610 // the headers provided afterwards) get dropped as malicious. 611 func TestInvalidNumberAnnouncement62(t *testing.T) { testInvalidNumberAnnouncement(t, 62) } 612 func TestInvalidNumberAnnouncement63(t *testing.T) { testInvalidNumberAnnouncement(t, 63) } 613 func TestInvalidNumberAnnouncement64(t *testing.T) { testInvalidNumberAnnouncement(t, 64) } 614 615 func testInvalidNumberAnnouncement(t *testing.T, protocol int) { 616 // Create a single block to import and check numbers against 617 hashes, blocks := makeChain(1, 0, genesis) 618 619 tester := newTester() 620 badHeaderFetcher := tester.makeHeaderFetcher("bad", blocks, -gatherSlack) 621 badBodyFetcher := tester.makeBodyFetcher("bad", blocks, 0) 622 623 imported := make(chan *types.Block) 624 tester.fetcher.importedHook = func(block *types.Block) { imported <- block } 625 626 // Announce a block with a bad number, check for immediate drop 627 tester.fetcher.Notify("bad", hashes[0], 2, time.Now().Add(-arriveTimeout), badHeaderFetcher, badBodyFetcher) 628 verifyImportEvent(t, imported, false) 629 630 tester.lock.RLock() 631 dropped := tester.drops["bad"] 632 tester.lock.RUnlock() 633 634 if !dropped { 635 t.Fatalf("peer with invalid numbered announcement not dropped") 636 } 637 638 goodHeaderFetcher := tester.makeHeaderFetcher("good", blocks, -gatherSlack) 639 goodBodyFetcher := tester.makeBodyFetcher("good", blocks, 0) 640 // Make sure a good announcement passes without a drop 641 tester.fetcher.Notify("good", hashes[0], 1, time.Now().Add(-arriveTimeout), goodHeaderFetcher, goodBodyFetcher) 642 verifyImportEvent(t, imported, true) 643 644 tester.lock.RLock() 645 dropped = tester.drops["good"] 646 tester.lock.RUnlock() 647 648 if dropped { 649 t.Fatalf("peer with valid numbered announcement dropped") 650 } 651 verifyImportDone(t, imported) 652 } 653 654 // Tests that if a block is empty (i.e. header only), no body request should be 655 // made, and instead the header should be assembled into a whole block in itself. 656 //func TestEmptyBlockShortCircuit62(t *testing.T) { testEmptyBlockShortCircuit(t, 62) } 657 //func TestEmptyBlockShortCircuit63(t *testing.T) { testEmptyBlockShortCircuit(t, 63) } 658 //func TestEmptyBlockShortCircuit64(t *testing.T) { testEmptyBlockShortCircuit(t, 64) } 659 660 func testEmptyBlockShortCircuit(t *testing.T, protocol int) { 661 // Create a chain of blocks to import 662 hashes, blocks := makeChain(32, 0, genesis) 663 664 tester := newTester() 665 headerFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack) 666 bodyFetcher := tester.makeBodyFetcher("valid", blocks, 0) 667 668 // Add a monitoring hook for all internal events 669 fetching := make(chan []common.Hash) 670 tester.fetcher.fetchingHook = func(hashes []common.Hash) { fetching <- hashes } 671 672 completing := make(chan []common.Hash) 673 tester.fetcher.completingHook = func(hashes []common.Hash) { completing <- hashes } 674 675 imported := make(chan *types.Block) 676 tester.fetcher.importedHook = func(block *types.Block) { imported <- block } 677 678 // Iteratively announce blocks until all are imported 679 for i := len(hashes) - 2; i >= 0; i-- { 680 tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), headerFetcher, bodyFetcher) 681 682 // All announces should fetch the header 683 verifyFetchingEvent(t, fetching, true) 684 685 // Only blocks with data contents should request bodies 686 verifyCompletingEvent(t, completing, len(blocks[hashes[i]].Transactions()) > 0 || len(blocks[hashes[i]].Uncles()) > 0) 687 688 // Irrelevant of the construct, import should succeed 689 verifyImportEvent(t, imported, true) 690 } 691 verifyImportDone(t, imported) 692 } 693 694 // Tests that a peer is unable to use unbounded memory with sending infinite 695 // block announcements to a node, but that even in the face of such an attack, 696 // the fetcher remains operational. 697 func TestHashMemoryExhaustionAttack62(t *testing.T) { testHashMemoryExhaustionAttack(t, 62) } 698 func TestHashMemoryExhaustionAttack63(t *testing.T) { testHashMemoryExhaustionAttack(t, 63) } 699 func TestHashMemoryExhaustionAttack64(t *testing.T) { testHashMemoryExhaustionAttack(t, 64) } 700 701 func testHashMemoryExhaustionAttack(t *testing.T, protocol int) { 702 // Create a tester with instrumented import hooks 703 tester := newTester() 704 705 imported, announces := make(chan *types.Block), int32(0) 706 tester.fetcher.importedHook = func(block *types.Block) { imported <- block } 707 tester.fetcher.announceChangeHook = func(hash common.Hash, added bool) { 708 if added { 709 atomic.AddInt32(&announces, 1) 710 } else { 711 atomic.AddInt32(&announces, -1) 712 } 713 } 714 // Create a valid chain and an infinite junk chain 715 targetBlocks := hashLimit + 2*maxQueueDist 716 hashes, blocks := makeChain(targetBlocks, 0, genesis) 717 validHeaderFetcher := tester.makeHeaderFetcher("valid", blocks, -gatherSlack) 718 validBodyFetcher := tester.makeBodyFetcher("valid", blocks, 0) 719 720 attack, _ := makeChain(targetBlocks, 0, unknownBlock) 721 attackerHeaderFetcher := tester.makeHeaderFetcher("attacker", nil, -gatherSlack) 722 attackerBodyFetcher := tester.makeBodyFetcher("attacker", nil, 0) 723 724 // Feed the tester a huge hashset from the attacker, and a limited from the valid peer 725 for i := 0; i < len(attack); i++ { 726 if i < maxQueueDist { 727 tester.fetcher.Notify("valid", hashes[len(hashes)-2-i], uint64(i+1), time.Now(), validHeaderFetcher, validBodyFetcher) 728 } 729 tester.fetcher.Notify("attacker", attack[i], 1 /* don't distance drop */, time.Now(), attackerHeaderFetcher, attackerBodyFetcher) 730 } 731 if count := atomic.LoadInt32(&announces); count != hashLimit+maxQueueDist { 732 t.Fatalf("queued announce count mismatch: have %d, want %d", count, hashLimit+maxQueueDist) 733 } 734 // Wait for fetches to complete 735 verifyImportCount(t, imported, maxQueueDist) 736 737 // Feed the remaining valid hashes to ensure DOS protection state remains clean 738 for i := len(hashes) - maxQueueDist - 2; i >= 0; i-- { 739 tester.fetcher.Notify("valid", hashes[i], uint64(len(hashes)-i-1), time.Now().Add(-arriveTimeout), validHeaderFetcher, validBodyFetcher) 740 verifyImportEvent(t, imported, true) 741 } 742 verifyImportDone(t, imported) 743 } 744 745 // Tests that blocks sent to the fetcher (either through propagation or via hash 746 // announces and retrievals) don't pile up indefinitely, exhausting available 747 // system memory. 748 func TestBlockMemoryExhaustionAttack(t *testing.T) { 749 // Create a tester with instrumented import hooks 750 tester := newTester() 751 752 imported, enqueued := make(chan *types.Block), int32(0) 753 tester.fetcher.importedHook = func(block *types.Block) { imported <- block } 754 tester.fetcher.queueChangeHook = func(hash common.Hash, added bool) { 755 if added { 756 atomic.AddInt32(&enqueued, 1) 757 } else { 758 atomic.AddInt32(&enqueued, -1) 759 } 760 } 761 // Create a valid chain and a batch of dangling (but in range) blocks 762 targetBlocks := hashLimit + 2*maxQueueDist 763 hashes, blocks := makeChain(targetBlocks, 0, genesis) 764 attack := make(map[common.Hash]*types.Block) 765 for i := byte(0); len(attack) < blockLimit+2*maxQueueDist; i++ { 766 hashes, blocks := makeChain(maxQueueDist-1, i, unknownBlock) 767 for _, hash := range hashes[:maxQueueDist-2] { 768 attack[hash] = blocks[hash] 769 } 770 } 771 // Try to feed all the attacker blocks make sure only a limited batch is accepted 772 for _, block := range attack { 773 tester.fetcher.Enqueue("attacker", block) 774 } 775 time.Sleep(200 * time.Millisecond) 776 if queued := atomic.LoadInt32(&enqueued); queued != blockLimit { 777 t.Fatalf("queued block count mismatch: have %d, want %d", queued, blockLimit) 778 } 779 // Queue up a batch of valid blocks, and check that a new peer is allowed to do so 780 for i := 0; i < maxQueueDist-1; i++ { 781 tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-3-i]]) 782 } 783 time.Sleep(100 * time.Millisecond) 784 if queued := atomic.LoadInt32(&enqueued); queued != blockLimit+maxQueueDist-1 { 785 t.Fatalf("queued block count mismatch: have %d, want %d", queued, blockLimit+maxQueueDist-1) 786 } 787 // Insert the missing piece (and sanity check the import) 788 tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-2]]) 789 verifyImportCount(t, imported, maxQueueDist) 790 791 // Insert the remaining blocks in chunks to ensure clean DOS protection 792 for i := maxQueueDist; i < len(hashes)-1; i++ { 793 tester.fetcher.Enqueue("valid", blocks[hashes[len(hashes)-2-i]]) 794 verifyImportEvent(t, imported, true) 795 } 796 verifyImportDone(t, imported) 797 }