protocol.go 11 KB

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