protocol.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. //For accounting, the design is to allow the Spec to describe which and how its messages are priced
  109. //To access this functionality, we provide a Hook interface which will call accounting methods
  110. //NOTE: there could be more such (horizontal) hooks in the future
  111. type Hook interface {
  112. //A hook for sending messages
  113. Send(peer *Peer, size uint32, msg interface{}) error
  114. //A hook for receiving messages
  115. Receive(peer *Peer, size uint32, msg interface{}) error
  116. }
  117. // Spec is a protocol specification including its name and version as well as
  118. // the types of messages which are exchanged
  119. type Spec struct {
  120. // Name is the name of the protocol, often a three-letter word
  121. Name string
  122. // Version is the version number of the protocol
  123. Version uint
  124. // MaxMsgSize is the maximum accepted length of the message payload
  125. MaxMsgSize uint32
  126. // Messages is a list of message data types which this protocol uses, with
  127. // each message type being sent with its array index as the code (so
  128. // [&foo{}, &bar{}, &baz{}] would send foo, bar and baz with codes
  129. // 0, 1 and 2 respectively)
  130. // each message must have a single unique data type
  131. Messages []interface{}
  132. //hook for accounting (could be extended to multiple hooks in the future)
  133. Hook Hook
  134. initOnce sync.Once
  135. codes map[reflect.Type]uint64
  136. types map[uint64]reflect.Type
  137. }
  138. func (s *Spec) init() {
  139. s.initOnce.Do(func() {
  140. s.codes = make(map[reflect.Type]uint64, len(s.Messages))
  141. s.types = make(map[uint64]reflect.Type, len(s.Messages))
  142. for i, msg := range s.Messages {
  143. code := uint64(i)
  144. typ := reflect.TypeOf(msg)
  145. if typ.Kind() == reflect.Ptr {
  146. typ = typ.Elem()
  147. }
  148. s.codes[typ] = code
  149. s.types[code] = typ
  150. }
  151. })
  152. }
  153. // Length returns the number of message types in the protocol
  154. func (s *Spec) Length() uint64 {
  155. return uint64(len(s.Messages))
  156. }
  157. // GetCode returns the message code of a type, and boolean second argument is
  158. // false if the message type is not found
  159. func (s *Spec) GetCode(msg interface{}) (uint64, bool) {
  160. s.init()
  161. typ := reflect.TypeOf(msg)
  162. if typ.Kind() == reflect.Ptr {
  163. typ = typ.Elem()
  164. }
  165. code, ok := s.codes[typ]
  166. return code, ok
  167. }
  168. // NewMsg construct a new message type given the code
  169. func (s *Spec) NewMsg(code uint64) (interface{}, bool) {
  170. s.init()
  171. typ, ok := s.types[code]
  172. if !ok {
  173. return nil, false
  174. }
  175. return reflect.New(typ).Interface(), true
  176. }
  177. // Peer represents a remote peer or protocol instance that is running on a peer connection with
  178. // a remote peer
  179. type Peer struct {
  180. *p2p.Peer // the p2p.Peer object representing the remote
  181. rw p2p.MsgReadWriter // p2p.MsgReadWriter to send messages to and read messages from
  182. spec *Spec
  183. }
  184. // NewPeer constructs a new peer
  185. // this constructor is called by the p2p.Protocol#Run function
  186. // the first two arguments are the arguments passed to p2p.Protocol.Run function
  187. // the third argument is the Spec describing the protocol
  188. func NewPeer(p *p2p.Peer, rw p2p.MsgReadWriter, spec *Spec) *Peer {
  189. return &Peer{
  190. Peer: p,
  191. rw: rw,
  192. spec: spec,
  193. }
  194. }
  195. // Run starts the forever loop that handles incoming messages
  196. // called within the p2p.Protocol#Run function
  197. // the handler argument is a function which is called for each message received
  198. // from the remote peer, a returned error causes the loop to exit
  199. // resulting in disconnection
  200. func (p *Peer) Run(handler func(ctx context.Context, msg interface{}) error) error {
  201. for {
  202. if err := p.handleIncoming(handler); err != nil {
  203. if err != io.EOF {
  204. metrics.GetOrRegisterCounter("peer.handleincoming.error", nil).Inc(1)
  205. log.Error("peer.handleIncoming", "err", err)
  206. }
  207. return err
  208. }
  209. }
  210. }
  211. // Drop disconnects a peer.
  212. // TODO: may need to implement protocol drop only? don't want to kick off the peer
  213. // if they are useful for other protocols
  214. func (p *Peer) Drop(err error) {
  215. p.Disconnect(p2p.DiscSubprotocolError)
  216. }
  217. // Send takes a message, encodes it in RLP, finds the right message code and sends the
  218. // message off to the peer
  219. // this low level call will be wrapped by libraries providing routed or broadcast sends
  220. // but often just used to forward and push messages to directly connected peers
  221. func (p *Peer) Send(ctx context.Context, msg interface{}) error {
  222. defer metrics.GetOrRegisterResettingTimer("peer.send_t", nil).UpdateSince(time.Now())
  223. metrics.GetOrRegisterCounter("peer.send", nil).Inc(1)
  224. var b bytes.Buffer
  225. if tracing.Enabled {
  226. writer := bufio.NewWriter(&b)
  227. tracer := opentracing.GlobalTracer()
  228. sctx := spancontext.FromContext(ctx)
  229. if sctx != nil {
  230. err := tracer.Inject(
  231. sctx,
  232. opentracing.Binary,
  233. writer)
  234. if err != nil {
  235. return err
  236. }
  237. }
  238. writer.Flush()
  239. }
  240. r, err := rlp.EncodeToBytes(msg)
  241. if err != nil {
  242. return err
  243. }
  244. wmsg := WrappedMsg{
  245. Context: b.Bytes(),
  246. Size: uint32(len(r)),
  247. Payload: r,
  248. }
  249. //if the accounting hook is set, call it
  250. if p.spec.Hook != nil {
  251. err := p.spec.Hook.Send(p, wmsg.Size, msg)
  252. if err != nil {
  253. p.Drop(err)
  254. return err
  255. }
  256. }
  257. code, found := p.spec.GetCode(msg)
  258. if !found {
  259. return errorf(ErrInvalidMsgType, "%v", code)
  260. }
  261. return p2p.Send(p.rw, code, wmsg)
  262. }
  263. // handleIncoming(code)
  264. // is called each cycle of the main forever loop that dispatches incoming messages
  265. // if this returns an error the loop returns and the peer is disconnected with the error
  266. // this generic handler
  267. // * checks message size,
  268. // * checks for out-of-range message codes,
  269. // * handles decoding with reflection,
  270. // * call handlers as callbacks
  271. func (p *Peer) handleIncoming(handle func(ctx context.Context, msg interface{}) error) error {
  272. msg, err := p.rw.ReadMsg()
  273. if err != nil {
  274. return err
  275. }
  276. // make sure that the payload has been fully consumed
  277. defer msg.Discard()
  278. if msg.Size > p.spec.MaxMsgSize {
  279. return errorf(ErrMsgTooLong, "%v > %v", msg.Size, p.spec.MaxMsgSize)
  280. }
  281. // unmarshal wrapped msg, which might contain context
  282. var wmsg WrappedMsg
  283. err = msg.Decode(&wmsg)
  284. if err != nil {
  285. log.Error(err.Error())
  286. return err
  287. }
  288. ctx := context.Background()
  289. // if tracing is enabled and the context coming within the request is
  290. // not empty, try to unmarshal it
  291. if tracing.Enabled && len(wmsg.Context) > 0 {
  292. var sctx opentracing.SpanContext
  293. tracer := opentracing.GlobalTracer()
  294. sctx, err = tracer.Extract(
  295. opentracing.Binary,
  296. bytes.NewReader(wmsg.Context))
  297. if err != nil {
  298. log.Error(err.Error())
  299. return err
  300. }
  301. ctx = spancontext.WithContext(ctx, sctx)
  302. }
  303. val, ok := p.spec.NewMsg(msg.Code)
  304. if !ok {
  305. return errorf(ErrInvalidMsgCode, "%v", msg.Code)
  306. }
  307. if err := rlp.DecodeBytes(wmsg.Payload, val); err != nil {
  308. return errorf(ErrDecode, "<= %v: %v", msg, err)
  309. }
  310. //if the accounting hook is set, call it
  311. if p.spec.Hook != nil {
  312. err := p.spec.Hook.Receive(p, wmsg.Size, val)
  313. if err != nil {
  314. return err
  315. }
  316. }
  317. // call the registered handler callbacks
  318. // a registered callback take the decoded message as argument as an interface
  319. // which the handler is supposed to cast to the appropriate type
  320. // it is entirely safe not to check the cast in the handler since the handler is
  321. // chosen based on the proper type in the first place
  322. if err := handle(ctx, val); err != nil {
  323. return errorf(ErrHandler, "(msg code %v): %v", msg.Code, err)
  324. }
  325. return nil
  326. }
  327. // Handshake negotiates a handshake on the peer connection
  328. // * arguments
  329. // * context
  330. // * the local handshake to be sent to the remote peer
  331. // * function to be called on the remote handshake (can be nil)
  332. // * expects a remote handshake back of the same type
  333. // * the dialing peer needs to send the handshake first and then waits for remote
  334. // * the listening peer waits for the remote handshake and then sends it
  335. // returns the remote handshake and an error
  336. func (p *Peer) Handshake(ctx context.Context, hs interface{}, verify func(interface{}) error) (rhs interface{}, err error) {
  337. if _, ok := p.spec.GetCode(hs); !ok {
  338. return nil, errorf(ErrHandshake, "unknown handshake message type: %T", hs)
  339. }
  340. errc := make(chan error, 2)
  341. handle := func(ctx context.Context, msg interface{}) error {
  342. rhs = msg
  343. if verify != nil {
  344. return verify(rhs)
  345. }
  346. return nil
  347. }
  348. send := func() { errc <- p.Send(ctx, hs) }
  349. receive := func() { errc <- p.handleIncoming(handle) }
  350. go func() {
  351. if p.Inbound() {
  352. receive()
  353. send()
  354. } else {
  355. send()
  356. receive()
  357. }
  358. }()
  359. for i := 0; i < 2; i++ {
  360. select {
  361. case err = <-errc:
  362. case <-ctx.Done():
  363. err = ctx.Err()
  364. }
  365. if err != nil {
  366. return nil, errorf(ErrHandshake, err.Error())
  367. }
  368. }
  369. return rhs, nil
  370. }
  371. // HasCap returns true if Peer has a capability
  372. // with provided name.
  373. func (p *Peer) HasCap(capName string) (yes bool) {
  374. if p == nil || p.Peer == nil {
  375. return false
  376. }
  377. for _, c := range p.Caps() {
  378. if c.Name == capName {
  379. return true
  380. }
  381. }
  382. return false
  383. }