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