github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/les/helper_test.go (about)

     1  // This file is part of the go-sberex library. The go-sberex library is 
     2  // free software: you can redistribute it and/or modify it under the terms 
     3  // of the GNU Lesser General Public License as published by the Free 
     4  // Software Foundation, either version 3 of the License, or (at your option)
     5  // any later version.
     6  //
     7  // The go-sberex library is distributed in the hope that it will be useful, 
     8  // but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
    10  // General Public License <http://www.gnu.org/licenses/> for more details.
    11  
    12  // This file contains some shares testing functionality, common to  multiple
    13  // different files and modules being tested.
    14  
    15  package les
    16  
    17  import (
    18  	"crypto/rand"
    19  	"math/big"
    20  	"sync"
    21  	"testing"
    22  
    23  	"github.com/Sberex/go-sberex/common"
    24  	"github.com/Sberex/go-sberex/consensus/ethash"
    25  	"github.com/Sberex/go-sberex/core"
    26  	"github.com/Sberex/go-sberex/core/types"
    27  	"github.com/Sberex/go-sberex/core/vm"
    28  	"github.com/Sberex/go-sberex/crypto"
    29  	"github.com/Sberex/go-sberex/eth"
    30  	"github.com/Sberex/go-sberex/ethdb"
    31  	"github.com/Sberex/go-sberex/event"
    32  	"github.com/Sberex/go-sberex/les/flowcontrol"
    33  	"github.com/Sberex/go-sberex/light"
    34  	"github.com/Sberex/go-sberex/p2p"
    35  	"github.com/Sberex/go-sberex/p2p/discover"
    36  	"github.com/Sberex/go-sberex/params"
    37  )
    38  
    39  var (
    40  	testBankKey, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    41  	testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
    42  	testBankFunds   = big.NewInt(1000000000000000000)
    43  
    44  	acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
    45  	acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
    46  	acc1Addr   = crypto.PubkeyToAddress(acc1Key.PublicKey)
    47  	acc2Addr   = crypto.PubkeyToAddress(acc2Key.PublicKey)
    48  
    49  	testContractCode         = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056")
    50  	testContractAddr         common.Address
    51  	testContractCodeDeployed = testContractCode[16:]
    52  	testContractDeployed     = uint64(2)
    53  
    54  	testEventEmitterCode = common.Hex2Bytes("60606040523415600e57600080fd5b7f57050ab73f6b9ebdd9f76b8d4997793f48cf956e965ee070551b9ca0bb71584e60405160405180910390a160358060476000396000f3006060604052600080fd00a165627a7a723058203f727efcad8b5811f8cb1fc2620ce5e8c63570d697aef968172de296ea3994140029")
    55  	testEventEmitterAddr common.Address
    56  
    57  	testBufLimit = uint64(100)
    58  )
    59  
    60  /*
    61  contract test {
    62  
    63      uint256[100] data;
    64  
    65      function Put(uint256 addr, uint256 value) {
    66          data[addr] = value;
    67      }
    68  
    69      function Get(uint256 addr) constant returns (uint256 value) {
    70          return data[addr];
    71      }
    72  }
    73  */
    74  
    75  func testChainGen(i int, block *core.BlockGen) {
    76  	signer := types.HomesteadSigner{}
    77  
    78  	switch i {
    79  	case 0:
    80  		// In block 1, the test bank sends account #1 some sbr.
    81  		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
    82  		block.AddTx(tx)
    83  	case 1:
    84  		// In block 2, the test bank sends some more sbr to account #1.
    85  		// acc1Addr passes it on to account #2.
    86  		// acc1Addr creates a test contract.
    87  		// acc1Addr creates a test event.
    88  		nonce := block.TxNonce(acc1Addr)
    89  
    90  		tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey)
    91  		tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key)
    92  		tx3, _ := types.SignTx(types.NewContractCreation(nonce+1, big.NewInt(0), 200000, big.NewInt(0), testContractCode), signer, acc1Key)
    93  		testContractAddr = crypto.CreateAddress(acc1Addr, nonce+1)
    94  		tx4, _ := types.SignTx(types.NewContractCreation(nonce+2, big.NewInt(0), 200000, big.NewInt(0), testEventEmitterCode), signer, acc1Key)
    95  		testEventEmitterAddr = crypto.CreateAddress(acc1Addr, nonce+2)
    96  		block.AddTx(tx1)
    97  		block.AddTx(tx2)
    98  		block.AddTx(tx3)
    99  		block.AddTx(tx4)
   100  	case 2:
   101  		// Block 3 is empty but was mined by account #2.
   102  		block.SetCoinbase(acc2Addr)
   103  		block.SetExtra([]byte("yeehaw"))
   104  		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001")
   105  		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey)
   106  		block.AddTx(tx)
   107  	case 3:
   108  		// Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
   109  		b2 := block.PrevBlock(1).Header()
   110  		b2.Extra = []byte("foo")
   111  		block.AddUncle(b2)
   112  		b3 := block.PrevBlock(2).Header()
   113  		b3.Extra = []byte("foo")
   114  		block.AddUncle(b3)
   115  		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002")
   116  		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey)
   117  		block.AddTx(tx)
   118  	}
   119  }
   120  
   121  func testRCL() RequestCostList {
   122  	cl := make(RequestCostList, len(reqList))
   123  	for i, code := range reqList {
   124  		cl[i].MsgCode = code
   125  		cl[i].BaseCost = 0
   126  		cl[i].ReqCost = 0
   127  	}
   128  	return cl
   129  }
   130  
   131  // newTestProtocolManager creates a new protocol manager for testing purposes,
   132  // with the given number of blocks already known, and potential notification
   133  // channels for different events.
   134  func newTestProtocolManager(lightSync bool, blocks int, generator func(int, *core.BlockGen), peers *peerSet, odr *LesOdr, db ethdb.Database) (*ProtocolManager, error) {
   135  	var (
   136  		evmux  = new(event.TypeMux)
   137  		engine = ethash.NewFaker()
   138  		gspec  = core.Genesis{
   139  			Config: params.TestChainConfig,
   140  			Alloc:  core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
   141  		}
   142  		genesis = gspec.MustCommit(db)
   143  		chain   BlockChain
   144  	)
   145  	if peers == nil {
   146  		peers = newPeerSet()
   147  	}
   148  
   149  	if lightSync {
   150  		chain, _ = light.NewLightChain(odr, gspec.Config, engine)
   151  	} else {
   152  		blockchain, _ := core.NewBlockChain(db, nil, gspec.Config, engine, vm.Config{})
   153  
   154  		chtIndexer := light.NewChtIndexer(db, false)
   155  		chtIndexer.Start(blockchain)
   156  
   157  		bbtIndexer := light.NewBloomTrieIndexer(db, false)
   158  
   159  		bloomIndexer := eth.NewBloomIndexer(db, params.BloomBitsBlocks)
   160  		bloomIndexer.AddChildIndexer(bbtIndexer)
   161  		bloomIndexer.Start(blockchain)
   162  
   163  		gchain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, blocks, generator)
   164  		if _, err := blockchain.InsertChain(gchain); err != nil {
   165  			panic(err)
   166  		}
   167  		chain = blockchain
   168  	}
   169  
   170  	var protocolVersions []uint
   171  	if lightSync {
   172  		protocolVersions = ClientProtocolVersions
   173  	} else {
   174  		protocolVersions = ServerProtocolVersions
   175  	}
   176  	pm, err := NewProtocolManager(gspec.Config, lightSync, protocolVersions, NetworkId, evmux, engine, peers, chain, nil, db, odr, nil, make(chan struct{}), new(sync.WaitGroup))
   177  	if err != nil {
   178  		return nil, err
   179  	}
   180  	if !lightSync {
   181  		srv := &LesServer{protocolManager: pm}
   182  		pm.server = srv
   183  
   184  		srv.defParams = &flowcontrol.ServerParams{
   185  			BufLimit:    testBufLimit,
   186  			MinRecharge: 1,
   187  		}
   188  
   189  		srv.fcManager = flowcontrol.NewClientManager(50, 10, 1000000000)
   190  		srv.fcCostStats = newCostStats(nil)
   191  	}
   192  	pm.Start(1000)
   193  	return pm, nil
   194  }
   195  
   196  // newTestProtocolManagerMust creates a new protocol manager for testing purposes,
   197  // with the given number of blocks already known, and potential notification
   198  // channels for different events. In case of an error, the constructor force-
   199  // fails the test.
   200  func newTestProtocolManagerMust(t *testing.T, lightSync bool, blocks int, generator func(int, *core.BlockGen), peers *peerSet, odr *LesOdr, db ethdb.Database) *ProtocolManager {
   201  	pm, err := newTestProtocolManager(lightSync, blocks, generator, peers, odr, db)
   202  	if err != nil {
   203  		t.Fatalf("Failed to create protocol manager: %v", err)
   204  	}
   205  	return pm
   206  }
   207  
   208  // testPeer is a simulated peer to allow testing direct network calls.
   209  type testPeer struct {
   210  	net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
   211  	app *p2p.MsgPipeRW    // Application layer reader/writer to simulate the local side
   212  	*peer
   213  }
   214  
   215  // newTestPeer creates a new peer registered at the given protocol manager.
   216  func newTestPeer(t *testing.T, name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) {
   217  	// Create a message pipe to communicate through
   218  	app, net := p2p.MsgPipe()
   219  
   220  	// Generate a random id and create the peer
   221  	var id discover.NodeID
   222  	rand.Read(id[:])
   223  
   224  	peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
   225  
   226  	// Start the peer on a new thread
   227  	errc := make(chan error, 1)
   228  	go func() {
   229  		select {
   230  		case pm.newPeerCh <- peer:
   231  			errc <- pm.handle(peer)
   232  		case <-pm.quitSync:
   233  			errc <- p2p.DiscQuitting
   234  		}
   235  	}()
   236  	tp := &testPeer{
   237  		app:  app,
   238  		net:  net,
   239  		peer: peer,
   240  	}
   241  	// Execute any implicitly requested handshakes and return
   242  	if shake {
   243  		var (
   244  			genesis = pm.blockchain.Genesis()
   245  			head    = pm.blockchain.CurrentHeader()
   246  			td      = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64())
   247  		)
   248  		tp.handshake(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash())
   249  	}
   250  	return tp, errc
   251  }
   252  
   253  func newTestPeerPair(name string, version int, pm, pm2 *ProtocolManager) (*peer, <-chan error, *peer, <-chan error) {
   254  	// Create a message pipe to communicate through
   255  	app, net := p2p.MsgPipe()
   256  
   257  	// Generate a random id and create the peer
   258  	var id discover.NodeID
   259  	rand.Read(id[:])
   260  
   261  	peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
   262  	peer2 := pm2.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), app)
   263  
   264  	// Start the peer on a new thread
   265  	errc := make(chan error, 1)
   266  	errc2 := make(chan error, 1)
   267  	go func() {
   268  		select {
   269  		case pm.newPeerCh <- peer:
   270  			errc <- pm.handle(peer)
   271  		case <-pm.quitSync:
   272  			errc <- p2p.DiscQuitting
   273  		}
   274  	}()
   275  	go func() {
   276  		select {
   277  		case pm2.newPeerCh <- peer2:
   278  			errc2 <- pm2.handle(peer2)
   279  		case <-pm2.quitSync:
   280  			errc2 <- p2p.DiscQuitting
   281  		}
   282  	}()
   283  	return peer, errc, peer2, errc2
   284  }
   285  
   286  // handshake simulates a trivial handshake that expects the same state from the
   287  // remote side as we are simulating locally.
   288  func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash) {
   289  	var expList keyValueList
   290  	expList = expList.add("protocolVersion", uint64(p.version))
   291  	expList = expList.add("networkId", uint64(NetworkId))
   292  	expList = expList.add("headTd", td)
   293  	expList = expList.add("headHash", head)
   294  	expList = expList.add("headNum", headNum)
   295  	expList = expList.add("genesisHash", genesis)
   296  	sendList := make(keyValueList, len(expList))
   297  	copy(sendList, expList)
   298  	expList = expList.add("serveHeaders", nil)
   299  	expList = expList.add("serveChainSince", uint64(0))
   300  	expList = expList.add("serveStateSince", uint64(0))
   301  	expList = expList.add("txRelay", nil)
   302  	expList = expList.add("flowControl/BL", testBufLimit)
   303  	expList = expList.add("flowControl/MRR", uint64(1))
   304  	expList = expList.add("flowControl/MRC", testRCL())
   305  
   306  	if err := p2p.ExpectMsg(p.app, StatusMsg, expList); err != nil {
   307  		t.Fatalf("status recv: %v", err)
   308  	}
   309  	if err := p2p.Send(p.app, StatusMsg, sendList); err != nil {
   310  		t.Fatalf("status send: %v", err)
   311  	}
   312  
   313  	p.fcServerParams = &flowcontrol.ServerParams{
   314  		BufLimit:    testBufLimit,
   315  		MinRecharge: 1,
   316  	}
   317  }
   318  
   319  // close terminates the local side of the peer, notifying the remote protocol
   320  // manager of termination.
   321  func (p *testPeer) close() {
   322  	p.app.Close()
   323  }