protocol.go 9.0 KB

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