ping-pong.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. // Copyright 2017 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 main
  17. import (
  18. "flag"
  19. "fmt"
  20. "io/ioutil"
  21. "net/http"
  22. "os"
  23. "sync/atomic"
  24. "time"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/node"
  27. "github.com/ethereum/go-ethereum/p2p"
  28. "github.com/ethereum/go-ethereum/p2p/enode"
  29. "github.com/ethereum/go-ethereum/p2p/simulations"
  30. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  31. )
  32. var adapterType = flag.String("adapter", "sim", `node adapter to use (one of "sim", "exec" or "docker")`)
  33. // main() starts a simulation network which contains nodes running a simple
  34. // ping-pong protocol
  35. func main() {
  36. flag.Parse()
  37. // set the log level to Trace
  38. log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))
  39. // register a single ping-pong service
  40. services := map[string]adapters.LifecycleConstructor{
  41. "ping-pong": func(ctx *adapters.ServiceContext, stack *node.Node) (node.Lifecycle, error) {
  42. pps := newPingPongService(ctx.Config.ID)
  43. stack.RegisterProtocols(pps.Protocols())
  44. return pps, nil
  45. },
  46. }
  47. adapters.RegisterLifecycles(services)
  48. // create the NodeAdapter
  49. var adapter adapters.NodeAdapter
  50. switch *adapterType {
  51. case "sim":
  52. log.Info("using sim adapter")
  53. adapter = adapters.NewSimAdapter(services)
  54. case "exec":
  55. tmpdir, err := ioutil.TempDir("", "p2p-example")
  56. if err != nil {
  57. log.Crit("error creating temp dir", "err", err)
  58. }
  59. defer os.RemoveAll(tmpdir)
  60. log.Info("using exec adapter", "tmpdir", tmpdir)
  61. adapter = adapters.NewExecAdapter(tmpdir)
  62. default:
  63. log.Crit(fmt.Sprintf("unknown node adapter %q", *adapterType))
  64. }
  65. // start the HTTP API
  66. log.Info("starting simulation server on 0.0.0.0:8888...")
  67. network := simulations.NewNetwork(adapter, &simulations.NetworkConfig{
  68. DefaultService: "ping-pong",
  69. })
  70. if err := http.ListenAndServe(":8888", simulations.NewServer(network)); err != nil {
  71. log.Crit("error starting simulation server", "err", err)
  72. }
  73. }
  74. // pingPongService runs a ping-pong protocol between nodes where each node
  75. // sends a ping to all its connected peers every 10s and receives a pong in
  76. // return
  77. type pingPongService struct {
  78. id enode.ID
  79. log log.Logger
  80. received int64
  81. }
  82. func newPingPongService(id enode.ID) *pingPongService {
  83. return &pingPongService{
  84. id: id,
  85. log: log.New("node.id", id),
  86. }
  87. }
  88. func (p *pingPongService) Protocols() []p2p.Protocol {
  89. return []p2p.Protocol{{
  90. Name: "ping-pong",
  91. Version: 1,
  92. Length: 2,
  93. Run: p.Run,
  94. NodeInfo: p.Info,
  95. }}
  96. }
  97. func (p *pingPongService) Start() error {
  98. p.log.Info("ping-pong service starting")
  99. return nil
  100. }
  101. func (p *pingPongService) Stop() error {
  102. p.log.Info("ping-pong service stopping")
  103. return nil
  104. }
  105. func (p *pingPongService) Info() interface{} {
  106. return struct {
  107. Received int64 `json:"received"`
  108. }{
  109. atomic.LoadInt64(&p.received),
  110. }
  111. }
  112. const (
  113. pingMsgCode = iota
  114. pongMsgCode
  115. )
  116. // Run implements the ping-pong protocol which sends ping messages to the peer
  117. // at 10s intervals, and responds to pings with pong messages.
  118. func (p *pingPongService) Run(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
  119. log := p.log.New("peer.id", peer.ID())
  120. errC := make(chan error)
  121. go func() {
  122. for range time.Tick(10 * time.Second) {
  123. log.Info("sending ping")
  124. if err := p2p.Send(rw, pingMsgCode, "PING"); err != nil {
  125. errC <- err
  126. return
  127. }
  128. }
  129. }()
  130. go func() {
  131. for {
  132. msg, err := rw.ReadMsg()
  133. if err != nil {
  134. errC <- err
  135. return
  136. }
  137. payload, err := ioutil.ReadAll(msg.Payload)
  138. if err != nil {
  139. errC <- err
  140. return
  141. }
  142. log.Info("received message", "msg.code", msg.Code, "msg.payload", string(payload))
  143. atomic.AddInt64(&p.received, 1)
  144. if msg.Code == pingMsgCode {
  145. log.Info("sending pong")
  146. go p2p.Send(rw, pongMsgCode, "PONG")
  147. }
  148. }
  149. }()
  150. return <-errC
  151. }