handler_diff_test.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. "crypto/rand"
  19. "math/big"
  20. "testing"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/consensus/ethash"
  24. "github.com/ethereum/go-ethereum/core"
  25. "github.com/ethereum/go-ethereum/core/rawdb"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/core/vm"
  28. "github.com/ethereum/go-ethereum/eth/downloader"
  29. "github.com/ethereum/go-ethereum/eth/protocols/diff"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/p2p"
  32. "github.com/ethereum/go-ethereum/p2p/enode"
  33. "github.com/ethereum/go-ethereum/params"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. )
  36. // testBackend is a mock implementation of the live Ethereum message handler. Its
  37. // purpose is to allow testing the request/reply workflows and wire serialization
  38. // in the `eth` protocol without actually doing any data processing.
  39. type testBackend struct {
  40. db ethdb.Database
  41. chain *core.BlockChain
  42. txpool *core.TxPool
  43. handler *handler
  44. }
  45. // newTestBackend creates an empty chain and wraps it into a mock backend.
  46. func newTestBackend(blocks int) *testBackend {
  47. return newTestBackendWithGenerator(blocks)
  48. }
  49. // newTestBackend creates a chain with a number of explicitly defined blocks and
  50. // wraps it into a mock backend.
  51. func newTestBackendWithGenerator(blocks int) *testBackend {
  52. signer := types.HomesteadSigner{}
  53. // Create a database pre-initialize with a genesis block
  54. db := rawdb.NewMemoryDatabase()
  55. (&core.Genesis{
  56. Config: params.TestChainConfig,
  57. Alloc: core.GenesisAlloc{testAddr: {Balance: big.NewInt(100000000000000000)}},
  58. }).MustCommit(db)
  59. chain, _ := core.NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
  60. generator := func(i int, block *core.BlockGen) {
  61. // The chain maker doesn't have access to a chain, so the difficulty will be
  62. // lets unset (nil). Set it here to the correct value.
  63. block.SetCoinbase(testAddr)
  64. // We want to simulate an empty middle block, having the same state as the
  65. // first one. The last is needs a state change again to force a reorg.
  66. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddr), common.Address{0x01}, big.NewInt(1), params.TxGas, big.NewInt(1), nil), signer, testKey)
  67. if err != nil {
  68. panic(err)
  69. }
  70. block.AddTxWithChain(chain, tx)
  71. }
  72. bs, _ := core.GenerateChain(params.TestChainConfig, chain.Genesis(), ethash.NewFaker(), db, blocks, generator)
  73. if _, err := chain.InsertChain(bs); err != nil {
  74. panic(err)
  75. }
  76. txpool := newTestTxPool()
  77. handler, _ := newHandler(&handlerConfig{
  78. Database: db,
  79. Chain: chain,
  80. TxPool: txpool,
  81. Network: 1,
  82. Sync: downloader.FullSync,
  83. BloomCache: 1,
  84. })
  85. handler.Start(100)
  86. txconfig := core.DefaultTxPoolConfig
  87. txconfig.Journal = "" // Don't litter the disk with test journals
  88. return &testBackend{
  89. db: db,
  90. chain: chain,
  91. txpool: core.NewTxPool(txconfig, params.TestChainConfig, chain),
  92. handler: handler,
  93. }
  94. }
  95. // close tears down the transaction pool and chain behind the mock backend.
  96. func (b *testBackend) close() {
  97. b.txpool.Stop()
  98. b.chain.Stop()
  99. b.handler.Stop()
  100. }
  101. func (b *testBackend) Chain() *core.BlockChain { return b.chain }
  102. func (b *testBackend) RunPeer(peer *diff.Peer, handler diff.Handler) error {
  103. // Normally the backend would do peer mainentance and handshakes. All that
  104. // is omitted and we will just give control back to the handler.
  105. return handler(peer)
  106. }
  107. func (b *testBackend) PeerInfo(enode.ID) interface{} { panic("not implemented") }
  108. func (b *testBackend) Handle(*diff.Peer, diff.Packet) error {
  109. panic("data processing tests should be done in the handler package")
  110. }
  111. type testPeer struct {
  112. *diff.Peer
  113. net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
  114. app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side
  115. }
  116. // newTestPeer creates a new peer registered at the given data backend.
  117. func newTestPeer(name string, version uint, backend *testBackend) (*testPeer, <-chan error) {
  118. // Create a message pipe to communicate through
  119. app, net := p2p.MsgPipe()
  120. // Start the peer on a new thread
  121. var id enode.ID
  122. rand.Read(id[:])
  123. peer := diff.NewPeer(version, p2p.NewPeer(id, name, nil), net)
  124. errc := make(chan error, 1)
  125. go func() {
  126. errc <- backend.RunPeer(peer, func(peer *diff.Peer) error {
  127. return diff.Handle((*diffHandler)(backend.handler), peer)
  128. })
  129. }()
  130. return &testPeer{app: app, net: net, Peer: peer}, errc
  131. }
  132. // close terminates the local side of the peer, notifying the remote protocol
  133. // manager of termination.
  134. func (p *testPeer) close() {
  135. p.Peer.Close()
  136. p.app.Close()
  137. }
  138. func TestHandleDiffLayer(t *testing.T) {
  139. t.Parallel()
  140. blockNum := 1024
  141. waitInterval := 100 * time.Millisecond
  142. backend := newTestBackend(blockNum)
  143. defer backend.close()
  144. peer, _ := newTestPeer("peer", diff.Diff1, backend)
  145. defer peer.close()
  146. tests := []struct {
  147. DiffLayer *types.DiffLayer
  148. Valid bool
  149. }{
  150. {DiffLayer: &types.DiffLayer{
  151. BlockHash: common.Hash{0x1},
  152. Number: 1025,
  153. }, Valid: true},
  154. {DiffLayer: &types.DiffLayer{
  155. BlockHash: common.Hash{0x2},
  156. Number: 3073,
  157. }, Valid: false},
  158. {DiffLayer: &types.DiffLayer{
  159. BlockHash: common.Hash{0x3},
  160. Number: 500,
  161. }, Valid: false},
  162. }
  163. for _, tt := range tests {
  164. bz, _ := rlp.EncodeToBytes(tt.DiffLayer)
  165. p2p.Send(peer.app, diff.DiffLayerMsg, diff.DiffLayersPacket{rlp.RawValue(bz)})
  166. }
  167. time.Sleep(waitInterval)
  168. for idx, tt := range tests {
  169. diff := backend.chain.GetUnTrustedDiffLayer(tt.DiffLayer.BlockHash, "")
  170. if (tt.Valid && diff == nil) || (!tt.Valid && diff != nil) {
  171. t.Errorf("test: %d, diff layer handle failed", idx)
  172. }
  173. }
  174. }