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

lightningnetwork / lnd / 12199391122

06 Dec 2024 01:10PM UTC coverage: 49.807% (-9.1%) from 58.933%
12199391122

push

github

web-flow
Merge pull request #9337 from Guayaba221/patch-1

chore: fix typo in ruby.md

100137 of 201051 relevant lines covered (49.81%)

2.07 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 {
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
// 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) {
4✔
117

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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