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