ping-pong.go 4.6 KB

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