helper_test.go 6.1 KB

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