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