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