• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 13035292482

29 Jan 2025 03:59PM UTC coverage: 49.3% (-9.5%) from 58.777%
13035292482

Pull #9456

github

mohamedawnallah
docs: update release-notes-0.19.0.md

In this commit, we warn users about the removal
of RPCs `SendToRoute`, `SendToRouteSync`, `SendPayment`,
and `SendPaymentSync` in the next release 0.20.
Pull Request #9456: lnrpc+docs: deprecate warning `SendToRoute`, `SendToRouteSync`, `SendPayment`, and `SendPaymentSync` in Release 0.19

100634 of 204126 relevant lines covered (49.3%)

1.54 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.81
/invoices/update.go
1
package invoices
2

3
import (
4
        "bytes"
5
        "encoding/hex"
6
        "errors"
7

8
        "github.com/btcsuite/btcd/chaincfg/chainhash"
9
        "github.com/lightningnetwork/lnd/amp"
10
        "github.com/lightningnetwork/lnd/lntypes"
11
        "github.com/lightningnetwork/lnd/lnwire"
12
        "github.com/lightningnetwork/lnd/record"
13
)
14

15
// invoiceUpdateCtx is an object that describes the context for the invoice
16
// update to be carried out.
17
type invoiceUpdateCtx struct {
18
        hash                 lntypes.Hash
19
        circuitKey           CircuitKey
20
        amtPaid              lnwire.MilliSatoshi
21
        expiry               uint32
22
        currentHeight        int32
23
        finalCltvRejectDelta int32
24

25
        // wireCustomRecords are the custom records that were included with the
26
        // HTLC wire message.
27
        wireCustomRecords lnwire.CustomRecords
28

29
        // customRecords is a map of custom records that were included with the
30
        // HTLC onion payload.
31
        customRecords record.CustomSet
32

33
        mpp          *record.MPP
34
        amp          *record.AMP
35
        metadata     []byte
36
        pathID       *chainhash.Hash
37
        totalAmtMsat lnwire.MilliSatoshi
38
}
39

40
// invoiceRef returns an identifier that can be used to lookup or update the
41
// invoice this HTLC is targeting.
42
func (i *invoiceUpdateCtx) invoiceRef() InvoiceRef {
3✔
43
        switch {
3✔
44
        case i.pathID != nil:
3✔
45
                return InvoiceRefByHashAndAddr(i.hash, *i.pathID)
3✔
46

47
        case i.amp != nil && i.mpp != nil:
3✔
48
                payAddr := i.mpp.PaymentAddr()
3✔
49
                return InvoiceRefByAddr(payAddr)
3✔
50

51
        case i.mpp != nil:
3✔
52
                payAddr := i.mpp.PaymentAddr()
3✔
53
                return InvoiceRefByHashAndAddr(i.hash, payAddr)
3✔
54

55
        default:
3✔
56
                return InvoiceRefByHash(i.hash)
3✔
57
        }
58
}
59

60
// setID returns an identifier that identifies other possible HTLCs that this
61
// particular one is related to. If nil is returned this means the HTLC is an
62
// MPP or legacy payment, otherwise the HTLC belongs AMP payment.
63
func (i invoiceUpdateCtx) setID() *[32]byte {
3✔
64
        if i.amp != nil {
6✔
65
                setID := i.amp.SetID()
3✔
66
                return &setID
3✔
67
        }
3✔
68
        return nil
3✔
69
}
70

71
// log logs a message specific to this update context.
72
func (i *invoiceUpdateCtx) log(s string) {
3✔
73
        // Don't use %x in the log statement below, because it doesn't
3✔
74
        // distinguish between nil and empty metadata.
3✔
75
        metadata := "<nil>"
3✔
76
        if i.metadata != nil {
3✔
77
                metadata = hex.EncodeToString(i.metadata)
×
78
        }
×
79

80
        log.Debugf("Invoice%v: %v, amt=%v, expiry=%v, circuit=%v, mpp=%v, "+
3✔
81
                "amp=%v, metadata=%v", i.invoiceRef(), s, i.amtPaid, i.expiry,
3✔
82
                i.circuitKey, i.mpp, i.amp, metadata)
3✔
83
}
84

85
// failRes is a helper function which creates a failure resolution with
86
// the information contained in the invoiceUpdateCtx and the fail resolution
87
// result provided.
88
func (i invoiceUpdateCtx) failRes(outcome FailResolutionResult) *HtlcFailResolution {
3✔
89
        return NewFailResolution(i.circuitKey, i.currentHeight, outcome)
3✔
90
}
3✔
91

92
// settleRes is a helper function which creates a settle resolution with
93
// the information contained in the invoiceUpdateCtx and the preimage and
94
// the settle resolution result provided.
95
func (i invoiceUpdateCtx) settleRes(preimage lntypes.Preimage,
96
        outcome SettleResolutionResult) *HtlcSettleResolution {
3✔
97

3✔
98
        return NewSettleResolution(
3✔
99
                preimage, i.circuitKey, i.currentHeight, outcome,
3✔
100
        )
3✔
101
}
3✔
102

103
// acceptRes is a helper function which creates an accept resolution with
104
// the information contained in the invoiceUpdateCtx and the accept resolution
105
// result provided.
106
func (i invoiceUpdateCtx) acceptRes(
107
        outcome acceptResolutionResult) *htlcAcceptResolution {
3✔
108

3✔
109
        return newAcceptResolution(i.circuitKey, outcome)
3✔
110
}
3✔
111

112
// updateInvoice is a callback for DB.UpdateInvoice that contains the invoice
113
// settlement logic. It returns a HTLC resolution that indicates what the
114
// outcome of the update was.
115
func updateInvoice(ctx *invoiceUpdateCtx, inv *Invoice) (
116
        *InvoiceUpdateDesc, HtlcResolution, error) {
3✔
117

3✔
118
        // Don't update the invoice when this is a replayed htlc.
3✔
119
        htlc, ok := inv.Htlcs[ctx.circuitKey]
3✔
120
        if ok {
6✔
121
                switch htlc.State {
3✔
122
                case HtlcStateCanceled:
3✔
123
                        return nil, ctx.failRes(ResultReplayToCanceled), nil
3✔
124

125
                case HtlcStateAccepted:
3✔
126
                        return nil, ctx.acceptRes(resultReplayToAccepted), nil
3✔
127

128
                case HtlcStateSettled:
3✔
129
                        pre := inv.Terms.PaymentPreimage
3✔
130

3✔
131
                        // Terms.PaymentPreimage will be nil for AMP invoices.
3✔
132
                        // Set it to the HTLCs AMP Preimage instead.
3✔
133
                        if pre == nil {
3✔
134
                                pre = htlc.AMP.Preimage
×
135
                        }
×
136

137
                        return nil, ctx.settleRes(
3✔
138
                                *pre,
3✔
139
                                ResultReplayToSettled,
3✔
140
                        ), nil
3✔
141

142
                default:
×
143
                        return nil, nil, errors.New("unknown htlc state")
×
144
                }
145
        }
146

147
        // If no MPP payload was provided, then we expect this to be a keysend,
148
        // or a payment to an invoice created before we started to require the
149
        // MPP payload.
150
        if ctx.mpp == nil && ctx.pathID == nil {
6✔
151
                return updateLegacy(ctx, inv)
3✔
152
        }
3✔
153

154
        return updateMpp(ctx, inv)
3✔
155
}
156

157
// updateMpp is a callback for DB.UpdateInvoice that contains the invoice
158
// settlement logic for mpp payments.
159
func updateMpp(ctx *invoiceUpdateCtx, inv *Invoice) (*InvoiceUpdateDesc,
160
        HtlcResolution, error) {
3✔
161

3✔
162
        // Reject HTLCs to AMP invoices if they are missing an AMP payload, and
3✔
163
        // HTLCs to MPP invoices if they have an AMP payload.
3✔
164
        switch {
3✔
165
        case inv.Terms.Features.RequiresFeature(lnwire.AMPRequired) &&
166
                ctx.amp == nil:
×
167

×
168
                return nil, ctx.failRes(ResultHtlcInvoiceTypeMismatch), nil
×
169

170
        case !inv.Terms.Features.RequiresFeature(lnwire.AMPRequired) &&
171
                ctx.amp != nil:
×
172

×
173
                return nil, ctx.failRes(ResultHtlcInvoiceTypeMismatch), nil
×
174
        }
175

176
        setID := ctx.setID()
3✔
177

3✔
178
        var (
3✔
179
                totalAmt    = ctx.totalAmtMsat
3✔
180
                paymentAddr []byte
3✔
181
        )
3✔
182
        // If an MPP record is present, then the payment address and total
3✔
183
        // payment amount is extracted from it. Otherwise, the pathID is used
3✔
184
        // to extract the payment address.
3✔
185
        if ctx.mpp != nil {
6✔
186
                totalAmt = ctx.mpp.TotalMsat()
3✔
187
                payAddr := ctx.mpp.PaymentAddr()
3✔
188
                paymentAddr = payAddr[:]
3✔
189
        } else {
6✔
190
                paymentAddr = ctx.pathID[:]
3✔
191
        }
3✔
192

193
        // For storage, we don't really care where the custom records came from.
194
        // So we merge them together and store them in the same field.
195
        customRecords := lnwire.CustomRecords(
3✔
196
                ctx.customRecords,
3✔
197
        ).MergedCopy(ctx.wireCustomRecords)
3✔
198

3✔
199
        // Start building the accept descriptor.
3✔
200
        acceptDesc := &HtlcAcceptDesc{
3✔
201
                Amt:           ctx.amtPaid,
3✔
202
                Expiry:        ctx.expiry,
3✔
203
                AcceptHeight:  ctx.currentHeight,
3✔
204
                MppTotalAmt:   totalAmt,
3✔
205
                CustomRecords: record.CustomSet(customRecords),
3✔
206
        }
3✔
207

3✔
208
        if ctx.amp != nil {
6✔
209
                acceptDesc.AMP = &InvoiceHtlcAMPData{
3✔
210
                        Record:   *ctx.amp,
3✔
211
                        Hash:     ctx.hash,
3✔
212
                        Preimage: nil,
3✔
213
                }
3✔
214
        }
3✔
215

216
        // Only accept payments to open invoices. This behaviour differs from
217
        // non-mpp payments that are accepted even after the invoice is settled.
218
        // Because non-mpp payments don't have a payment address, this is needed
219
        // to thwart probing.
220
        if inv.State != ContractOpen {
3✔
221
                return nil, ctx.failRes(ResultInvoiceNotOpen), nil
×
222
        }
×
223

224
        // Check the payment address that authorizes the payment.
225
        if !bytes.Equal(paymentAddr, inv.Terms.PaymentAddr[:]) {
3✔
226
                return nil, ctx.failRes(ResultAddressMismatch), nil
×
227
        }
×
228

229
        // Don't accept zero-valued sets.
230
        if totalAmt == 0 {
3✔
231
                return nil, ctx.failRes(ResultHtlcSetTotalTooLow), nil
×
232
        }
×
233

234
        // Check that the total amt of the htlc set is high enough. In case this
235
        // is a zero-valued invoice, it will always be enough.
236
        if totalAmt < inv.Terms.Value {
3✔
237
                return nil, ctx.failRes(ResultHtlcSetTotalTooLow), nil
×
238
        }
×
239

240
        htlcSet := inv.HTLCSet(setID, HtlcStateAccepted)
3✔
241

3✔
242
        // Check whether total amt matches other HTLCs in the set.
3✔
243
        var newSetTotal lnwire.MilliSatoshi
3✔
244
        for _, htlc := range htlcSet {
6✔
245
                if totalAmt != htlc.MppTotalAmt {
3✔
246
                        return nil, ctx.failRes(ResultHtlcSetTotalMismatch), nil
×
247
                }
×
248

249
                newSetTotal += htlc.Amt
3✔
250
        }
251

252
        // Add amount of new htlc.
253
        newSetTotal += ctx.amtPaid
3✔
254

3✔
255
        // The invoice is still open. Check the expiry.
3✔
256
        if ctx.expiry < uint32(ctx.currentHeight+ctx.finalCltvRejectDelta) {
3✔
257
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
258
        }
×
259

260
        if ctx.expiry < uint32(ctx.currentHeight+inv.Terms.FinalCltvDelta) {
3✔
261
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
262
        }
×
263

264
        if setID != nil && *setID == BlankPayAddr {
3✔
265
                return nil, ctx.failRes(ResultAmpError), nil
×
266
        }
×
267

268
        // Record HTLC in the invoice database.
269
        newHtlcs := map[CircuitKey]*HtlcAcceptDesc{
3✔
270
                ctx.circuitKey: acceptDesc,
3✔
271
        }
3✔
272

3✔
273
        update := InvoiceUpdateDesc{
3✔
274
                UpdateType: AddHTLCsUpdate,
3✔
275
                AddHtlcs:   newHtlcs,
3✔
276
        }
3✔
277

3✔
278
        // If the invoice cannot be settled yet, only record the htlc.
3✔
279
        setComplete := newSetTotal >= totalAmt
3✔
280
        if !setComplete {
6✔
281
                return &update, ctx.acceptRes(resultPartialAccepted), nil
3✔
282
        }
3✔
283

284
        // Check to see if we can settle or this is a hold invoice, and
285
        // we need to wait for the preimage.
286
        if inv.HodlInvoice {
6✔
287
                update.State = &InvoiceStateUpdateDesc{
3✔
288
                        NewState: ContractAccepted,
3✔
289
                }
3✔
290
                return &update, ctx.acceptRes(resultAccepted), nil
3✔
291
        }
3✔
292

293
        var (
3✔
294
                htlcPreimages map[CircuitKey]lntypes.Preimage
3✔
295
                htlcPreimage  lntypes.Preimage
3✔
296
        )
3✔
297
        if ctx.amp != nil {
6✔
298
                var failRes *HtlcFailResolution
3✔
299
                htlcPreimages, failRes = reconstructAMPPreimages(ctx, htlcSet)
3✔
300
                if failRes != nil {
3✔
301
                        update.UpdateType = CancelInvoiceUpdate
×
302
                        update.State = &InvoiceStateUpdateDesc{
×
303
                                NewState: ContractCanceled,
×
304
                                SetID:    setID,
×
305
                        }
×
306
                        return &update, failRes, nil
×
307
                }
×
308

309
                // The preimage for _this_ HTLC will be the one with context's
310
                // circuit key.
311
                htlcPreimage = htlcPreimages[ctx.circuitKey]
3✔
312
        } else {
3✔
313
                htlcPreimage = *inv.Terms.PaymentPreimage
3✔
314
        }
3✔
315

316
        update.State = &InvoiceStateUpdateDesc{
3✔
317
                NewState:      ContractSettled,
3✔
318
                Preimage:      inv.Terms.PaymentPreimage,
3✔
319
                HTLCPreimages: htlcPreimages,
3✔
320
                SetID:         setID,
3✔
321
        }
3✔
322

3✔
323
        return &update, ctx.settleRes(htlcPreimage, ResultSettled), nil
3✔
324
}
325

326
// HTLCSet is a map of CircuitKey to InvoiceHTLC.
327
type HTLCSet = map[CircuitKey]*InvoiceHTLC
328

329
// HTLCPreimages is a map of CircuitKey to preimage.
330
type HTLCPreimages = map[CircuitKey]lntypes.Preimage
331

332
// reconstructAMPPreimages reconstructs the root seed for an AMP HTLC set and
333
// verifies that all derived child hashes match the payment hashes of the HTLCs
334
// in the set. This method is meant to be called after receiving the full amount
335
// committed to via mpp_total_msat. This method will return a fail resolution if
336
// any of the child hashes fail to match their corresponding HTLCs.
337
func reconstructAMPPreimages(ctx *invoiceUpdateCtx,
338
        htlcSet HTLCSet) (HTLCPreimages, *HtlcFailResolution) {
3✔
339

3✔
340
        // Create a slice containing all the child descriptors to be used for
3✔
341
        // reconstruction. This should include all HTLCs currently in the HTLC
3✔
342
        // set, plus the incoming HTLC.
3✔
343
        childDescs := make([]amp.ChildDesc, 0, 1+len(htlcSet))
3✔
344

3✔
345
        // Add the new HTLC's child descriptor at index 0.
3✔
346
        childDescs = append(childDescs, amp.ChildDesc{
3✔
347
                Share: ctx.amp.RootShare(),
3✔
348
                Index: ctx.amp.ChildIndex(),
3✔
349
        })
3✔
350

3✔
351
        // Next, construct an index mapping the position in childDescs to a
3✔
352
        // circuit key for all preexisting HTLCs.
3✔
353
        indexToCircuitKey := make(map[int]CircuitKey)
3✔
354

3✔
355
        // Add the child descriptor for each HTLC in the HTLC set, recording
3✔
356
        // it's position within the slice.
3✔
357
        var htlcSetIndex int
3✔
358
        for circuitKey, htlc := range htlcSet {
6✔
359
                childDescs = append(childDescs, amp.ChildDesc{
3✔
360
                        Share: htlc.AMP.Record.RootShare(),
3✔
361
                        Index: htlc.AMP.Record.ChildIndex(),
3✔
362
                })
3✔
363
                indexToCircuitKey[htlcSetIndex] = circuitKey
3✔
364
                htlcSetIndex++
3✔
365
        }
3✔
366

367
        // Using the child descriptors, reconstruct the root seed and derive the
368
        // child hash/preimage pairs for each of the HTLCs.
369
        children := amp.ReconstructChildren(childDescs...)
3✔
370

3✔
371
        // Validate that the derived child preimages match the hash of each
3✔
372
        // HTLC's respective hash.
3✔
373
        if ctx.hash != children[0].Hash {
3✔
374
                return nil, ctx.failRes(ResultAmpReconstruction)
×
375
        }
×
376
        for idx, child := range children[1:] {
6✔
377
                circuitKey := indexToCircuitKey[idx]
3✔
378
                htlc := htlcSet[circuitKey]
3✔
379
                if htlc.AMP.Hash != child.Hash {
3✔
380
                        return nil, ctx.failRes(ResultAmpReconstruction)
×
381
                }
×
382
        }
383

384
        // Finally, construct the map of learned preimages indexed by circuit
385
        // key, so that they can be persisted along with each HTLC when updating
386
        // the invoice.
387
        htlcPreimages := make(map[CircuitKey]lntypes.Preimage)
3✔
388
        htlcPreimages[ctx.circuitKey] = children[0].Preimage
3✔
389
        for idx, child := range children[1:] {
6✔
390
                circuitKey := indexToCircuitKey[idx]
3✔
391
                htlcPreimages[circuitKey] = child.Preimage
3✔
392
        }
3✔
393

394
        return htlcPreimages, nil
3✔
395
}
396

397
// updateLegacy is a callback for DB.UpdateInvoice that contains the invoice
398
// settlement logic for legacy payments.
399
//
400
// NOTE: This function is only kept in place in order to be able to handle key
401
// send payments and any invoices we created in the past that are valid and
402
// still had the optional mpp bit set.
403
func updateLegacy(ctx *invoiceUpdateCtx,
404
        inv *Invoice) (*InvoiceUpdateDesc, HtlcResolution, error) {
3✔
405

3✔
406
        // If the invoice is already canceled, there is no further
3✔
407
        // checking to do.
3✔
408
        if inv.State == ContractCanceled {
3✔
409
                return nil, ctx.failRes(ResultInvoiceAlreadyCanceled), nil
×
410
        }
×
411

412
        // If an invoice amount is specified, check that enough is paid. Also
413
        // check this for duplicate payments if the invoice is already settled
414
        // or accepted. In case this is a zero-valued invoice, it will always be
415
        // enough.
416
        if ctx.amtPaid < inv.Terms.Value {
6✔
417
                return nil, ctx.failRes(ResultAmountTooLow), nil
3✔
418
        }
3✔
419

420
        // If the invoice had the required feature bit set at this point, then
421
        // if we're in this method it means that the remote party didn't supply
422
        // the expected payload. However if this is a keysend payment, then
423
        // we'll permit it to pass.
424
        _, isKeySend := ctx.customRecords[record.KeySendType]
3✔
425
        invoiceFeatures := inv.Terms.Features
3✔
426
        paymentAddrRequired := invoiceFeatures.RequiresFeature(
3✔
427
                lnwire.PaymentAddrRequired,
3✔
428
        )
3✔
429
        if !isKeySend && paymentAddrRequired {
3✔
430
                log.Warnf("Payment to pay_hash=%v doesn't include MPP "+
×
431
                        "payload, rejecting", ctx.hash)
×
432
                return nil, ctx.failRes(ResultAddressMismatch), nil
×
433
        }
×
434

435
        // Don't allow settling the invoice with an old style
436
        // htlc if we are already in the process of gathering an
437
        // mpp set.
438
        for _, htlc := range inv.HTLCSet(nil, HtlcStateAccepted) {
3✔
439
                if htlc.MppTotalAmt > 0 {
×
440
                        return nil, ctx.failRes(ResultMppInProgress), nil
×
441
                }
×
442
        }
443

444
        // The invoice is still open. Check the expiry.
445
        if ctx.expiry < uint32(ctx.currentHeight+ctx.finalCltvRejectDelta) {
3✔
446
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
447
        }
×
448

449
        if ctx.expiry < uint32(ctx.currentHeight+inv.Terms.FinalCltvDelta) {
3✔
450
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
451
        }
×
452

453
        // For storage, we don't really care where the custom records came from.
454
        // So we merge them together and store them in the same field.
455
        customRecords := lnwire.CustomRecords(
3✔
456
                ctx.customRecords,
3✔
457
        ).MergedCopy(ctx.wireCustomRecords)
3✔
458

3✔
459
        // Record HTLC in the invoice database.
3✔
460
        newHtlcs := map[CircuitKey]*HtlcAcceptDesc{
3✔
461
                ctx.circuitKey: {
3✔
462
                        Amt:           ctx.amtPaid,
3✔
463
                        Expiry:        ctx.expiry,
3✔
464
                        AcceptHeight:  ctx.currentHeight,
3✔
465
                        CustomRecords: record.CustomSet(customRecords),
3✔
466
                },
3✔
467
        }
3✔
468

3✔
469
        update := InvoiceUpdateDesc{
3✔
470
                AddHtlcs:   newHtlcs,
3✔
471
                UpdateType: AddHTLCsUpdate,
3✔
472
        }
3✔
473

3✔
474
        // Don't update invoice state if we are accepting a duplicate payment.
3✔
475
        // We do accept or settle the HTLC.
3✔
476
        switch inv.State {
3✔
477
        case ContractAccepted:
×
478
                return &update, ctx.acceptRes(resultDuplicateToAccepted), nil
×
479

480
        case ContractSettled:
×
481
                return &update, ctx.settleRes(
×
482
                        *inv.Terms.PaymentPreimage, ResultDuplicateToSettled,
×
483
                ), nil
×
484
        }
485

486
        // Check to see if we can settle or this is an hold invoice and we need
487
        // to wait for the preimage.
488
        if inv.HodlInvoice {
3✔
489
                update.State = &InvoiceStateUpdateDesc{
×
490
                        NewState: ContractAccepted,
×
491
                }
×
492

×
493
                return &update, ctx.acceptRes(resultAccepted), nil
×
494
        }
×
495

496
        update.State = &InvoiceStateUpdateDesc{
3✔
497
                NewState: ContractSettled,
3✔
498
                Preimage: inv.Terms.PaymentPreimage,
3✔
499
        }
3✔
500

3✔
501
        return &update, ctx.settleRes(
3✔
502
                *inv.Terms.PaymentPreimage, ResultSettled,
3✔
503
        ), nil
3✔
504
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc