github.com/phillinzzz/newBsc@v1.1.6/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  	"github.com/phillinzzz/newBsc/accounts/abi/bind"
    33  	"github.com/phillinzzz/newBsc/accounts/abi/bind/backends"
    34  	"github.com/phillinzzz/newBsc/common"
    35  	"github.com/phillinzzz/newBsc/common/mclock"
    36  	"github.com/phillinzzz/newBsc/consensus/ethash"
    37  	"github.com/phillinzzz/newBsc/contracts/checkpointoracle/contract"
    38  	"github.com/phillinzzz/newBsc/core"
    39  	"github.com/phillinzzz/newBsc/core/forkid"
    40  	"github.com/phillinzzz/newBsc/core/rawdb"
    41  	"github.com/phillinzzz/newBsc/core/types"
    42  	"github.com/phillinzzz/newBsc/crypto"
    43  	"github.com/phillinzzz/newBsc/eth/ethconfig"
    44  	"github.com/phillinzzz/newBsc/ethdb"
    45  	"github.com/phillinzzz/newBsc/event"
    46  	"github.com/phillinzzz/newBsc/les/checkpointoracle"
    47  	"github.com/phillinzzz/newBsc/les/flowcontrol"
    48  	vfs "github.com/phillinzzz/newBsc/les/vflux/server"
    49  	"github.com/phillinzzz/newBsc/light"
    50  	"github.com/phillinzzz/newBsc/p2p"
    51  	"github.com/phillinzzz/newBsc/p2p/enode"
    52  	"github.com/phillinzzz/newBsc/params"
    53  )
    54  
    55  var (
    56  	bankKey, _ = crypto.GenerateKey()
    57  	bankAddr   = crypto.PubkeyToAddress(bankKey.PublicKey)
    58  	bankFunds  = big.NewInt(1000000000000000000)
    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(10000), params.TxGas, nil, 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(1000), params.TxGas, nil, 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(1000), params.TxGas, nil, 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(0), 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(0), 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, nil, 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, nil, 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, nil, 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  		}
   201  		oracle *checkpointoracle.CheckpointOracle
   202  	)
   203  	genesis := gspec.MustCommit(db)
   204  	chain, _ := light.NewLightChain(odr, gspec.Config, engine, nil)
   205  	if indexers != nil {
   206  		checkpointConfig := &params.CheckpointOracleConfig{
   207  			Address:   crypto.CreateAddress(bankAddr, 0),
   208  			Signers:   []common.Address{signerAddr},
   209  			Threshold: 1,
   210  		}
   211  		getLocal := func(index uint64) params.TrustedCheckpoint {
   212  			chtIndexer := indexers[0]
   213  			sectionHead := chtIndexer.SectionHead(index)
   214  			return params.TrustedCheckpoint{
   215  				SectionIndex: index,
   216  				SectionHead:  sectionHead,
   217  				CHTRoot:      light.GetChtRoot(db, index, sectionHead),
   218  				BloomRoot:    light.GetBloomTrieRoot(db, index, sectionHead),
   219  			}
   220  		}
   221  		oracle = checkpointoracle.New(checkpointConfig, getLocal)
   222  	}
   223  	client := &LightEthereum{
   224  		lesCommons: lesCommons{
   225  			genesis:     genesis.Hash(),
   226  			config:      &ethconfig.Config{LightPeers: 100, NetworkId: NetworkId},
   227  			chainConfig: params.AllEthashProtocolChanges,
   228  			iConfig:     light.TestClientIndexerConfig,
   229  			chainDb:     db,
   230  			oracle:      oracle,
   231  			chainReader: chain,
   232  			closeCh:     make(chan struct{}),
   233  		},
   234  		peers:      peers,
   235  		reqDist:    odr.retriever.dist,
   236  		retriever:  odr.retriever,
   237  		odr:        odr,
   238  		engine:     engine,
   239  		blockchain: chain,
   240  		eventMux:   evmux,
   241  	}
   242  	client.handler = newClientHandler(ulcServers, ulcFraction, nil, client)
   243  
   244  	if client.oracle != nil {
   245  		client.oracle.Start(backend)
   246  	}
   247  	client.handler.start()
   248  	return client.handler, func() {
   249  		client.handler.stop()
   250  	}
   251  }
   252  
   253  func newTestServerHandler(blocks int, indexers []*core.ChainIndexer, db ethdb.Database, clock mclock.Clock) (*serverHandler, *backends.SimulatedBackend, func()) {
   254  	var (
   255  		gspec = core.Genesis{
   256  			Config:   params.AllEthashProtocolChanges,
   257  			Alloc:    core.GenesisAlloc{bankAddr: {Balance: bankFunds}},
   258  			GasLimit: 100000000,
   259  		}
   260  		oracle *checkpointoracle.CheckpointOracle
   261  	)
   262  	genesis := gspec.MustCommit(db)
   263  
   264  	// create a simulation backend and pre-commit several customized block to the database.
   265  	simulation := backends.NewSimulatedBackendWithDatabase(db, gspec.Alloc, 100000000)
   266  	prepare(blocks, simulation)
   267  
   268  	txpoolConfig := core.DefaultTxPoolConfig
   269  	txpoolConfig.Journal = ""
   270  	txpool := core.NewTxPool(txpoolConfig, gspec.Config, simulation.Blockchain())
   271  	if indexers != nil {
   272  		checkpointConfig := &params.CheckpointOracleConfig{
   273  			Address:   crypto.CreateAddress(bankAddr, 0),
   274  			Signers:   []common.Address{signerAddr},
   275  			Threshold: 1,
   276  		}
   277  		getLocal := func(index uint64) params.TrustedCheckpoint {
   278  			chtIndexer := indexers[0]
   279  			sectionHead := chtIndexer.SectionHead(index)
   280  			return params.TrustedCheckpoint{
   281  				SectionIndex: index,
   282  				SectionHead:  sectionHead,
   283  				CHTRoot:      light.GetChtRoot(db, index, sectionHead),
   284  				BloomRoot:    light.GetBloomTrieRoot(db, index, sectionHead),
   285  			}
   286  		}
   287  		oracle = checkpointoracle.New(checkpointConfig, getLocal)
   288  	}
   289  	server := &LesServer{
   290  		lesCommons: lesCommons{
   291  			genesis:     genesis.Hash(),
   292  			config:      &ethconfig.Config{LightPeers: 100, NetworkId: NetworkId},
   293  			chainConfig: params.AllEthashProtocolChanges,
   294  			iConfig:     light.TestServerIndexerConfig,
   295  			chainDb:     db,
   296  			chainReader: simulation.Blockchain(),
   297  			oracle:      oracle,
   298  			closeCh:     make(chan struct{}),
   299  		},
   300  		peers:        newClientPeerSet(),
   301  		servingQueue: newServingQueue(int64(time.Millisecond*10), 1),
   302  		defParams: flowcontrol.ServerParams{
   303  			BufLimit:    testBufLimit,
   304  			MinRecharge: testBufRecharge,
   305  		},
   306  		fcManager: flowcontrol.NewClientManager(nil, clock),
   307  	}
   308  	server.costTracker, server.minCapacity = newCostTracker(db, server.config)
   309  	server.costTracker.testCostList = testCostList(0) // Disable flow control mechanism.
   310  	server.clientPool = vfs.NewClientPool(db, testBufRecharge, defaultConnectedBias, clock, alwaysTrueFn)
   311  	server.clientPool.Start()
   312  	server.clientPool.SetLimits(10000, 10000) // Assign enough capacity for clientpool
   313  	server.handler = newServerHandler(server, simulation.Blockchain(), db, txpool, func() bool { return true })
   314  	if server.oracle != nil {
   315  		server.oracle.Start(simulation)
   316  	}
   317  	server.servingQueue.setThreads(4)
   318  	server.handler.start()
   319  	closer := func() { server.Stop() }
   320  	return server.handler, simulation, closer
   321  }
   322  
   323  func alwaysTrueFn() bool {
   324  	return true
   325  }
   326  
   327  // testPeer is a simulated peer to allow testing direct network calls.
   328  type testPeer struct {
   329  	cpeer *clientPeer
   330  	speer *serverPeer
   331  
   332  	net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
   333  	app *p2p.MsgPipeRW    // Application layer reader/writer to simulate the local side
   334  }
   335  
   336  // handshakeWithServer executes the handshake with the remote server peer.
   337  func (p *testPeer) handshakeWithServer(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, forkID forkid.ID) {
   338  	// It only works for the simulated client peer
   339  	if p.cpeer == nil {
   340  		t.Fatal("handshake for client peer only")
   341  	}
   342  	var sendList keyValueList
   343  	sendList = sendList.add("protocolVersion", uint64(p.cpeer.version))
   344  	sendList = sendList.add("networkId", uint64(NetworkId))
   345  	sendList = sendList.add("headTd", td)
   346  	sendList = sendList.add("headHash", head)
   347  	sendList = sendList.add("headNum", headNum)
   348  	sendList = sendList.add("genesisHash", genesis)
   349  	if p.cpeer.version >= lpv4 {
   350  		sendList = sendList.add("forkID", &forkID)
   351  	}
   352  	if err := p2p.ExpectMsg(p.app, StatusMsg, nil); err != nil {
   353  		t.Fatalf("status recv: %v", err)
   354  	}
   355  	if err := p2p.Send(p.app, StatusMsg, sendList); err != nil {
   356  		t.Fatalf("status send: %v", err)
   357  	}
   358  }
   359  
   360  // handshakeWithClient executes the handshake with the remote client peer.
   361  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) {
   362  	// It only works for the simulated client peer
   363  	if p.speer == nil {
   364  		t.Fatal("handshake for server peer only")
   365  	}
   366  	var sendList keyValueList
   367  	sendList = sendList.add("protocolVersion", uint64(p.speer.version))
   368  	sendList = sendList.add("networkId", uint64(NetworkId))
   369  	sendList = sendList.add("headTd", td)
   370  	sendList = sendList.add("headHash", head)
   371  	sendList = sendList.add("headNum", headNum)
   372  	sendList = sendList.add("genesisHash", genesis)
   373  	sendList = sendList.add("serveHeaders", nil)
   374  	sendList = sendList.add("serveChainSince", uint64(0))
   375  	sendList = sendList.add("serveStateSince", uint64(0))
   376  	sendList = sendList.add("serveRecentState", uint64(128-4))
   377  	sendList = sendList.add("txRelay", nil)
   378  	sendList = sendList.add("flowControl/BL", testBufLimit)
   379  	sendList = sendList.add("flowControl/MRR", testBufRecharge)
   380  	sendList = sendList.add("flowControl/MRC", costList)
   381  	if p.speer.version >= lpv4 {
   382  		sendList = sendList.add("forkID", &forkID)
   383  		sendList = sendList.add("recentTxLookup", recentTxLookup)
   384  	}
   385  	if err := p2p.ExpectMsg(p.app, StatusMsg, nil); err != nil {
   386  		t.Fatalf("status recv: %v", err)
   387  	}
   388  	if err := p2p.Send(p.app, StatusMsg, sendList); err != nil {
   389  		t.Fatalf("status send: %v", err)
   390  	}
   391  }
   392  
   393  // close terminates the local side of the peer, notifying the remote protocol
   394  // manager of termination.
   395  func (p *testPeer) close() {
   396  	p.app.Close()
   397  }
   398  
   399  func newTestPeerPair(name string, version int, server *serverHandler, client *clientHandler) (*testPeer, *testPeer, error) {
   400  	// Create a message pipe to communicate through
   401  	app, net := p2p.MsgPipe()
   402  
   403  	// Generate a random id and create the peer
   404  	var id enode.ID
   405  	rand.Read(id[:])
   406  
   407  	peer1 := newClientPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
   408  	peer2 := newServerPeer(version, NetworkId, false, p2p.NewPeer(id, name, nil), app)
   409  
   410  	// Start the peer on a new thread
   411  	errc1 := make(chan error, 1)
   412  	errc2 := make(chan error, 1)
   413  	go func() {
   414  		select {
   415  		case <-server.closeCh:
   416  			errc1 <- p2p.DiscQuitting
   417  		case errc1 <- server.handle(peer1):
   418  		}
   419  	}()
   420  	go func() {
   421  		select {
   422  		case <-client.closeCh:
   423  			errc2 <- p2p.DiscQuitting
   424  		case errc2 <- client.handle(peer2):
   425  		}
   426  	}()
   427  	// Ensure the connection is established or exits when any error occurs
   428  	for {
   429  		select {
   430  		case err := <-errc1:
   431  			return nil, nil, fmt.Errorf("Failed to establish protocol connection %v", err)
   432  		case err := <-errc2:
   433  			return nil, nil, fmt.Errorf("Failed to establish protocol connection %v", err)
   434  		default:
   435  		}
   436  		if atomic.LoadUint32(&peer1.serving) == 1 && atomic.LoadUint32(&peer2.serving) == 1 {
   437  			break
   438  		}
   439  		time.Sleep(50 * time.Millisecond)
   440  	}
   441  	return &testPeer{cpeer: peer1, net: net, app: app}, &testPeer{speer: peer2, net: app, app: net}, nil
   442  }
   443  
   444  type indexerCallback func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer)
   445  
   446  // testClient represents a client object for testing with necessary auxiliary fields.
   447  type testClient struct {
   448  	clock   mclock.Clock
   449  	db      ethdb.Database
   450  	peer    *testPeer
   451  	handler *clientHandler
   452  
   453  	chtIndexer       *core.ChainIndexer
   454  	bloomIndexer     *core.ChainIndexer
   455  	bloomTrieIndexer *core.ChainIndexer
   456  }
   457  
   458  // newRawPeer creates a new server peer connects to the server and do the handshake.
   459  func (client *testClient) newRawPeer(t *testing.T, name string, version int, recentTxLookup uint64) (*testPeer, func(), <-chan error) {
   460  	// Create a message pipe to communicate through
   461  	app, net := p2p.MsgPipe()
   462  
   463  	// Generate a random id and create the peer
   464  	var id enode.ID
   465  	rand.Read(id[:])
   466  	peer := newServerPeer(version, NetworkId, false, p2p.NewPeer(id, name, nil), net)
   467  
   468  	// Start the peer on a new thread
   469  	errCh := make(chan error, 1)
   470  	go func() {
   471  		select {
   472  		case <-client.handler.closeCh:
   473  			errCh <- p2p.DiscQuitting
   474  		case errCh <- client.handler.handle(peer):
   475  		}
   476  	}()
   477  	tp := &testPeer{
   478  		app:   app,
   479  		net:   net,
   480  		speer: peer,
   481  	}
   482  	var (
   483  		genesis = client.handler.backend.blockchain.Genesis()
   484  		head    = client.handler.backend.blockchain.CurrentHeader()
   485  		td      = client.handler.backend.blockchain.GetTd(head.Hash(), head.Number.Uint64())
   486  	)
   487  	forkID := forkid.NewID(client.handler.backend.blockchain.Config(), genesis.Hash(), head.Number.Uint64())
   488  	tp.handshakeWithClient(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash(), forkID, testCostList(0), recentTxLookup) // disable flow control by default
   489  
   490  	// Ensure the connection is established or exits when any error occurs
   491  	for {
   492  		select {
   493  		case <-errCh:
   494  			return nil, nil, nil
   495  		default:
   496  		}
   497  		if atomic.LoadUint32(&peer.serving) == 1 {
   498  			break
   499  		}
   500  		time.Sleep(50 * time.Millisecond)
   501  	}
   502  	closePeer := func() {
   503  		tp.speer.close()
   504  		tp.close()
   505  	}
   506  	return tp, closePeer, errCh
   507  }
   508  
   509  // testServer represents a server object for testing with necessary auxiliary fields.
   510  type testServer struct {
   511  	clock   mclock.Clock
   512  	backend *backends.SimulatedBackend
   513  	db      ethdb.Database
   514  	peer    *testPeer
   515  	handler *serverHandler
   516  
   517  	chtIndexer       *core.ChainIndexer
   518  	bloomIndexer     *core.ChainIndexer
   519  	bloomTrieIndexer *core.ChainIndexer
   520  }
   521  
   522  // newRawPeer creates a new client peer connects to the server and do the handshake.
   523  func (server *testServer) newRawPeer(t *testing.T, name string, version int) (*testPeer, func(), <-chan error) {
   524  	// Create a message pipe to communicate through
   525  	app, net := p2p.MsgPipe()
   526  
   527  	// Generate a random id and create the peer
   528  	var id enode.ID
   529  	rand.Read(id[:])
   530  	peer := newClientPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
   531  
   532  	// Start the peer on a new thread
   533  	errCh := make(chan error, 1)
   534  	go func() {
   535  		select {
   536  		case <-server.handler.closeCh:
   537  			errCh <- p2p.DiscQuitting
   538  		case errCh <- server.handler.handle(peer):
   539  		}
   540  	}()
   541  	tp := &testPeer{
   542  		app:   app,
   543  		net:   net,
   544  		cpeer: peer,
   545  	}
   546  	var (
   547  		genesis = server.handler.blockchain.Genesis()
   548  		head    = server.handler.blockchain.CurrentHeader()
   549  		td      = server.handler.blockchain.GetTd(head.Hash(), head.Number.Uint64())
   550  	)
   551  	forkID := forkid.NewID(server.handler.blockchain.Config(), genesis.Hash(), head.Number.Uint64())
   552  	tp.handshakeWithServer(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash(), forkID)
   553  
   554  	// Ensure the connection is established or exits when any error occurs
   555  	for {
   556  		select {
   557  		case <-errCh:
   558  			return nil, nil, nil
   559  		default:
   560  		}
   561  		if atomic.LoadUint32(&peer.serving) == 1 {
   562  			break
   563  		}
   564  		time.Sleep(50 * time.Millisecond)
   565  	}
   566  	closePeer := func() {
   567  		tp.cpeer.close()
   568  		tp.close()
   569  	}
   570  	return tp, closePeer, errCh
   571  }
   572  
   573  // testnetConfig wraps all the configurations for testing network.
   574  type testnetConfig struct {
   575  	blocks      int
   576  	protocol    int
   577  	indexFn     indexerCallback
   578  	ulcServers  []string
   579  	ulcFraction int
   580  	simClock    bool
   581  	connect     bool
   582  	nopruning   bool
   583  }
   584  
   585  func newClientServerEnv(t *testing.T, config testnetConfig) (*testServer, *testClient, func()) {
   586  	var (
   587  		sdb    = rawdb.NewMemoryDatabase()
   588  		cdb    = rawdb.NewMemoryDatabase()
   589  		speers = newServerPeerSet()
   590  	)
   591  	var clock mclock.Clock = &mclock.System{}
   592  	if config.simClock {
   593  		clock = &mclock.Simulated{}
   594  	}
   595  	dist := newRequestDistributor(speers, clock)
   596  	rm := newRetrieveManager(speers, dist, func() time.Duration { return time.Millisecond * 500 })
   597  	odr := NewLesOdr(cdb, light.TestClientIndexerConfig, speers, rm)
   598  
   599  	sindexers := testIndexers(sdb, nil, light.TestServerIndexerConfig, true)
   600  	cIndexers := testIndexers(cdb, odr, light.TestClientIndexerConfig, config.nopruning)
   601  
   602  	scIndexer, sbIndexer, sbtIndexer := sindexers[0], sindexers[1], sindexers[2]
   603  	ccIndexer, cbIndexer, cbtIndexer := cIndexers[0], cIndexers[1], cIndexers[2]
   604  	odr.SetIndexers(ccIndexer, cbIndexer, cbtIndexer)
   605  
   606  	server, b, serverClose := newTestServerHandler(config.blocks, sindexers, sdb, clock)
   607  	client, clientClose := newTestClientHandler(b, odr, cIndexers, cdb, speers, config.ulcServers, config.ulcFraction)
   608  
   609  	scIndexer.Start(server.blockchain)
   610  	sbIndexer.Start(server.blockchain)
   611  	ccIndexer.Start(client.backend.blockchain)
   612  	cbIndexer.Start(client.backend.blockchain)
   613  
   614  	if config.indexFn != nil {
   615  		config.indexFn(scIndexer, sbIndexer, sbtIndexer)
   616  	}
   617  	var (
   618  		err          error
   619  		speer, cpeer *testPeer
   620  	)
   621  	if config.connect {
   622  		done := make(chan struct{})
   623  		client.syncEnd = func(_ *types.Header) { close(done) }
   624  		cpeer, speer, err = newTestPeerPair("peer", config.protocol, server, client)
   625  		if err != nil {
   626  			t.Fatalf("Failed to connect testing peers %v", err)
   627  		}
   628  		select {
   629  		case <-done:
   630  		case <-time.After(10 * time.Second):
   631  			t.Fatal("test peer did not connect and sync within 3s")
   632  		}
   633  	}
   634  	s := &testServer{
   635  		clock:            clock,
   636  		backend:          b,
   637  		db:               sdb,
   638  		peer:             cpeer,
   639  		handler:          server,
   640  		chtIndexer:       scIndexer,
   641  		bloomIndexer:     sbIndexer,
   642  		bloomTrieIndexer: sbtIndexer,
   643  	}
   644  	c := &testClient{
   645  		clock:            clock,
   646  		db:               cdb,
   647  		peer:             speer,
   648  		handler:          client,
   649  		chtIndexer:       ccIndexer,
   650  		bloomIndexer:     cbIndexer,
   651  		bloomTrieIndexer: cbtIndexer,
   652  	}
   653  	teardown := func() {
   654  		if config.connect {
   655  			speer.close()
   656  			cpeer.close()
   657  			cpeer.cpeer.close()
   658  			speer.speer.close()
   659  		}
   660  		ccIndexer.Close()
   661  		cbIndexer.Close()
   662  		scIndexer.Close()
   663  		sbIndexer.Close()
   664  		dist.close()
   665  		serverClose()
   666  		b.Close()
   667  		clientClose()
   668  	}
   669  	return s, c, teardown
   670  }
   671  
   672  // NewFuzzerPeer creates a client peer for test purposes, and also returns
   673  // a function to close the peer: this is needed to avoid goroutine leaks in the
   674  // exec queue.
   675  func NewFuzzerPeer(version int) (p *clientPeer, closer func()) {
   676  	p = newClientPeer(version, 0, p2p.NewPeer(enode.ID{}, "", nil), nil)
   677  	return p, func() { p.peerCommons.close() }
   678  }