peer_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // This file contains some shares testing functionality, common to multiple
  17. // different files and modules being tested.
  18. package diff
  19. import (
  20. "crypto/rand"
  21. "github.com/ethereum/go-ethereum/p2p"
  22. "github.com/ethereum/go-ethereum/p2p/enode"
  23. )
  24. // testPeer is a simulated peer to allow testing direct network calls.
  25. type testPeer struct {
  26. *Peer
  27. net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging
  28. app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side
  29. }
  30. // newTestPeer creates a new peer registered at the given data backend.
  31. func newTestPeer(name string, version uint, backend Backend) (*testPeer, <-chan error) {
  32. // Create a message pipe to communicate through
  33. app, net := p2p.MsgPipe()
  34. // Start the peer on a new thread
  35. var id enode.ID
  36. rand.Read(id[:])
  37. peer := NewPeer(version, p2p.NewPeer(id, name, nil), net)
  38. errc := make(chan error, 1)
  39. go func() {
  40. errc <- backend.RunPeer(peer, func(peer *Peer) error {
  41. return Handle(backend, peer)
  42. })
  43. }()
  44. return &testPeer{app: app, net: net, Peer: peer}, errc
  45. }
  46. // close terminates the local side of the peer, notifying the remote protocol
  47. // manager of termination.
  48. func (p *testPeer) close() {
  49. p.Peer.Close()
  50. p.app.Close()
  51. }