protocolsession.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. // Copyright 2018 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 testing
  17. import (
  18. "errors"
  19. "fmt"
  20. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/log"
  23. "github.com/ethereum/go-ethereum/p2p"
  24. "github.com/ethereum/go-ethereum/p2p/enode"
  25. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  26. )
  27. var errTimedOut = errors.New("timed out")
  28. // ProtocolSession is a quasi simulation of a pivot node running
  29. // a service and a number of dummy peers that can send (trigger) or
  30. // receive (expect) messages
  31. type ProtocolSession struct {
  32. Server *p2p.Server
  33. Nodes []*enode.Node
  34. adapter *adapters.SimAdapter
  35. events chan *p2p.PeerEvent
  36. }
  37. // Exchange is the basic units of protocol tests
  38. // the triggers and expects in the arrays are run immediately and asynchronously
  39. // thus one cannot have multiple expects for the SAME peer with DIFFERENT message types
  40. // because it's unpredictable which expect will receive which message
  41. // (with expect #1 and #2, messages might be sent #2 and #1, and both expects will complain about wrong message code)
  42. // an exchange is defined on a session
  43. type Exchange struct {
  44. Label string
  45. Triggers []Trigger
  46. Expects []Expect
  47. Timeout time.Duration
  48. }
  49. // Trigger is part of the exchange, incoming message for the pivot node
  50. // sent by a peer
  51. type Trigger struct {
  52. Msg interface{} // type of message to be sent
  53. Code uint64 // code of message is given
  54. Peer enode.ID // the peer to send the message to
  55. Timeout time.Duration // timeout duration for the sending
  56. }
  57. // Expect is part of an exchange, outgoing message from the pivot node
  58. // received by a peer
  59. type Expect struct {
  60. Msg interface{} // type of message to expect
  61. Code uint64 // code of message is now given
  62. Peer enode.ID // the peer that expects the message
  63. Timeout time.Duration // timeout duration for receiving
  64. }
  65. // Disconnect represents a disconnect event, used and checked by TestDisconnected
  66. type Disconnect struct {
  67. Peer enode.ID // discconnected peer
  68. Error error // disconnect reason
  69. }
  70. // trigger sends messages from peers
  71. func (s *ProtocolSession) trigger(trig Trigger) error {
  72. simNode, ok := s.adapter.GetNode(trig.Peer)
  73. if !ok {
  74. return fmt.Errorf("trigger: peer %v does not exist (1- %v)", trig.Peer, len(s.Nodes))
  75. }
  76. mockNode, ok := simNode.Services()[0].(*mockNode)
  77. if !ok {
  78. return fmt.Errorf("trigger: peer %v is not a mock", trig.Peer)
  79. }
  80. errc := make(chan error)
  81. go func() {
  82. log.Trace(fmt.Sprintf("trigger %v (%v)....", trig.Msg, trig.Code))
  83. errc <- mockNode.Trigger(&trig)
  84. log.Trace(fmt.Sprintf("triggered %v (%v)", trig.Msg, trig.Code))
  85. }()
  86. t := trig.Timeout
  87. if t == time.Duration(0) {
  88. t = 1000 * time.Millisecond
  89. }
  90. select {
  91. case err := <-errc:
  92. return err
  93. case <-time.After(t):
  94. return fmt.Errorf("timout expecting %v to send to peer %v", trig.Msg, trig.Peer)
  95. }
  96. }
  97. // expect checks an expectation of a message sent out by the pivot node
  98. func (s *ProtocolSession) expect(exps []Expect) error {
  99. // construct a map of expectations for each node
  100. peerExpects := make(map[enode.ID][]Expect)
  101. for _, exp := range exps {
  102. if exp.Msg == nil {
  103. return errors.New("no message to expect")
  104. }
  105. peerExpects[exp.Peer] = append(peerExpects[exp.Peer], exp)
  106. }
  107. // construct a map of mockNodes for each node
  108. mockNodes := make(map[enode.ID]*mockNode)
  109. for nodeID := range peerExpects {
  110. simNode, ok := s.adapter.GetNode(nodeID)
  111. if !ok {
  112. return fmt.Errorf("trigger: peer %v does not exist (1- %v)", nodeID, len(s.Nodes))
  113. }
  114. mockNode, ok := simNode.Services()[0].(*mockNode)
  115. if !ok {
  116. return fmt.Errorf("trigger: peer %v is not a mock", nodeID)
  117. }
  118. mockNodes[nodeID] = mockNode
  119. }
  120. // done chanell cancels all created goroutines when function returns
  121. done := make(chan struct{})
  122. defer close(done)
  123. // errc catches the first error from
  124. errc := make(chan error)
  125. wg := &sync.WaitGroup{}
  126. wg.Add(len(mockNodes))
  127. for nodeID, mockNode := range mockNodes {
  128. nodeID := nodeID
  129. mockNode := mockNode
  130. go func() {
  131. defer wg.Done()
  132. // Sum all Expect timeouts to give the maximum
  133. // time for all expectations to finish.
  134. // mockNode.Expect checks all received messages against
  135. // a list of expected messages and timeout for each
  136. // of them can not be checked separately.
  137. var t time.Duration
  138. for _, exp := range peerExpects[nodeID] {
  139. if exp.Timeout == time.Duration(0) {
  140. t += 2000 * time.Millisecond
  141. } else {
  142. t += exp.Timeout
  143. }
  144. }
  145. alarm := time.NewTimer(t)
  146. defer alarm.Stop()
  147. // expectErrc is used to check if error returned
  148. // from mockNode.Expect is not nil and to send it to
  149. // errc only in that case.
  150. // done channel will be closed when function
  151. expectErrc := make(chan error)
  152. go func() {
  153. select {
  154. case expectErrc <- mockNode.Expect(peerExpects[nodeID]...):
  155. case <-done:
  156. case <-alarm.C:
  157. }
  158. }()
  159. select {
  160. case err := <-expectErrc:
  161. if err != nil {
  162. select {
  163. case errc <- err:
  164. case <-done:
  165. case <-alarm.C:
  166. errc <- errTimedOut
  167. }
  168. }
  169. case <-done:
  170. case <-alarm.C:
  171. errc <- errTimedOut
  172. }
  173. }()
  174. }
  175. go func() {
  176. wg.Wait()
  177. // close errc when all goroutines finish to return nill err from errc
  178. close(errc)
  179. }()
  180. return <-errc
  181. }
  182. // TestExchanges tests a series of exchanges against the session
  183. func (s *ProtocolSession) TestExchanges(exchanges ...Exchange) error {
  184. for i, e := range exchanges {
  185. if err := s.testExchange(e); err != nil {
  186. return fmt.Errorf("exchange #%d %q: %v", i, e.Label, err)
  187. }
  188. log.Trace(fmt.Sprintf("exchange #%d %q: run successfully", i, e.Label))
  189. }
  190. return nil
  191. }
  192. // testExchange tests a single Exchange.
  193. // Default timeout value is 2 seconds.
  194. func (s *ProtocolSession) testExchange(e Exchange) error {
  195. errc := make(chan error)
  196. done := make(chan struct{})
  197. defer close(done)
  198. go func() {
  199. for _, trig := range e.Triggers {
  200. err := s.trigger(trig)
  201. if err != nil {
  202. errc <- err
  203. return
  204. }
  205. }
  206. select {
  207. case errc <- s.expect(e.Expects):
  208. case <-done:
  209. }
  210. }()
  211. // time out globally or finish when all expectations satisfied
  212. t := e.Timeout
  213. if t == 0 {
  214. t = 2000 * time.Millisecond
  215. }
  216. alarm := time.NewTimer(t)
  217. defer alarm.Stop()
  218. select {
  219. case err := <-errc:
  220. return err
  221. case <-alarm.C:
  222. return errTimedOut
  223. }
  224. }
  225. // TestDisconnected tests the disconnections given as arguments
  226. // the disconnect structs describe what disconnect error is expected on which peer
  227. func (s *ProtocolSession) TestDisconnected(disconnects ...*Disconnect) error {
  228. expects := make(map[enode.ID]error)
  229. for _, disconnect := range disconnects {
  230. expects[disconnect.Peer] = disconnect.Error
  231. }
  232. timeout := time.After(time.Second)
  233. for len(expects) > 0 {
  234. select {
  235. case event := <-s.events:
  236. if event.Type != p2p.PeerEventTypeDrop {
  237. continue
  238. }
  239. expectErr, ok := expects[event.Peer]
  240. if !ok {
  241. continue
  242. }
  243. if !(expectErr == nil && event.Error == "" || expectErr != nil && expectErr.Error() == event.Error) {
  244. return fmt.Errorf("unexpected error on peer %v. expected '%v', got '%v'", event.Peer, expectErr, event.Error)
  245. }
  246. delete(expects, event.Peer)
  247. case <-timeout:
  248. return fmt.Errorf("timed out waiting for peers to disconnect")
  249. }
  250. }
  251. return nil
  252. }