helper_test.go 6.0 KB

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