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