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