message_test.go 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. package lnwire_test
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "image/color"
  7. "io"
  8. "math"
  9. "math/rand"
  10. "net"
  11. "sync"
  12. "testing"
  13. "github.com/btcsuite/btcd/btcec/v2"
  14. "github.com/btcsuite/btcd/btcec/v2/ecdsa"
  15. "github.com/btcsuite/btcd/btcutil"
  16. "github.com/lightningnetwork/lnd/lnwire"
  17. "github.com/lightningnetwork/lnd/tor"
  18. "github.com/stretchr/testify/mock"
  19. "github.com/stretchr/testify/require"
  20. )
  21. const deliveryAddressMaxSize = 34
  22. const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  23. var (
  24. testSig = &ecdsa.Signature{}
  25. testNodeSig, _ = lnwire.NewSigFromSignature(testSig)
  26. testNumExtraBytes = 1000
  27. testNumSigs = 100
  28. testNumChanIDs = 1000
  29. buffer = make([]byte, 0, lnwire.MaxSliceLength)
  30. bufPool = sync.Pool{
  31. New: func() interface{} {
  32. return bytes.NewBuffer(buffer)
  33. },
  34. }
  35. )
  36. type mockMsg struct {
  37. mock.Mock
  38. }
  39. func (m *mockMsg) Decode(r io.Reader, pver uint32) error {
  40. args := m.Called(r, pver)
  41. return args.Error(0)
  42. }
  43. func (m *mockMsg) Encode(w *bytes.Buffer, pver uint32) error {
  44. args := m.Called(w, pver)
  45. return args.Error(0)
  46. }
  47. func (m *mockMsg) MsgType() lnwire.MessageType {
  48. args := m.Called()
  49. return lnwire.MessageType(args.Int(0))
  50. }
  51. // A compile time check to ensure mockMsg implements the lnwire.Message
  52. // interface.
  53. var _ lnwire.Message = (*mockMsg)(nil)
  54. // TestWriteMessage tests the function lnwire.WriteMessage.
  55. func TestWriteMessage(t *testing.T) {
  56. var (
  57. buf = new(bytes.Buffer)
  58. // encodeNormalSize specifies a message size that is normal.
  59. encodeNormalSize = 1000
  60. // encodeOversize specifies a message size that's too big.
  61. encodeOversize = lnwire.MaxMsgBody + 1
  62. // errDummy is returned by the msg.Encode when specified.
  63. errDummy = errors.New("test error")
  64. // oneByte is a dummy byte used to fill up the buffer.
  65. oneByte = [1]byte{}
  66. )
  67. testCases := []struct {
  68. name string
  69. // encodeSize controls how many bytes are written to the buffer
  70. // by the method msg.Encode(buf, pver).
  71. encodeSize int
  72. // encodeErr determines the return value of the method
  73. // msg.Encode(buf, pver).
  74. encodeErr error
  75. errorExpected error
  76. }{
  77. {
  78. name: "successful write",
  79. encodeSize: encodeNormalSize,
  80. encodeErr: nil,
  81. errorExpected: nil,
  82. },
  83. {
  84. name: "failed to encode payload",
  85. encodeSize: encodeNormalSize,
  86. encodeErr: errDummy,
  87. errorExpected: lnwire.ErrorEncodeMessage(errDummy),
  88. },
  89. {
  90. name: "exceeds MaxMsgBody",
  91. encodeSize: encodeOversize,
  92. encodeErr: nil,
  93. errorExpected: lnwire.ErrorPayloadTooLarge(
  94. encodeOversize,
  95. ),
  96. },
  97. }
  98. for _, test := range testCases {
  99. tc := test
  100. t.Run(tc.name, func(t *testing.T) {
  101. // Start the test by creating a mock message and patch
  102. // the relevant methods.
  103. msg := &mockMsg{}
  104. // Use message type Ping here since all types are
  105. // encoded using 2 bytes, it won't affect anything
  106. // here.
  107. msg.On("MsgType").Return(lnwire.MsgPing)
  108. // Encode will return the specified error (could be
  109. // nil) and has the side effect of filling up the
  110. // buffer by repeating the oneByte encodeSize times.
  111. msg.On("Encode", mock.Anything, mock.Anything).Return(
  112. tc.encodeErr,
  113. ).Run(func(_ mock.Arguments) {
  114. for i := 0; i < tc.encodeSize; i++ {
  115. _, err := buf.Write(oneByte[:])
  116. require.NoError(t, err)
  117. }
  118. })
  119. // Record the initial state of the buffer and write the
  120. // message.
  121. oldBytesSize := buf.Len()
  122. bytesWritten, err := lnwire.WriteMessage(
  123. buf, msg, 1,
  124. )
  125. // Check that the returned error is expected.
  126. require.Equal(
  127. t, tc.errorExpected, err, "unexpected err",
  128. )
  129. // If there's an error, no bytes should be written to
  130. // the buf.
  131. if tc.errorExpected != nil {
  132. require.Equal(
  133. t, 0, bytesWritten,
  134. "bytes written should be 0",
  135. )
  136. // We also check that the old buf was not
  137. // affected.
  138. require.Equal(
  139. t, oldBytesSize, buf.Len(),
  140. "original buffer should not change",
  141. )
  142. } else {
  143. expected := buf.Len() - oldBytesSize
  144. require.Equal(
  145. t, expected, bytesWritten,
  146. "bytes written not matched",
  147. )
  148. }
  149. // Finally, check the mocked methods are called as
  150. // expected.
  151. msg.AssertExpectations(t)
  152. })
  153. }
  154. }
  155. // BenchmarkWriteMessage benchmarks the performance of lnwire.WriteMessage. It
  156. // generates a test message for each of the lnwire.Message, calls the
  157. // WriteMessage method and benchmark it.
  158. func BenchmarkWriteMessage(b *testing.B) {
  159. // Create testing messages. We will use a constant seed to make sure
  160. // the benchmark uses the same data every time.
  161. r := rand.New(rand.NewSource(42))
  162. msgAll := makeAllMessages(b, r)
  163. // Iterate all messages and write each once.
  164. for _, msg := range msgAll {
  165. m := msg
  166. // Run each message as a sub benchmark test.
  167. b.Run(msg.MsgType().String(), func(b *testing.B) {
  168. b.ResetTimer()
  169. for i := 0; i < b.N; i++ {
  170. // Fetch a buffer from the pool and reset it.
  171. buf := bufPool.Get().(*bytes.Buffer)
  172. buf.Reset()
  173. _, err := lnwire.WriteMessage(buf, m, 0)
  174. require.NoError(b, err, "unable to write msg")
  175. // Put the buffer back when done.
  176. bufPool.Put(buf)
  177. }
  178. })
  179. }
  180. }
  181. // BenchmarkReadMessage benchmarks the performance of lnwire.ReadMessage. It
  182. // first creates a test message for each of the lnwire.Message, writes it to
  183. // the buffer, then later reads it from the buffer.
  184. func BenchmarkReadMessage(b *testing.B) {
  185. // Create testing messages. We will use a constant seed to make sure
  186. // the benchmark uses the same data every time.
  187. r := rand.New(rand.NewSource(42))
  188. msgAll := makeAllMessages(b, r)
  189. // Write all the messages to the buffer.
  190. for _, msg := range msgAll {
  191. // Fetch a buffer from the pool and reset it.
  192. buf := bufPool.Get().(*bytes.Buffer)
  193. buf.Reset()
  194. _, err := lnwire.WriteMessage(buf, msg, 0)
  195. require.NoError(b, err, "unable to write msg")
  196. // Run each message as a sub benchmark test.
  197. m := msg
  198. b.Run(m.MsgType().String(), func(b *testing.B) {
  199. b.ResetTimer()
  200. for i := 0; i < b.N; i++ {
  201. r := bytes.NewBuffer(buf.Bytes())
  202. // Read the message from the buffer.
  203. _, err := lnwire.ReadMessage(r, 0)
  204. require.NoError(b, err, "unable to read msg")
  205. }
  206. })
  207. // Put the buffer back when done.
  208. bufPool.Put(buf)
  209. }
  210. }
  211. // makeAllMessages is used to create testing messages for each lnwire message
  212. // type.
  213. //
  214. // TODO(yy): the following testing messages are created somewhat arbitrary. We
  215. // should standardize each of the testing messages so that a better baseline
  216. // can be used.
  217. func makeAllMessages(t testing.TB, r *rand.Rand) []lnwire.Message {
  218. msgAll := []lnwire.Message{}
  219. msgAll = append(msgAll, newMsgWarning(t, r))
  220. msgAll = append(msgAll, newMsgInit(t, r))
  221. msgAll = append(msgAll, newMsgError(t, r))
  222. msgAll = append(msgAll, newMsgPing(t, r))
  223. msgAll = append(msgAll, newMsgPong(t, r))
  224. msgAll = append(msgAll, newMsgOpenChannel(t, r))
  225. msgAll = append(msgAll, newMsgAcceptChannel(t, r))
  226. msgAll = append(msgAll, newMsgFundingCreated(t, r))
  227. msgAll = append(msgAll, newMsgFundingSigned(t, r))
  228. msgAll = append(msgAll, newMsgChannelReady(t, r))
  229. msgAll = append(msgAll, newMsgShutdown(t, r))
  230. msgAll = append(msgAll, newMsgClosingSigned(t, r))
  231. msgAll = append(msgAll, newMsgUpdateAddHTLC(t, r))
  232. msgAll = append(msgAll, newMsgUpdateFulfillHTLC(t, r))
  233. msgAll = append(msgAll, newMsgUpdateFailHTLC(t, r))
  234. msgAll = append(msgAll, newMsgCommitSig(t, r))
  235. msgAll = append(msgAll, newMsgRevokeAndAck(t, r))
  236. msgAll = append(msgAll, newMsgUpdateFee(t, r))
  237. msgAll = append(msgAll, newMsgUpdateFailMalformedHTLC(t, r))
  238. msgAll = append(msgAll, newMsgChannelReestablish(t, r))
  239. msgAll = append(msgAll, newMsgChannelAnnouncement(t, r))
  240. msgAll = append(msgAll, newMsgNodeAnnouncement(t, r))
  241. msgAll = append(msgAll, newMsgChannelUpdate(t, r))
  242. msgAll = append(msgAll, newMsgAnnounceSignatures(t, r))
  243. msgAll = append(msgAll, newMsgQueryShortChanIDs(t, r))
  244. msgAll = append(msgAll, newMsgReplyShortChanIDsEnd(t, r))
  245. msgAll = append(msgAll, newMsgQueryChannelRange(t, r))
  246. msgAll = append(msgAll, newMsgReplyChannelRange(t, r))
  247. msgAll = append(msgAll, newMsgGossipTimestampRange(t, r))
  248. msgAll = append(msgAll, newMsgQueryShortChanIDsZlib(t, r))
  249. msgAll = append(msgAll, newMsgReplyChannelRangeZlib(t, r))
  250. return msgAll
  251. }
  252. func newMsgWarning(tb testing.TB, r io.Reader) *lnwire.Warning {
  253. tb.Helper()
  254. msg := lnwire.NewWarning()
  255. _, err := r.Read(msg.ChanID[:])
  256. require.NoError(tb, err, "unable to generate chan id")
  257. msg.Data = createExtraData(tb, r)
  258. return msg
  259. }
  260. func newMsgInit(t testing.TB, r io.Reader) *lnwire.Init {
  261. t.Helper()
  262. return &lnwire.Init{
  263. GlobalFeatures: rawFeatureVector(),
  264. Features: rawFeatureVector(),
  265. ExtraData: createExtraData(t, r),
  266. }
  267. }
  268. // newMsgOpenChannel creates a testing OpenChannel message.
  269. func newMsgOpenChannel(t testing.TB, r *rand.Rand) *lnwire.OpenChannel {
  270. t.Helper()
  271. msg := &lnwire.OpenChannel{
  272. FundingAmount: btcutil.Amount(r.Int63()),
  273. PushAmount: lnwire.MilliSatoshi(r.Int63()),
  274. DustLimit: btcutil.Amount(r.Int63()),
  275. MaxValueInFlight: lnwire.MilliSatoshi(r.Int63()),
  276. ChannelReserve: btcutil.Amount(r.Int63()),
  277. HtlcMinimum: lnwire.MilliSatoshi(r.Int63()),
  278. FeePerKiloWeight: uint32(r.Int31()),
  279. CsvDelay: uint16(r.Intn(1 << 16)),
  280. MaxAcceptedHTLCs: uint16(r.Intn(1 << 16)),
  281. ChannelFlags: lnwire.FundingFlag(uint8(r.Intn(1 << 8))),
  282. FundingKey: randPubKey(t),
  283. RevocationPoint: randPubKey(t),
  284. PaymentPoint: randPubKey(t),
  285. DelayedPaymentPoint: randPubKey(t),
  286. HtlcPoint: randPubKey(t),
  287. FirstCommitmentPoint: randPubKey(t),
  288. ExtraData: createExtraData(t, r),
  289. }
  290. _, err := r.Read(msg.ChainHash[:])
  291. require.NoError(t, err, "unable to read bytes for ChainHash")
  292. _, err = r.Read(msg.PendingChannelID[:])
  293. require.NoError(t, err, "unable to read bytes for PendingChannelID")
  294. return msg
  295. }
  296. func newMsgAcceptChannel(t testing.TB, r *rand.Rand) *lnwire.AcceptChannel {
  297. t.Helper()
  298. msg := &lnwire.AcceptChannel{
  299. DustLimit: btcutil.Amount(r.Int63()),
  300. MaxValueInFlight: lnwire.MilliSatoshi(r.Int63()),
  301. ChannelReserve: btcutil.Amount(r.Int63()),
  302. MinAcceptDepth: uint32(r.Int31()),
  303. HtlcMinimum: lnwire.MilliSatoshi(r.Int63()),
  304. CsvDelay: uint16(r.Intn(1 << 16)),
  305. MaxAcceptedHTLCs: uint16(r.Intn(1 << 16)),
  306. FundingKey: randPubKey(t),
  307. RevocationPoint: randPubKey(t),
  308. PaymentPoint: randPubKey(t),
  309. DelayedPaymentPoint: randPubKey(t),
  310. HtlcPoint: randPubKey(t),
  311. FirstCommitmentPoint: randPubKey(t),
  312. UpfrontShutdownScript: randDeliveryAddress(t, r),
  313. ExtraData: createExtraData(t, r),
  314. }
  315. _, err := r.Read(msg.PendingChannelID[:])
  316. require.NoError(t, err, "unable to generate pending chan id")
  317. return msg
  318. }
  319. func newMsgError(t testing.TB, r io.Reader) *lnwire.Error {
  320. t.Helper()
  321. msg := lnwire.NewError()
  322. _, err := r.Read(msg.ChanID[:])
  323. require.NoError(t, err, "unable to generate chan id")
  324. msg.Data = createExtraData(t, r)
  325. return msg
  326. }
  327. func newMsgPing(t testing.TB, r *rand.Rand) *lnwire.Ping {
  328. t.Helper()
  329. return &lnwire.Ping{
  330. NumPongBytes: uint16(r.Intn(1 << 16)),
  331. PaddingBytes: createExtraData(t, r),
  332. }
  333. }
  334. func newMsgPong(t testing.TB, r io.Reader) *lnwire.Pong {
  335. t.Helper()
  336. return &lnwire.Pong{
  337. PongBytes: createExtraData(t, r),
  338. }
  339. }
  340. func newMsgFundingCreated(t testing.TB, r *rand.Rand) *lnwire.FundingCreated {
  341. t.Helper()
  342. msg := &lnwire.FundingCreated{
  343. CommitSig: testNodeSig,
  344. ExtraData: createExtraData(t, r),
  345. }
  346. _, err := r.Read(msg.PendingChannelID[:])
  347. require.NoError(t, err, "unable to generate pending chan id")
  348. _, err = r.Read(msg.FundingPoint.Hash[:])
  349. require.NoError(t, err, "unable to generate hash")
  350. msg.FundingPoint.Index = uint32(r.Int31()) % math.MaxUint16
  351. return msg
  352. }
  353. func newMsgFundingSigned(t testing.TB, r io.Reader) *lnwire.FundingSigned {
  354. t.Helper()
  355. var c [32]byte
  356. _, err := r.Read(c[:])
  357. require.NoError(t, err, "unable to generate chan id")
  358. msg := &lnwire.FundingSigned{
  359. ChanID: lnwire.ChannelID(c),
  360. CommitSig: testNodeSig,
  361. ExtraData: createExtraData(t, r),
  362. }
  363. return msg
  364. }
  365. func newMsgChannelReady(t testing.TB, r io.Reader) *lnwire.ChannelReady {
  366. t.Helper()
  367. var c [32]byte
  368. _, err := r.Read(c[:])
  369. require.NoError(t, err, "unable to generate chan id")
  370. pubKey := randPubKey(t)
  371. // When testing the ChannelReady msg type in the WriteMessage
  372. // function we need to populate the alias here to test the encoding
  373. // of the TLV stream.
  374. aliasScid := lnwire.NewShortChanIDFromInt(rand.Uint64())
  375. msg := &lnwire.ChannelReady{
  376. ChanID: lnwire.ChannelID(c),
  377. NextPerCommitmentPoint: pubKey,
  378. AliasScid: &aliasScid,
  379. ExtraData: make([]byte, 0),
  380. }
  381. // We do not include the TLV record (aliasScid) into the ExtraData
  382. // because when the msg is encoded the ExtraData is overwritten
  383. // with the current aliasScid value.
  384. return msg
  385. }
  386. func newMsgShutdown(t testing.TB, r *rand.Rand) *lnwire.Shutdown {
  387. t.Helper()
  388. msg := &lnwire.Shutdown{
  389. Address: randDeliveryAddress(t, r),
  390. ExtraData: createExtraData(t, r),
  391. }
  392. _, err := r.Read(msg.ChannelID[:])
  393. require.NoError(t, err, "unable to generate channel id")
  394. return msg
  395. }
  396. func newMsgClosingSigned(t testing.TB, r *rand.Rand) *lnwire.ClosingSigned {
  397. t.Helper()
  398. msg := &lnwire.ClosingSigned{
  399. FeeSatoshis: btcutil.Amount(r.Int63()),
  400. Signature: testNodeSig,
  401. ExtraData: createExtraData(t, r),
  402. }
  403. _, err := r.Read(msg.ChannelID[:])
  404. require.NoError(t, err, "unable to generate chan id")
  405. return msg
  406. }
  407. func newMsgUpdateAddHTLC(t testing.TB, r *rand.Rand) *lnwire.UpdateAddHTLC {
  408. t.Helper()
  409. msg := &lnwire.UpdateAddHTLC{
  410. ID: r.Uint64(),
  411. Amount: lnwire.MilliSatoshi(r.Int63()),
  412. Expiry: r.Uint32(),
  413. ExtraData: createExtraData(t, r),
  414. }
  415. _, err := r.Read(msg.ChanID[:])
  416. require.NoError(t, err, "unable to generate chan id")
  417. _, err = r.Read(msg.PaymentHash[:])
  418. require.NoError(t, err, "unable to generate paymenthash")
  419. _, err = r.Read(msg.OnionBlob[:])
  420. require.NoError(t, err, "unable to generate onion blob")
  421. return msg
  422. }
  423. func newMsgUpdateFulfillHTLC(t testing.TB,
  424. r *rand.Rand) *lnwire.UpdateFulfillHTLC {
  425. t.Helper()
  426. msg := &lnwire.UpdateFulfillHTLC{
  427. ID: r.Uint64(),
  428. ExtraData: createExtraData(t, r),
  429. }
  430. _, err := r.Read(msg.ChanID[:])
  431. require.NoError(t, err, "unable to generate chan id")
  432. _, err = r.Read(msg.PaymentPreimage[:])
  433. require.NoError(t, err, "unable to generate payment preimage")
  434. return msg
  435. }
  436. func newMsgUpdateFailHTLC(t testing.TB, r *rand.Rand) *lnwire.UpdateFailHTLC {
  437. t.Helper()
  438. msg := &lnwire.UpdateFailHTLC{
  439. ID: r.Uint64(),
  440. ExtraData: createExtraData(t, r),
  441. }
  442. _, err := r.Read(msg.ChanID[:])
  443. require.NoError(t, err, "unable to generate chan id")
  444. return msg
  445. }
  446. func newMsgCommitSig(t testing.TB, r io.Reader) *lnwire.CommitSig {
  447. t.Helper()
  448. msg := lnwire.NewCommitSig()
  449. _, err := r.Read(msg.ChanID[:])
  450. require.NoError(t, err, "unable to generate chan id")
  451. msg.CommitSig = testNodeSig
  452. msg.ExtraData = createExtraData(t, r)
  453. msg.HtlcSigs = make([]lnwire.Sig, testNumSigs)
  454. for i := 0; i < testNumSigs; i++ {
  455. msg.HtlcSigs[i] = testNodeSig
  456. }
  457. return msg
  458. }
  459. func newMsgRevokeAndAck(t testing.TB, r io.Reader) *lnwire.RevokeAndAck {
  460. t.Helper()
  461. msg := lnwire.NewRevokeAndAck()
  462. _, err := r.Read(msg.ChanID[:])
  463. require.NoError(t, err, "unable to generate chan id")
  464. _, err = r.Read(msg.Revocation[:])
  465. require.NoError(t, err, "unable to generate bytes")
  466. msg.NextRevocationKey = randPubKey(t)
  467. require.NoError(t, err, "unable to generate key")
  468. msg.ExtraData = createExtraData(t, r)
  469. return msg
  470. }
  471. func newMsgUpdateFee(t testing.TB, r *rand.Rand) *lnwire.UpdateFee {
  472. t.Helper()
  473. msg := &lnwire.UpdateFee{
  474. FeePerKw: uint32(r.Int31()),
  475. ExtraData: createExtraData(t, r),
  476. }
  477. _, err := r.Read(msg.ChanID[:])
  478. require.NoError(t, err, "unable to generate chan id")
  479. return msg
  480. }
  481. func newMsgUpdateFailMalformedHTLC(t testing.TB,
  482. r *rand.Rand) *lnwire.UpdateFailMalformedHTLC {
  483. t.Helper()
  484. msg := &lnwire.UpdateFailMalformedHTLC{
  485. ID: r.Uint64(),
  486. FailureCode: lnwire.FailCode(r.Intn(1 << 16)),
  487. ExtraData: createExtraData(t, r),
  488. }
  489. _, err := r.Read(msg.ChanID[:])
  490. require.NoError(t, err, "unable to generate chan id")
  491. _, err = r.Read(msg.ShaOnionBlob[:])
  492. require.NoError(t, err, "unable to generate sha256 onion blob")
  493. return msg
  494. }
  495. func newMsgChannelReestablish(t testing.TB,
  496. r *rand.Rand) *lnwire.ChannelReestablish {
  497. t.Helper()
  498. msg := &lnwire.ChannelReestablish{
  499. NextLocalCommitHeight: uint64(r.Int63()),
  500. RemoteCommitTailHeight: uint64(r.Int63()),
  501. LocalUnrevokedCommitPoint: randPubKey(t),
  502. ExtraData: createExtraData(t, r),
  503. }
  504. _, err := r.Read(msg.LastRemoteCommitSecret[:])
  505. require.NoError(t, err, "unable to read commit secret")
  506. return msg
  507. }
  508. func newMsgChannelAnnouncement(t testing.TB,
  509. r *rand.Rand) *lnwire.ChannelAnnouncement {
  510. t.Helper()
  511. msg := &lnwire.ChannelAnnouncement{
  512. ShortChannelID: lnwire.NewShortChanIDFromInt(uint64(r.Int63())),
  513. Features: rawFeatureVector(),
  514. NodeID1: randRawKey(t),
  515. NodeID2: randRawKey(t),
  516. BitcoinKey1: randRawKey(t),
  517. BitcoinKey2: randRawKey(t),
  518. ExtraOpaqueData: createExtraData(t, r),
  519. NodeSig1: testNodeSig,
  520. NodeSig2: testNodeSig,
  521. BitcoinSig1: testNodeSig,
  522. BitcoinSig2: testNodeSig,
  523. }
  524. _, err := r.Read(msg.ChainHash[:])
  525. require.NoError(t, err, "unable to generate chain hash")
  526. return msg
  527. }
  528. func newMsgNodeAnnouncement(t testing.TB,
  529. r *rand.Rand) *lnwire.NodeAnnouncement {
  530. t.Helper()
  531. msg := &lnwire.NodeAnnouncement{
  532. Features: rawFeatureVector(),
  533. Timestamp: uint32(r.Int31()),
  534. Alias: randAlias(r),
  535. RGBColor: color.RGBA{
  536. R: uint8(r.Intn(1 << 8)),
  537. G: uint8(r.Intn(1 << 8)),
  538. B: uint8(r.Intn(1 << 8)),
  539. },
  540. NodeID: randRawKey(t),
  541. Addresses: randAddrs(t, r),
  542. ExtraOpaqueData: createExtraData(t, r),
  543. Signature: testNodeSig,
  544. }
  545. return msg
  546. }
  547. func newMsgChannelUpdate(t testing.TB, r *rand.Rand) *lnwire.ChannelUpdate {
  548. t.Helper()
  549. msgFlags := lnwire.ChanUpdateMsgFlags(r.Int31())
  550. maxHtlc := lnwire.MilliSatoshi(r.Int63())
  551. // We make the max_htlc field zero if it is not flagged
  552. // as being part of the ChannelUpdate, to pass
  553. // serialization tests, as it will be ignored if the bit
  554. // is not set.
  555. if msgFlags&lnwire.ChanUpdateRequiredMaxHtlc == 0 {
  556. maxHtlc = 0
  557. }
  558. msg := &lnwire.ChannelUpdate{
  559. ShortChannelID: lnwire.NewShortChanIDFromInt(r.Uint64()),
  560. Timestamp: uint32(r.Int31()),
  561. MessageFlags: msgFlags,
  562. ChannelFlags: lnwire.ChanUpdateChanFlags(r.Int31()),
  563. TimeLockDelta: uint16(r.Int31()),
  564. HtlcMinimumMsat: lnwire.MilliSatoshi(r.Int63()),
  565. HtlcMaximumMsat: maxHtlc,
  566. BaseFee: uint32(r.Int31()),
  567. FeeRate: uint32(r.Int31()),
  568. ExtraOpaqueData: createExtraData(t, r),
  569. Signature: testNodeSig,
  570. }
  571. _, err := r.Read(msg.ChainHash[:])
  572. require.NoError(t, err, "unable to generate chain hash")
  573. return msg
  574. }
  575. func newMsgAnnounceSignatures(t testing.TB,
  576. r *rand.Rand) *lnwire.AnnounceSignatures {
  577. t.Helper()
  578. msg := &lnwire.AnnounceSignatures{
  579. ShortChannelID: lnwire.NewShortChanIDFromInt(
  580. uint64(r.Int63()),
  581. ),
  582. ExtraOpaqueData: createExtraData(t, r),
  583. NodeSignature: testNodeSig,
  584. BitcoinSignature: testNodeSig,
  585. }
  586. _, err := r.Read(msg.ChannelID[:])
  587. require.NoError(t, err, "unable to generate chan id")
  588. return msg
  589. }
  590. func newMsgQueryShortChanIDs(t testing.TB,
  591. r *rand.Rand) *lnwire.QueryShortChanIDs {
  592. t.Helper()
  593. msg := &lnwire.QueryShortChanIDs{
  594. EncodingType: lnwire.EncodingSortedPlain,
  595. ExtraData: createExtraData(t, r),
  596. }
  597. _, err := rand.Read(msg.ChainHash[:])
  598. require.NoError(t, err, "unable to read chain hash")
  599. for i := 0; i < testNumChanIDs; i++ {
  600. msg.ShortChanIDs = append(msg.ShortChanIDs,
  601. lnwire.NewShortChanIDFromInt(uint64(r.Int63())))
  602. }
  603. return msg
  604. }
  605. func newMsgQueryShortChanIDsZlib(t testing.TB,
  606. r *rand.Rand) *lnwire.QueryShortChanIDs {
  607. t.Helper()
  608. msg := &lnwire.QueryShortChanIDs{
  609. EncodingType: lnwire.EncodingSortedZlib,
  610. ExtraData: createExtraData(t, r),
  611. }
  612. _, err := rand.Read(msg.ChainHash[:])
  613. require.NoError(t, err, "unable to read chain hash")
  614. for i := 0; i < testNumChanIDs; i++ {
  615. msg.ShortChanIDs = append(msg.ShortChanIDs,
  616. lnwire.NewShortChanIDFromInt(uint64(r.Int63())))
  617. }
  618. return msg
  619. }
  620. func newMsgReplyShortChanIDsEnd(t testing.TB,
  621. r *rand.Rand) *lnwire.ReplyShortChanIDsEnd {
  622. t.Helper()
  623. msg := lnwire.NewReplyShortChanIDsEnd()
  624. _, err := rand.Read(msg.ChainHash[:])
  625. require.NoError(t, err, "unable to read chain hash")
  626. msg.Complete = uint8(r.Int31n(2))
  627. msg.ExtraData = createExtraData(t, r)
  628. return msg
  629. }
  630. func newMsgQueryChannelRange(t testing.TB,
  631. r *rand.Rand) *lnwire.QueryChannelRange {
  632. t.Helper()
  633. msg := lnwire.NewQueryChannelRange()
  634. _, err := rand.Read(msg.ChainHash[:])
  635. require.NoError(t, err, "unable to read chain hash")
  636. msg.FirstBlockHeight = r.Uint32()
  637. msg.NumBlocks = r.Uint32()
  638. msg.ExtraData = createExtraData(t, r)
  639. return msg
  640. }
  641. func newMsgReplyChannelRange(t testing.TB,
  642. r *rand.Rand) *lnwire.ReplyChannelRange {
  643. t.Helper()
  644. msg := &lnwire.ReplyChannelRange{
  645. EncodingType: lnwire.EncodingSortedPlain,
  646. ExtraData: createExtraData(t, r),
  647. }
  648. _, err := rand.Read(msg.ChainHash[:])
  649. require.NoError(t, err, "unable to read chain hash")
  650. msg.Complete = uint8(r.Int31n(2))
  651. for i := 0; i < testNumChanIDs; i++ {
  652. msg.ShortChanIDs = append(msg.ShortChanIDs,
  653. lnwire.NewShortChanIDFromInt(uint64(r.Int63())))
  654. }
  655. return msg
  656. }
  657. func newMsgReplyChannelRangeZlib(t testing.TB,
  658. r *rand.Rand) *lnwire.ReplyChannelRange {
  659. t.Helper()
  660. msg := &lnwire.ReplyChannelRange{
  661. EncodingType: lnwire.EncodingSortedZlib,
  662. ExtraData: createExtraData(t, r),
  663. }
  664. _, err := rand.Read(msg.ChainHash[:])
  665. require.NoError(t, err, "unable to read chain hash")
  666. msg.Complete = uint8(r.Int31n(2))
  667. for i := 0; i < testNumChanIDs; i++ {
  668. msg.ShortChanIDs = append(msg.ShortChanIDs,
  669. lnwire.NewShortChanIDFromInt(uint64(r.Int63())))
  670. }
  671. return msg
  672. }
  673. func newMsgGossipTimestampRange(t testing.TB,
  674. r *rand.Rand) *lnwire.GossipTimestampRange {
  675. t.Helper()
  676. msg := lnwire.NewGossipTimestampRange()
  677. msg.FirstTimestamp = r.Uint32()
  678. msg.TimestampRange = r.Uint32()
  679. msg.ExtraData = createExtraData(t, r)
  680. _, err := r.Read(msg.ChainHash[:])
  681. require.NoError(t, err, "unable to read chain hash")
  682. return msg
  683. }
  684. func randRawKey(t testing.TB) [33]byte {
  685. t.Helper()
  686. var n [33]byte
  687. priv, err := btcec.NewPrivateKey()
  688. require.NoError(t, err, "failed to create privKey")
  689. copy(n[:], priv.PubKey().SerializeCompressed())
  690. return n
  691. }
  692. func randPubKey(t testing.TB) *btcec.PublicKey {
  693. t.Helper()
  694. priv, err := btcec.NewPrivateKey()
  695. require.NoError(t, err, "failed to create pubkey")
  696. return priv.PubKey()
  697. }
  698. func rawFeatureVector() *lnwire.RawFeatureVector {
  699. // Get a slice of known feature bits.
  700. featureBits := make([]lnwire.FeatureBit, 0, len(lnwire.Features))
  701. for fb := range lnwire.Features {
  702. featureBits = append(featureBits, fb)
  703. }
  704. featureVec := lnwire.NewRawFeatureVector(featureBits...)
  705. return featureVec
  706. }
  707. func randDeliveryAddress(t testing.TB, r *rand.Rand) lnwire.DeliveryAddress {
  708. t.Helper()
  709. // Generate a max sized address.
  710. size := r.Intn(deliveryAddressMaxSize) + 1
  711. da := lnwire.DeliveryAddress(make([]byte, size))
  712. _, err := r.Read(da)
  713. require.NoError(t, err, "unable to read address")
  714. return da
  715. }
  716. func randTCP4Addr(t testing.TB, r *rand.Rand) *net.TCPAddr {
  717. t.Helper()
  718. var ip [4]byte
  719. _, err := r.Read(ip[:])
  720. require.NoError(t, err, "unable to read ip")
  721. var port [2]byte
  722. _, err = r.Read(port[:])
  723. require.NoError(t, err, "unable to read port")
  724. addrIP := net.IP(ip[:])
  725. addrPort := int(binary.BigEndian.Uint16(port[:]))
  726. return &net.TCPAddr{IP: addrIP, Port: addrPort}
  727. }
  728. func randTCP6Addr(t testing.TB, r *rand.Rand) *net.TCPAddr {
  729. t.Helper()
  730. var ip [16]byte
  731. _, err := r.Read(ip[:])
  732. require.NoError(t, err, "unable to read ip")
  733. var port [2]byte
  734. _, err = r.Read(port[:])
  735. require.NoError(t, err, "unable to read port")
  736. addrIP := net.IP(ip[:])
  737. addrPort := int(binary.BigEndian.Uint16(port[:]))
  738. return &net.TCPAddr{IP: addrIP, Port: addrPort}
  739. }
  740. func randV2OnionAddr(t testing.TB, r *rand.Rand) *tor.OnionAddr {
  741. t.Helper()
  742. var serviceID [tor.V2DecodedLen]byte
  743. _, err := r.Read(serviceID[:])
  744. require.NoError(t, err, "unable to read serviceID")
  745. var port [2]byte
  746. _, err = r.Read(port[:])
  747. require.NoError(t, err, "unable to read port")
  748. onionService := tor.Base32Encoding.EncodeToString(serviceID[:])
  749. onionService += tor.OnionSuffix
  750. addrPort := int(binary.BigEndian.Uint16(port[:]))
  751. return &tor.OnionAddr{OnionService: onionService, Port: addrPort}
  752. }
  753. func randV3OnionAddr(t testing.TB, r *rand.Rand) *tor.OnionAddr {
  754. t.Helper()
  755. var serviceID [tor.V3DecodedLen]byte
  756. _, err := r.Read(serviceID[:])
  757. require.NoError(t, err, "unable to read serviceID")
  758. var port [2]byte
  759. _, err = r.Read(port[:])
  760. require.NoError(t, err, "unable to read port")
  761. onionService := tor.Base32Encoding.EncodeToString(serviceID[:])
  762. onionService += tor.OnionSuffix
  763. addrPort := int(binary.BigEndian.Uint16(port[:]))
  764. return &tor.OnionAddr{OnionService: onionService, Port: addrPort}
  765. }
  766. func randAddrs(t testing.TB, r *rand.Rand) []net.Addr {
  767. tcp4Addr := randTCP4Addr(t, r)
  768. tcp6Addr := randTCP6Addr(t, r)
  769. v2OnionAddr := randV2OnionAddr(t, r)
  770. v3OnionAddr := randV3OnionAddr(t, r)
  771. return []net.Addr{tcp4Addr, tcp6Addr, v2OnionAddr, v3OnionAddr}
  772. }
  773. func randAlias(r *rand.Rand) lnwire.NodeAlias {
  774. var a lnwire.NodeAlias
  775. for i := range a {
  776. a[i] = letterBytes[r.Intn(len(letterBytes))]
  777. }
  778. return a
  779. }
  780. func createExtraData(t testing.TB, r io.Reader) []byte {
  781. t.Helper()
  782. // Read random bytes.
  783. extraData := make([]byte, testNumExtraBytes)
  784. _, err := r.Read(extraData)
  785. require.NoError(t, err, "unable to generate extra data")
  786. // Encode the data length.
  787. binary.BigEndian.PutUint16(extraData[:2], uint16(len(extraData[2:])))
  788. return extraData
  789. }