ping-pong.go 4.5 KB

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