helper_test.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. // This file contains some shares testing functionality, common to multiple
  2. // different files and modules being tested.
  3. package eth
  4. import (
  5. "crypto/rand"
  6. "math/big"
  7. "sync"
  8. "testing"
  9. "github.com/ethereum/go-ethereum/common"
  10. "github.com/ethereum/go-ethereum/core"
  11. "github.com/ethereum/go-ethereum/core/types"
  12. "github.com/ethereum/go-ethereum/crypto"
  13. "github.com/ethereum/go-ethereum/ethdb"
  14. "github.com/ethereum/go-ethereum/event"
  15. "github.com/ethereum/go-ethereum/p2p"
  16. "github.com/ethereum/go-ethereum/p2p/discover"
  17. )
  18. var (
  19. testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  20. testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
  21. testBankFunds = big.NewInt(1000000)
  22. )
  23. // newTestProtocolManager creates a new protocol manager for testing purposes,
  24. // with the given number of blocks already known, and potential notification
  25. // channels for different events.
  26. func newTestProtocolManager(fastSync bool, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) (*ProtocolManager, error) {
  27. var (
  28. evmux = new(event.TypeMux)
  29. pow = new(core.FakePow)
  30. db, _ = ethdb.NewMemDatabase()
  31. genesis = core.WriteGenesisBlockForTesting(db, core.GenesisAccount{testBankAddress, testBankFunds})
  32. blockchain, _ = core.NewBlockChain(db, pow, evmux)
  33. blockproc = core.NewBlockProcessor(db, pow, blockchain, evmux)
  34. )
  35. blockchain.SetProcessor(blockproc)
  36. chain, _ := core.GenerateChain(genesis, db, blocks, generator)
  37. if _, err := blockchain.InsertChain(chain); err != nil {
  38. panic(err)
  39. }
  40. pm, err := NewProtocolManager(fastSync, NetworkId, evmux, &testTxPool{added: newtx}, pow, blockchain, db)
  41. if err != nil {
  42. return nil, err
  43. }
  44. pm.Start()
  45. return pm, nil
  46. }
  47. // newTestProtocolManagerMust creates a new protocol manager for testing purposes,
  48. // with the given number of blocks already known, and potential notification
  49. // channels for different events. In case of an error, the constructor force-
  50. // fails the test.
  51. func newTestProtocolManagerMust(t *testing.T, fastSync bool, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) *ProtocolManager {
  52. pm, err := newTestProtocolManager(fastSync, blocks, generator, newtx)
  53. if err != nil {
  54. t.Fatalf("Failed to create protocol manager: %v", err)
  55. }
  56. return pm
  57. }
  58. // testTxPool is a fake, helper transaction pool for testing purposes
  59. type testTxPool struct {
  60. pool []*types.Transaction // Collection of all transactions
  61. added chan<- []*types.Transaction // Notification channel for new transactions
  62. lock sync.RWMutex // Protects the transaction pool
  63. }
  64. // AddTransactions appends a batch of transactions to the pool, and notifies any
  65. // listeners if the addition channel is non nil
  66. func (p *testTxPool) AddTransactions(txs []*types.Transaction) {
  67. p.lock.Lock()
  68. defer p.lock.Unlock()
  69. p.pool = append(p.pool, txs...)
  70. if p.added != nil {
  71. p.added <- txs
  72. }
  73. }
  74. // GetTransactions returns all the transactions known to the pool
  75. func (p *testTxPool) GetTransactions() types.Transactions {
  76. p.lock.RLock()
  77. defer p.lock.RUnlock()
  78. txs := make([]*types.Transaction, len(p.pool))
  79. copy(txs, p.pool)
  80. return txs
  81. }
  82. // newTestTransaction create a new dummy transaction.
  83. func newTestTransaction(from *crypto.Key, nonce uint64, datasize int) *types.Transaction {
  84. tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize))
  85. tx, _ = tx.SignECDSA(from.PrivateKey)
  86. return tx
  87. }
  88. // testPeer is a simulated peer to allow testing direct network calls.
  89. type testPeer struct {
  90. net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
  91. app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side
  92. *peer
  93. }
  94. // newTestPeer creates a new peer registered at the given protocol manager.
  95. func newTestPeer(name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) {
  96. // Create a message pipe to communicate through
  97. app, net := p2p.MsgPipe()
  98. // Generate a random id and create the peer
  99. var id discover.NodeID
  100. rand.Read(id[:])
  101. peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
  102. // Start the peer on a new thread
  103. errc := make(chan error, 1)
  104. go func() {
  105. pm.newPeerCh <- peer
  106. errc <- pm.handle(peer)
  107. }()
  108. tp := &testPeer{
  109. app: app,
  110. net: net,
  111. peer: peer,
  112. }
  113. // Execute any implicitly requested handshakes and return
  114. if shake {
  115. td, head, genesis := pm.blockchain.Status()
  116. tp.handshake(nil, td, head, genesis)
  117. }
  118. return tp, errc
  119. }
  120. // handshake simulates a trivial handshake that expects the same state from the
  121. // remote side as we are simulating locally.
  122. func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, genesis common.Hash) {
  123. msg := &statusData{
  124. ProtocolVersion: uint32(p.version),
  125. NetworkId: uint32(NetworkId),
  126. TD: td,
  127. CurrentBlock: head,
  128. GenesisBlock: genesis,
  129. }
  130. if err := p2p.ExpectMsg(p.app, StatusMsg, msg); err != nil {
  131. t.Fatalf("status recv: %v", err)
  132. }
  133. if err := p2p.Send(p.app, StatusMsg, msg); err != nil {
  134. t.Fatalf("status send: %v", err)
  135. }
  136. }
  137. // close terminates the local side of the peer, notifying the remote protocol
  138. // manager of termination.
  139. func (p *testPeer) close() {
  140. p.app.Close()
  141. }