writer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. package lnwire
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "image/color"
  8. "math"
  9. "net"
  10. "github.com/btcsuite/btcd/btcec/v2"
  11. "github.com/btcsuite/btcd/btcutil"
  12. "github.com/btcsuite/btcd/wire"
  13. "github.com/lightningnetwork/lnd/tor"
  14. )
  15. var (
  16. // ErrNilFeatureVector is returned when the supplied feature is nil.
  17. ErrNilFeatureVector = errors.New("cannot write nil feature vector")
  18. // ErrPkScriptTooLong is returned when the length of the provided
  19. // script exceeds 34.
  20. ErrPkScriptTooLong = errors.New("'PkScript' too long")
  21. // ErrNilTCPAddress is returned when the supplied address is nil.
  22. ErrNilTCPAddress = errors.New("cannot write nil TCPAddr")
  23. // ErrNilOnionAddress is returned when the supplied address is nil.
  24. ErrNilOnionAddress = errors.New("cannot write nil onion address")
  25. // ErrNilNetAddress is returned when a nil value is used in []net.Addr.
  26. ErrNilNetAddress = errors.New("cannot write nil address")
  27. // ErrNilOpaqueAddrs is returned when the supplied address is nil.
  28. ErrNilOpaqueAddrs = errors.New("cannot write nil OpaqueAddrs")
  29. // ErrNilPublicKey is returned when a nil pubkey is used.
  30. ErrNilPublicKey = errors.New("cannot write nil pubkey")
  31. // ErrUnknownServiceLength is returned when the onion service length is
  32. // unknown.
  33. ErrUnknownServiceLength = errors.New("unknown onion service length")
  34. )
  35. // ErrOutpointIndexTooBig is used when the outpoint index exceeds the max value
  36. // of uint16.
  37. func ErrOutpointIndexTooBig(index uint32) error {
  38. return fmt.Errorf(
  39. "index for outpoint (%v) is greater than "+
  40. "max index of %v", index, math.MaxUint16,
  41. )
  42. }
  43. // WriteBytes appends the given bytes to the provided buffer.
  44. func WriteBytes(buf *bytes.Buffer, b []byte) error {
  45. _, err := buf.Write(b)
  46. return err
  47. }
  48. // WriteUint8 appends the uint8 to the provided buffer.
  49. func WriteUint8(buf *bytes.Buffer, n uint8) error {
  50. _, err := buf.Write([]byte{n})
  51. return err
  52. }
  53. // WriteUint16 appends the uint16 to the provided buffer. It encodes the
  54. // integer using big endian byte order.
  55. func WriteUint16(buf *bytes.Buffer, n uint16) error {
  56. var b [2]byte
  57. binary.BigEndian.PutUint16(b[:], n)
  58. _, err := buf.Write(b[:])
  59. return err
  60. }
  61. // WriteUint32 appends the uint32 to the provided buffer. It encodes the
  62. // integer using big endian byte order.
  63. func WriteUint32(buf *bytes.Buffer, n uint32) error {
  64. var b [4]byte
  65. binary.BigEndian.PutUint32(b[:], n)
  66. _, err := buf.Write(b[:])
  67. return err
  68. }
  69. // WriteUint64 appends the uint64 to the provided buffer. It encodes the
  70. // integer using big endian byte order.
  71. func WriteUint64(buf *bytes.Buffer, n uint64) error {
  72. var b [8]byte
  73. binary.BigEndian.PutUint64(b[:], n)
  74. _, err := buf.Write(b[:])
  75. return err
  76. }
  77. // WriteSatoshi appends the Satoshi value to the provided buffer.
  78. func WriteSatoshi(buf *bytes.Buffer, amount btcutil.Amount) error {
  79. return WriteUint64(buf, uint64(amount))
  80. }
  81. // WriteMilliSatoshi appends the MilliSatoshi value to the provided buffer.
  82. func WriteMilliSatoshi(buf *bytes.Buffer, amount MilliSatoshi) error {
  83. return WriteUint64(buf, uint64(amount))
  84. }
  85. // WritePublicKey appends the compressed public key to the provided buffer.
  86. func WritePublicKey(buf *bytes.Buffer, pub *btcec.PublicKey) error {
  87. if pub == nil {
  88. return ErrNilPublicKey
  89. }
  90. serializedPubkey := pub.SerializeCompressed()
  91. return WriteBytes(buf, serializedPubkey)
  92. }
  93. // WriteChannelID appends the ChannelID to the provided buffer.
  94. func WriteChannelID(buf *bytes.Buffer, channelID ChannelID) error {
  95. return WriteBytes(buf, channelID[:])
  96. }
  97. // WriteNodeAlias appends the alias to the provided buffer.
  98. func WriteNodeAlias(buf *bytes.Buffer, alias NodeAlias) error {
  99. return WriteBytes(buf, alias[:])
  100. }
  101. // WriteShortChannelID appends the ShortChannelID to the provided buffer. It
  102. // encodes the BlockHeight and TxIndex each using 3 bytes with big endian byte
  103. // order, and encodes txPosition using 2 bytes with big endian byte order.
  104. func WriteShortChannelID(buf *bytes.Buffer, shortChanID ShortChannelID) error {
  105. // Check that field fit in 3 bytes and write the blockHeight
  106. if shortChanID.BlockHeight > ((1 << 24) - 1) {
  107. return errors.New("block height should fit in 3 bytes")
  108. }
  109. var blockHeight [4]byte
  110. binary.BigEndian.PutUint32(blockHeight[:], shortChanID.BlockHeight)
  111. if _, err := buf.Write(blockHeight[1:]); err != nil {
  112. return err
  113. }
  114. // Check that field fit in 3 bytes and write the txIndex
  115. if shortChanID.TxIndex > ((1 << 24) - 1) {
  116. return errors.New("tx index should fit in 3 bytes")
  117. }
  118. var txIndex [4]byte
  119. binary.BigEndian.PutUint32(txIndex[:], shortChanID.TxIndex)
  120. if _, err := buf.Write(txIndex[1:]); err != nil {
  121. return err
  122. }
  123. // Write the TxPosition
  124. return WriteUint16(buf, shortChanID.TxPosition)
  125. }
  126. // WriteSig appends the signature to the provided buffer.
  127. func WriteSig(buf *bytes.Buffer, sig Sig) error {
  128. return WriteBytes(buf, sig.bytes[:])
  129. }
  130. // WriteSigs appends the slice of signatures to the provided buffer with its
  131. // length.
  132. func WriteSigs(buf *bytes.Buffer, sigs []Sig) error {
  133. // Write the length of the sigs.
  134. if err := WriteUint16(buf, uint16(len(sigs))); err != nil {
  135. return err
  136. }
  137. for _, sig := range sigs {
  138. if err := WriteSig(buf, sig); err != nil {
  139. return err
  140. }
  141. }
  142. return nil
  143. }
  144. // WriteFailCode appends the FailCode to the provided buffer.
  145. func WriteFailCode(buf *bytes.Buffer, e FailCode) error {
  146. return WriteUint16(buf, uint16(e))
  147. }
  148. // WriteRawFeatureVector encodes the feature using the feature's Encode method
  149. // and appends the data to the provided buffer. An error will return if the
  150. // passed feature is nil.
  151. func WriteRawFeatureVector(buf *bytes.Buffer, feature *RawFeatureVector) error {
  152. if feature == nil {
  153. return ErrNilFeatureVector
  154. }
  155. return feature.Encode(buf)
  156. }
  157. // WriteColorRGBA appends the RGBA color using three bytes.
  158. func WriteColorRGBA(buf *bytes.Buffer, e color.RGBA) error {
  159. // Write R
  160. if err := WriteUint8(buf, e.R); err != nil {
  161. return err
  162. }
  163. // Write G
  164. if err := WriteUint8(buf, e.G); err != nil {
  165. return err
  166. }
  167. // Write B
  168. return WriteUint8(buf, e.B)
  169. }
  170. // WriteQueryEncoding appends the QueryEncoding to the provided buffer.
  171. func WriteQueryEncoding(buf *bytes.Buffer, e QueryEncoding) error {
  172. return WriteUint8(buf, uint8(e))
  173. }
  174. // WriteFundingFlag appends the FundingFlag to the provided buffer.
  175. func WriteFundingFlag(buf *bytes.Buffer, flag FundingFlag) error {
  176. return WriteUint8(buf, uint8(flag))
  177. }
  178. // WriteChanUpdateMsgFlags appends the update flag to the provided buffer.
  179. func WriteChanUpdateMsgFlags(buf *bytes.Buffer, f ChanUpdateMsgFlags) error {
  180. return WriteUint8(buf, uint8(f))
  181. }
  182. // WriteChanUpdateChanFlags appends the update flag to the provided buffer.
  183. func WriteChanUpdateChanFlags(buf *bytes.Buffer, f ChanUpdateChanFlags) error {
  184. return WriteUint8(buf, uint8(f))
  185. }
  186. // WriteDeliveryAddress appends the address to the provided buffer.
  187. func WriteDeliveryAddress(buf *bytes.Buffer, addr DeliveryAddress) error {
  188. return writeDataWithLength(buf, addr)
  189. }
  190. // WritePingPayload appends the payload to the provided buffer.
  191. func WritePingPayload(buf *bytes.Buffer, payload PingPayload) error {
  192. return writeDataWithLength(buf, payload)
  193. }
  194. // WritePongPayload appends the payload to the provided buffer.
  195. func WritePongPayload(buf *bytes.Buffer, payload PongPayload) error {
  196. return writeDataWithLength(buf, payload)
  197. }
  198. // WriteWarningData appends the data to the provided buffer.
  199. func WriteWarningData(buf *bytes.Buffer, data WarningData) error {
  200. return writeDataWithLength(buf, data)
  201. }
  202. // WriteErrorData appends the data to the provided buffer.
  203. func WriteErrorData(buf *bytes.Buffer, data ErrorData) error {
  204. return writeDataWithLength(buf, data)
  205. }
  206. // WriteOpaqueReason appends the reason to the provided buffer.
  207. func WriteOpaqueReason(buf *bytes.Buffer, reason OpaqueReason) error {
  208. return writeDataWithLength(buf, reason)
  209. }
  210. // WriteBool appends the boolean to the provided buffer.
  211. func WriteBool(buf *bytes.Buffer, b bool) error {
  212. if b {
  213. return WriteBytes(buf, []byte{1})
  214. }
  215. return WriteBytes(buf, []byte{0})
  216. }
  217. // WritePkScript appends the script to the provided buffer. Returns an error if
  218. // the provided script exceeds 34 bytes.
  219. func WritePkScript(buf *bytes.Buffer, s PkScript) error {
  220. // The largest script we'll accept is a p2wsh which is exactly
  221. // 34 bytes long.
  222. scriptLength := len(s)
  223. if scriptLength > 34 {
  224. return ErrPkScriptTooLong
  225. }
  226. return wire.WriteVarBytes(buf, 0, s)
  227. }
  228. // WriteOutPoint appends the outpoint to the provided buffer.
  229. func WriteOutPoint(buf *bytes.Buffer, p wire.OutPoint) error {
  230. // Before we write anything to the buffer, check the Index is sane.
  231. if p.Index > math.MaxUint16 {
  232. return ErrOutpointIndexTooBig(p.Index)
  233. }
  234. var h [32]byte
  235. copy(h[:], p.Hash[:])
  236. if _, err := buf.Write(h[:]); err != nil {
  237. return err
  238. }
  239. // Write the index using two bytes.
  240. return WriteUint16(buf, uint16(p.Index))
  241. }
  242. // WriteTCPAddr appends the TCP address to the provided buffer, either a IPv4
  243. // or a IPv6.
  244. func WriteTCPAddr(buf *bytes.Buffer, addr *net.TCPAddr) error {
  245. if addr == nil {
  246. return ErrNilTCPAddress
  247. }
  248. // Make a slice of bytes to hold the data of descriptor and ip. At
  249. // most, we need 17 bytes - 1 byte for the descriptor, 16 bytes for
  250. // IPv6.
  251. data := make([]byte, 0, 17)
  252. if addr.IP.To4() != nil {
  253. data = append(data, uint8(tcp4Addr))
  254. data = append(data, addr.IP.To4()...)
  255. } else {
  256. data = append(data, uint8(tcp6Addr))
  257. data = append(data, addr.IP.To16()...)
  258. }
  259. if _, err := buf.Write(data); err != nil {
  260. return err
  261. }
  262. return WriteUint16(buf, uint16(addr.Port))
  263. }
  264. // WriteOnionAddr appends the onion address to the provided buffer.
  265. func WriteOnionAddr(buf *bytes.Buffer, addr *tor.OnionAddr) error {
  266. if addr == nil {
  267. return ErrNilOnionAddress
  268. }
  269. var (
  270. suffixIndex int
  271. descriptor []byte
  272. )
  273. // Decide the suffixIndex and descriptor.
  274. switch len(addr.OnionService) {
  275. case tor.V2Len:
  276. descriptor = []byte{byte(v2OnionAddr)}
  277. suffixIndex = tor.V2Len - tor.OnionSuffixLen
  278. case tor.V3Len:
  279. descriptor = []byte{byte(v3OnionAddr)}
  280. suffixIndex = tor.V3Len - tor.OnionSuffixLen
  281. default:
  282. return ErrUnknownServiceLength
  283. }
  284. // Decode the address.
  285. host, err := tor.Base32Encoding.DecodeString(
  286. addr.OnionService[:suffixIndex],
  287. )
  288. if err != nil {
  289. return err
  290. }
  291. // Perform the actual write when the above checks passed.
  292. if _, err := buf.Write(descriptor); err != nil {
  293. return err
  294. }
  295. if _, err := buf.Write(host); err != nil {
  296. return err
  297. }
  298. return WriteUint16(buf, uint16(addr.Port))
  299. }
  300. // WriteOpaqueAddrs appends the payload of the given OpaqueAddrs to buffer.
  301. func WriteOpaqueAddrs(buf *bytes.Buffer, addr *OpaqueAddrs) error {
  302. if addr == nil {
  303. return ErrNilOpaqueAddrs
  304. }
  305. _, err := buf.Write(addr.Payload)
  306. return err
  307. }
  308. // WriteNetAddrs appends a slice of addresses to the provided buffer with the
  309. // length info.
  310. func WriteNetAddrs(buf *bytes.Buffer, addresses []net.Addr) error {
  311. // First, we'll encode all the addresses into an intermediate
  312. // buffer. We need to do this in order to compute the total
  313. // length of the addresses.
  314. buffer := make([]byte, 0, MaxMsgBody)
  315. addrBuf := bytes.NewBuffer(buffer)
  316. for _, address := range addresses {
  317. switch a := address.(type) {
  318. case *net.TCPAddr:
  319. if err := WriteTCPAddr(addrBuf, a); err != nil {
  320. return err
  321. }
  322. case *tor.OnionAddr:
  323. if err := WriteOnionAddr(addrBuf, a); err != nil {
  324. return err
  325. }
  326. case *OpaqueAddrs:
  327. if err := WriteOpaqueAddrs(addrBuf, a); err != nil {
  328. return err
  329. }
  330. default:
  331. return ErrNilNetAddress
  332. }
  333. }
  334. // With the addresses fully encoded, we can now write out data.
  335. return writeDataWithLength(buf, addrBuf.Bytes())
  336. }
  337. // writeDataWithLength writes the data and its length to the buffer.
  338. func writeDataWithLength(buf *bytes.Buffer, data []byte) error {
  339. var l [2]byte
  340. binary.BigEndian.PutUint16(l[:], uint16(len(data)))
  341. if _, err := buf.Write(l[:]); err != nil {
  342. return err
  343. }
  344. _, err := buf.Write(data)
  345. return err
  346. }