protocol.go 9.2 KB

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