helper_test.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. blockchain, _ = core.NewBlockChain(db, pow, evmux)
  33. blockproc = core.NewBlockProcessor(db, pow, blockchain, evmux)
  34. )
  35. blockchain.SetProcessor(blockproc)
  36. chain := core.GenerateChain(genesis, db, blocks, generator)
  37. if _, err := blockchain.InsertChain(chain); err != nil {
  38. panic(err)
  39. }
  40. pm := NewProtocolManager(NetworkId, evmux, &testTxPool{added: newtx}, pow, blockchain, db)
  41. pm.Start()
  42. return pm
  43. }
  44. // testTxPool is a fake, helper transaction pool for testing purposes
  45. type testTxPool struct {
  46. pool []*types.Transaction // Collection of all transactions
  47. added chan<- []*types.Transaction // Notification channel for new transactions
  48. lock sync.RWMutex // Protects the transaction pool
  49. }
  50. // AddTransactions appends a batch of transactions to the pool, and notifies any
  51. // listeners if the addition channel is non nil
  52. func (p *testTxPool) AddTransactions(txs []*types.Transaction) {
  53. p.lock.Lock()
  54. defer p.lock.Unlock()
  55. p.pool = append(p.pool, txs...)
  56. if p.added != nil {
  57. p.added <- txs
  58. }
  59. }
  60. // GetTransactions returns all the transactions known to the pool
  61. func (p *testTxPool) GetTransactions() types.Transactions {
  62. p.lock.RLock()
  63. defer p.lock.RUnlock()
  64. txs := make([]*types.Transaction, len(p.pool))
  65. copy(txs, p.pool)
  66. return txs
  67. }
  68. // newTestTransaction create a new dummy transaction.
  69. func newTestTransaction(from *crypto.Key, nonce uint64, datasize int) *types.Transaction {
  70. tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize))
  71. tx, _ = tx.SignECDSA(from.PrivateKey)
  72. return tx
  73. }
  74. // testPeer is a simulated peer to allow testing direct network calls.
  75. type testPeer struct {
  76. net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
  77. app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side
  78. *peer
  79. }
  80. // newTestPeer creates a new peer registered at the given protocol manager.
  81. func newTestPeer(name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) {
  82. // Create a message pipe to communicate through
  83. app, net := p2p.MsgPipe()
  84. // Generate a random id and create the peer
  85. var id discover.NodeID
  86. rand.Read(id[:])
  87. peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net)
  88. // Start the peer on a new thread
  89. errc := make(chan error, 1)
  90. go func() {
  91. pm.newPeerCh <- peer
  92. errc <- pm.handle(peer)
  93. }()
  94. tp := &testPeer{
  95. app: app,
  96. net: net,
  97. peer: peer,
  98. }
  99. // Execute any implicitly requested handshakes and return
  100. if shake {
  101. td, head, genesis := pm.blockchain.Status()
  102. tp.handshake(nil, td, head, genesis)
  103. }
  104. return tp, errc
  105. }
  106. // handshake simulates a trivial handshake that expects the same state from the
  107. // remote side as we are simulating locally.
  108. func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, genesis common.Hash) {
  109. msg := &statusData{
  110. ProtocolVersion: uint32(p.version),
  111. NetworkId: uint32(NetworkId),
  112. TD: td,
  113. CurrentBlock: head,
  114. GenesisBlock: genesis,
  115. }
  116. if err := p2p.ExpectMsg(p.app, StatusMsg, msg); err != nil {
  117. t.Fatalf("status recv: %v", err)
  118. }
  119. if err := p2p.Send(p.app, StatusMsg, msg); err != nil {
  120. t.Fatalf("status send: %v", err)
  121. }
  122. }
  123. // close terminates the local side of the peer, notifying the remote protocol
  124. // manager of termination.
  125. func (p *testPeer) close() {
  126. p.app.Close()
  127. }