protocolsession.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 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/discover"
  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. IDs []discover.NodeID
  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 discover.NodeID // 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 discover.NodeID // 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 discover.NodeID // 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.IDs))
  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. errc <- mockNode.Trigger(&trig)
  83. }()
  84. t := trig.Timeout
  85. if t == time.Duration(0) {
  86. t = 1000 * time.Millisecond
  87. }
  88. select {
  89. case err := <-errc:
  90. return err
  91. case <-time.After(t):
  92. return fmt.Errorf("timout expecting %v to send to peer %v", trig.Msg, trig.Peer)
  93. }
  94. }
  95. // expect checks an expectation of a message sent out by the pivot node
  96. func (s *ProtocolSession) expect(exps []Expect) error {
  97. // construct a map of expectations for each node
  98. peerExpects := make(map[discover.NodeID][]Expect)
  99. for _, exp := range exps {
  100. if exp.Msg == nil {
  101. return errors.New("no message to expect")
  102. }
  103. peerExpects[exp.Peer] = append(peerExpects[exp.Peer], exp)
  104. }
  105. // construct a map of mockNodes for each node
  106. mockNodes := make(map[discover.NodeID]*mockNode)
  107. for nodeID := range peerExpects {
  108. simNode, ok := s.adapter.GetNode(nodeID)
  109. if !ok {
  110. return fmt.Errorf("trigger: peer %v does not exist (1- %v)", nodeID, len(s.IDs))
  111. }
  112. mockNode, ok := simNode.Services()[0].(*mockNode)
  113. if !ok {
  114. return fmt.Errorf("trigger: peer %v is not a mock", nodeID)
  115. }
  116. mockNodes[nodeID] = mockNode
  117. }
  118. // done chanell cancels all created goroutines when function returns
  119. done := make(chan struct{})
  120. defer close(done)
  121. // errc catches the first error from
  122. errc := make(chan error)
  123. wg := &sync.WaitGroup{}
  124. wg.Add(len(mockNodes))
  125. for nodeID, mockNode := range mockNodes {
  126. nodeID := nodeID
  127. mockNode := mockNode
  128. go func() {
  129. defer wg.Done()
  130. // Sum all Expect timeouts to give the maximum
  131. // time for all expectations to finish.
  132. // mockNode.Expect checks all received messages against
  133. // a list of expected messages and timeout for each
  134. // of them can not be checked separately.
  135. var t time.Duration
  136. for _, exp := range peerExpects[nodeID] {
  137. if exp.Timeout == time.Duration(0) {
  138. t += 2000 * time.Millisecond
  139. } else {
  140. t += exp.Timeout
  141. }
  142. }
  143. alarm := time.NewTimer(t)
  144. defer alarm.Stop()
  145. // expectErrc is used to check if error returned
  146. // from mockNode.Expect is not nil and to send it to
  147. // errc only in that case.
  148. // done channel will be closed when function
  149. expectErrc := make(chan error)
  150. go func() {
  151. select {
  152. case expectErrc <- mockNode.Expect(peerExpects[nodeID]...):
  153. case <-done:
  154. case <-alarm.C:
  155. }
  156. }()
  157. select {
  158. case err := <-expectErrc:
  159. if err != nil {
  160. select {
  161. case errc <- err:
  162. case <-done:
  163. case <-alarm.C:
  164. errc <- errTimedOut
  165. }
  166. }
  167. case <-done:
  168. case <-alarm.C:
  169. errc <- errTimedOut
  170. }
  171. }()
  172. }
  173. go func() {
  174. wg.Wait()
  175. // close errc when all goroutines finish to return nill err from errc
  176. close(errc)
  177. }()
  178. return <-errc
  179. }
  180. // TestExchanges tests a series of exchanges against the session
  181. func (s *ProtocolSession) TestExchanges(exchanges ...Exchange) error {
  182. for i, e := range exchanges {
  183. if err := s.testExchange(e); err != nil {
  184. return fmt.Errorf("exchange #%d %q: %v", i, e.Label, err)
  185. }
  186. log.Trace(fmt.Sprintf("exchange #%d %q: run successfully", i, e.Label))
  187. }
  188. return nil
  189. }
  190. // testExchange tests a single Exchange.
  191. // Default timeout value is 2 seconds.
  192. func (s *ProtocolSession) testExchange(e Exchange) error {
  193. errc := make(chan error)
  194. done := make(chan struct{})
  195. defer close(done)
  196. go func() {
  197. for _, trig := range e.Triggers {
  198. err := s.trigger(trig)
  199. if err != nil {
  200. errc <- err
  201. return
  202. }
  203. }
  204. select {
  205. case errc <- s.expect(e.Expects):
  206. case <-done:
  207. }
  208. }()
  209. // time out globally or finish when all expectations satisfied
  210. t := e.Timeout
  211. if t == 0 {
  212. t = 2000 * time.Millisecond
  213. }
  214. alarm := time.NewTimer(t)
  215. select {
  216. case err := <-errc:
  217. return err
  218. case <-alarm.C:
  219. return errTimedOut
  220. }
  221. }
  222. // TestDisconnected tests the disconnections given as arguments
  223. // the disconnect structs describe what disconnect error is expected on which peer
  224. func (s *ProtocolSession) TestDisconnected(disconnects ...*Disconnect) error {
  225. expects := make(map[discover.NodeID]error)
  226. for _, disconnect := range disconnects {
  227. expects[disconnect.Peer] = disconnect.Error
  228. }
  229. timeout := time.After(time.Second)
  230. for len(expects) > 0 {
  231. select {
  232. case event := <-s.events:
  233. if event.Type != p2p.PeerEventTypeDrop {
  234. continue
  235. }
  236. expectErr, ok := expects[event.Peer]
  237. if !ok {
  238. continue
  239. }
  240. if !(expectErr == nil && event.Error == "" || expectErr != nil && expectErr.Error() == event.Error) {
  241. return fmt.Errorf("unexpected error on peer %v. expected '%v', got '%v'", event.Peer, expectErr, event.Error)
  242. }
  243. delete(expects, event.Peer)
  244. case <-timeout:
  245. return fmt.Errorf("timed out waiting for peers to disconnect")
  246. }
  247. }
  248. return nil
  249. }