helper_test.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. // This file contains some shares testing functionality, common to multiple
  2. // different files and modules being tested.
  3. package eth
  4. import (
  5. "crypto/rand"
  6. "math/big"
  7. "sync"
  8. "testing"
  9. "github.com/ethereum/go-ethereum/common"
  10. "github.com/ethereum/go-ethereum/core"
  11. "github.com/ethereum/go-ethereum/core/types"
  12. "github.com/ethereum/go-ethereum/crypto"
  13. "github.com/ethereum/go-ethereum/ethdb"
  14. "github.com/ethereum/go-ethereum/event"
  15. "github.com/ethereum/go-ethereum/p2p"
  16. "github.com/ethereum/go-ethereum/p2p/discover"
  17. )
  18. var (
  19. testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  20. testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
  21. testBankFunds = big.NewInt(1000000)
  22. )
  23. // newTestProtocolManager creates a new protocol manager for testing purposes,
  24. // with the given number of blocks already known, and potential notification
  25. // channels for different events.
  26. func newTestProtocolManager(blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) *ProtocolManager {
  27. var (
  28. evmux = new(event.TypeMux)
  29. pow = new(core.FakePow)
  30. db, _ = ethdb.NewMemDatabase()
  31. genesis = core.WriteGenesisBlockForTesting(db, core.GenesisAccount{testBankAddress, testBankFunds})
  32. chainman, _ = core.NewChainManager(db, pow, evmux)
  33. blockproc = core.NewBlockProcessor(db, pow, chainman, evmux)
  34. )
  35. chainman.SetProcessor(blockproc)
  36. if _, err := chainman.InsertChain(core.GenerateChain(genesis, db, blocks, generator)); err != nil {
  37. panic(err)
  38. }
  39. pm := NewProtocolManager(NetworkId, evmux, &testTxPool{added: newtx}, pow, chainman, db)
  40. pm.Start()
  41. return pm
  42. }
  43. // testTxPool is a fake, helper transaction pool for testing purposes
  44. type testTxPool struct {
  45. pool []*types.Transaction // Collection of all transactions
  46. added chan<- []*types.Transaction // Notification channel for new transactions
  47. lock sync.RWMutex // Protects the transaction pool
  48. }
  49. // AddTransactions appends a batch of transactions to the pool, and notifies any
  50. // listeners if the addition channel is non nil
  51. func (p *testTxPool) AddTransactions(txs []*types.Transaction) {
  52. p.lock.Lock()
  53. defer p.lock.Unlock()
  54. p.pool = append(p.pool, txs...)
  55. if p.added != nil {
  56. p.added <- txs
  57. }
  58. }
  59. // GetTransactions returns all the transactions known to the pool
  60. func (p *testTxPool) GetTransactions() types.Transactions {
  61. p.lock.RLock()
  62. defer p.lock.RUnlock()
  63. txs := make([]*types.Transaction, len(p.pool))
  64. copy(txs, p.pool)
  65. return txs
  66. }
  67. // newTestTransaction create a new dummy transaction.
  68. func newTestTransaction(from *crypto.Key, nonce uint64, datasize int) *types.Transaction {
  69. tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize))
  70. tx, _ = tx.SignECDSA(from.PrivateKey)
  71. return tx
  72. }
  73. // testPeer is a simulated peer to allow testing direct network calls.
  74. type testPeer struct {
  75. net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
  76. app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side
  77. *peer
  78. }
  79. // newTestPeer creates a new peer registered at the given protocol manager.
  80. func newTestPeer(name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) {
  81. // Create a message pipe to communicate through
  82. app, net := p2p.MsgPipe()
  83. // Generate a random id and create the peer
  84. var id discover.NodeID
  85. rand.Read(id[:])
  86. peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
  87. // Start the peer on a new thread
  88. errc := make(chan error, 1)
  89. go func() {
  90. pm.newPeerCh <- peer
  91. errc <- pm.handle(peer)
  92. }()
  93. tp := &testPeer{
  94. app: app,
  95. net: net,
  96. peer: peer,
  97. }
  98. // Execute any implicitly requested handshakes and return
  99. if shake {
  100. td, head, genesis := pm.chainman.Status()
  101. tp.handshake(nil, td, head, genesis)
  102. }
  103. return tp, errc
  104. }
  105. // handshake simulates a trivial handshake that expects the same state from the
  106. // remote side as we are simulating locally.
  107. func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, genesis common.Hash) {
  108. msg := &statusData{
  109. ProtocolVersion: uint32(p.version),
  110. NetworkId: uint32(NetworkId),
  111. TD: td,
  112. CurrentBlock: head,
  113. GenesisBlock: genesis,
  114. }
  115. if err := p2p.ExpectMsg(p.app, StatusMsg, msg); err != nil {
  116. t.Fatalf("status recv: %v", err)
  117. }
  118. if err := p2p.Send(p.app, StatusMsg, msg); err != nil {
  119. t.Fatalf("status send: %v", err)
  120. }
  121. }
  122. // close terminates the local side of the peer, notifying the remote protocol
  123. // manager of termination.
  124. func (p *testPeer) close() {
  125. p.app.Close()
  126. }