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

lightningnetwork / lnd / 13045835407

30 Jan 2025 04:48AM UTC coverage: 58.782% (+0.005%) from 58.777%
13045835407

push

github

web-flow
Merge pull request #9454 from ziggie1984/add_custom_error_msg

Add Custom Error msg and Prioritise replayed HTLCs

113 of 133 new or added lines in 6 files covered. (84.96%)

76 existing lines in 21 files now uncovered.

136069 of 231481 relevant lines covered (58.78%)

19289.04 hits per line

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

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

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

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

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

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

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

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

434✔
109
        return newAcceptResolution(i.circuitKey, outcome)
434✔
110
}
434✔
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) {
936✔
116

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

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

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

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

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

139
                return true, ctx.settleRes(
9✔
140
                        *pre,
9✔
141
                        ResultReplayToSettled,
9✔
142
                ), nil
9✔
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) {
917✔
157

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

165
        return updateMpp(ctx, inv)
669✔
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) {
669✔
172

669✔
173
        // Reject HTLCs to AMP invoices if they are missing an AMP payload, and
669✔
174
        // HTLCs to MPP invoices if they have an AMP payload.
669✔
175
        switch {
669✔
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()
669✔
188

669✔
189
        var (
669✔
190
                totalAmt    = ctx.totalAmtMsat
669✔
191
                paymentAddr []byte
669✔
192
        )
669✔
193
        // If an MPP record is present, then the payment address and total
669✔
194
        // payment amount is extracted from it. Otherwise, the pathID is used
669✔
195
        // to extract the payment address.
669✔
196
        if ctx.mpp != nil {
1,338✔
197
                totalAmt = ctx.mpp.TotalMsat()
669✔
198
                payAddr := ctx.mpp.PaymentAddr()
669✔
199
                paymentAddr = payAddr[:]
669✔
200
        } else {
672✔
201
                paymentAddr = ctx.pathID[:]
3✔
202
        }
3✔
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(
669✔
207
                ctx.customRecords,
669✔
208
        ).MergedCopy(ctx.wireCustomRecords)
669✔
209

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

669✔
219
        if ctx.amp != nil {
705✔
220
                acceptDesc.AMP = &InvoiceHtlcAMPData{
36✔
221
                        Record:   *ctx.amp,
36✔
222
                        Hash:     ctx.hash,
36✔
223
                        Preimage: nil,
36✔
224
                }
36✔
225
        }
36✔
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 {
669✔
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[:]) {
669✔
237
                return nil, ctx.failRes(ResultAddressMismatch), nil
×
238
        }
×
239

240
        // Don't accept zero-valued sets.
241
        if totalAmt == 0 {
669✔
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 {
669✔
248
                return nil, ctx.failRes(ResultHtlcSetTotalTooLow), nil
×
249
        }
×
250

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

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

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

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

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

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

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

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

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

669✔
289
        // If the invoice cannot be settled yet, only record the htlc.
669✔
290
        setComplete := newSetTotal >= totalAmt
669✔
291
        if !setComplete {
1,014✔
292
                return &update, ctx.acceptRes(resultPartialAccepted), nil
345✔
293
        }
345✔
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 {
339✔
298
                update.State = &InvoiceStateUpdateDesc{
12✔
299
                        NewState: ContractAccepted,
12✔
300
                }
12✔
301
                return &update, ctx.acceptRes(resultAccepted), nil
12✔
302
        }
12✔
303

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

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

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

312✔
334
        return &update, ctx.settleRes(htlcPreimage, ResultSettled), nil
312✔
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) {
15✔
350

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

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

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

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

15✔
382
        // Validate that the derived child preimages match the hash of each
15✔
383
        // HTLC's respective hash.
15✔
384
        if ctx.hash != children[0].Hash {
21✔
385
                return nil, ctx.failRes(ResultAmpReconstruction)
6✔
386
        }
6✔
387
        for idx, child := range children[1:] {
18✔
388
                circuitKey := indexToCircuitKey[idx]
9✔
389
                htlc := htlcSet[circuitKey]
9✔
390
                if htlc.AMP.Hash != child.Hash {
9✔
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)
9✔
399
        htlcPreimages[ctx.circuitKey] = children[0].Preimage
9✔
400
        for idx, child := range children[1:] {
18✔
401
                circuitKey := indexToCircuitKey[idx]
9✔
402
                htlcPreimages[circuitKey] = child.Preimage
9✔
403
        }
9✔
404

405
        return htlcPreimages, nil
9✔
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) {
251✔
416

251✔
417
        // If the invoice is already canceled, there is no further
251✔
418
        // checking to do.
251✔
419
        if inv.State == ContractCanceled {
255✔
420
                return nil, ctx.failRes(ResultInvoiceAlreadyCanceled), nil
4✔
421
        }
4✔
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 {
253✔
428
                return nil, ctx.failRes(ResultAmountTooLow), nil
6✔
429
        }
6✔
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]
244✔
436
        invoiceFeatures := inv.Terms.Features
244✔
437
        paymentAddrRequired := invoiceFeatures.RequiresFeature(
244✔
438
                lnwire.PaymentAddrRequired,
244✔
439
        )
244✔
440
        if !isKeySend && paymentAddrRequired {
247✔
441
                log.Warnf("Payment to pay_hash=%v doesn't include MPP "+
3✔
442
                        "payload, rejecting", ctx.hash)
3✔
443
                return nil, ctx.failRes(ResultAddressMismatch), nil
3✔
444
        }
3✔
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) {
244✔
450
                if htlc.MppTotalAmt > 0 {
3✔
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) {
247✔
457
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
6✔
458
        }
6✔
459

460
        if ctx.expiry < uint32(ctx.currentHeight+inv.Terms.FinalCltvDelta) {
236✔
461
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
1✔
462
        }
1✔
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(
234✔
467
                ctx.customRecords,
234✔
468
        ).MergedCopy(ctx.wireCustomRecords)
234✔
469

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

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

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

491
        case ContractSettled:
3✔
492
                return &update, ctx.settleRes(
3✔
493
                        *inv.Terms.PaymentPreimage, ResultDuplicateToSettled,
3✔
494
                ), nil
3✔
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 {
304✔
500
                update.State = &InvoiceStateUpdateDesc{
73✔
501
                        NewState: ContractAccepted,
73✔
502
                }
73✔
503

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

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

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