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

lightningnetwork / lnd / 13079354088

31 Jan 2025 07:19PM UTC coverage: 50.131%. First build
13079354088

Pull #9460

github

Roasbeef
docs/release-notes: add entry for AMP HTLC bug fix
Pull Request #9460: release: create branch for v0.18.5-beta.rc1

137 of 338 new or added lines in 15 files covered. (40.53%)

98580 of 196644 relevant lines covered (50.13%)

2.08 hits per line

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

80.25
/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 {
4✔
43
        switch {
4✔
44
        case i.pathID != nil:
4✔
45
                return InvoiceRefByHashAndAddr(i.hash, *i.pathID)
4✔
46

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

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

55
        default:
4✔
56
                return InvoiceRefByHash(i.hash)
4✔
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 {
4✔
64
        if i.amp != nil {
8✔
65
                setID := i.amp.SetID()
4✔
66
                return &setID
4✔
67
        }
4✔
68
        return nil
4✔
69
}
70

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

80
        log.Debugf("Invoice%v: %v, amt=%v, expiry=%v, circuit=%v, mpp=%v, "+
4✔
81
                "amp=%v, metadata=%v", i.invoiceRef(), s, i.amtPaid, i.expiry,
4✔
82
                i.circuitKey, i.mpp, i.amp, metadata)
4✔
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 {
4✔
89
        return NewFailResolution(i.circuitKey, i.currentHeight, outcome)
4✔
90
}
4✔
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 {
4✔
97

4✔
98
        return NewSettleResolution(
4✔
99
                preimage, i.circuitKey, i.currentHeight, outcome,
4✔
100
        )
4✔
101
}
4✔
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 {
4✔
108

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

112
// resolveReplayedHtlc returns the HTLC resolution for a replayed HTLC. The
113
// returned boolean indicates whether the HTLC was replayed or not.
114
func resolveReplayedHtlc(ctx *invoiceUpdateCtx, inv *Invoice) (bool,
115
        HtlcResolution, error) {
4✔
116

4✔
117
        // Don't update the invoice when this is a replayed htlc.
4✔
118
        htlc, replayedHTLC := inv.Htlcs[ctx.circuitKey]
4✔
119
        if !replayedHTLC {
8✔
120
                return false, nil, nil
4✔
121
        }
4✔
122

123
        switch htlc.State {
4✔
124
        case HtlcStateCanceled:
4✔
125
                return true, ctx.failRes(ResultReplayToCanceled), nil
4✔
126

127
        case HtlcStateAccepted:
4✔
128
                return true, ctx.acceptRes(resultReplayToAccepted), nil
4✔
129

130
        case HtlcStateSettled:
4✔
131
                pre := inv.Terms.PaymentPreimage
4✔
132

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

139
                return true, ctx.settleRes(
4✔
140
                        *pre,
4✔
141
                        ResultReplayToSettled,
4✔
142
                ), nil
4✔
143

NEW
144
        default:
×
NEW
145
                return true, nil, errors.New("unknown htlc state")
×
146
        }
147
}
148

149
// updateInvoice is a callback for DB.UpdateInvoice that contains the invoice
150
// settlement logic. It returns a HTLC resolution that indicates what the
151
// outcome of the update was.
152
//
153
// NOTE: Make sure replayed HTLCs are always considered before calling this
154
// function.
155
func updateInvoice(ctx *invoiceUpdateCtx, inv *Invoice) (
156
        *InvoiceUpdateDesc, HtlcResolution, error) {
4✔
157

4✔
158
        // If no MPP payload was provided, then we expect this to be a keysend,
4✔
159
        // or a payment to an invoice created before we started to require the
4✔
160
        // MPP payload.
4✔
161
        if ctx.mpp == nil && ctx.pathID == nil {
8✔
162
                return updateLegacy(ctx, inv)
4✔
163
        }
4✔
164

165
        return updateMpp(ctx, inv)
4✔
166
}
167

168
// updateMpp is a callback for DB.UpdateInvoice that contains the invoice
169
// settlement logic for mpp payments.
170
func updateMpp(ctx *invoiceUpdateCtx, inv *Invoice) (*InvoiceUpdateDesc,
171
        HtlcResolution, error) {
4✔
172

4✔
173
        // Reject HTLCs to AMP invoices if they are missing an AMP payload, and
4✔
174
        // HTLCs to MPP invoices if they have an AMP payload.
4✔
175
        switch {
4✔
176
        case inv.Terms.Features.RequiresFeature(lnwire.AMPRequired) &&
177
                ctx.amp == nil:
×
178

×
179
                return nil, ctx.failRes(ResultHtlcInvoiceTypeMismatch), nil
×
180

181
        case !inv.Terms.Features.RequiresFeature(lnwire.AMPRequired) &&
182
                ctx.amp != nil:
×
183

×
184
                return nil, ctx.failRes(ResultHtlcInvoiceTypeMismatch), nil
×
185
        }
186

187
        setID := ctx.setID()
4✔
188

4✔
189
        var (
4✔
190
                totalAmt    = ctx.totalAmtMsat
4✔
191
                paymentAddr []byte
4✔
192
        )
4✔
193
        // If an MPP record is present, then the payment address and total
4✔
194
        // payment amount is extracted from it. Otherwise, the pathID is used
4✔
195
        // to extract the payment address.
4✔
196
        if ctx.mpp != nil {
8✔
197
                totalAmt = ctx.mpp.TotalMsat()
4✔
198
                payAddr := ctx.mpp.PaymentAddr()
4✔
199
                paymentAddr = payAddr[:]
4✔
200
        } else {
8✔
201
                paymentAddr = ctx.pathID[:]
4✔
202
        }
4✔
203

204
        // For storage, we don't really care where the custom records came from.
205
        // So we merge them together and store them in the same field.
206
        customRecords := lnwire.CustomRecords(
4✔
207
                ctx.customRecords,
4✔
208
        ).MergedCopy(ctx.wireCustomRecords)
4✔
209

4✔
210
        // Start building the accept descriptor.
4✔
211
        acceptDesc := &HtlcAcceptDesc{
4✔
212
                Amt:           ctx.amtPaid,
4✔
213
                Expiry:        ctx.expiry,
4✔
214
                AcceptHeight:  ctx.currentHeight,
4✔
215
                MppTotalAmt:   totalAmt,
4✔
216
                CustomRecords: record.CustomSet(customRecords),
4✔
217
        }
4✔
218

4✔
219
        if ctx.amp != nil {
8✔
220
                acceptDesc.AMP = &InvoiceHtlcAMPData{
4✔
221
                        Record:   *ctx.amp,
4✔
222
                        Hash:     ctx.hash,
4✔
223
                        Preimage: nil,
4✔
224
                }
4✔
225
        }
4✔
226

227
        // Only accept payments to open invoices. This behaviour differs from
228
        // non-mpp payments that are accepted even after the invoice is settled.
229
        // Because non-mpp payments don't have a payment address, this is needed
230
        // to thwart probing.
231
        if inv.State != ContractOpen {
4✔
232
                return nil, ctx.failRes(ResultInvoiceNotOpen), nil
×
233
        }
×
234

235
        // Check the payment address that authorizes the payment.
236
        if !bytes.Equal(paymentAddr, inv.Terms.PaymentAddr[:]) {
4✔
237
                return nil, ctx.failRes(ResultAddressMismatch), nil
×
238
        }
×
239

240
        // Don't accept zero-valued sets.
241
        if totalAmt == 0 {
4✔
242
                return nil, ctx.failRes(ResultHtlcSetTotalTooLow), nil
×
243
        }
×
244

245
        // Check that the total amt of the htlc set is high enough. In case this
246
        // is a zero-valued invoice, it will always be enough.
247
        if totalAmt < inv.Terms.Value {
4✔
248
                return nil, ctx.failRes(ResultHtlcSetTotalTooLow), nil
×
249
        }
×
250

251
        htlcSet := inv.HTLCSet(setID, HtlcStateAccepted)
4✔
252

4✔
253
        // Check whether total amt matches other HTLCs in the set.
4✔
254
        var newSetTotal lnwire.MilliSatoshi
4✔
255
        for _, htlc := range htlcSet {
8✔
256
                if totalAmt != htlc.MppTotalAmt {
4✔
257
                        return nil, ctx.failRes(ResultHtlcSetTotalMismatch), nil
×
258
                }
×
259

260
                newSetTotal += htlc.Amt
4✔
261
        }
262

263
        // Add amount of new htlc.
264
        newSetTotal += ctx.amtPaid
4✔
265

4✔
266
        // The invoice is still open. Check the expiry.
4✔
267
        if ctx.expiry < uint32(ctx.currentHeight+ctx.finalCltvRejectDelta) {
4✔
268
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
269
        }
×
270

271
        if ctx.expiry < uint32(ctx.currentHeight+inv.Terms.FinalCltvDelta) {
4✔
272
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
273
        }
×
274

275
        if setID != nil && *setID == BlankPayAddr {
4✔
276
                return nil, ctx.failRes(ResultAmpError), nil
×
277
        }
×
278

279
        // Record HTLC in the invoice database.
280
        newHtlcs := map[CircuitKey]*HtlcAcceptDesc{
4✔
281
                ctx.circuitKey: acceptDesc,
4✔
282
        }
4✔
283

4✔
284
        update := InvoiceUpdateDesc{
4✔
285
                UpdateType: AddHTLCsUpdate,
4✔
286
                AddHtlcs:   newHtlcs,
4✔
287
        }
4✔
288

4✔
289
        // If the invoice cannot be settled yet, only record the htlc.
4✔
290
        setComplete := newSetTotal >= totalAmt
4✔
291
        if !setComplete {
8✔
292
                return &update, ctx.acceptRes(resultPartialAccepted), nil
4✔
293
        }
4✔
294

295
        // Check to see if we can settle or this is a hold invoice, and
296
        // we need to wait for the preimage.
297
        if inv.HodlInvoice {
8✔
298
                update.State = &InvoiceStateUpdateDesc{
4✔
299
                        NewState: ContractAccepted,
4✔
300
                }
4✔
301
                return &update, ctx.acceptRes(resultAccepted), nil
4✔
302
        }
4✔
303

304
        var (
4✔
305
                htlcPreimages map[CircuitKey]lntypes.Preimage
4✔
306
                htlcPreimage  lntypes.Preimage
4✔
307
        )
4✔
308
        if ctx.amp != nil {
8✔
309
                var failRes *HtlcFailResolution
4✔
310
                htlcPreimages, failRes = reconstructAMPPreimages(ctx, htlcSet)
4✔
311
                if failRes != nil {
4✔
312
                        update.UpdateType = CancelInvoiceUpdate
×
313
                        update.State = &InvoiceStateUpdateDesc{
×
314
                                NewState: ContractCanceled,
×
315
                                SetID:    setID,
×
316
                        }
×
317
                        return &update, failRes, nil
×
318
                }
×
319

320
                // The preimage for _this_ HTLC will be the one with context's
321
                // circuit key.
322
                htlcPreimage = htlcPreimages[ctx.circuitKey]
4✔
323
        } else {
4✔
324
                htlcPreimage = *inv.Terms.PaymentPreimage
4✔
325
        }
4✔
326

327
        update.State = &InvoiceStateUpdateDesc{
4✔
328
                NewState:      ContractSettled,
4✔
329
                Preimage:      inv.Terms.PaymentPreimage,
4✔
330
                HTLCPreimages: htlcPreimages,
4✔
331
                SetID:         setID,
4✔
332
        }
4✔
333

4✔
334
        return &update, ctx.settleRes(htlcPreimage, ResultSettled), nil
4✔
335
}
336

337
// HTLCSet is a map of CircuitKey to InvoiceHTLC.
338
type HTLCSet = map[CircuitKey]*InvoiceHTLC
339

340
// HTLCPreimages is a map of CircuitKey to preimage.
341
type HTLCPreimages = map[CircuitKey]lntypes.Preimage
342

343
// reconstructAMPPreimages reconstructs the root seed for an AMP HTLC set and
344
// verifies that all derived child hashes match the payment hashes of the HTLCs
345
// in the set. This method is meant to be called after receiving the full amount
346
// committed to via mpp_total_msat. This method will return a fail resolution if
347
// any of the child hashes fail to match their corresponding HTLCs.
348
func reconstructAMPPreimages(ctx *invoiceUpdateCtx,
349
        htlcSet HTLCSet) (HTLCPreimages, *HtlcFailResolution) {
4✔
350

4✔
351
        // Create a slice containing all the child descriptors to be used for
4✔
352
        // reconstruction. This should include all HTLCs currently in the HTLC
4✔
353
        // set, plus the incoming HTLC.
4✔
354
        childDescs := make([]amp.ChildDesc, 0, 1+len(htlcSet))
4✔
355

4✔
356
        // Add the new HTLC's child descriptor at index 0.
4✔
357
        childDescs = append(childDescs, amp.ChildDesc{
4✔
358
                Share: ctx.amp.RootShare(),
4✔
359
                Index: ctx.amp.ChildIndex(),
4✔
360
        })
4✔
361

4✔
362
        // Next, construct an index mapping the position in childDescs to a
4✔
363
        // circuit key for all preexisting HTLCs.
4✔
364
        indexToCircuitKey := make(map[int]CircuitKey)
4✔
365

4✔
366
        // Add the child descriptor for each HTLC in the HTLC set, recording
4✔
367
        // it's position within the slice.
4✔
368
        var htlcSetIndex int
4✔
369
        for circuitKey, htlc := range htlcSet {
8✔
370
                childDescs = append(childDescs, amp.ChildDesc{
4✔
371
                        Share: htlc.AMP.Record.RootShare(),
4✔
372
                        Index: htlc.AMP.Record.ChildIndex(),
4✔
373
                })
4✔
374
                indexToCircuitKey[htlcSetIndex] = circuitKey
4✔
375
                htlcSetIndex++
4✔
376
        }
4✔
377

378
        // Using the child descriptors, reconstruct the root seed and derive the
379
        // child hash/preimage pairs for each of the HTLCs.
380
        children := amp.ReconstructChildren(childDescs...)
4✔
381

4✔
382
        // Validate that the derived child preimages match the hash of each
4✔
383
        // HTLC's respective hash.
4✔
384
        if ctx.hash != children[0].Hash {
4✔
385
                return nil, ctx.failRes(ResultAmpReconstruction)
×
386
        }
×
387
        for idx, child := range children[1:] {
8✔
388
                circuitKey := indexToCircuitKey[idx]
4✔
389
                htlc := htlcSet[circuitKey]
4✔
390
                if htlc.AMP.Hash != child.Hash {
4✔
391
                        return nil, ctx.failRes(ResultAmpReconstruction)
×
392
                }
×
393
        }
394

395
        // Finally, construct the map of learned preimages indexed by circuit
396
        // key, so that they can be persisted along with each HTLC when updating
397
        // the invoice.
398
        htlcPreimages := make(map[CircuitKey]lntypes.Preimage)
4✔
399
        htlcPreimages[ctx.circuitKey] = children[0].Preimage
4✔
400
        for idx, child := range children[1:] {
8✔
401
                circuitKey := indexToCircuitKey[idx]
4✔
402
                htlcPreimages[circuitKey] = child.Preimage
4✔
403
        }
4✔
404

405
        return htlcPreimages, nil
4✔
406
}
407

408
// updateLegacy is a callback for DB.UpdateInvoice that contains the invoice
409
// settlement logic for legacy payments.
410
//
411
// NOTE: This function is only kept in place in order to be able to handle key
412
// send payments and any invoices we created in the past that are valid and
413
// still had the optional mpp bit set.
414
func updateLegacy(ctx *invoiceUpdateCtx,
415
        inv *Invoice) (*InvoiceUpdateDesc, HtlcResolution, error) {
4✔
416

4✔
417
        // If the invoice is already canceled, there is no further
4✔
418
        // checking to do.
4✔
419
        if inv.State == ContractCanceled {
4✔
420
                return nil, ctx.failRes(ResultInvoiceAlreadyCanceled), nil
×
421
        }
×
422

423
        // If an invoice amount is specified, check that enough is paid. Also
424
        // check this for duplicate payments if the invoice is already settled
425
        // or accepted. In case this is a zero-valued invoice, it will always be
426
        // enough.
427
        if ctx.amtPaid < inv.Terms.Value {
8✔
428
                return nil, ctx.failRes(ResultAmountTooLow), nil
4✔
429
        }
4✔
430

431
        // If the invoice had the required feature bit set at this point, then
432
        // if we're in this method it means that the remote party didn't supply
433
        // the expected payload. However if this is a keysend payment, then
434
        // we'll permit it to pass.
435
        _, isKeySend := ctx.customRecords[record.KeySendType]
4✔
436
        invoiceFeatures := inv.Terms.Features
4✔
437
        paymentAddrRequired := invoiceFeatures.RequiresFeature(
4✔
438
                lnwire.PaymentAddrRequired,
4✔
439
        )
4✔
440
        if !isKeySend && paymentAddrRequired {
4✔
441
                log.Warnf("Payment to pay_hash=%v doesn't include MPP "+
×
442
                        "payload, rejecting", ctx.hash)
×
443
                return nil, ctx.failRes(ResultAddressMismatch), nil
×
444
        }
×
445

446
        // Don't allow settling the invoice with an old style
447
        // htlc if we are already in the process of gathering an
448
        // mpp set.
449
        for _, htlc := range inv.HTLCSet(nil, HtlcStateAccepted) {
4✔
450
                if htlc.MppTotalAmt > 0 {
×
451
                        return nil, ctx.failRes(ResultMppInProgress), nil
×
452
                }
×
453
        }
454

455
        // The invoice is still open. Check the expiry.
456
        if ctx.expiry < uint32(ctx.currentHeight+ctx.finalCltvRejectDelta) {
4✔
457
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
458
        }
×
459

460
        if ctx.expiry < uint32(ctx.currentHeight+inv.Terms.FinalCltvDelta) {
4✔
461
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
462
        }
×
463

464
        // For storage, we don't really care where the custom records came from.
465
        // So we merge them together and store them in the same field.
466
        customRecords := lnwire.CustomRecords(
4✔
467
                ctx.customRecords,
4✔
468
        ).MergedCopy(ctx.wireCustomRecords)
4✔
469

4✔
470
        // Record HTLC in the invoice database.
4✔
471
        newHtlcs := map[CircuitKey]*HtlcAcceptDesc{
4✔
472
                ctx.circuitKey: {
4✔
473
                        Amt:           ctx.amtPaid,
4✔
474
                        Expiry:        ctx.expiry,
4✔
475
                        AcceptHeight:  ctx.currentHeight,
4✔
476
                        CustomRecords: record.CustomSet(customRecords),
4✔
477
                },
4✔
478
        }
4✔
479

4✔
480
        update := InvoiceUpdateDesc{
4✔
481
                AddHtlcs:   newHtlcs,
4✔
482
                UpdateType: AddHTLCsUpdate,
4✔
483
        }
4✔
484

4✔
485
        // Don't update invoice state if we are accepting a duplicate payment.
4✔
486
        // We do accept or settle the HTLC.
4✔
487
        switch inv.State {
4✔
488
        case ContractAccepted:
×
489
                return &update, ctx.acceptRes(resultDuplicateToAccepted), nil
×
490

491
        case ContractSettled:
×
492
                return &update, ctx.settleRes(
×
493
                        *inv.Terms.PaymentPreimage, ResultDuplicateToSettled,
×
494
                ), nil
×
495
        }
496

497
        // Check to see if we can settle or this is an hold invoice and we need
498
        // to wait for the preimage.
499
        if inv.HodlInvoice {
4✔
500
                update.State = &InvoiceStateUpdateDesc{
×
501
                        NewState: ContractAccepted,
×
502
                }
×
503

×
504
                return &update, ctx.acceptRes(resultAccepted), nil
×
505
        }
×
506

507
        update.State = &InvoiceStateUpdateDesc{
4✔
508
                NewState: ContractSettled,
4✔
509
                Preimage: inv.Terms.PaymentPreimage,
4✔
510
        }
4✔
511

4✔
512
        return &update, ctx.settleRes(
4✔
513
                *inv.Terms.PaymentPreimage, ResultSettled,
4✔
514
        ), nil
4✔
515
}
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