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