github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/eth/helper_test.go (about)

     1  // Copyright 2015 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 eth
    21  
    22  import (
    23  	"crypto/ecdsa"
    24  	"crypto/rand"
    25  	"fmt"
    26  	"math/big"
    27  	"sort"
    28  	"sync"
    29  	"testing"
    30  
    31  	"github.com/zhiqiangxu/go-ethereum/common"
    32  	"github.com/zhiqiangxu/go-ethereum/consensus/ethash"
    33  	"github.com/zhiqiangxu/go-ethereum/core"
    34  	"github.com/zhiqiangxu/go-ethereum/core/forkid"
    35  	"github.com/zhiqiangxu/go-ethereum/core/rawdb"
    36  	"github.com/zhiqiangxu/go-ethereum/core/types"
    37  	"github.com/zhiqiangxu/go-ethereum/core/vm"
    38  	"github.com/zhiqiangxu/go-ethereum/crypto"
    39  	"github.com/zhiqiangxu/go-ethereum/eth/downloader"
    40  	"github.com/zhiqiangxu/go-ethereum/ethdb"
    41  	"github.com/zhiqiangxu/go-ethereum/event"
    42  	"github.com/zhiqiangxu/go-ethereum/p2p"
    43  	"github.com/zhiqiangxu/go-ethereum/p2p/enode"
    44  	"github.com/zhiqiangxu/go-ethereum/params"
    45  )
    46  
    47  var (
    48  	testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    49  	testBank       = crypto.PubkeyToAddress(testBankKey.PublicKey)
    50  )
    51  
    52  // newTestProtocolManager creates a new protocol manager for testing purposes,
    53  // with the given number of blocks already known, and potential notification
    54  // channels for different events.
    55  func newTestProtocolManager(mode downloader.SyncMode, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) (*ProtocolManager, ethdb.Database, error) {
    56  	var (
    57  		evmux  = new(event.TypeMux)
    58  		engine = ethash.NewFaker()
    59  		db     = rawdb.NewMemoryDatabase()
    60  		gspec  = &core.Genesis{
    61  			Config: params.TestChainConfig,
    62  			Alloc:  core.GenesisAlloc{testBank: {Balance: big.NewInt(1000000)}},
    63  		}
    64  		genesis       = gspec.MustCommit(db)
    65  		blockchain, _ = core.NewBlockChain(db, nil, gspec.Config, engine, vm.Config{}, nil, nil)
    66  	)
    67  	chain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, blocks, generator)
    68  	if _, err := blockchain.InsertChain(chain); err != nil {
    69  		panic(err)
    70  	}
    71  	pm, err := NewProtocolManager(gspec.Config, nil, mode, DefaultConfig.NetworkId, evmux, &testTxPool{added: newtx, pool: make(map[common.Hash]*types.Transaction)}, engine, blockchain, db, 1, nil)
    72  	if err != nil {
    73  		return nil, nil, err
    74  	}
    75  	pm.Start(1000)
    76  	return pm, db, nil
    77  }
    78  
    79  // newTestProtocolManagerMust creates a new protocol manager for testing purposes,
    80  // with the given number of blocks already known, and potential notification
    81  // channels for different events. In case of an error, the constructor force-
    82  // fails the test.
    83  func newTestProtocolManagerMust(t *testing.T, mode downloader.SyncMode, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) (*ProtocolManager, ethdb.Database) {
    84  	pm, db, err := newTestProtocolManager(mode, blocks, generator, newtx)
    85  	if err != nil {
    86  		t.Fatalf("Failed to create protocol manager: %v", err)
    87  	}
    88  	return pm, db
    89  }
    90  
    91  // testTxPool is a fake, helper transaction pool for testing purposes
    92  type testTxPool struct {
    93  	txFeed event.Feed
    94  	pool   map[common.Hash]*types.Transaction // Hash map of collected transactions
    95  	added  chan<- []*types.Transaction        // Notification channel for new transactions
    96  
    97  	lock sync.RWMutex // Protects the transaction pool
    98  }
    99  
   100  // Has returns an indicator whether txpool has a transaction
   101  // cached with the given hash.
   102  func (p *testTxPool) Has(hash common.Hash) bool {
   103  	p.lock.Lock()
   104  	defer p.lock.Unlock()
   105  
   106  	return p.pool[hash] != nil
   107  }
   108  
   109  // Get retrieves the transaction from local txpool with given
   110  // tx hash.
   111  func (p *testTxPool) Get(hash common.Hash) *types.Transaction {
   112  	p.lock.Lock()
   113  	defer p.lock.Unlock()
   114  
   115  	return p.pool[hash]
   116  }
   117  
   118  // AddRemotes appends a batch of transactions to the pool, and notifies any
   119  // listeners if the addition channel is non nil
   120  func (p *testTxPool) AddRemotes(txs []*types.Transaction) []error {
   121  	p.lock.Lock()
   122  	defer p.lock.Unlock()
   123  
   124  	for _, tx := range txs {
   125  		p.pool[tx.Hash()] = tx
   126  	}
   127  	if p.added != nil {
   128  		p.added <- txs
   129  	}
   130  	p.txFeed.Send(core.NewTxsEvent{Txs: txs})
   131  	return make([]error, len(txs))
   132  }
   133  
   134  // Pending returns all the transactions known to the pool
   135  func (p *testTxPool) Pending() (map[common.Address]types.Transactions, error) {
   136  	p.lock.RLock()
   137  	defer p.lock.RUnlock()
   138  
   139  	batches := make(map[common.Address]types.Transactions)
   140  	for _, tx := range p.pool {
   141  		from, _ := types.Sender(types.HomesteadSigner{}, tx)
   142  		batches[from] = append(batches[from], tx)
   143  	}
   144  	for _, batch := range batches {
   145  		sort.Sort(types.TxByNonce(batch))
   146  	}
   147  	return batches, nil
   148  }
   149  
   150  func (p *testTxPool) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
   151  	return p.txFeed.Subscribe(ch)
   152  }
   153  
   154  // newTestTransaction create a new dummy transaction.
   155  func newTestTransaction(from *ecdsa.PrivateKey, nonce uint64, datasize int) *types.Transaction {
   156  	tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), 100000, big.NewInt(0), make([]byte, datasize))
   157  	tx, _ = types.SignTx(tx, types.HomesteadSigner{}, from)
   158  	return tx
   159  }
   160  
   161  // testPeer is a simulated peer to allow testing direct network calls.
   162  type testPeer struct {
   163  	net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
   164  	app *p2p.MsgPipeRW    // Application layer reader/writer to simulate the local side
   165  	*peer
   166  }
   167  
   168  // newTestPeer creates a new peer registered at the given protocol manager.
   169  func newTestPeer(name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) {
   170  	// Create a message pipe to communicate through
   171  	app, net := p2p.MsgPipe()
   172  
   173  	// Start the peer on a new thread
   174  	var id enode.ID
   175  	rand.Read(id[:])
   176  	peer := pm.newPeer(version, p2p.NewPeer(id, name, nil), net, pm.txpool.Get)
   177  	errc := make(chan error, 1)
   178  	go func() { errc <- pm.runPeer(peer) }()
   179  	tp := &testPeer{app: app, net: net, peer: peer}
   180  
   181  	// Execute any implicitly requested handshakes and return
   182  	if shake {
   183  		var (
   184  			genesis = pm.blockchain.Genesis()
   185  			head    = pm.blockchain.CurrentHeader()
   186  			td      = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64())
   187  		)
   188  		tp.handshake(nil, td, head.Hash(), genesis.Hash(), forkid.NewID(pm.blockchain), forkid.NewFilter(pm.blockchain))
   189  	}
   190  	return tp, errc
   191  }
   192  
   193  // handshake simulates a trivial handshake that expects the same state from the
   194  // remote side as we are simulating locally.
   195  func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, genesis common.Hash, forkID forkid.ID, forkFilter forkid.Filter) {
   196  	var msg interface{}
   197  	switch {
   198  	case p.version == eth63:
   199  		msg = &statusData63{
   200  			ProtocolVersion: uint32(p.version),
   201  			NetworkId:       DefaultConfig.NetworkId,
   202  			TD:              td,
   203  			CurrentBlock:    head,
   204  			GenesisBlock:    genesis,
   205  		}
   206  	case p.version >= eth64:
   207  		msg = &statusData{
   208  			ProtocolVersion: uint32(p.version),
   209  			NetworkID:       DefaultConfig.NetworkId,
   210  			TD:              td,
   211  			Head:            head,
   212  			Genesis:         genesis,
   213  			ForkID:          forkID,
   214  		}
   215  	default:
   216  		panic(fmt.Sprintf("unsupported eth protocol version: %d", p.version))
   217  	}
   218  	if err := p2p.ExpectMsg(p.app, StatusMsg, msg); err != nil {
   219  		t.Fatalf("status recv: %v", err)
   220  	}
   221  	if err := p2p.Send(p.app, StatusMsg, msg); err != nil {
   222  		t.Fatalf("status send: %v", err)
   223  	}
   224  }
   225  
   226  // close terminates the local side of the peer, notifying the remote protocol
   227  // manager of termination.
   228  func (p *testPeer) close() {
   229  	p.app.Close()
   230  }