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