github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/les/helper_test.go (about)

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