protocol.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. /*
  17. Package protocols is an extension to p2p. It offers a user friendly simple way to define
  18. devp2p subprotocols by abstracting away code standardly shared by protocols.
  19. * automate assigments of code indexes to messages
  20. * automate RLP decoding/encoding based on reflecting
  21. * provide the forever loop to read incoming messages
  22. * standardise error handling related to communication
  23. * standardised handshake negotiation
  24. * TODO: automatic generation of wire protocol specification for peers
  25. */
  26. package protocols
  27. import (
  28. "context"
  29. "fmt"
  30. "reflect"
  31. "sync"
  32. "github.com/ethereum/go-ethereum/p2p"
  33. )
  34. // error codes used by this protocol scheme
  35. const (
  36. ErrMsgTooLong = iota
  37. ErrDecode
  38. ErrWrite
  39. ErrInvalidMsgCode
  40. ErrInvalidMsgType
  41. ErrHandshake
  42. ErrNoHandler
  43. ErrHandler
  44. )
  45. // error description strings associated with the codes
  46. var errorToString = map[int]string{
  47. ErrMsgTooLong: "Message too long",
  48. ErrDecode: "Invalid message (RLP error)",
  49. ErrWrite: "Error sending message",
  50. ErrInvalidMsgCode: "Invalid message code",
  51. ErrInvalidMsgType: "Invalid message type",
  52. ErrHandshake: "Handshake error",
  53. ErrNoHandler: "No handler registered error",
  54. ErrHandler: "Message handler error",
  55. }
  56. /*
  57. Error implements the standard go error interface.
  58. Use:
  59. errorf(code, format, params ...interface{})
  60. Prints as:
  61. <description>: <details>
  62. where description is given by code in errorToString
  63. and details is fmt.Sprintf(format, params...)
  64. exported field Code can be checked
  65. */
  66. type Error struct {
  67. Code int
  68. message string
  69. format string
  70. params []interface{}
  71. }
  72. func (e Error) Error() (message string) {
  73. if len(e.message) == 0 {
  74. name, ok := errorToString[e.Code]
  75. if !ok {
  76. panic("invalid message code")
  77. }
  78. e.message = name
  79. if e.format != "" {
  80. e.message += ": " + fmt.Sprintf(e.format, e.params...)
  81. }
  82. }
  83. return e.message
  84. }
  85. func errorf(code int, format string, params ...interface{}) *Error {
  86. return &Error{
  87. Code: code,
  88. format: format,
  89. params: params,
  90. }
  91. }
  92. // Spec is a protocol specification including its name and version as well as
  93. // the types of messages which are exchanged
  94. type Spec struct {
  95. // Name is the name of the protocol, often a three-letter word
  96. Name string
  97. // Version is the version number of the protocol
  98. Version uint
  99. // MaxMsgSize is the maximum accepted length of the message payload
  100. MaxMsgSize uint32
  101. // Messages is a list of message data types which this protocol uses, with
  102. // each message type being sent with its array index as the code (so
  103. // [&foo{}, &bar{}, &baz{}] would send foo, bar and baz with codes
  104. // 0, 1 and 2 respectively)
  105. // each message must have a single unique data type
  106. Messages []interface{}
  107. initOnce sync.Once
  108. codes map[reflect.Type]uint64
  109. types map[uint64]reflect.Type
  110. }
  111. func (s *Spec) init() {
  112. s.initOnce.Do(func() {
  113. s.codes = make(map[reflect.Type]uint64, len(s.Messages))
  114. s.types = make(map[uint64]reflect.Type, len(s.Messages))
  115. for i, msg := range s.Messages {
  116. code := uint64(i)
  117. typ := reflect.TypeOf(msg)
  118. if typ.Kind() == reflect.Ptr {
  119. typ = typ.Elem()
  120. }
  121. s.codes[typ] = code
  122. s.types[code] = typ
  123. }
  124. })
  125. }
  126. // Length returns the number of message types in the protocol
  127. func (s *Spec) Length() uint64 {
  128. return uint64(len(s.Messages))
  129. }
  130. // GetCode returns the message code of a type, and boolean second argument is
  131. // false if the message type is not found
  132. func (s *Spec) GetCode(msg interface{}) (uint64, bool) {
  133. s.init()
  134. typ := reflect.TypeOf(msg)
  135. if typ.Kind() == reflect.Ptr {
  136. typ = typ.Elem()
  137. }
  138. code, ok := s.codes[typ]
  139. return code, ok
  140. }
  141. // NewMsg construct a new message type given the code
  142. func (s *Spec) NewMsg(code uint64) (interface{}, bool) {
  143. s.init()
  144. typ, ok := s.types[code]
  145. if !ok {
  146. return nil, false
  147. }
  148. return reflect.New(typ).Interface(), true
  149. }
  150. // Peer represents a remote peer or protocol instance that is running on a peer connection with
  151. // a remote peer
  152. type Peer struct {
  153. *p2p.Peer // the p2p.Peer object representing the remote
  154. rw p2p.MsgReadWriter // p2p.MsgReadWriter to send messages to and read messages from
  155. spec *Spec
  156. }
  157. // NewPeer constructs a new peer
  158. // this constructor is called by the p2p.Protocol#Run function
  159. // the first two arguments are the arguments passed to p2p.Protocol.Run function
  160. // the third argument is the Spec describing the protocol
  161. func NewPeer(p *p2p.Peer, rw p2p.MsgReadWriter, spec *Spec) *Peer {
  162. return &Peer{
  163. Peer: p,
  164. rw: rw,
  165. spec: spec,
  166. }
  167. }
  168. // Run starts the forever loop that handles incoming messages
  169. // called within the p2p.Protocol#Run function
  170. // the handler argument is a function which is called for each message received
  171. // from the remote peer, a returned error causes the loop to exit
  172. // resulting in disconnection
  173. func (p *Peer) Run(handler func(msg interface{}) error) error {
  174. for {
  175. if err := p.handleIncoming(handler); err != nil {
  176. return err
  177. }
  178. }
  179. }
  180. // Drop disconnects a peer.
  181. // TODO: may need to implement protocol drop only? don't want to kick off the peer
  182. // if they are useful for other protocols
  183. func (p *Peer) Drop(err error) {
  184. p.Disconnect(p2p.DiscSubprotocolError)
  185. }
  186. // Send takes a message, encodes it in RLP, finds the right message code and sends the
  187. // message off to the peer
  188. // this low level call will be wrapped by libraries providing routed or broadcast sends
  189. // but often just used to forward and push messages to directly connected peers
  190. func (p *Peer) Send(msg interface{}) error {
  191. code, found := p.spec.GetCode(msg)
  192. if !found {
  193. return errorf(ErrInvalidMsgType, "%v", code)
  194. }
  195. return p2p.Send(p.rw, code, msg)
  196. }
  197. // handleIncoming(code)
  198. // is called each cycle of the main forever loop that dispatches incoming messages
  199. // if this returns an error the loop returns and the peer is disconnected with the error
  200. // this generic handler
  201. // * checks message size,
  202. // * checks for out-of-range message codes,
  203. // * handles decoding with reflection,
  204. // * call handlers as callbacks
  205. func (p *Peer) handleIncoming(handle func(msg interface{}) error) error {
  206. msg, err := p.rw.ReadMsg()
  207. if err != nil {
  208. return err
  209. }
  210. // make sure that the payload has been fully consumed
  211. defer msg.Discard()
  212. if msg.Size > p.spec.MaxMsgSize {
  213. return errorf(ErrMsgTooLong, "%v > %v", msg.Size, p.spec.MaxMsgSize)
  214. }
  215. val, ok := p.spec.NewMsg(msg.Code)
  216. if !ok {
  217. return errorf(ErrInvalidMsgCode, "%v", msg.Code)
  218. }
  219. if err := msg.Decode(val); err != nil {
  220. return errorf(ErrDecode, "<= %v: %v", msg, err)
  221. }
  222. // call the registered handler callbacks
  223. // a registered callback take the decoded message as argument as an interface
  224. // which the handler is supposed to cast to the appropriate type
  225. // it is entirely safe not to check the cast in the handler since the handler is
  226. // chosen based on the proper type in the first place
  227. if err := handle(val); err != nil {
  228. return errorf(ErrHandler, "(msg code %v): %v", msg.Code, err)
  229. }
  230. return nil
  231. }
  232. // Handshake negotiates a handshake on the peer connection
  233. // * arguments
  234. // * context
  235. // * the local handshake to be sent to the remote peer
  236. // * funcion to be called on the remote handshake (can be nil)
  237. // * expects a remote handshake back of the same type
  238. // * the dialing peer needs to send the handshake first and then waits for remote
  239. // * the listening peer waits for the remote handshake and then sends it
  240. // returns the remote handshake and an error
  241. func (p *Peer) Handshake(ctx context.Context, hs interface{}, verify func(interface{}) error) (rhs interface{}, err error) {
  242. if _, ok := p.spec.GetCode(hs); !ok {
  243. return nil, errorf(ErrHandshake, "unknown handshake message type: %T", hs)
  244. }
  245. errc := make(chan error, 2)
  246. handle := func(msg interface{}) error {
  247. rhs = msg
  248. if verify != nil {
  249. return verify(rhs)
  250. }
  251. return nil
  252. }
  253. send := func() { errc <- p.Send(hs) }
  254. receive := func() { errc <- p.handleIncoming(handle) }
  255. go func() {
  256. if p.Inbound() {
  257. receive()
  258. send()
  259. } else {
  260. send()
  261. receive()
  262. }
  263. }()
  264. for i := 0; i < 2; i++ {
  265. select {
  266. case err = <-errc:
  267. case <-ctx.Done():
  268. err = ctx.Err()
  269. }
  270. if err != nil {
  271. return nil, errorf(ErrHandshake, err.Error())
  272. }
  273. }
  274. return rhs, nil
  275. }