helper_test.go 7.9 KB

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