github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/eth/downloader/queue_test.go (about) 1 // Copyright 2019 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 downloader 18 19 import ( 20 "fmt" 21 "math/big" 22 "math/rand" 23 "sync" 24 "testing" 25 "time" 26 27 "github.com/ethereum/go-ethereum/common" 28 "github.com/ethereum/go-ethereum/consensus/ethash" 29 "github.com/ethereum/go-ethereum/core" 30 "github.com/ethereum/go-ethereum/core/rawdb" 31 "github.com/ethereum/go-ethereum/core/types" 32 "github.com/ethereum/go-ethereum/log" 33 "github.com/ethereum/go-ethereum/params" 34 "github.com/ethereum/go-ethereum/trie" 35 ) 36 37 var ( 38 testdb = rawdb.NewMemoryDatabase() 39 genesis = core.GenesisBlockForTesting(testdb, testAddress, big.NewInt(1000000000000000)) 40 ) 41 42 // makeChain creates a chain of n blocks starting at and including parent. 43 // the returned hash chain is ordered head->parent. In addition, every 3rd block 44 // contains a transaction and every 5th an uncle to allow testing correct block 45 // reassembly. 46 func makeChain(n int, seed byte, parent *types.Block, empty bool) ([]*types.Block, []types.Receipts) { 47 blocks, receipts := core.GenerateChain(params.TestChainConfig, parent, ethash.NewFaker(), testdb, n, func(i int, block *core.BlockGen) { 48 block.SetCoinbase(common.Address{seed}) 49 // Add one tx to every secondblock 50 if !empty && i%2 == 0 { 51 signer := types.MakeSigner(params.TestChainConfig, block.Number()) 52 tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddress), common.Address{seed}, big.NewInt(1000), params.TxGas, block.BaseFee(), nil), signer, testKey) 53 if err != nil { 54 panic(err) 55 } 56 block.AddTx(tx) 57 } 58 }) 59 return blocks, receipts 60 } 61 62 type chainData struct { 63 blocks []*types.Block 64 offset int 65 } 66 67 var chain *chainData 68 var emptyChain *chainData 69 70 func init() { 71 // Create a chain of blocks to import 72 targetBlocks := 128 73 blocks, _ := makeChain(targetBlocks, 0, genesis, false) 74 chain = &chainData{blocks, 0} 75 76 blocks, _ = makeChain(targetBlocks, 0, genesis, true) 77 emptyChain = &chainData{blocks, 0} 78 } 79 80 func (chain *chainData) headers() []*types.Header { 81 hdrs := make([]*types.Header, len(chain.blocks)) 82 for i, b := range chain.blocks { 83 hdrs[i] = b.Header() 84 } 85 return hdrs 86 } 87 88 func (chain *chainData) Len() int { 89 return len(chain.blocks) 90 } 91 92 func dummyPeer(id string) *peerConnection { 93 p := &peerConnection{ 94 id: id, 95 lacking: make(map[common.Hash]struct{}), 96 } 97 return p 98 } 99 100 func TestBasics(t *testing.T) { 101 numOfBlocks := len(emptyChain.blocks) 102 numOfReceipts := len(emptyChain.blocks) / 2 103 104 q := newQueue(10, 10) 105 if !q.Idle() { 106 t.Errorf("new queue should be idle") 107 } 108 q.Prepare(1, SnapSync) 109 if res := q.Results(false); len(res) != 0 { 110 t.Fatal("new queue should have 0 results") 111 } 112 113 // Schedule a batch of headers 114 headers := chain.headers() 115 hashes := make([]common.Hash, len(headers)) 116 for i, header := range headers { 117 hashes[i] = header.Hash() 118 } 119 q.Schedule(headers, hashes, 1) 120 if q.Idle() { 121 t.Errorf("queue should not be idle") 122 } 123 if got, exp := q.PendingBodies(), chain.Len(); got != exp { 124 t.Errorf("wrong pending block count, got %d, exp %d", got, exp) 125 } 126 // Only non-empty receipts get added to task-queue 127 if got, exp := q.PendingReceipts(), 64; got != exp { 128 t.Errorf("wrong pending receipt count, got %d, exp %d", got, exp) 129 } 130 // Items are now queued for downloading, next step is that we tell the 131 // queue that a certain peer will deliver them for us 132 { 133 peer := dummyPeer("peer-1") 134 fetchReq, _, throttle := q.ReserveBodies(peer, 50) 135 if !throttle { 136 // queue size is only 10, so throttling should occur 137 t.Fatal("should throttle") 138 } 139 // But we should still get the first things to fetch 140 if got, exp := len(fetchReq.Headers), 5; got != exp { 141 t.Fatalf("expected %d requests, got %d", exp, got) 142 } 143 if got, exp := fetchReq.Headers[0].Number.Uint64(), uint64(1); got != exp { 144 t.Fatalf("expected header %d, got %d", exp, got) 145 } 146 } 147 if exp, got := q.blockTaskQueue.Size(), numOfBlocks-10; exp != got { 148 t.Errorf("expected block task queue to be %d, got %d", exp, got) 149 } 150 if exp, got := q.receiptTaskQueue.Size(), numOfReceipts; exp != got { 151 t.Errorf("expected receipt task queue to be %d, got %d", exp, got) 152 } 153 { 154 peer := dummyPeer("peer-2") 155 fetchReq, _, throttle := q.ReserveBodies(peer, 50) 156 157 // The second peer should hit throttling 158 if !throttle { 159 t.Fatalf("should not throttle") 160 } 161 // And not get any fetches at all, since it was throttled to begin with 162 if fetchReq != nil { 163 t.Fatalf("should have no fetches, got %d", len(fetchReq.Headers)) 164 } 165 } 166 if exp, got := q.blockTaskQueue.Size(), numOfBlocks-10; exp != got { 167 t.Errorf("expected block task queue to be %d, got %d", exp, got) 168 } 169 if exp, got := q.receiptTaskQueue.Size(), numOfReceipts; exp != got { 170 t.Errorf("expected receipt task queue to be %d, got %d", exp, got) 171 } 172 { 173 // The receipt delivering peer should not be affected 174 // by the throttling of body deliveries 175 peer := dummyPeer("peer-3") 176 fetchReq, _, throttle := q.ReserveReceipts(peer, 50) 177 if !throttle { 178 // queue size is only 10, so throttling should occur 179 t.Fatal("should throttle") 180 } 181 // But we should still get the first things to fetch 182 if got, exp := len(fetchReq.Headers), 5; got != exp { 183 t.Fatalf("expected %d requests, got %d", exp, got) 184 } 185 if got, exp := fetchReq.Headers[0].Number.Uint64(), uint64(1); got != exp { 186 t.Fatalf("expected header %d, got %d", exp, got) 187 } 188 189 } 190 if exp, got := q.blockTaskQueue.Size(), numOfBlocks-10; exp != got { 191 t.Errorf("expected block task queue to be %d, got %d", exp, got) 192 } 193 if exp, got := q.receiptTaskQueue.Size(), numOfReceipts-5; exp != got { 194 t.Errorf("expected receipt task queue to be %d, got %d", exp, got) 195 } 196 if got, exp := q.resultCache.countCompleted(), 0; got != exp { 197 t.Errorf("wrong processable count, got %d, exp %d", got, exp) 198 } 199 } 200 201 func TestEmptyBlocks(t *testing.T) { 202 numOfBlocks := len(emptyChain.blocks) 203 204 q := newQueue(10, 10) 205 206 q.Prepare(1, SnapSync) 207 208 // Schedule a batch of headers 209 headers := emptyChain.headers() 210 hashes := make([]common.Hash, len(headers)) 211 for i, header := range headers { 212 hashes[i] = header.Hash() 213 } 214 q.Schedule(headers, hashes, 1) 215 if q.Idle() { 216 t.Errorf("queue should not be idle") 217 } 218 if got, exp := q.PendingBodies(), len(emptyChain.blocks); got != exp { 219 t.Errorf("wrong pending block count, got %d, exp %d", got, exp) 220 } 221 if got, exp := q.PendingReceipts(), 0; got != exp { 222 t.Errorf("wrong pending receipt count, got %d, exp %d", got, exp) 223 } 224 // They won't be processable, because the fetchresults haven't been 225 // created yet 226 if got, exp := q.resultCache.countCompleted(), 0; got != exp { 227 t.Errorf("wrong processable count, got %d, exp %d", got, exp) 228 } 229 230 // Items are now queued for downloading, next step is that we tell the 231 // queue that a certain peer will deliver them for us 232 // That should trigger all of them to suddenly become 'done' 233 { 234 // Reserve blocks 235 peer := dummyPeer("peer-1") 236 fetchReq, _, _ := q.ReserveBodies(peer, 50) 237 238 // there should be nothing to fetch, blocks are empty 239 if fetchReq != nil { 240 t.Fatal("there should be no body fetch tasks remaining") 241 } 242 243 } 244 if q.blockTaskQueue.Size() != numOfBlocks-10 { 245 t.Errorf("expected block task queue to be %d, got %d", numOfBlocks-10, q.blockTaskQueue.Size()) 246 } 247 if q.receiptTaskQueue.Size() != 0 { 248 t.Errorf("expected receipt task queue to be %d, got %d", 0, q.receiptTaskQueue.Size()) 249 } 250 { 251 peer := dummyPeer("peer-3") 252 fetchReq, _, _ := q.ReserveReceipts(peer, 50) 253 254 // there should be nothing to fetch, blocks are empty 255 if fetchReq != nil { 256 t.Fatal("there should be no body fetch tasks remaining") 257 } 258 } 259 if q.blockTaskQueue.Size() != numOfBlocks-10 { 260 t.Errorf("expected block task queue to be %d, got %d", numOfBlocks-10, q.blockTaskQueue.Size()) 261 } 262 if q.receiptTaskQueue.Size() != 0 { 263 t.Errorf("expected receipt task queue to be %d, got %d", 0, q.receiptTaskQueue.Size()) 264 } 265 if got, exp := q.resultCache.countCompleted(), 10; got != exp { 266 t.Errorf("wrong processable count, got %d, exp %d", got, exp) 267 } 268 } 269 270 // XTestDelivery does some more extensive testing of events that happen, 271 // blocks that become known and peers that make reservations and deliveries. 272 // disabled since it's not really a unit-test, but can be executed to test 273 // some more advanced scenarios 274 func XTestDelivery(t *testing.T) { 275 // the outside network, holding blocks 276 blo, rec := makeChain(128, 0, genesis, false) 277 world := newNetwork() 278 world.receipts = rec 279 world.chain = blo 280 world.progress(10) 281 if false { 282 log.Root().SetHandler(log.StdoutHandler) 283 284 } 285 q := newQueue(10, 10) 286 var wg sync.WaitGroup 287 q.Prepare(1, SnapSync) 288 wg.Add(1) 289 go func() { 290 // deliver headers 291 defer wg.Done() 292 c := 1 293 for { 294 //fmt.Printf("getting headers from %d\n", c) 295 headers := world.headers(c) 296 hashes := make([]common.Hash, len(headers)) 297 for i, header := range headers { 298 hashes[i] = header.Hash() 299 } 300 l := len(headers) 301 //fmt.Printf("scheduling %d headers, first %d last %d\n", 302 // l, headers[0].Number.Uint64(), headers[len(headers)-1].Number.Uint64()) 303 q.Schedule(headers, hashes, uint64(c)) 304 c += l 305 } 306 }() 307 wg.Add(1) 308 go func() { 309 // collect results 310 defer wg.Done() 311 tot := 0 312 for { 313 res := q.Results(true) 314 tot += len(res) 315 fmt.Printf("got %d results, %d tot\n", len(res), tot) 316 // Now we can forget about these 317 world.forget(res[len(res)-1].Header.Number.Uint64()) 318 319 } 320 }() 321 wg.Add(1) 322 go func() { 323 defer wg.Done() 324 // reserve body fetch 325 i := 4 326 for { 327 peer := dummyPeer(fmt.Sprintf("peer-%d", i)) 328 f, _, _ := q.ReserveBodies(peer, rand.Intn(30)) 329 if f != nil { 330 var ( 331 emptyList []*types.Header 332 txset [][]*types.Transaction 333 uncleset [][]*types.Header 334 ) 335 numToSkip := rand.Intn(len(f.Headers)) 336 for _, hdr := range f.Headers[0 : len(f.Headers)-numToSkip] { 337 txset = append(txset, world.getTransactions(hdr.Number.Uint64())) 338 uncleset = append(uncleset, emptyList) 339 } 340 var ( 341 txsHashes = make([]common.Hash, len(txset)) 342 uncleHashes = make([]common.Hash, len(uncleset)) 343 ) 344 hasher := trie.NewStackTrie(nil) 345 for i, txs := range txset { 346 txsHashes[i] = types.DeriveSha(types.Transactions(txs), hasher) 347 } 348 for i, uncles := range uncleset { 349 uncleHashes[i] = types.CalcUncleHash(uncles) 350 } 351 time.Sleep(100 * time.Millisecond) 352 _, err := q.DeliverBodies(peer.id, txset, txsHashes, uncleset, uncleHashes) 353 if err != nil { 354 fmt.Printf("delivered %d bodies %v\n", len(txset), err) 355 } 356 } else { 357 i++ 358 time.Sleep(200 * time.Millisecond) 359 } 360 } 361 }() 362 go func() { 363 defer wg.Done() 364 // reserve receiptfetch 365 peer := dummyPeer("peer-3") 366 for { 367 f, _, _ := q.ReserveReceipts(peer, rand.Intn(50)) 368 if f != nil { 369 var rcs [][]*types.Receipt 370 for _, hdr := range f.Headers { 371 rcs = append(rcs, world.getReceipts(hdr.Number.Uint64())) 372 } 373 hasher := trie.NewStackTrie(nil) 374 hashes := make([]common.Hash, len(rcs)) 375 for i, receipt := range rcs { 376 hashes[i] = types.DeriveSha(types.Receipts(receipt), hasher) 377 } 378 _, err := q.DeliverReceipts(peer.id, rcs, hashes) 379 if err != nil { 380 fmt.Printf("delivered %d receipts %v\n", len(rcs), err) 381 } 382 time.Sleep(100 * time.Millisecond) 383 } else { 384 time.Sleep(200 * time.Millisecond) 385 } 386 } 387 }() 388 wg.Add(1) 389 go func() { 390 defer wg.Done() 391 for i := 0; i < 50; i++ { 392 time.Sleep(300 * time.Millisecond) 393 //world.tick() 394 //fmt.Printf("trying to progress\n") 395 world.progress(rand.Intn(100)) 396 } 397 for i := 0; i < 50; i++ { 398 time.Sleep(2990 * time.Millisecond) 399 400 } 401 }() 402 wg.Add(1) 403 go func() { 404 defer wg.Done() 405 for { 406 time.Sleep(990 * time.Millisecond) 407 fmt.Printf("world block tip is %d\n", 408 world.chain[len(world.chain)-1].Header().Number.Uint64()) 409 fmt.Println(q.Stats()) 410 } 411 }() 412 wg.Wait() 413 } 414 415 func newNetwork() *network { 416 var l sync.RWMutex 417 return &network{ 418 cond: sync.NewCond(&l), 419 offset: 1, // block 1 is at blocks[0] 420 } 421 } 422 423 // represents the network 424 type network struct { 425 offset int 426 chain []*types.Block 427 receipts []types.Receipts 428 lock sync.RWMutex 429 cond *sync.Cond 430 } 431 432 func (n *network) getTransactions(blocknum uint64) types.Transactions { 433 index := blocknum - uint64(n.offset) 434 return n.chain[index].Transactions() 435 } 436 func (n *network) getReceipts(blocknum uint64) types.Receipts { 437 index := blocknum - uint64(n.offset) 438 if got := n.chain[index].Header().Number.Uint64(); got != blocknum { 439 fmt.Printf("Err, got %d exp %d\n", got, blocknum) 440 panic("sd") 441 } 442 return n.receipts[index] 443 } 444 445 func (n *network) forget(blocknum uint64) { 446 index := blocknum - uint64(n.offset) 447 n.chain = n.chain[index:] 448 n.receipts = n.receipts[index:] 449 n.offset = int(blocknum) 450 451 } 452 func (n *network) progress(numBlocks int) { 453 454 n.lock.Lock() 455 defer n.lock.Unlock() 456 //fmt.Printf("progressing...\n") 457 newBlocks, newR := makeChain(numBlocks, 0, n.chain[len(n.chain)-1], false) 458 n.chain = append(n.chain, newBlocks...) 459 n.receipts = append(n.receipts, newR...) 460 n.cond.Broadcast() 461 462 } 463 464 func (n *network) headers(from int) []*types.Header { 465 numHeaders := 128 466 var hdrs []*types.Header 467 index := from - n.offset 468 469 for index >= len(n.chain) { 470 // wait for progress 471 n.cond.L.Lock() 472 //fmt.Printf("header going into wait\n") 473 n.cond.Wait() 474 index = from - n.offset 475 n.cond.L.Unlock() 476 } 477 n.lock.RLock() 478 defer n.lock.RUnlock() 479 for i, b := range n.chain[index:] { 480 hdrs = append(hdrs, b.Header()) 481 if i >= numHeaders { 482 break 483 } 484 } 485 return hdrs 486 }