handler_test.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. lock sync.RWMutex // Protects the transaction pool
  46. }
  47. // newTestTxPool creates a mock transaction pool.
  48. func newTestTxPool() *testTxPool {
  49. return &testTxPool{
  50. pool: make(map[common.Hash]*types.Transaction),
  51. }
  52. }
  53. // Has returns an indicator whether txpool has a transaction
  54. // cached with the given hash.
  55. func (p *testTxPool) Has(hash common.Hash) bool {
  56. p.lock.Lock()
  57. defer p.lock.Unlock()
  58. return p.pool[hash] != nil
  59. }
  60. // Get retrieves the transaction from local txpool with given
  61. // tx hash.
  62. func (p *testTxPool) Get(hash common.Hash) *types.Transaction {
  63. p.lock.Lock()
  64. defer p.lock.Unlock()
  65. return p.pool[hash]
  66. }
  67. // AddRemotes appends a batch of transactions to the pool, and notifies any
  68. // listeners if the addition channel is non nil
  69. func (p *testTxPool) AddRemotes(txs []*types.Transaction) []error {
  70. p.lock.Lock()
  71. defer p.lock.Unlock()
  72. for _, tx := range txs {
  73. p.pool[tx.Hash()] = tx
  74. }
  75. p.txFeed.Send(core.NewTxsEvent{Txs: txs})
  76. return make([]error, len(txs))
  77. }
  78. // Pending returns all the transactions known to the pool
  79. func (p *testTxPool) Pending() (map[common.Address]types.Transactions, error) {
  80. p.lock.RLock()
  81. defer p.lock.RUnlock()
  82. batches := make(map[common.Address]types.Transactions)
  83. for _, tx := range p.pool {
  84. from, _ := types.Sender(types.HomesteadSigner{}, tx)
  85. batches[from] = append(batches[from], tx)
  86. }
  87. for _, batch := range batches {
  88. sort.Sort(types.TxByNonce(batch))
  89. }
  90. return batches, nil
  91. }
  92. // SubscribeNewTxsEvent should return an event subscription of NewTxsEvent and
  93. // send events to the given channel.
  94. func (p *testTxPool) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
  95. return p.txFeed.Subscribe(ch)
  96. }
  97. // testHandler is a live implementation of the Ethereum protocol handler, just
  98. // preinitialized with some sane testing defaults and the transaction pool mocked
  99. // out.
  100. type testHandler struct {
  101. db ethdb.Database
  102. chain *core.BlockChain
  103. txpool *testTxPool
  104. handler *handler
  105. }
  106. // newTestHandler creates a new handler for testing purposes with no blocks.
  107. func newTestHandler() *testHandler {
  108. return newTestHandlerWithBlocks(0)
  109. }
  110. // newTestHandlerWithBlocks creates a new handler for testing purposes, with a
  111. // given number of initial blocks.
  112. func newTestHandlerWithBlocks(blocks int) *testHandler {
  113. // Create a database pre-initialize with a genesis block
  114. db := rawdb.NewMemoryDatabase()
  115. (&core.Genesis{
  116. Config: params.TestChainConfig,
  117. Alloc: core.GenesisAlloc{testAddr: {Balance: big.NewInt(1000000)}},
  118. }).MustCommit(db)
  119. chain, _ := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil, nil)
  120. bs, _ := core.GenerateChain(params.TestChainConfig, chain.Genesis(), ethash.NewFaker(), db, blocks, nil)
  121. if _, err := chain.InsertChain(bs); err != nil {
  122. panic(err)
  123. }
  124. txpool := newTestTxPool()
  125. handler, _ := newHandler(&handlerConfig{
  126. Database: db,
  127. Chain: chain,
  128. TxPool: txpool,
  129. Network: 1,
  130. Sync: downloader.FastSync,
  131. BloomCache: 1,
  132. })
  133. handler.Start(1000)
  134. return &testHandler{
  135. db: db,
  136. chain: chain,
  137. txpool: txpool,
  138. handler: handler,
  139. }
  140. }
  141. // close tears down the handler and all its internal constructs.
  142. func (b *testHandler) close() {
  143. b.handler.Stop()
  144. b.chain.Stop()
  145. }