lnd_payment_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. package itest
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "fmt"
  6. "testing"
  7. "time"
  8. "github.com/btcsuite/btcd/btcutil"
  9. "github.com/lightningnetwork/lnd/input"
  10. "github.com/lightningnetwork/lnd/lnrpc"
  11. "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
  12. "github.com/lightningnetwork/lnd/lntest"
  13. "github.com/lightningnetwork/lnd/lntest/node"
  14. "github.com/lightningnetwork/lnd/lntest/wait"
  15. "github.com/stretchr/testify/require"
  16. )
  17. // testSendDirectPayment creates a topology Alice->Bob and then tests that
  18. // Alice can send a direct payment to Bob. This test modifies the fee estimator
  19. // to return floor fee rate(1 sat/vb).
  20. func testSendDirectPayment(ht *lntest.HarnessTest) {
  21. // Grab Alice and Bob's nodes for convenience.
  22. alice, bob := ht.Alice, ht.Bob
  23. // Create a list of commitment types we want to test.
  24. commitTyes := []lnrpc.CommitmentType{
  25. lnrpc.CommitmentType_ANCHORS,
  26. lnrpc.CommitmentType_SIMPLE_TAPROOT,
  27. }
  28. // testSendPayment opens a channel between Alice and Bob using the
  29. // specified params. It then sends a payment from Alice to Bob and
  30. // asserts it being successful.
  31. testSendPayment := func(ht *lntest.HarnessTest,
  32. params lntest.OpenChannelParams) {
  33. // Check that there are no payments before test.
  34. chanPoint := ht.OpenChannel(alice, bob, params)
  35. // Now that the channel is open, create an invoice for Bob
  36. // which expects a payment of 1000 satoshis from Alice paid via
  37. // a particular preimage.
  38. const paymentAmt = 1000
  39. preimage := ht.Random32Bytes()
  40. invoice := &lnrpc.Invoice{
  41. RPreimage: preimage,
  42. Value: paymentAmt,
  43. }
  44. invoiceResp := bob.RPC.AddInvoice(invoice)
  45. // With the invoice for Bob added, send a payment towards Alice
  46. // paying to the above generated invoice.
  47. payReqs := []string{invoiceResp.PaymentRequest}
  48. ht.CompletePaymentRequests(alice, payReqs)
  49. p := ht.AssertNumPayments(alice, 1)[0]
  50. path := p.Htlcs[len(p.Htlcs)-1].Route.Hops
  51. // Ensure that the stored path shows a direct payment to Bob
  52. // with no other nodes in-between.
  53. require.Len(ht, path, 1, "wrong number of routes in path")
  54. require.Equal(ht, bob.PubKeyStr, path[0].PubKey, "wrong pubkey")
  55. // The payment amount should also match our previous payment
  56. // directly.
  57. require.EqualValues(ht, paymentAmt, p.ValueSat,
  58. "incorrect sat amount")
  59. require.EqualValues(ht, paymentAmt*1000, p.ValueMsat,
  60. "incorrect msat amount")
  61. // The payment hash (or r-hash) should have been stored
  62. // correctly.
  63. correctRHash := hex.EncodeToString(invoiceResp.RHash)
  64. require.Equal(ht, correctRHash, p.PaymentHash, "incorrect hash")
  65. // As we made a single-hop direct payment, there should have
  66. // been no fee applied.
  67. require.Zero(ht, p.FeeSat, "fee should be 0")
  68. require.Zero(ht, p.FeeMsat, "fee should be 0")
  69. // Now verify that the payment request returned by the rpc
  70. // matches the invoice that we paid.
  71. require.Equal(ht, invoiceResp.PaymentRequest, p.PaymentRequest,
  72. "incorrect payreq")
  73. // Delete all payments from Alice. DB should have no payments.
  74. alice.RPC.DeleteAllPayments()
  75. ht.AssertNumPayments(alice, 0)
  76. // TODO(yy): remove the sleep once the following bug is fixed.
  77. // When the invoice is reported settled, the commitment dance
  78. // is not yet finished, which can cause an error when closing
  79. // the channel, saying there's active HTLCs. We need to
  80. // investigate this issue and reverse the order to, first
  81. // finish the commitment dance, then report the invoice as
  82. // settled.
  83. time.Sleep(2 * time.Second)
  84. // Close the channel.
  85. //
  86. // NOTE: This implicitly tests that the channel link is active
  87. // before closing this channel. The above payment will trigger
  88. // a commitment dance in both of the nodes. If the node fails
  89. // to update the commitment state, we will fail to close the
  90. // channel as the link won't be active.
  91. ht.CloseChannel(alice, chanPoint)
  92. }
  93. // Run the test cases.
  94. for _, ct := range commitTyes {
  95. ht.Run(ct.String(), func(t *testing.T) {
  96. st := ht.Subtest(t)
  97. // Set the fee estimate to 1sat/vbyte.
  98. st.SetFeeEstimate(250)
  99. // Restart the nodes with the specified commitment type.
  100. args := lntest.NodeArgsForCommitType(ct)
  101. st.RestartNodeWithExtraArgs(alice, args)
  102. st.RestartNodeWithExtraArgs(bob, args)
  103. // Make sure they are connected.
  104. st.EnsureConnected(alice, bob)
  105. // Open a channel with 100k satoshis between Alice and
  106. // Bob with Alice being the sole funder of the channel.
  107. params := lntest.OpenChannelParams{
  108. Amt: 100_000,
  109. CommitmentType: ct,
  110. }
  111. // Open private channel for taproot channels.
  112. params.Private = ct ==
  113. lnrpc.CommitmentType_SIMPLE_TAPROOT
  114. testSendPayment(st, params)
  115. })
  116. }
  117. }
  118. func testListPayments(ht *lntest.HarnessTest) {
  119. alice, bob := ht.Alice, ht.Bob
  120. // Check that there are no payments before test.
  121. ht.AssertNumPayments(alice, 0)
  122. // Open a channel with 100k satoshis between Alice and Bob with Alice
  123. // being the sole funder of the channel.
  124. chanAmt := btcutil.Amount(100000)
  125. chanPoint := ht.OpenChannel(
  126. alice, bob, lntest.OpenChannelParams{Amt: chanAmt},
  127. )
  128. // Now that the channel is open, create an invoice for Bob which
  129. // expects a payment of 1000 satoshis from Alice paid via a particular
  130. // preimage.
  131. const paymentAmt = 1000
  132. preimage := ht.Random32Bytes()
  133. invoice := &lnrpc.Invoice{
  134. Memo: "testing",
  135. RPreimage: preimage,
  136. Value: paymentAmt,
  137. }
  138. invoiceResp := bob.RPC.AddInvoice(invoice)
  139. // Check that Bob has added the invoice.
  140. invoice = ht.AssertNumInvoices(bob, 1)[0]
  141. // With the invoice for Bob added, send a payment towards Alice paying
  142. // to the above generated invoice.
  143. payReqs := []string{invoiceResp.PaymentRequest}
  144. ht.CompletePaymentRequests(alice, payReqs)
  145. // Grab Alice's list of payments, she should show the existence of
  146. // exactly one payment.
  147. p := ht.AssertNumPayments(alice, 1)[0]
  148. path := p.Htlcs[len(p.Htlcs)-1].Route.Hops
  149. // Ensure that the stored path shows a direct payment to Bob with no
  150. // other nodes in-between.
  151. require.Len(ht, path, 1, "wrong number of routes in path")
  152. require.Equal(ht, bob.PubKeyStr, path[0].PubKey, "wrong pub key")
  153. // The payment amount should also match our previous payment directly.
  154. require.EqualValues(ht, paymentAmt, p.ValueSat, "incorrect sat amount")
  155. require.EqualValues(ht, paymentAmt*1000, p.ValueMsat,
  156. "incorrect msat amount")
  157. // The payment hash (or r-hash) should have been stored correctly.
  158. correctRHash := hex.EncodeToString(invoiceResp.RHash)
  159. require.Equal(ht, correctRHash, p.PaymentHash, "incorrect RHash")
  160. // As we made a single-hop direct payment, there should have been no
  161. // fee applied.
  162. require.Zero(ht, p.FeeSat, "fee should be 0")
  163. require.Zero(ht, p.FeeMsat, "fee should be 0")
  164. // Now verify that the payment request returned by the rpc matches the
  165. // invoice that we paid.
  166. require.Equal(ht, invoiceResp.PaymentRequest, p.PaymentRequest,
  167. "incorrect payreq")
  168. // testCase holds a case to be used by both the payment and the invoice
  169. // tests.
  170. type testCase struct {
  171. name string
  172. startDate uint64
  173. endDate uint64
  174. expected bool
  175. }
  176. // Create test cases to check the timestamp filters.
  177. createCases := func(createTimeSeconds uint64) []testCase {
  178. return []testCase{
  179. {
  180. // Use a start date same as the creation date
  181. // should return us the item.
  182. name: "exact start date",
  183. startDate: createTimeSeconds,
  184. expected: true,
  185. },
  186. {
  187. // Use an earlier start date should return us
  188. // the item.
  189. name: "earlier start date",
  190. startDate: createTimeSeconds - 1,
  191. expected: true,
  192. },
  193. {
  194. // Use a future start date should return us
  195. // nothing.
  196. name: "future start date",
  197. startDate: createTimeSeconds + 1,
  198. expected: false,
  199. },
  200. {
  201. // Use an end date same as the creation date
  202. // should return us the item.
  203. name: "exact end date",
  204. endDate: createTimeSeconds,
  205. expected: true,
  206. },
  207. {
  208. // Use an end date in the future should return
  209. // us the item.
  210. name: "future end date",
  211. endDate: createTimeSeconds + 1,
  212. expected: true,
  213. },
  214. {
  215. // Use an earlier end date should return us
  216. // nothing.
  217. name: "earlier end date",
  218. endDate: createTimeSeconds - 1,
  219. expected: false,
  220. },
  221. }
  222. }
  223. // Get the payment creation time in seconds.
  224. paymentCreateSeconds := uint64(
  225. p.CreationTimeNs / time.Second.Nanoseconds(),
  226. )
  227. // Create test cases from the payment creation time.
  228. testCases := createCases(paymentCreateSeconds)
  229. // We now check the timestamp filters in `ListPayments`.
  230. for _, tc := range testCases {
  231. ht.Run("payment_"+tc.name, func(t *testing.T) {
  232. req := &lnrpc.ListPaymentsRequest{
  233. CreationDateStart: tc.startDate,
  234. CreationDateEnd: tc.endDate,
  235. }
  236. resp := alice.RPC.ListPayments(req)
  237. if tc.expected {
  238. require.Lenf(t, resp.Payments, 1, "req=%v", req)
  239. } else {
  240. require.Emptyf(t, resp.Payments, "req=%v", req)
  241. }
  242. })
  243. }
  244. // Create test cases from the invoice creation time.
  245. testCases = createCases(uint64(invoice.CreationDate))
  246. // We now do the same check for `ListInvoices`.
  247. for _, tc := range testCases {
  248. ht.Run("invoice_"+tc.name, func(t *testing.T) {
  249. req := &lnrpc.ListInvoiceRequest{
  250. CreationDateStart: tc.startDate,
  251. CreationDateEnd: tc.endDate,
  252. }
  253. resp := bob.RPC.ListInvoices(req)
  254. if tc.expected {
  255. require.Lenf(t, resp.Invoices, 1, "req: %v",
  256. req)
  257. } else {
  258. require.Emptyf(t, resp.Invoices, "req: %v", req)
  259. }
  260. })
  261. }
  262. // Delete all payments from Alice. DB should have no payments.
  263. alice.RPC.DeleteAllPayments()
  264. // Check that there are no payments after test.
  265. ht.AssertNumPayments(alice, 0)
  266. // TODO(yy): remove the sleep once the following bug is fixed.
  267. // When the invoice is reported settled, the commitment dance is not
  268. // yet finished, which can cause an error when closing the channel,
  269. // saying there's active HTLCs. We need to investigate this issue and
  270. // reverse the order to, first finish the commitment dance, then report
  271. // the invoice as settled.
  272. time.Sleep(2 * time.Second)
  273. // Close the channel.
  274. ht.CloseChannel(alice, chanPoint)
  275. }
  276. // testPaymentFollowingChannelOpen tests that the channel transition from
  277. // 'pending' to 'open' state does not cause any inconsistencies within other
  278. // subsystems trying to update the channel state in the db. We follow this
  279. // transition with a payment that updates the commitment state and verify that
  280. // the pending state is up to date.
  281. func testPaymentFollowingChannelOpen(ht *lntest.HarnessTest) {
  282. const paymentAmt = btcutil.Amount(100)
  283. channelCapacity := paymentAmt * 1000
  284. // We first establish a channel between Alice and Bob.
  285. alice, bob := ht.Alice, ht.Bob
  286. p := lntest.OpenChannelParams{
  287. Amt: channelCapacity,
  288. }
  289. pendingUpdate := ht.OpenChannelAssertPending(alice, bob, p)
  290. // At this point, the channel's funding transaction will have been
  291. // broadcast, but not confirmed. Alice and Bob's nodes
  292. // should reflect this when queried via RPC.
  293. ht.AssertNodesNumPendingOpenChannels(alice, bob, 1)
  294. // We are restarting Bob's node to let the link be created for the
  295. // pending channel.
  296. ht.RestartNode(bob)
  297. // We ensure that Bob reconnects to Alice.
  298. ht.EnsureConnected(bob, alice)
  299. // We mine six blocks for the channel to be confirmed.
  300. ht.MineBlocksAndAssertNumTxes(6, 1)
  301. // We verify that the channel is open from both nodes point of view.
  302. chanPoint := lntest.ChanPointFromPendingUpdate(pendingUpdate)
  303. ht.AssertNodesNumPendingOpenChannels(alice, bob, 0)
  304. ht.AssertChannelExists(alice, chanPoint)
  305. ht.AssertChannelExists(bob, chanPoint)
  306. // With the channel open, we'll create invoices for Bob that Alice will
  307. // pay to in order to advance the state of the channel.
  308. bobPayReqs, _, _ := ht.CreatePayReqs(bob, paymentAmt, 1)
  309. // Send payment to Bob so that a channel update to disk will be
  310. // executed.
  311. ht.CompletePaymentRequests(alice, []string{bobPayReqs[0]})
  312. // TODO(yy): remove the sleep once the following bug is fixed.
  313. // When the invoice is reported settled, the commitment dance is not
  314. // yet finished, which can cause an error when closing the channel,
  315. // saying there's active HTLCs. We need to investigate this issue and
  316. // reverse the order to, first finish the commitment dance, then report
  317. // the invoice as settled.
  318. time.Sleep(2 * time.Second)
  319. // Finally, immediately close the channel. This function will also
  320. // block until the channel is closed and will additionally assert the
  321. // relevant channel closing post conditions.
  322. ht.CloseChannel(alice, chanPoint)
  323. }
  324. // testAsyncPayments tests the performance of the async payments.
  325. func testAsyncPayments(ht *lntest.HarnessTest) {
  326. // We use new nodes here as the benchmark test creates lots of data
  327. // which can be costly to be carried on.
  328. alice := ht.NewNode("Alice", []string{"--pending-commit-interval=3m"})
  329. bob := ht.NewNode("Bob", []string{"--pending-commit-interval=3m"})
  330. ht.EnsureConnected(alice, bob)
  331. ht.FundCoins(btcutil.SatoshiPerBitcoin, alice)
  332. runAsyncPayments(ht, alice, bob, nil)
  333. }
  334. // runAsyncPayments tests the performance of the async payments.
  335. func runAsyncPayments(ht *lntest.HarnessTest, alice, bob *node.HarnessNode,
  336. commitType *lnrpc.CommitmentType) {
  337. const paymentAmt = 100
  338. channelCapacity := btcutil.Amount(paymentAmt * 2000)
  339. chanArgs := lntest.OpenChannelParams{
  340. Amt: channelCapacity,
  341. }
  342. if commitType != nil {
  343. chanArgs.CommitmentType = *commitType
  344. if *commitType == lnrpc.CommitmentType_SIMPLE_TAPROOT {
  345. chanArgs.Private = true
  346. }
  347. }
  348. // First establish a channel with a capacity equals to the overall
  349. // amount of payments, between Alice and Bob, at the end of the test
  350. // Alice should send all money from her side to Bob.
  351. chanPoint := ht.OpenChannel(
  352. alice, bob, chanArgs,
  353. )
  354. info := ht.QueryChannelByChanPoint(alice, chanPoint)
  355. // We'll create a number of invoices equal the max number of HTLCs that
  356. // can be carried in one direction. The number on the commitment will
  357. // likely be lower, but we can't guarantee that any more HTLCs will
  358. // succeed due to the limited path diversity and inability of the router
  359. // to retry via another path.
  360. numInvoices := int(input.MaxHTLCNumber / 2)
  361. bobAmt := int64(numInvoices * paymentAmt)
  362. aliceAmt := info.LocalBalance - bobAmt
  363. // With the channel open, we'll create invoices for Bob that Alice
  364. // will pay to in order to advance the state of the channel.
  365. bobPayReqs, _, _ := ht.CreatePayReqs(bob, paymentAmt, numInvoices)
  366. // Simultaneously send payments from Alice to Bob using of Bob's
  367. // payment hashes generated above.
  368. now := time.Now()
  369. settled := make(chan struct{})
  370. defer close(settled)
  371. timeout := wait.AsyncBenchmarkTimeout
  372. for i := 0; i < numInvoices; i++ {
  373. payReq := bobPayReqs[i]
  374. go func() {
  375. req := &routerrpc.SendPaymentRequest{
  376. PaymentRequest: payReq,
  377. TimeoutSeconds: int32(timeout.Seconds()),
  378. FeeLimitMsat: noFeeLimitMsat,
  379. }
  380. // AssertPaymentStatusWithTimeout will assert that the
  381. // payment is settled.
  382. stream := alice.RPC.SendPayment(req)
  383. ht.AssertPaymentSucceedWithTimeout(stream, timeout)
  384. settled <- struct{}{}
  385. }()
  386. }
  387. // Wait until all the payments have settled.
  388. timer := time.After(timeout)
  389. for i := 0; i < numInvoices; i++ {
  390. select {
  391. case <-settled:
  392. case <-timer:
  393. require.Fail(ht, "timeout", "wait payment failed")
  394. }
  395. }
  396. // All payments have been sent, mark the finish time.
  397. timeTaken := time.Since(now)
  398. // Wait for the revocation to be received so alice no longer has
  399. // pending htlcs listed and has correct balances. This is needed due to
  400. // the fact that we now pipeline the settles.
  401. assertChannelState(ht, alice, chanPoint, aliceAmt, bobAmt)
  402. // Wait for Bob to receive revocation from Alice.
  403. assertChannelState(ht, bob, chanPoint, bobAmt, aliceAmt)
  404. ht.Log("\tBenchmark info: Elapsed time: ", timeTaken)
  405. ht.Log("\tBenchmark info: TPS: ",
  406. float64(numInvoices)/timeTaken.Seconds())
  407. // Finally, immediately close the channel. This function will also
  408. // block until the channel is closed and will additionally assert the
  409. // relevant channel closing post conditions.
  410. ht.CloseChannel(alice, chanPoint)
  411. }
  412. // testBidirectionalAsyncPayments tests that nodes are able to send the
  413. // payments to each other in async manner without blocking.
  414. func testBidirectionalAsyncPayments(ht *lntest.HarnessTest) {
  415. const paymentAmt = 1000
  416. // We use new nodes here as the benchmark test creates lots of data
  417. // which can be costly to be carried on.
  418. args := []string{
  419. // Increase the dust threshold to avoid the payments fail due
  420. // to threshold limit reached.
  421. "--dust-threshold=5000000",
  422. // Increase the pending commit interval since there are lots of
  423. // commitment dances.
  424. "--pending-commit-interval=5m",
  425. // Increase the mailbox delivery timeout as there are lots of
  426. // ADDs going on.
  427. "--htlcswitch.mailboxdeliverytimeout=2m",
  428. }
  429. alice := ht.NewNode("Alice", args)
  430. bob := ht.NewNode("Bob", args)
  431. ht.EnsureConnected(alice, bob)
  432. ht.FundCoins(btcutil.SatoshiPerBitcoin, alice)
  433. // First establish a channel with a capacity equals to the overall
  434. // amount of payments, between Alice and Bob, at the end of the test
  435. // Alice should send all money from her side to Bob.
  436. chanPoint := ht.OpenChannel(
  437. alice, bob, lntest.OpenChannelParams{
  438. Amt: paymentAmt * 2000,
  439. PushAmt: paymentAmt * 1000,
  440. },
  441. )
  442. info := ht.QueryChannelByChanPoint(alice, chanPoint)
  443. // We'll create a number of invoices equal the max number of HTLCs that
  444. // can be carried in one direction. The number on the commitment will
  445. // likely be lower, but we can't guarantee that any more HTLCs will
  446. // succeed due to the limited path diversity and inability of the router
  447. // to retry via another path.
  448. numInvoices := int(input.MaxHTLCNumber / 2)
  449. // Nodes should exchange the same amount of money and because of this
  450. // at the end balances should remain the same.
  451. aliceAmt := info.LocalBalance
  452. bobAmt := info.RemoteBalance
  453. // With the channel open, we'll create invoices for Bob that Alice
  454. // will pay to in order to advance the state of the channel.
  455. bobPayReqs, _, _ := ht.CreatePayReqs(bob, paymentAmt, numInvoices)
  456. // With the channel open, we'll create invoices for Alice that Bob
  457. // will pay to in order to advance the state of the channel.
  458. alicePayReqs, _, _ := ht.CreatePayReqs(alice, paymentAmt, numInvoices)
  459. // Reset mission control to prevent previous payment results from
  460. // interfering with this test. A new channel has been opened, but
  461. // mission control operates on node pairs.
  462. alice.RPC.ResetMissionControl()
  463. // Send payments from Alice to Bob and from Bob to Alice in async
  464. // manner.
  465. settled := make(chan struct{})
  466. defer close(settled)
  467. timeout := wait.AsyncBenchmarkTimeout * 2
  468. send := func(node *node.HarnessNode, payReq string) {
  469. req := &routerrpc.SendPaymentRequest{
  470. PaymentRequest: payReq,
  471. TimeoutSeconds: int32(timeout.Seconds()),
  472. FeeLimitMsat: noFeeLimitMsat,
  473. }
  474. // AssertPaymentStatusWithTimeout will assert that the
  475. // payment is settled.
  476. stream := node.RPC.SendPayment(req)
  477. ht.AssertPaymentSucceedWithTimeout(stream, timeout)
  478. settled <- struct{}{}
  479. }
  480. for i := 0; i < numInvoices; i++ {
  481. go send(bob, alicePayReqs[i])
  482. go send(alice, bobPayReqs[i])
  483. }
  484. // Expect all payments to succeed.
  485. timer := time.After(timeout)
  486. for i := 0; i < 2*numInvoices; i++ {
  487. select {
  488. case <-settled:
  489. case <-timer:
  490. require.Fail(ht, "timeout", "wait payment failed")
  491. }
  492. }
  493. // Wait for Alice and Bob to receive revocations messages, and update
  494. // states, i.e. balance info.
  495. assertChannelState(ht, alice, chanPoint, aliceAmt, bobAmt)
  496. // Next query for Bob's and Alice's channel states, in order to confirm
  497. // that all payment have been successful transmitted.
  498. assertChannelState(ht, bob, chanPoint, bobAmt, aliceAmt)
  499. // Finally, immediately close the channel. This function will also
  500. // block until the channel is closed and will additionally assert the
  501. // relevant channel closing post conditions.
  502. ht.CloseChannel(alice, chanPoint)
  503. }
  504. func testInvoiceSubscriptions(ht *lntest.HarnessTest) {
  505. const chanAmt = btcutil.Amount(500000)
  506. alice, bob := ht.Alice, ht.Bob
  507. // Create a new invoice subscription client for Bob, the notification
  508. // should be dispatched shortly below.
  509. req := &lnrpc.InvoiceSubscription{}
  510. bobInvoiceSubscription := bob.RPC.SubscribeInvoices(req)
  511. // Open a channel with 500k satoshis between Alice and Bob with Alice
  512. // being the sole funder of the channel.
  513. chanPoint := ht.OpenChannel(
  514. alice, bob, lntest.OpenChannelParams{Amt: chanAmt},
  515. )
  516. // Next create a new invoice for Bob requesting 1k satoshis.
  517. const paymentAmt = 1000
  518. invoice := &lnrpc.Invoice{
  519. Memo: "testing",
  520. RPreimage: ht.Random32Bytes(),
  521. Value: paymentAmt,
  522. }
  523. invoiceResp := bob.RPC.AddInvoice(invoice)
  524. lastAddIndex := invoiceResp.AddIndex
  525. // With the above invoice added, we should receive an update event.
  526. invoiceUpdate := ht.ReceiveInvoiceUpdate(bobInvoiceSubscription)
  527. require.NotEqual(ht, lnrpc.Invoice_SETTLED, invoiceUpdate.State,
  528. "invoice should not be settled")
  529. // With the assertion above set up, send a payment from Alice to Bob
  530. // which should finalize and settle the invoice.
  531. ht.CompletePaymentRequests(alice, []string{invoiceResp.PaymentRequest})
  532. // The invoice update should exactly match the invoice created
  533. // above, but should now be settled and have SettleDate
  534. invoiceUpdate = ht.ReceiveInvoiceUpdate(bobInvoiceSubscription)
  535. require.Equal(ht, lnrpc.Invoice_SETTLED, invoiceUpdate.State,
  536. "invoice not settled but should be")
  537. require.NotZero(ht, invoiceUpdate.SettleDate,
  538. "invoice should have non zero settle date, but doesn't")
  539. require.Equal(ht, invoice.RPreimage, invoiceUpdate.RPreimage,
  540. "payment preimages don't match")
  541. require.NotZero(ht, invoiceUpdate.SettleIndex,
  542. "invoice should have settle index")
  543. settleIndex := invoiceUpdate.SettleIndex
  544. // We'll now add 3 more invoices to Bob's invoice registry.
  545. const numInvoices = 3
  546. payReqs, _, newInvoices := ht.CreatePayReqs(
  547. bob, paymentAmt, numInvoices,
  548. )
  549. // Now that the set of invoices has been added, we'll re-register for
  550. // streaming invoice notifications for Bob, this time specifying the
  551. // add invoice of the last prior invoice.
  552. req = &lnrpc.InvoiceSubscription{AddIndex: lastAddIndex}
  553. bobInvoiceSubscription = bob.RPC.SubscribeInvoices(req)
  554. // Since we specified a value of the prior add index above, we should
  555. // now immediately get the invoices we just added as we should get the
  556. // backlog of notifications.
  557. for i := 0; i < numInvoices; i++ {
  558. invoiceUpdate := ht.ReceiveInvoiceUpdate(bobInvoiceSubscription)
  559. // We should now get the ith invoice we added, as they should
  560. // be returned in order.
  561. require.NotEqual(ht, lnrpc.Invoice_SETTLED, invoiceUpdate.State,
  562. "should have only received add events")
  563. originalInvoice := newInvoices[i]
  564. rHash := sha256.Sum256(originalInvoice.RPreimage)
  565. require.Equal(ht, rHash[:], invoiceUpdate.RHash,
  566. "invoices have mismatched payment hashes")
  567. }
  568. // We'll now have Bob settle out the remainder of these invoices so we
  569. // can test that all settled invoices are properly notified.
  570. ht.CompletePaymentRequests(alice, payReqs)
  571. // With the set of invoices paid, we'll now cancel the old
  572. // subscription, and create a new one for Bob, this time using the
  573. // settle index to obtain the backlog of settled invoices.
  574. req = &lnrpc.InvoiceSubscription{
  575. SettleIndex: settleIndex,
  576. }
  577. bobInvoiceSubscription = bob.RPC.SubscribeInvoices(req)
  578. // As we specified the index of the past settle index, we should now
  579. // receive notifications for the three HTLCs that we just settled. As
  580. // the order that the HTLCs will be settled in is partially randomized,
  581. // we'll use a map to assert that the proper set has been settled.
  582. settledInvoices := make(map[[32]byte]struct{})
  583. for _, invoice := range newInvoices {
  584. rHash := sha256.Sum256(invoice.RPreimage)
  585. settledInvoices[rHash] = struct{}{}
  586. }
  587. for i := 0; i < numInvoices; i++ {
  588. invoiceUpdate := ht.ReceiveInvoiceUpdate(bobInvoiceSubscription)
  589. // We should now get the ith invoice we added, as they should
  590. // be returned in order.
  591. require.Equal(ht, lnrpc.Invoice_SETTLED, invoiceUpdate.State,
  592. "should have only received settle events")
  593. var rHash [32]byte
  594. copy(rHash[:], invoiceUpdate.RHash)
  595. require.Contains(ht, settledInvoices, rHash,
  596. "unknown invoice settled")
  597. delete(settledInvoices, rHash)
  598. }
  599. // At this point, all the invoices should be fully settled.
  600. require.Empty(ht, settledInvoices, "not all invoices settled")
  601. // TODO(yy): remove the sleep once the following bug is fixed.
  602. // When the invoice is reported settled, the commitment dance is not
  603. // yet finished, which can cause an error when closing the channel,
  604. // saying there's active HTLCs. We need to investigate this issue and
  605. // reverse the order to, first finish the commitment dance, then report
  606. // the invoice as settled.
  607. time.Sleep(2 * time.Second)
  608. ht.CloseChannel(alice, chanPoint)
  609. }
  610. // assertChannelState asserts the channel state by checking the values in
  611. // fields, LocalBalance, RemoteBalance and num of PendingHtlcs.
  612. func assertChannelState(ht *lntest.HarnessTest, hn *node.HarnessNode,
  613. cp *lnrpc.ChannelPoint, localBalance, remoteBalance int64) {
  614. // Get the funding point.
  615. err := wait.NoError(func() error {
  616. // Find the target channel first.
  617. target := ht.GetChannelByChanPoint(hn, cp)
  618. if len(target.PendingHtlcs) != 0 {
  619. return fmt.Errorf("pending htlcs is "+
  620. "incorrect, got %v, expected %v",
  621. len(target.PendingHtlcs), 0)
  622. }
  623. if target.LocalBalance != localBalance {
  624. return fmt.Errorf("local balance is "+
  625. "incorrect, got %v, expected %v",
  626. target.LocalBalance, localBalance)
  627. }
  628. if target.RemoteBalance != remoteBalance {
  629. return fmt.Errorf("remote balance is "+
  630. "incorrect, got %v, expected %v",
  631. target.RemoteBalance, remoteBalance)
  632. }
  633. return nil
  634. }, lntest.DefaultTimeout)
  635. require.NoError(ht, err, "timeout while chekcing for balance")
  636. }