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

lightningnetwork / lnd / 12033440129

26 Nov 2024 03:03PM UTC coverage: 48.738% (-10.3%) from 58.999%
12033440129

Pull #9309

github

yyforyongyu
gomod: update `btcd` for shutdown fix
Pull Request #9309: chainntnfs: fix `TestHistoricalConfDetailsTxIndex`

97664 of 200385 relevant lines covered (48.74%)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

293
        var (
1✔
294
                htlcPreimages map[CircuitKey]lntypes.Preimage
1✔
295
                htlcPreimage  lntypes.Preimage
1✔
296
        )
1✔
297
        if ctx.amp != nil {
2✔
298
                var failRes *HtlcFailResolution
1✔
299
                htlcPreimages, failRes = reconstructAMPPreimages(ctx, htlcSet)
1✔
300
                if failRes != nil {
1✔
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]
1✔
312
        } else {
1✔
313
                htlcPreimage = *inv.Terms.PaymentPreimage
1✔
314
        }
1✔
315

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

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

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

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

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

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

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

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

1✔
406
        // If the invoice is already canceled, there is no further
1✔
407
        // checking to do.
1✔
408
        if inv.State == ContractCanceled {
1✔
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 {
2✔
417
                return nil, ctx.failRes(ResultAmountTooLow), nil
1✔
418
        }
1✔
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]
1✔
425
        invoiceFeatures := inv.Terms.Features
1✔
426
        paymentAddrRequired := invoiceFeatures.RequiresFeature(
1✔
427
                lnwire.PaymentAddrRequired,
1✔
428
        )
1✔
429
        if !isKeySend && paymentAddrRequired {
1✔
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) {
1✔
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) {
1✔
446
                return nil, ctx.failRes(ResultExpiryTooSoon), nil
×
447
        }
×
448

449
        if ctx.expiry < uint32(ctx.currentHeight+inv.Terms.FinalCltvDelta) {
1✔
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(
1✔
456
                ctx.customRecords,
1✔
457
        ).MergedCopy(ctx.wireCustomRecords)
1✔
458

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

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

1✔
474
        // Don't update invoice state if we are accepting a duplicate payment.
1✔
475
        // We do accept or settle the HTLC.
1✔
476
        switch inv.State {
1✔
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 {
1✔
489
                update.State = &InvoiceStateUpdateDesc{
×
490
                        NewState: ContractAccepted,
×
491
                }
×
492

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

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

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