message.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // Copyright (c) 2013-2017 The btcsuite developers
  2. // Copyright (c) 2015-2016 The Decred developers
  3. // code derived from https://github .com/btcsuite/btcd/blob/master/wire/message.go
  4. // Copyright (C) 2015-2022 The Lightning Network Developers
  5. package lnwire
  6. import (
  7. "bytes"
  8. "encoding/binary"
  9. "fmt"
  10. "io"
  11. )
  12. // MessageType is the unique 2 byte big-endian integer that indicates the type
  13. // of message on the wire. All messages have a very simple header which
  14. // consists simply of 2-byte message type. We omit a length field, and checksum
  15. // as the Lightning Protocol is intended to be encapsulated within a
  16. // confidential+authenticated cryptographic messaging protocol.
  17. type MessageType uint16
  18. // The currently defined message types within this current version of the
  19. // Lightning protocol.
  20. const (
  21. MsgWarning MessageType = 1
  22. MsgInit = 16
  23. MsgError = 17
  24. MsgPing = 18
  25. MsgPong = 19
  26. MsgOpenChannel = 32
  27. MsgAcceptChannel = 33
  28. MsgFundingCreated = 34
  29. MsgFundingSigned = 35
  30. MsgChannelReady = 36
  31. MsgShutdown = 38
  32. MsgClosingSigned = 39
  33. MsgClosingComplete = 40
  34. MsgClosingSig = 41
  35. MsgDynPropose = 111
  36. MsgDynAck = 113
  37. MsgDynReject = 115
  38. MsgUpdateAddHTLC = 128
  39. MsgUpdateFulfillHTLC = 130
  40. MsgUpdateFailHTLC = 131
  41. MsgCommitSig = 132
  42. MsgRevokeAndAck = 133
  43. MsgUpdateFee = 134
  44. MsgUpdateFailMalformedHTLC = 135
  45. MsgChannelReestablish = 136
  46. MsgChannelAnnouncement = 256
  47. MsgNodeAnnouncement = 257
  48. MsgChannelUpdate = 258
  49. MsgAnnounceSignatures = 259
  50. MsgQueryShortChanIDs = 261
  51. MsgReplyShortChanIDsEnd = 262
  52. MsgQueryChannelRange = 263
  53. MsgReplyChannelRange = 264
  54. MsgGossipTimestampRange = 265
  55. MsgKickoffSig = 777
  56. )
  57. // ErrorEncodeMessage is used when failed to encode the message payload.
  58. func ErrorEncodeMessage(err error) error {
  59. return fmt.Errorf("failed to encode message to buffer, got %w", err)
  60. }
  61. // ErrorWriteMessageType is used when failed to write the message type.
  62. func ErrorWriteMessageType(err error) error {
  63. return fmt.Errorf("failed to write message type, got %w", err)
  64. }
  65. // ErrorPayloadTooLarge is used when the payload size exceeds the
  66. // MaxMsgBody.
  67. func ErrorPayloadTooLarge(size int) error {
  68. return fmt.Errorf(
  69. "message payload is too large - encoded %d bytes, "+
  70. "but maximum message payload is %d bytes",
  71. size, MaxMsgBody,
  72. )
  73. }
  74. // String return the string representation of message type.
  75. func (t MessageType) String() string {
  76. switch t {
  77. case MsgWarning:
  78. return "Warning"
  79. case MsgInit:
  80. return "Init"
  81. case MsgOpenChannel:
  82. return "MsgOpenChannel"
  83. case MsgAcceptChannel:
  84. return "MsgAcceptChannel"
  85. case MsgFundingCreated:
  86. return "MsgFundingCreated"
  87. case MsgFundingSigned:
  88. return "MsgFundingSigned"
  89. case MsgChannelReady:
  90. return "ChannelReady"
  91. case MsgShutdown:
  92. return "Shutdown"
  93. case MsgClosingSigned:
  94. return "ClosingSigned"
  95. case MsgDynPropose:
  96. return "DynPropose"
  97. case MsgDynAck:
  98. return "DynAck"
  99. case MsgDynReject:
  100. return "DynReject"
  101. case MsgKickoffSig:
  102. return "KickoffSig"
  103. case MsgUpdateAddHTLC:
  104. return "UpdateAddHTLC"
  105. case MsgUpdateFailHTLC:
  106. return "UpdateFailHTLC"
  107. case MsgUpdateFulfillHTLC:
  108. return "UpdateFulfillHTLC"
  109. case MsgCommitSig:
  110. return "CommitSig"
  111. case MsgRevokeAndAck:
  112. return "RevokeAndAck"
  113. case MsgUpdateFailMalformedHTLC:
  114. return "UpdateFailMalformedHTLC"
  115. case MsgChannelReestablish:
  116. return "ChannelReestablish"
  117. case MsgError:
  118. return "Error"
  119. case MsgChannelAnnouncement:
  120. return "ChannelAnnouncement"
  121. case MsgChannelUpdate:
  122. return "ChannelUpdate"
  123. case MsgNodeAnnouncement:
  124. return "NodeAnnouncement"
  125. case MsgPing:
  126. return "Ping"
  127. case MsgAnnounceSignatures:
  128. return "AnnounceSignatures"
  129. case MsgPong:
  130. return "Pong"
  131. case MsgUpdateFee:
  132. return "UpdateFee"
  133. case MsgQueryShortChanIDs:
  134. return "QueryShortChanIDs"
  135. case MsgReplyShortChanIDsEnd:
  136. return "ReplyShortChanIDsEnd"
  137. case MsgQueryChannelRange:
  138. return "QueryChannelRange"
  139. case MsgReplyChannelRange:
  140. return "ReplyChannelRange"
  141. case MsgGossipTimestampRange:
  142. return "GossipTimestampRange"
  143. case MsgClosingComplete:
  144. return "ClosingComplete"
  145. case MsgClosingSig:
  146. return "ClosingSig"
  147. default:
  148. return "<unknown>"
  149. }
  150. }
  151. // UnknownMessage is an implementation of the error interface that allows the
  152. // creation of an error in response to an unknown message.
  153. type UnknownMessage struct {
  154. messageType MessageType
  155. }
  156. // Error returns a human readable string describing the error.
  157. //
  158. // This is part of the error interface.
  159. func (u *UnknownMessage) Error() string {
  160. return fmt.Sprintf("unable to parse message of unknown type: %v",
  161. u.messageType)
  162. }
  163. // Serializable is an interface which defines a lightning wire serializable
  164. // object.
  165. type Serializable interface {
  166. // Decode reads the bytes stream and converts it to the object.
  167. Decode(io.Reader, uint32) error
  168. // Encode converts object to the bytes stream and write it into the
  169. // write buffer.
  170. Encode(*bytes.Buffer, uint32) error
  171. }
  172. // Message is an interface that defines a lightning wire protocol message. The
  173. // interface is general in order to allow implementing types full control over
  174. // the representation of its data.
  175. type Message interface {
  176. Serializable
  177. MsgType() MessageType
  178. }
  179. // LinkUpdater is an interface implemented by most messages in BOLT 2 that are
  180. // allowed to update the channel state.
  181. type LinkUpdater interface {
  182. // All LinkUpdater messages are messages and so we embed the interface
  183. // so that we can treat it as a message if all we know about it is that
  184. // it is a LinkUpdater message.
  185. Message
  186. // TargetChanID returns the channel id of the link for which this
  187. // message is intended.
  188. TargetChanID() ChannelID
  189. }
  190. // makeEmptyMessage creates a new empty message of the proper concrete type
  191. // based on the passed message type.
  192. func makeEmptyMessage(msgType MessageType) (Message, error) {
  193. var msg Message
  194. switch msgType {
  195. case MsgWarning:
  196. msg = &Warning{}
  197. case MsgInit:
  198. msg = &Init{}
  199. case MsgOpenChannel:
  200. msg = &OpenChannel{}
  201. case MsgAcceptChannel:
  202. msg = &AcceptChannel{}
  203. case MsgFundingCreated:
  204. msg = &FundingCreated{}
  205. case MsgFundingSigned:
  206. msg = &FundingSigned{}
  207. case MsgChannelReady:
  208. msg = &ChannelReady{}
  209. case MsgShutdown:
  210. msg = &Shutdown{}
  211. case MsgClosingSigned:
  212. msg = &ClosingSigned{}
  213. case MsgDynPropose:
  214. msg = &DynPropose{}
  215. case MsgDynAck:
  216. msg = &DynAck{}
  217. case MsgDynReject:
  218. msg = &DynReject{}
  219. case MsgKickoffSig:
  220. msg = &KickoffSig{}
  221. case MsgUpdateAddHTLC:
  222. msg = &UpdateAddHTLC{}
  223. case MsgUpdateFailHTLC:
  224. msg = &UpdateFailHTLC{}
  225. case MsgUpdateFulfillHTLC:
  226. msg = &UpdateFulfillHTLC{}
  227. case MsgCommitSig:
  228. msg = &CommitSig{}
  229. case MsgRevokeAndAck:
  230. msg = &RevokeAndAck{}
  231. case MsgUpdateFee:
  232. msg = &UpdateFee{}
  233. case MsgUpdateFailMalformedHTLC:
  234. msg = &UpdateFailMalformedHTLC{}
  235. case MsgChannelReestablish:
  236. msg = &ChannelReestablish{}
  237. case MsgError:
  238. msg = &Error{}
  239. case MsgChannelAnnouncement:
  240. msg = &ChannelAnnouncement{}
  241. case MsgChannelUpdate:
  242. msg = &ChannelUpdate{}
  243. case MsgNodeAnnouncement:
  244. msg = &NodeAnnouncement{}
  245. case MsgPing:
  246. msg = &Ping{}
  247. case MsgAnnounceSignatures:
  248. msg = &AnnounceSignatures{}
  249. case MsgPong:
  250. msg = &Pong{}
  251. case MsgQueryShortChanIDs:
  252. msg = &QueryShortChanIDs{}
  253. case MsgReplyShortChanIDsEnd:
  254. msg = &ReplyShortChanIDsEnd{}
  255. case MsgQueryChannelRange:
  256. msg = &QueryChannelRange{}
  257. case MsgReplyChannelRange:
  258. msg = &ReplyChannelRange{}
  259. case MsgGossipTimestampRange:
  260. msg = &GossipTimestampRange{}
  261. case MsgClosingComplete:
  262. msg = &ClosingComplete{}
  263. case MsgClosingSig:
  264. msg = &ClosingSig{}
  265. default:
  266. // If the message is not within our custom range and has not
  267. // specifically been overridden, return an unknown message.
  268. //
  269. // Note that we do not allow custom message overrides to replace
  270. // known message types, only protocol messages that are not yet
  271. // known to lnd.
  272. if msgType < CustomTypeStart && !IsCustomOverride(msgType) {
  273. return nil, &UnknownMessage{msgType}
  274. }
  275. msg = &Custom{
  276. Type: msgType,
  277. }
  278. }
  279. return msg, nil
  280. }
  281. // WriteMessage writes a lightning Message to a buffer including the necessary
  282. // header information and returns the number of bytes written. If any error is
  283. // encountered, the buffer passed will be reset to its original state since we
  284. // don't want any broken bytes left. In other words, no bytes will be written
  285. // if there's an error. Either all or none of the message bytes will be written
  286. // to the buffer.
  287. //
  288. // NOTE: this method is not concurrent safe.
  289. func WriteMessage(buf *bytes.Buffer, msg Message, pver uint32) (int, error) {
  290. // Record the size of the bytes already written in buffer.
  291. oldByteSize := buf.Len()
  292. // cleanBrokenBytes is a helper closure that helps reset the buffer to
  293. // its original state. It truncates all the bytes written in current
  294. // scope.
  295. var cleanBrokenBytes = func(b *bytes.Buffer) int {
  296. b.Truncate(oldByteSize)
  297. return 0
  298. }
  299. // Write the message type.
  300. var mType [2]byte
  301. binary.BigEndian.PutUint16(mType[:], uint16(msg.MsgType()))
  302. msgTypeBytes, err := buf.Write(mType[:])
  303. if err != nil {
  304. return cleanBrokenBytes(buf), ErrorWriteMessageType(err)
  305. }
  306. // Use the write buffer to encode our message.
  307. if err := msg.Encode(buf, pver); err != nil {
  308. return cleanBrokenBytes(buf), ErrorEncodeMessage(err)
  309. }
  310. // Enforce maximum overall message payload. The write buffer now has
  311. // the size of len(originalBytes) + len(payload) + len(type). We want
  312. // to enforce the payload here, so we subtract it by the length of the
  313. // type and old bytes.
  314. lenp := buf.Len() - oldByteSize - msgTypeBytes
  315. if lenp > MaxMsgBody {
  316. return cleanBrokenBytes(buf), ErrorPayloadTooLarge(lenp)
  317. }
  318. return buf.Len() - oldByteSize, nil
  319. }
  320. // ReadMessage reads, validates, and parses the next Lightning message from r
  321. // for the provided protocol version.
  322. func ReadMessage(r io.Reader, pver uint32) (Message, error) {
  323. // First, we'll read out the first two bytes of the message so we can
  324. // create the proper empty message.
  325. var mType [2]byte
  326. if _, err := io.ReadFull(r, mType[:]); err != nil {
  327. return nil, err
  328. }
  329. msgType := MessageType(binary.BigEndian.Uint16(mType[:]))
  330. // Now that we know the target message type, we can create the proper
  331. // empty message type and decode the message into it.
  332. msg, err := makeEmptyMessage(msgType)
  333. if err != nil {
  334. return nil, err
  335. }
  336. if err := msg.Decode(r, pver); err != nil {
  337. return nil, err
  338. }
  339. return msg, nil
  340. }