helper_test.go 6.9 KB

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