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

lightningnetwork / lnd / 11170835610

03 Oct 2024 10:41PM UTC coverage: 49.188% (-9.6%) from 58.738%
11170835610

push

github

web-flow
Merge pull request #9154 from ziggie1984/master

multi: bump btcd version.

3 of 6 new or added lines in 6 files covered. (50.0%)

26110 existing lines in 428 files now uncovered.

97359 of 197934 relevant lines covered (49.19%)

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

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

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

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

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

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

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

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

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

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

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

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

137
                        return nil, ctx.settleRes(
2✔
138
                                *pre,
2✔
139
                                ResultReplayToSettled,
2✔
140
                        ), nil
2✔
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 {
4✔
151
                return updateLegacy(ctx, inv)
2✔
152
        }
2✔
153

154
        return updateMpp(ctx, inv)
2✔
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) {
2✔
161

2✔
162
        // Reject HTLCs to AMP invoices if they are missing an AMP payload, and
2✔
163
        // HTLCs to MPP invoices if they have an AMP payload.
2✔
164
        switch {
2✔
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()
2✔
177

2✔
178
        var (
2✔
179
                totalAmt    = ctx.totalAmtMsat
2✔
180
                paymentAddr []byte
2✔
181
        )
2✔
182
        // If an MPP record is present, then the payment address and total
2✔
183
        // payment amount is extracted from it. Otherwise, the pathID is used
2✔
184
        // to extract the payment address.
2✔
185
        if ctx.mpp != nil {
4✔
186
                totalAmt = ctx.mpp.TotalMsat()
2✔
187
                payAddr := ctx.mpp.PaymentAddr()
2✔
188
                paymentAddr = payAddr[:]
2✔
189
        } else {
4✔
190
                paymentAddr = ctx.pathID[:]
2✔
191
        }
2✔
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(
2✔
196
                ctx.customRecords,
2✔
197
        ).MergedCopy(ctx.wireCustomRecords)
2✔
198

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

2✔
208
        if ctx.amp != nil {
4✔
209
                acceptDesc.AMP = &InvoiceHtlcAMPData{
2✔
210
                        Record:   *ctx.amp,
2✔
211
                        Hash:     ctx.hash,
2✔
212
                        Preimage: nil,
2✔
213
                }
2✔
214
        }
2✔
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 {
2✔
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[:]) {
2✔
226
                return nil, ctx.failRes(ResultAddressMismatch), nil
×
227
        }
×
228

229
        // Don't accept zero-valued sets.
230
        if totalAmt == 0 {
2✔
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 {
2✔
237
                return nil, ctx.failRes(ResultHtlcSetTotalTooLow), nil
×
238
        }
×
239

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

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

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

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

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

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

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

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

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

2✔
278
        // If the invoice cannot be settled yet, only record the htlc.
2✔
279
        setComplete := newSetTotal >= totalAmt
2✔
280
        if !setComplete {
4✔
281
                return &update, ctx.acceptRes(resultPartialAccepted), nil
2✔
282
        }
2✔
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 {
4✔
287
                update.State = &InvoiceStateUpdateDesc{
2✔
288
                        NewState: ContractAccepted,
2✔
289
                }
2✔
290
                return &update, ctx.acceptRes(resultAccepted), nil
2✔
291
        }
2✔
292

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

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

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

2✔
323
        return &update, ctx.settleRes(htlcPreimage, ResultSettled), nil
2✔
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) {
2✔
339

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

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

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

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

2✔
371
        // Validate that the derived child preimages match the hash of each
2✔
372
        // HTLC's respective hash.
2✔
373
        if ctx.hash != children[0].Hash {
2✔
UNCOV
374
                return nil, ctx.failRes(ResultAmpReconstruction)
×
UNCOV
375
        }
×
376
        for idx, child := range children[1:] {
4✔
377
                circuitKey := indexToCircuitKey[idx]
2✔
378
                htlc := htlcSet[circuitKey]
2✔
379
                if htlc.AMP.Hash != child.Hash {
2✔
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)
2✔
388
        htlcPreimages[ctx.circuitKey] = children[0].Preimage
2✔
389
        for idx, child := range children[1:] {
4✔
390
                circuitKey := indexToCircuitKey[idx]
2✔
391
                htlcPreimages[circuitKey] = child.Preimage
2✔
392
        }
2✔
393

394
        return htlcPreimages, nil
2✔
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) {
2✔
405

2✔
406
        // If the invoice is already canceled, there is no further
2✔
407
        // checking to do.
2✔
408
        if inv.State == ContractCanceled {
2✔
UNCOV
409
                return nil, ctx.failRes(ResultInvoiceAlreadyCanceled), nil
×
UNCOV
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 {
4✔
417
                return nil, ctx.failRes(ResultAmountTooLow), nil
2✔
418
        }
2✔
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]
2✔
425
        invoiceFeatures := inv.Terms.Features
2✔
426
        paymentAddrRequired := invoiceFeatures.RequiresFeature(
2✔
427
                lnwire.PaymentAddrRequired,
2✔
428
        )
2✔
429
        if !isKeySend && paymentAddrRequired {
2✔
UNCOV
430
                log.Warnf("Payment to pay_hash=%v doesn't include MPP "+
×
UNCOV
431
                        "payload, rejecting", ctx.hash)
×
UNCOV
432
                return nil, ctx.failRes(ResultAddressMismatch), nil
×
UNCOV
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) {
2✔
UNCOV
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) {
2✔
UNCOV
446
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
UNCOV
447
        }
×
448

449
        if ctx.expiry < uint32(ctx.currentHeight+inv.Terms.FinalCltvDelta) {
2✔
UNCOV
450
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
UNCOV
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(
2✔
456
                ctx.customRecords,
2✔
457
        ).MergedCopy(ctx.wireCustomRecords)
2✔
458

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

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

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

UNCOV
480
        case ContractSettled:
×
UNCOV
481
                return &update, ctx.settleRes(
×
UNCOV
482
                        *inv.Terms.PaymentPreimage, ResultDuplicateToSettled,
×
UNCOV
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 {
2✔
UNCOV
489
                update.State = &InvoiceStateUpdateDesc{
×
UNCOV
490
                        NewState: ContractAccepted,
×
UNCOV
491
                }
×
UNCOV
492

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

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

2✔
501
        return &update, ctx.settleRes(
2✔
502
                *inv.Terms.PaymentPreimage, ResultSettled,
2✔
503
        ), nil
2✔
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