gitee.com/liu-zhao234568/cntest@v1.0.0/les/test_helper.go (about) 1 // Copyright 2016 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 // This file contains some shares testing functionality, common to multiple 18 // different files and modules being tested. Client based network and Server 19 // based network can be created easily with available APIs. 20 21 package les 22 23 import ( 24 "context" 25 "crypto/rand" 26 "fmt" 27 "math/big" 28 "sync/atomic" 29 "testing" 30 "time" 31 32 "gitee.com/liu-zhao234568/cntest/accounts/abi/bind" 33 "gitee.com/liu-zhao234568/cntest/accounts/abi/bind/backends" 34 "gitee.com/liu-zhao234568/cntest/common" 35 "gitee.com/liu-zhao234568/cntest/common/mclock" 36 "gitee.com/liu-zhao234568/cntest/consensus/ethash" 37 "gitee.com/liu-zhao234568/cntest/contracts/checkpointoracle/contract" 38 "gitee.com/liu-zhao234568/cntest/core" 39 "gitee.com/liu-zhao234568/cntest/core/forkid" 40 "gitee.com/liu-zhao234568/cntest/core/rawdb" 41 "gitee.com/liu-zhao234568/cntest/core/types" 42 "gitee.com/liu-zhao234568/cntest/crypto" 43 "gitee.com/liu-zhao234568/cntest/eth/ethconfig" 44 "gitee.com/liu-zhao234568/cntest/ethdb" 45 "gitee.com/liu-zhao234568/cntest/event" 46 "gitee.com/liu-zhao234568/cntest/les/checkpointoracle" 47 "gitee.com/liu-zhao234568/cntest/les/flowcontrol" 48 vfs "gitee.com/liu-zhao234568/cntest/les/vflux/server" 49 "gitee.com/liu-zhao234568/cntest/light" 50 "gitee.com/liu-zhao234568/cntest/p2p" 51 "gitee.com/liu-zhao234568/cntest/p2p/enode" 52 "gitee.com/liu-zhao234568/cntest/params" 53 ) 54 55 var ( 56 bankKey, _ = crypto.GenerateKey() 57 bankAddr = crypto.PubkeyToAddress(bankKey.PublicKey) 58 bankFunds = big.NewInt(1_000_000_000_000_000_000) 59 60 userKey1, _ = crypto.GenerateKey() 61 userKey2, _ = crypto.GenerateKey() 62 userAddr1 = crypto.PubkeyToAddress(userKey1.PublicKey) 63 userAddr2 = crypto.PubkeyToAddress(userKey2.PublicKey) 64 65 testContractAddr common.Address 66 testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056") 67 testContractCodeDeployed = testContractCode[16:] 68 testContractDeployed = uint64(2) 69 70 testEventEmitterCode = common.Hex2Bytes("60606040523415600e57600080fd5b7f57050ab73f6b9ebdd9f76b8d4997793f48cf956e965ee070551b9ca0bb71584e60405160405180910390a160358060476000396000f3006060604052600080fd00a165627a7a723058203f727efcad8b5811f8cb1fc2620ce5e8c63570d697aef968172de296ea3994140029") 71 72 // Checkpoint oracle relative fields 73 oracleAddr common.Address 74 signerKey, _ = crypto.GenerateKey() 75 signerAddr = crypto.PubkeyToAddress(signerKey.PublicKey) 76 ) 77 78 var ( 79 // The block frequency for creating checkpoint(only used in test) 80 sectionSize = big.NewInt(128) 81 82 // The number of confirmations needed to generate a checkpoint(only used in test). 83 processConfirms = big.NewInt(1) 84 85 // The token bucket buffer limit for testing purpose. 86 testBufLimit = uint64(1000000) 87 88 // The buffer recharging speed for testing purpose. 89 testBufRecharge = uint64(1000) 90 ) 91 92 /* 93 contract test { 94 95 uint256[100] data; 96 97 function Put(uint256 addr, uint256 value) { 98 data[addr] = value; 99 } 100 101 function Get(uint256 addr) constant returns (uint256 value) { 102 return data[addr]; 103 } 104 } 105 */ 106 107 // prepare pre-commits specified number customized blocks into chain. 108 func prepare(n int, backend *backends.SimulatedBackend) { 109 var ( 110 ctx = context.Background() 111 signer = types.HomesteadSigner{} 112 ) 113 for i := 0; i < n; i++ { 114 switch i { 115 case 0: 116 // Builtin-block 117 // number: 1 118 // txs: 2 119 120 // deploy checkpoint contract 121 auth, _ := bind.NewKeyedTransactorWithChainID(bankKey, big.NewInt(1337)) 122 oracleAddr, _, _, _ = contract.DeployCheckpointOracle(auth, backend, []common.Address{signerAddr}, sectionSize, processConfirms, big.NewInt(1)) 123 124 // bankUser transfers some ether to user1 125 nonce, _ := backend.PendingNonceAt(ctx, bankAddr) 126 tx, _ := types.SignTx(types.NewTransaction(nonce, userAddr1, big.NewInt(10_000_000_000_000_000), params.TxGas, big.NewInt(params.InitialBaseFee), nil), signer, bankKey) 127 backend.SendTransaction(ctx, tx) 128 case 1: 129 // Builtin-block 130 // number: 2 131 // txs: 4 132 133 bankNonce, _ := backend.PendingNonceAt(ctx, bankAddr) 134 userNonce1, _ := backend.PendingNonceAt(ctx, userAddr1) 135 136 // bankUser transfers more ether to user1 137 tx1, _ := types.SignTx(types.NewTransaction(bankNonce, userAddr1, big.NewInt(1_000_000_000_000_000), params.TxGas, big.NewInt(params.InitialBaseFee), nil), signer, bankKey) 138 backend.SendTransaction(ctx, tx1) 139 140 // user1 relays ether to user2 141 tx2, _ := types.SignTx(types.NewTransaction(userNonce1, userAddr2, big.NewInt(1_000_000_000_000_000), params.TxGas, big.NewInt(params.InitialBaseFee), nil), signer, userKey1) 142 backend.SendTransaction(ctx, tx2) 143 144 // user1 deploys a test contract 145 tx3, _ := types.SignTx(types.NewContractCreation(userNonce1+1, big.NewInt(0), 200000, big.NewInt(params.InitialBaseFee), testContractCode), signer, userKey1) 146 backend.SendTransaction(ctx, tx3) 147 testContractAddr = crypto.CreateAddress(userAddr1, userNonce1+1) 148 149 // user1 deploys a event contract 150 tx4, _ := types.SignTx(types.NewContractCreation(userNonce1+2, big.NewInt(0), 200000, big.NewInt(params.InitialBaseFee), testEventEmitterCode), signer, userKey1) 151 backend.SendTransaction(ctx, tx4) 152 case 2: 153 // Builtin-block 154 // number: 3 155 // txs: 2 156 157 // bankUser transfer some ether to signer 158 bankNonce, _ := backend.PendingNonceAt(ctx, bankAddr) 159 tx1, _ := types.SignTx(types.NewTransaction(bankNonce, signerAddr, big.NewInt(1000000000), params.TxGas, big.NewInt(params.InitialBaseFee), nil), signer, bankKey) 160 backend.SendTransaction(ctx, tx1) 161 162 // invoke test contract 163 data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001") 164 tx2, _ := types.SignTx(types.NewTransaction(bankNonce+1, testContractAddr, big.NewInt(0), 100000, big.NewInt(params.InitialBaseFee), data), signer, bankKey) 165 backend.SendTransaction(ctx, tx2) 166 case 3: 167 // Builtin-block 168 // number: 4 169 // txs: 1 170 171 // invoke test contract 172 bankNonce, _ := backend.PendingNonceAt(ctx, bankAddr) 173 data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002") 174 tx, _ := types.SignTx(types.NewTransaction(bankNonce, testContractAddr, big.NewInt(0), 100000, big.NewInt(params.InitialBaseFee), data), signer, bankKey) 175 backend.SendTransaction(ctx, tx) 176 } 177 backend.Commit() 178 } 179 } 180 181 // testIndexers creates a set of indexers with specified params for testing purpose. 182 func testIndexers(db ethdb.Database, odr light.OdrBackend, config *light.IndexerConfig, disablePruning bool) []*core.ChainIndexer { 183 var indexers [3]*core.ChainIndexer 184 indexers[0] = light.NewChtIndexer(db, odr, config.ChtSize, config.ChtConfirms, disablePruning) 185 indexers[1] = core.NewBloomIndexer(db, config.BloomSize, config.BloomConfirms) 186 indexers[2] = light.NewBloomTrieIndexer(db, odr, config.BloomSize, config.BloomTrieSize, disablePruning) 187 // make bloomTrieIndexer as a child indexer of bloom indexer. 188 indexers[1].AddChildIndexer(indexers[2]) 189 return indexers[:] 190 } 191 192 func newTestClientHandler(backend *backends.SimulatedBackend, odr *LesOdr, indexers []*core.ChainIndexer, db ethdb.Database, peers *serverPeerSet, ulcServers []string, ulcFraction int) (*clientHandler, func()) { 193 var ( 194 evmux = new(event.TypeMux) 195 engine = ethash.NewFaker() 196 gspec = core.Genesis{ 197 Config: params.AllEthashProtocolChanges, 198 Alloc: core.GenesisAlloc{bankAddr: {Balance: bankFunds}}, 199 GasLimit: 100000000, 200 BaseFee: big.NewInt(params.InitialBaseFee), 201 } 202 oracle *checkpointoracle.CheckpointOracle 203 ) 204 genesis := gspec.MustCommit(db) 205 chain, _ := light.NewLightChain(odr, gspec.Config, engine, nil) 206 if indexers != nil { 207 checkpointConfig := ¶ms.CheckpointOracleConfig{ 208 Address: crypto.CreateAddress(bankAddr, 0), 209 Signers: []common.Address{signerAddr}, 210 Threshold: 1, 211 } 212 getLocal := func(index uint64) params.TrustedCheckpoint { 213 chtIndexer := indexers[0] 214 sectionHead := chtIndexer.SectionHead(index) 215 return params.TrustedCheckpoint{ 216 SectionIndex: index, 217 SectionHead: sectionHead, 218 CHTRoot: light.GetChtRoot(db, index, sectionHead), 219 BloomRoot: light.GetBloomTrieRoot(db, index, sectionHead), 220 } 221 } 222 oracle = checkpointoracle.New(checkpointConfig, getLocal) 223 } 224 client := &LightEthereum{ 225 lesCommons: lesCommons{ 226 genesis: genesis.Hash(), 227 config: ðconfig.Config{LightPeers: 100, NetworkId: NetworkId}, 228 chainConfig: params.AllEthashProtocolChanges, 229 iConfig: light.TestClientIndexerConfig, 230 chainDb: db, 231 oracle: oracle, 232 chainReader: chain, 233 closeCh: make(chan struct{}), 234 }, 235 peers: peers, 236 reqDist: odr.retriever.dist, 237 retriever: odr.retriever, 238 odr: odr, 239 engine: engine, 240 blockchain: chain, 241 eventMux: evmux, 242 } 243 client.handler = newClientHandler(ulcServers, ulcFraction, nil, client) 244 245 if client.oracle != nil { 246 client.oracle.Start(backend) 247 } 248 client.handler.start() 249 return client.handler, func() { 250 client.handler.stop() 251 } 252 } 253 254 func newTestServerHandler(blocks int, indexers []*core.ChainIndexer, db ethdb.Database, clock mclock.Clock) (*serverHandler, *backends.SimulatedBackend, func()) { 255 var ( 256 gspec = core.Genesis{ 257 Config: params.AllEthashProtocolChanges, 258 Alloc: core.GenesisAlloc{bankAddr: {Balance: bankFunds}}, 259 GasLimit: 100000000, 260 BaseFee: big.NewInt(params.InitialBaseFee), 261 } 262 oracle *checkpointoracle.CheckpointOracle 263 ) 264 genesis := gspec.MustCommit(db) 265 266 // create a simulation backend and pre-commit several customized block to the database. 267 simulation := backends.NewSimulatedBackendWithDatabase(db, gspec.Alloc, 100000000) 268 prepare(blocks, simulation) 269 270 txpoolConfig := core.DefaultTxPoolConfig 271 txpoolConfig.Journal = "" 272 txpool := core.NewTxPool(txpoolConfig, gspec.Config, simulation.Blockchain()) 273 if indexers != nil { 274 checkpointConfig := ¶ms.CheckpointOracleConfig{ 275 Address: crypto.CreateAddress(bankAddr, 0), 276 Signers: []common.Address{signerAddr}, 277 Threshold: 1, 278 } 279 getLocal := func(index uint64) params.TrustedCheckpoint { 280 chtIndexer := indexers[0] 281 sectionHead := chtIndexer.SectionHead(index) 282 return params.TrustedCheckpoint{ 283 SectionIndex: index, 284 SectionHead: sectionHead, 285 CHTRoot: light.GetChtRoot(db, index, sectionHead), 286 BloomRoot: light.GetBloomTrieRoot(db, index, sectionHead), 287 } 288 } 289 oracle = checkpointoracle.New(checkpointConfig, getLocal) 290 } 291 server := &LesServer{ 292 lesCommons: lesCommons{ 293 genesis: genesis.Hash(), 294 config: ðconfig.Config{LightPeers: 100, NetworkId: NetworkId}, 295 chainConfig: params.AllEthashProtocolChanges, 296 iConfig: light.TestServerIndexerConfig, 297 chainDb: db, 298 chainReader: simulation.Blockchain(), 299 oracle: oracle, 300 closeCh: make(chan struct{}), 301 }, 302 peers: newClientPeerSet(), 303 servingQueue: newServingQueue(int64(time.Millisecond*10), 1), 304 defParams: flowcontrol.ServerParams{ 305 BufLimit: testBufLimit, 306 MinRecharge: testBufRecharge, 307 }, 308 fcManager: flowcontrol.NewClientManager(nil, clock), 309 } 310 server.costTracker, server.minCapacity = newCostTracker(db, server.config) 311 server.costTracker.testCostList = testCostList(0) // Disable flow control mechanism. 312 server.clientPool = vfs.NewClientPool(db, testBufRecharge, defaultConnectedBias, clock, alwaysTrueFn) 313 server.clientPool.Start() 314 server.clientPool.SetLimits(10000, 10000) // Assign enough capacity for clientpool 315 server.handler = newServerHandler(server, simulation.Blockchain(), db, txpool, func() bool { return true }) 316 if server.oracle != nil { 317 server.oracle.Start(simulation) 318 } 319 server.servingQueue.setThreads(4) 320 server.handler.start() 321 closer := func() { server.Stop() } 322 return server.handler, simulation, closer 323 } 324 325 func alwaysTrueFn() bool { 326 return true 327 } 328 329 // testPeer is a simulated peer to allow testing direct network calls. 330 type testPeer struct { 331 cpeer *clientPeer 332 speer *serverPeer 333 334 net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging 335 app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side 336 } 337 338 // handshakeWithServer executes the handshake with the remote server peer. 339 func (p *testPeer) handshakeWithServer(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, forkID forkid.ID) { 340 // It only works for the simulated client peer 341 if p.cpeer == nil { 342 t.Fatal("handshake for client peer only") 343 } 344 var sendList keyValueList 345 sendList = sendList.add("protocolVersion", uint64(p.cpeer.version)) 346 sendList = sendList.add("networkId", uint64(NetworkId)) 347 sendList = sendList.add("headTd", td) 348 sendList = sendList.add("headHash", head) 349 sendList = sendList.add("headNum", headNum) 350 sendList = sendList.add("genesisHash", genesis) 351 if p.cpeer.version >= lpv4 { 352 sendList = sendList.add("forkID", &forkID) 353 } 354 if err := p2p.ExpectMsg(p.app, StatusMsg, nil); err != nil { 355 t.Fatalf("status recv: %v", err) 356 } 357 if err := p2p.Send(p.app, StatusMsg, sendList); err != nil { 358 t.Fatalf("status send: %v", err) 359 } 360 } 361 362 // handshakeWithClient executes the handshake with the remote client peer. 363 func (p *testPeer) handshakeWithClient(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, forkID forkid.ID, costList RequestCostList, recentTxLookup uint64) { 364 // It only works for the simulated client peer 365 if p.speer == nil { 366 t.Fatal("handshake for server peer only") 367 } 368 var sendList keyValueList 369 sendList = sendList.add("protocolVersion", uint64(p.speer.version)) 370 sendList = sendList.add("networkId", uint64(NetworkId)) 371 sendList = sendList.add("headTd", td) 372 sendList = sendList.add("headHash", head) 373 sendList = sendList.add("headNum", headNum) 374 sendList = sendList.add("genesisHash", genesis) 375 sendList = sendList.add("serveHeaders", nil) 376 sendList = sendList.add("serveChainSince", uint64(0)) 377 sendList = sendList.add("serveStateSince", uint64(0)) 378 sendList = sendList.add("serveRecentState", uint64(core.TriesInMemory-4)) 379 sendList = sendList.add("txRelay", nil) 380 sendList = sendList.add("flowControl/BL", testBufLimit) 381 sendList = sendList.add("flowControl/MRR", testBufRecharge) 382 sendList = sendList.add("flowControl/MRC", costList) 383 if p.speer.version >= lpv4 { 384 sendList = sendList.add("forkID", &forkID) 385 sendList = sendList.add("recentTxLookup", recentTxLookup) 386 } 387 if err := p2p.ExpectMsg(p.app, StatusMsg, nil); err != nil { 388 t.Fatalf("status recv: %v", err) 389 } 390 if err := p2p.Send(p.app, StatusMsg, sendList); err != nil { 391 t.Fatalf("status send: %v", err) 392 } 393 } 394 395 // close terminates the local side of the peer, notifying the remote protocol 396 // manager of termination. 397 func (p *testPeer) close() { 398 p.app.Close() 399 } 400 401 func newTestPeerPair(name string, version int, server *serverHandler, client *clientHandler) (*testPeer, *testPeer, error) { 402 // Create a message pipe to communicate through 403 app, net := p2p.MsgPipe() 404 405 // Generate a random id and create the peer 406 var id enode.ID 407 rand.Read(id[:]) 408 409 peer1 := newClientPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 410 peer2 := newServerPeer(version, NetworkId, false, p2p.NewPeer(id, name, nil), app) 411 412 // Start the peer on a new thread 413 errc1 := make(chan error, 1) 414 errc2 := make(chan error, 1) 415 go func() { 416 select { 417 case <-server.closeCh: 418 errc1 <- p2p.DiscQuitting 419 case errc1 <- server.handle(peer1): 420 } 421 }() 422 go func() { 423 select { 424 case <-client.closeCh: 425 errc2 <- p2p.DiscQuitting 426 case errc2 <- client.handle(peer2): 427 } 428 }() 429 // Ensure the connection is established or exits when any error occurs 430 for { 431 select { 432 case err := <-errc1: 433 return nil, nil, fmt.Errorf("Failed to establish protocol connection %v", err) 434 case err := <-errc2: 435 return nil, nil, fmt.Errorf("Failed to establish protocol connection %v", err) 436 default: 437 } 438 if atomic.LoadUint32(&peer1.serving) == 1 && atomic.LoadUint32(&peer2.serving) == 1 { 439 break 440 } 441 time.Sleep(50 * time.Millisecond) 442 } 443 return &testPeer{cpeer: peer1, net: net, app: app}, &testPeer{speer: peer2, net: app, app: net}, nil 444 } 445 446 type indexerCallback func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer) 447 448 // testClient represents a client object for testing with necessary auxiliary fields. 449 type testClient struct { 450 clock mclock.Clock 451 db ethdb.Database 452 peer *testPeer 453 handler *clientHandler 454 455 chtIndexer *core.ChainIndexer 456 bloomIndexer *core.ChainIndexer 457 bloomTrieIndexer *core.ChainIndexer 458 } 459 460 // newRawPeer creates a new server peer connects to the server and do the handshake. 461 func (client *testClient) newRawPeer(t *testing.T, name string, version int, recentTxLookup uint64) (*testPeer, func(), <-chan error) { 462 // Create a message pipe to communicate through 463 app, net := p2p.MsgPipe() 464 465 // Generate a random id and create the peer 466 var id enode.ID 467 rand.Read(id[:]) 468 peer := newServerPeer(version, NetworkId, false, p2p.NewPeer(id, name, nil), net) 469 470 // Start the peer on a new thread 471 errCh := make(chan error, 1) 472 go func() { 473 select { 474 case <-client.handler.closeCh: 475 errCh <- p2p.DiscQuitting 476 case errCh <- client.handler.handle(peer): 477 } 478 }() 479 tp := &testPeer{ 480 app: app, 481 net: net, 482 speer: peer, 483 } 484 var ( 485 genesis = client.handler.backend.blockchain.Genesis() 486 head = client.handler.backend.blockchain.CurrentHeader() 487 td = client.handler.backend.blockchain.GetTd(head.Hash(), head.Number.Uint64()) 488 ) 489 forkID := forkid.NewID(client.handler.backend.blockchain.Config(), genesis.Hash(), head.Number.Uint64()) 490 tp.handshakeWithClient(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash(), forkID, testCostList(0), recentTxLookup) // disable flow control by default 491 492 // Ensure the connection is established or exits when any error occurs 493 for { 494 select { 495 case <-errCh: 496 return nil, nil, nil 497 default: 498 } 499 if atomic.LoadUint32(&peer.serving) == 1 { 500 break 501 } 502 time.Sleep(50 * time.Millisecond) 503 } 504 closePeer := func() { 505 tp.speer.close() 506 tp.close() 507 } 508 return tp, closePeer, errCh 509 } 510 511 // testServer represents a server object for testing with necessary auxiliary fields. 512 type testServer struct { 513 clock mclock.Clock 514 backend *backends.SimulatedBackend 515 db ethdb.Database 516 peer *testPeer 517 handler *serverHandler 518 519 chtIndexer *core.ChainIndexer 520 bloomIndexer *core.ChainIndexer 521 bloomTrieIndexer *core.ChainIndexer 522 } 523 524 // newRawPeer creates a new client peer connects to the server and do the handshake. 525 func (server *testServer) newRawPeer(t *testing.T, name string, version int) (*testPeer, func(), <-chan error) { 526 // Create a message pipe to communicate through 527 app, net := p2p.MsgPipe() 528 529 // Generate a random id and create the peer 530 var id enode.ID 531 rand.Read(id[:]) 532 peer := newClientPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 533 534 // Start the peer on a new thread 535 errCh := make(chan error, 1) 536 go func() { 537 select { 538 case <-server.handler.closeCh: 539 errCh <- p2p.DiscQuitting 540 case errCh <- server.handler.handle(peer): 541 } 542 }() 543 tp := &testPeer{ 544 app: app, 545 net: net, 546 cpeer: peer, 547 } 548 var ( 549 genesis = server.handler.blockchain.Genesis() 550 head = server.handler.blockchain.CurrentHeader() 551 td = server.handler.blockchain.GetTd(head.Hash(), head.Number.Uint64()) 552 ) 553 forkID := forkid.NewID(server.handler.blockchain.Config(), genesis.Hash(), head.Number.Uint64()) 554 tp.handshakeWithServer(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash(), forkID) 555 556 // Ensure the connection is established or exits when any error occurs 557 for { 558 select { 559 case <-errCh: 560 return nil, nil, nil 561 default: 562 } 563 if atomic.LoadUint32(&peer.serving) == 1 { 564 break 565 } 566 time.Sleep(50 * time.Millisecond) 567 } 568 closePeer := func() { 569 tp.cpeer.close() 570 tp.close() 571 } 572 return tp, closePeer, errCh 573 } 574 575 // testnetConfig wraps all the configurations for testing network. 576 type testnetConfig struct { 577 blocks int 578 protocol int 579 indexFn indexerCallback 580 ulcServers []string 581 ulcFraction int 582 simClock bool 583 connect bool 584 nopruning bool 585 } 586 587 func newClientServerEnv(t *testing.T, config testnetConfig) (*testServer, *testClient, func()) { 588 var ( 589 sdb = rawdb.NewMemoryDatabase() 590 cdb = rawdb.NewMemoryDatabase() 591 speers = newServerPeerSet() 592 ) 593 var clock mclock.Clock = &mclock.System{} 594 if config.simClock { 595 clock = &mclock.Simulated{} 596 } 597 dist := newRequestDistributor(speers, clock) 598 rm := newRetrieveManager(speers, dist, func() time.Duration { return time.Millisecond * 500 }) 599 odr := NewLesOdr(cdb, light.TestClientIndexerConfig, speers, rm) 600 601 sindexers := testIndexers(sdb, nil, light.TestServerIndexerConfig, true) 602 cIndexers := testIndexers(cdb, odr, light.TestClientIndexerConfig, config.nopruning) 603 604 scIndexer, sbIndexer, sbtIndexer := sindexers[0], sindexers[1], sindexers[2] 605 ccIndexer, cbIndexer, cbtIndexer := cIndexers[0], cIndexers[1], cIndexers[2] 606 odr.SetIndexers(ccIndexer, cbIndexer, cbtIndexer) 607 608 server, b, serverClose := newTestServerHandler(config.blocks, sindexers, sdb, clock) 609 client, clientClose := newTestClientHandler(b, odr, cIndexers, cdb, speers, config.ulcServers, config.ulcFraction) 610 611 scIndexer.Start(server.blockchain) 612 sbIndexer.Start(server.blockchain) 613 ccIndexer.Start(client.backend.blockchain) 614 cbIndexer.Start(client.backend.blockchain) 615 616 if config.indexFn != nil { 617 config.indexFn(scIndexer, sbIndexer, sbtIndexer) 618 } 619 var ( 620 err error 621 speer, cpeer *testPeer 622 ) 623 if config.connect { 624 done := make(chan struct{}) 625 client.syncEnd = func(_ *types.Header) { close(done) } 626 cpeer, speer, err = newTestPeerPair("peer", config.protocol, server, client) 627 if err != nil { 628 t.Fatalf("Failed to connect testing peers %v", err) 629 } 630 select { 631 case <-done: 632 case <-time.After(10 * time.Second): 633 t.Fatal("test peer did not connect and sync within 3s") 634 } 635 } 636 s := &testServer{ 637 clock: clock, 638 backend: b, 639 db: sdb, 640 peer: cpeer, 641 handler: server, 642 chtIndexer: scIndexer, 643 bloomIndexer: sbIndexer, 644 bloomTrieIndexer: sbtIndexer, 645 } 646 c := &testClient{ 647 clock: clock, 648 db: cdb, 649 peer: speer, 650 handler: client, 651 chtIndexer: ccIndexer, 652 bloomIndexer: cbIndexer, 653 bloomTrieIndexer: cbtIndexer, 654 } 655 teardown := func() { 656 if config.connect { 657 speer.close() 658 cpeer.close() 659 cpeer.cpeer.close() 660 speer.speer.close() 661 } 662 ccIndexer.Close() 663 cbIndexer.Close() 664 scIndexer.Close() 665 sbIndexer.Close() 666 dist.close() 667 serverClose() 668 b.Close() 669 clientClose() 670 } 671 return s, c, teardown 672 } 673 674 // NewFuzzerPeer creates a client peer for test purposes, and also returns 675 // a function to close the peer: this is needed to avoid goroutine leaks in the 676 // exec queue. 677 func NewFuzzerPeer(version int) (p *clientPeer, closer func()) { 678 p = newClientPeer(version, 0, p2p.NewPeer(enode.ID{}, "", nil), nil) 679 return p, func() { p.peerCommons.close() } 680 }