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