github.com/reapchain/go-reapchain@v0.2.15-0.20210609012950-9735c110c705/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/ecdsa"
    24  	"crypto/rand"
    25  	"math/big"
    26  	"sync"
    27  	"testing"
    28  	"time"
    29  
    30  	"github.com/ethereum/go-ethereum/common"
    31  	"github.com/ethereum/go-ethereum/consensus/ethash"
    32  	"github.com/ethereum/go-ethereum/core"
    33  	"github.com/ethereum/go-ethereum/core/types"
    34  	"github.com/ethereum/go-ethereum/core/vm"
    35  	"github.com/ethereum/go-ethereum/crypto"
    36  	"github.com/ethereum/go-ethereum/ethdb"
    37  	"github.com/ethereum/go-ethereum/event"
    38  	"github.com/ethereum/go-ethereum/les/flowcontrol"
    39  	"github.com/ethereum/go-ethereum/light"
    40  	"github.com/ethereum/go-ethereum/p2p"
    41  	"github.com/ethereum/go-ethereum/p2p/discover"
    42  	"github.com/ethereum/go-ethereum/params"
    43  )
    44  
    45  var (
    46  	testBankKey, _  = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    47  	testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
    48  	testBankFunds   = big.NewInt(1000000)
    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  	testBufLimit = uint64(100)
    61  
    62  	bigTxGas = new(big.Int).SetUint64(params.TxGas)
    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), bigTxGas, 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  		tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), bigTxGas, nil, nil), signer, testBankKey)
    93  		nonce := block.TxNonce(acc1Addr)
    94  		tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), bigTxGas, nil, nil), signer, acc1Key)
    95  		nonce++
    96  		tx3, _ := types.SignTx(types.NewContractCreation(nonce, big.NewInt(0), big.NewInt(200000), big.NewInt(0), testContractCode), signer, acc1Key)
    97  		testContractAddr = crypto.CreateAddress(acc1Addr, nonce)
    98  		block.AddTx(tx1)
    99  		block.AddTx(tx2)
   100  		block.AddTx(tx3)
   101  	case 2:
   102  		// Block 3 is empty but was mined by account #2.
   103  		block.SetCoinbase(acc2Addr)
   104  		block.SetExtra([]byte("yeehaw"))
   105  		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001")
   106  		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), big.NewInt(100000), nil, data), signer, testBankKey)
   107  		block.AddTx(tx)
   108  	case 3:
   109  		// Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
   110  		b2 := block.PrevBlock(1).Header()
   111  		b2.Extra = []byte("foo")
   112  		block.AddUncle(b2)
   113  		b3 := block.PrevBlock(2).Header()
   114  		b3.Extra = []byte("foo")
   115  		block.AddUncle(b3)
   116  		data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002")
   117  		tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), big.NewInt(100000), nil, data), signer, testBankKey)
   118  		block.AddTx(tx)
   119  	}
   120  }
   121  
   122  func testRCL() RequestCostList {
   123  	cl := make(RequestCostList, len(reqList))
   124  	for i, code := range reqList {
   125  		cl[i].MsgCode = code
   126  		cl[i].BaseCost = 0
   127  		cl[i].ReqCost = 0
   128  	}
   129  	return cl
   130  }
   131  
   132  // newTestProtocolManager creates a new protocol manager for testing purposes,
   133  // with the given number of blocks already known, and potential notification
   134  // channels for different events.
   135  func newTestProtocolManager(lightSync bool, blocks int, generator func(int, *core.BlockGen)) (*ProtocolManager, ethdb.Database, *LesOdr, error) {
   136  	var (
   137  		evmux  = new(event.TypeMux)
   138  		engine = ethash.NewFaker()
   139  		db, _  = ethdb.NewMemDatabase()
   140  		gspec  = core.Genesis{
   141  			Config: params.TestChainConfig,
   142  			Alloc:  core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
   143  		}
   144  		genesis = gspec.MustCommit(db)
   145  		odr     *LesOdr
   146  		chain   BlockChain
   147  	)
   148  
   149  	if lightSync {
   150  		odr = NewLesOdr(db)
   151  		chain, _ = light.NewLightChain(odr, gspec.Config, engine, evmux)
   152  	} else {
   153  		blockchain, _ := core.NewBlockChain(db, gspec.Config, engine, evmux, vm.Config{})
   154  		gchain, _ := core.GenerateChain(gspec.Config, genesis, db, blocks, generator)
   155  		if _, err := blockchain.InsertChain(gchain); err != nil {
   156  			panic(err)
   157  		}
   158  		chain = blockchain
   159  	}
   160  
   161  	pm, err := NewProtocolManager(gspec.Config, lightSync, NetworkId, evmux, engine, chain, nil, db, odr, nil)
   162  	if err != nil {
   163  		return nil, nil, nil, err
   164  	}
   165  	if !lightSync {
   166  		srv := &LesServer{protocolManager: pm}
   167  		pm.server = srv
   168  
   169  		srv.defParams = &flowcontrol.ServerParams{
   170  			BufLimit:    testBufLimit,
   171  			MinRecharge: 1,
   172  		}
   173  
   174  		srv.fcManager = flowcontrol.NewClientManager(50, 10, 1000000000)
   175  		srv.fcCostStats = newCostStats(nil)
   176  	}
   177  	pm.Start(nil)
   178  	return pm, db, odr, nil
   179  }
   180  
   181  // newTestProtocolManagerMust creates a new protocol manager for testing purposes,
   182  // with the given number of blocks already known, and potential notification
   183  // channels for different events. In case of an error, the constructor force-
   184  // fails the test.
   185  func newTestProtocolManagerMust(t *testing.T, lightSync bool, blocks int, generator func(int, *core.BlockGen)) (*ProtocolManager, ethdb.Database, *LesOdr) {
   186  	pm, db, odr, err := newTestProtocolManager(lightSync, blocks, generator)
   187  	if err != nil {
   188  		t.Fatalf("Failed to create protocol manager: %v", err)
   189  	}
   190  	return pm, db, odr
   191  }
   192  
   193  // testTxPool is a fake, helper transaction pool for testing purposes
   194  type testTxPool struct {
   195  	pool  []*types.Transaction        // Collection of all transactions
   196  	added chan<- []*types.Transaction // Notification channel for new transactions
   197  
   198  	lock sync.RWMutex // Protects the transaction pool
   199  }
   200  
   201  // AddTransactions appends a batch of transactions to the pool, and notifies any
   202  // listeners if the addition channel is non nil
   203  func (p *testTxPool) AddBatch(txs []*types.Transaction) {
   204  	p.lock.Lock()
   205  	defer p.lock.Unlock()
   206  
   207  	p.pool = append(p.pool, txs...)
   208  	if p.added != nil {
   209  		p.added <- txs
   210  	}
   211  }
   212  
   213  // GetTransactions returns all the transactions known to the pool
   214  func (p *testTxPool) GetTransactions() types.Transactions {
   215  	p.lock.RLock()
   216  	defer p.lock.RUnlock()
   217  
   218  	txs := make([]*types.Transaction, len(p.pool))
   219  	copy(txs, p.pool)
   220  
   221  	return txs
   222  }
   223  
   224  // newTestTransaction create a new dummy transaction.
   225  func newTestTransaction(from *ecdsa.PrivateKey, nonce uint64, datasize int) *types.Transaction {
   226  	tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize))
   227  	tx, _ = types.SignTx(tx, types.HomesteadSigner{}, from)
   228  
   229  	return tx
   230  }
   231  
   232  // testPeer is a simulated peer to allow testing direct network calls.
   233  type testPeer struct {
   234  	net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
   235  	app *p2p.MsgPipeRW    // Application layer reader/writer to simulate the local side
   236  	*peer
   237  }
   238  
   239  // newTestPeer creates a new peer registered at the given protocol manager.
   240  func newTestPeer(t *testing.T, name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) {
   241  	// Create a message pipe to communicate through
   242  	app, net := p2p.MsgPipe()
   243  
   244  	// Generate a random id and create the peer
   245  	var id discover.NodeID
   246  	rand.Read(id[:])
   247  
   248  	peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
   249  
   250  	// Start the peer on a new thread
   251  	errc := make(chan error, 1)
   252  	go func() {
   253  		select {
   254  		case pm.newPeerCh <- peer:
   255  			errc <- pm.handle(peer)
   256  		case <-pm.quitSync:
   257  			errc <- p2p.DiscQuitting
   258  		}
   259  	}()
   260  	tp := &testPeer{
   261  		app:  app,
   262  		net:  net,
   263  		peer: peer,
   264  	}
   265  	// Execute any implicitly requested handshakes and return
   266  	if shake {
   267  		td, head, genesis := pm.blockchain.Status()
   268  		headNum := pm.blockchain.CurrentHeader().Number.Uint64()
   269  		tp.handshake(t, td, head, headNum, genesis)
   270  	}
   271  	return tp, errc
   272  }
   273  
   274  func newTestPeerPair(name string, version int, pm, pm2 *ProtocolManager) (*peer, <-chan error, *peer, <-chan error) {
   275  	// Create a message pipe to communicate through
   276  	app, net := p2p.MsgPipe()
   277  
   278  	// Generate a random id and create the peer
   279  	var id discover.NodeID
   280  	rand.Read(id[:])
   281  
   282  	peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
   283  	peer2 := pm2.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), app)
   284  
   285  	// Start the peer on a new thread
   286  	errc := make(chan error, 1)
   287  	errc2 := make(chan error, 1)
   288  	go func() {
   289  		select {
   290  		case pm.newPeerCh <- peer:
   291  			errc <- pm.handle(peer)
   292  		case <-pm.quitSync:
   293  			errc <- p2p.DiscQuitting
   294  		}
   295  	}()
   296  	go func() {
   297  		select {
   298  		case pm2.newPeerCh <- peer2:
   299  			errc2 <- pm2.handle(peer2)
   300  		case <-pm2.quitSync:
   301  			errc2 <- p2p.DiscQuitting
   302  		}
   303  	}()
   304  	return peer, errc, peer2, errc2
   305  }
   306  
   307  // handshake simulates a trivial handshake that expects the same state from the
   308  // remote side as we are simulating locally.
   309  func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash) {
   310  	var expList keyValueList
   311  	expList = expList.add("protocolVersion", uint64(p.version))
   312  	expList = expList.add("networkId", uint64(NetworkId))
   313  	expList = expList.add("headTd", td)
   314  	expList = expList.add("headHash", head)
   315  	expList = expList.add("headNum", headNum)
   316  	expList = expList.add("genesisHash", genesis)
   317  	sendList := make(keyValueList, len(expList))
   318  	copy(sendList, expList)
   319  	expList = expList.add("serveHeaders", nil)
   320  	expList = expList.add("serveChainSince", uint64(0))
   321  	expList = expList.add("serveStateSince", uint64(0))
   322  	expList = expList.add("txRelay", nil)
   323  	expList = expList.add("flowControl/BL", testBufLimit)
   324  	expList = expList.add("flowControl/MRR", uint64(1))
   325  	expList = expList.add("flowControl/MRC", testRCL())
   326  
   327  	if err := p2p.ExpectMsg(p.app, StatusMsg, expList); err != nil {
   328  		t.Fatalf("status recv: %v", err)
   329  	}
   330  	if err := p2p.Send(p.app, StatusMsg, sendList); err != nil {
   331  		t.Fatalf("status send: %v", err)
   332  	}
   333  
   334  	p.fcServerParams = &flowcontrol.ServerParams{
   335  		BufLimit:    testBufLimit,
   336  		MinRecharge: 1,
   337  	}
   338  }
   339  
   340  // close terminates the local side of the peer, notifying the remote protocol
   341  // manager of termination.
   342  func (p *testPeer) close() {
   343  	p.app.Close()
   344  }
   345  
   346  type testServerPool struct {
   347  	peer *peer
   348  	lock sync.RWMutex
   349  }
   350  
   351  func (p *testServerPool) setPeer(peer *peer) {
   352  	p.lock.Lock()
   353  	defer p.lock.Unlock()
   354  
   355  	p.peer = peer
   356  }
   357  
   358  func (p *testServerPool) getAllPeers() map[distPeer]struct{} {
   359  	p.lock.RLock()
   360  	defer p.lock.RUnlock()
   361  
   362  	m := make(map[distPeer]struct{})
   363  	if p.peer != nil {
   364  		m[p.peer] = struct{}{}
   365  	}
   366  	return m
   367  }
   368  
   369  func (p *testServerPool) adjustResponseTime(*poolEntry, time.Duration, bool) {
   370  
   371  }