handler_test.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. package eth
  17. import (
  18. "math/big"
  19. "sort"
  20. "sync"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/consensus/ethash"
  23. "github.com/ethereum/go-ethereum/core"
  24. "github.com/ethereum/go-ethereum/core/rawdb"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/core/vm"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/eth/downloader"
  29. "github.com/ethereum/go-ethereum/ethdb"
  30. "github.com/ethereum/go-ethereum/event"
  31. "github.com/ethereum/go-ethereum/params"
  32. )
  33. var (
  34. // testKey is a private key to use for funding a tester account.
  35. testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  36. // testAddr is the Ethereum address of the tester account.
  37. testAddr = crypto.PubkeyToAddress(testKey.PublicKey)
  38. )
  39. // testTxPool is a mock transaction pool that blindly accepts all transactions.
  40. // Its goal is to get around setting up a valid statedb for the balance and nonce
  41. // checks.
  42. type testTxPool struct {
  43. pool map[common.Hash]*types.Transaction // Hash map of collected transactions
  44. txFeed event.Feed // Notification feed to allow waiting for inclusion
  45. reannoTxFeed event.Feed // Notification feed to trigger reannouce
  46. lock sync.RWMutex // Protects the transaction pool
  47. }
  48. // newTestTxPool creates a mock transaction pool.
  49. func newTestTxPool() *testTxPool {
  50. return &testTxPool{
  51. pool: make(map[common.Hash]*types.Transaction),
  52. }
  53. }
  54. // Has returns an indicator whether txpool has a transaction
  55. // cached with the given hash.
  56. func (p *testTxPool) Has(hash common.Hash) bool {
  57. p.lock.Lock()
  58. defer p.lock.Unlock()
  59. return p.pool[hash] != nil
  60. }
  61. // Get retrieves the transaction from local txpool with given
  62. // tx hash.
  63. func (p *testTxPool) Get(hash common.Hash) *types.Transaction {
  64. p.lock.Lock()
  65. defer p.lock.Unlock()
  66. return p.pool[hash]
  67. }
  68. // AddRemotes appends a batch of transactions to the pool, and notifies any
  69. // listeners if the addition channel is non nil
  70. func (p *testTxPool) AddRemotes(txs []*types.Transaction) []error {
  71. p.lock.Lock()
  72. defer p.lock.Unlock()
  73. for _, tx := range txs {
  74. p.pool[tx.Hash()] = tx
  75. }
  76. p.txFeed.Send(core.NewTxsEvent{Txs: txs})
  77. return make([]error, len(txs))
  78. }
  79. // ReannouceTransactions announce the transactions to some peers.
  80. func (p *testTxPool) ReannouceTransactions(txs []*types.Transaction) []error {
  81. p.lock.Lock()
  82. defer p.lock.Unlock()
  83. for _, tx := range txs {
  84. p.pool[tx.Hash()] = tx
  85. }
  86. p.reannoTxFeed.Send(core.ReannoTxsEvent{Txs: txs})
  87. return make([]error, len(txs))
  88. }
  89. // Pending returns all the transactions known to the pool
  90. func (p *testTxPool) Pending() (map[common.Address]types.Transactions, error) {
  91. p.lock.RLock()
  92. defer p.lock.RUnlock()
  93. batches := make(map[common.Address]types.Transactions)
  94. for _, tx := range p.pool {
  95. from, _ := types.Sender(types.HomesteadSigner{}, tx)
  96. batches[from] = append(batches[from], tx)
  97. }
  98. for _, batch := range batches {
  99. sort.Sort(types.TxByNonce(batch))
  100. }
  101. return batches, nil
  102. }
  103. // SubscribeNewTxsEvent should return an event subscription of NewTxsEvent and
  104. // send events to the given channel.
  105. func (p *testTxPool) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
  106. return p.txFeed.Subscribe(ch)
  107. }
  108. // SubscribeReannoTxsEvent should return an event subscription of ReannoTxsEvent and
  109. // send events to the given channel.
  110. func (p *testTxPool) SubscribeReannoTxsEvent(ch chan<- core.ReannoTxsEvent) event.Subscription {
  111. return p.reannoTxFeed.Subscribe(ch)
  112. }
  113. // testHandler is a live implementation of the Ethereum protocol handler, just
  114. // preinitialized with some sane testing defaults and the transaction pool mocked
  115. // out.
  116. type testHandler struct {
  117. db ethdb.Database
  118. chain *core.BlockChain
  119. txpool *testTxPool
  120. handler *handler
  121. }
  122. // newTestHandler creates a new handler for testing purposes with no blocks.
  123. func newTestHandler() *testHandler {
  124. return newTestHandlerWithBlocks(0)
  125. }
  126. // newTestHandlerWithBlocks creates a new handler for testing purposes, with a
  127. // given number of initial blocks.
  128. func newTestHandlerWithBlocks(blocks int) *testHandler {
  129. // Create a database pre-initialize with a genesis block
  130. db := rawdb.NewMemoryDatabase()
  131. (&core.Genesis{
  132. Config: params.TestChainConfig,
  133. Alloc: core.GenesisAlloc{testAddr: {Balance: big.NewInt(1000000)}},
  134. }).MustCommit(db)
  135. chain, _ := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
  136. bs, _ := core.GenerateChain(params.TestChainConfig, chain.Genesis(), ethash.NewFaker(), db, blocks, nil)
  137. if _, err := chain.InsertChain(bs); err != nil {
  138. panic(err)
  139. }
  140. txpool := newTestTxPool()
  141. handler, _ := newHandler(&handlerConfig{
  142. Database: db,
  143. Chain: chain,
  144. TxPool: txpool,
  145. Network: 1,
  146. Sync: downloader.FastSync,
  147. BloomCache: 1,
  148. })
  149. handler.Start(1000)
  150. return &testHandler{
  151. db: db,
  152. chain: chain,
  153. txpool: txpool,
  154. handler: handler,
  155. }
  156. }
  157. // close tears down the handler and all its internal constructs.
  158. func (b *testHandler) close() {
  159. b.handler.Stop()
  160. b.chain.Stop()
  161. }