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

lightningnetwork / lnd / 12168656289

04 Dec 2024 09:30PM UTC coverage: 49.3% (-9.5%) from 58.789%
12168656289

Pull #9316

github

ziggie1984
docs: add release-notes.
Pull Request #9316: routing: fix mc blinded path behaviour.

75 of 79 new or added lines in 4 files covered. (94.94%)

26127 existing lines in 423 files now uncovered.

99116 of 201048 relevant lines covered (49.3%)

1.56 hits per line

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

69.15
/routing/result_interpretation.go
1
package routing
2

3
import (
4
        "bytes"
5
        "fmt"
6
        "io"
7

8
        "github.com/lightningnetwork/lnd/channeldb"
9
        "github.com/lightningnetwork/lnd/fn"
10
        "github.com/lightningnetwork/lnd/lnwire"
11
        "github.com/lightningnetwork/lnd/routing/route"
12
        "github.com/lightningnetwork/lnd/tlv"
13
)
14

15
// Instantiate variables to allow taking a reference from the failure reason.
16
var (
17
        reasonError            = channeldb.FailureReasonError
18
        reasonIncorrectDetails = channeldb.FailureReasonPaymentDetails
19
)
20

21
// pairResult contains the result of the interpretation of a payment attempt for
22
// a specific node pair.
23
type pairResult struct {
24
        // amt is the amount that was forwarded for this pair. Can be set to
25
        // zero for failures that are amount independent.
26
        amt lnwire.MilliSatoshi
27

28
        // success indicates whether the payment attempt was successful through
29
        // this pair.
30
        success bool
31
}
32

33
// failPairResult creates a new result struct for a failure.
34
func failPairResult(minPenalizeAmt lnwire.MilliSatoshi) pairResult {
3✔
35
        return pairResult{
3✔
36
                amt: minPenalizeAmt,
3✔
37
        }
3✔
38
}
3✔
39

40
// newSuccessPairResult creates a new result struct for a success.
41
func successPairResult(successAmt lnwire.MilliSatoshi) pairResult {
3✔
42
        return pairResult{
3✔
43
                success: true,
3✔
44
                amt:     successAmt,
3✔
45
        }
3✔
46
}
3✔
47

48
// String returns the human-readable representation of a pair result.
49
func (p pairResult) String() string {
×
50
        var resultType string
×
51
        if p.success {
×
52
                resultType = "success"
×
53
        } else {
×
54
                resultType = "failed"
×
55
        }
×
56

57
        return fmt.Sprintf("%v (amt=%v)", resultType, p.amt)
×
58
}
59

60
// interpretedResult contains the result of the interpretation of a payment
61
// attempt.
62
type interpretedResult struct {
63
        // nodeFailure points to a node pubkey if all channels of that node are
64
        // responsible for the result.
65
        nodeFailure *route.Vertex
66

67
        // pairResults contains a map of node pairs for which we have a result.
68
        pairResults map[DirectedNodePair]pairResult
69

70
        // finalFailureReason is set to a non-nil value if it makes no more
71
        // sense to start another payment attempt. It will contain the reason
72
        // why.
73
        finalFailureReason *channeldb.FailureReason
74

75
        // policyFailure is set to a node pair if there is a policy failure on
76
        // that connection. This is used to control the second chance logic for
77
        // policy failures.
78
        policyFailure *DirectedNodePair
79
}
80

81
// interpretResult interprets a payment outcome and returns an object that
82
// contains information required to update mission control.
83
func interpretResult(rt *mcRoute,
84
        failure fn.Option[paymentFailure]) *interpretedResult {
3✔
85

3✔
86
        i := &interpretedResult{
3✔
87
                pairResults: make(map[DirectedNodePair]pairResult),
3✔
88
        }
3✔
89

3✔
90
        return fn.ElimOption(failure, func() *interpretedResult {
6✔
91
                i.processSuccess(rt)
3✔
92

3✔
93
                return i
3✔
94
        }, func(info paymentFailure) *interpretedResult {
6✔
95
                i.processFail(rt, info)
3✔
96

3✔
97
                return i
3✔
98
        })
3✔
99
}
100

101
// processSuccess processes a successful payment attempt.
102
func (i *interpretedResult) processSuccess(route *mcRoute) {
3✔
103
        // For successes, all nodes must have acted in the right way. Therefore
3✔
104
        // we mark all of them with a success result.
3✔
105
        i.successPairRange(route, 0, len(route.hops.Val)-1)
3✔
106
}
3✔
107

108
// processFail processes a failed payment attempt.
109
func (i *interpretedResult) processFail(rt *mcRoute, failure paymentFailure) {
3✔
110
        if failure.info.IsNone() {
3✔
UNCOV
111
                i.processPaymentOutcomeUnknown(rt)
×
UNCOV
112
                return
×
UNCOV
113
        }
×
114

115
        var (
3✔
116
                idx     int
3✔
117
                failMsg lnwire.FailureMessage
3✔
118
        )
3✔
119

3✔
120
        failure.info.WhenSome(
3✔
121
                func(r tlv.RecordT[tlv.TlvType0, paymentFailureInfo]) {
6✔
122
                        idx = int(r.Val.sourceIdx.Val)
3✔
123
                        failMsg = r.Val.msg.Val.FailureMessage
3✔
124
                },
3✔
125
        )
126

127
        // If the payment was to a blinded route and we received an error from
128
        // after the introduction point, handle this error separately - there
129
        // has been a protocol violation from the introduction node. This
130
        // penalty applies regardless of the error code that is returned.
131
        introIdx, isBlinded := introductionPointIndex(rt)
3✔
132
        if isBlinded && introIdx < idx {
3✔
UNCOV
133
                i.processPaymentOutcomeBadIntro(rt, introIdx, idx)
×
UNCOV
134
                return
×
UNCOV
135
        }
×
136

137
        switch idx {
3✔
138
        // We are the source of the failure.
139
        case 0:
3✔
140
                i.processPaymentOutcomeSelf(rt, failMsg)
3✔
141

142
        // A failure from the final hop was received.
143
        case len(rt.hops.Val):
3✔
144
                i.processPaymentOutcomeFinal(rt, failMsg)
3✔
145

146
        // An intermediate hop failed. Interpret the outcome, update reputation
147
        // and try again.
148
        default:
3✔
149
                i.processPaymentOutcomeIntermediate(rt, idx, failMsg)
3✔
150
        }
151
}
152

153
// processPaymentOutcomeBadIntro handles the case where we have made payment
154
// to a blinded route, but received an error from a node after the introduction
155
// node. This indicates that the introduction node is not obeying the route
156
// blinding specification, as we expect all errors from the introduction node
157
// to be source from it.
158
func (i *interpretedResult) processPaymentOutcomeBadIntro(route *mcRoute,
UNCOV
159
        introIdx, errSourceIdx int) {
×
UNCOV
160

×
UNCOV
161
        // We fail the introduction node for not obeying the specification.
×
UNCOV
162
        i.failNode(route, introIdx)
×
UNCOV
163

×
UNCOV
164
        // Other preceding channels in the route forwarded correctly. Note
×
UNCOV
165
        // that we do not assign success to the incoming link to the
×
UNCOV
166
        // introduction node because it has not handled the error correctly.
×
UNCOV
167
        if introIdx > 1 {
×
UNCOV
168
                i.successPairRange(route, 0, introIdx-2)
×
UNCOV
169
        }
×
170

171
        // If the source of the failure was from the final node, we also set
172
        // a final failure reason because the recipient can't process the
173
        // payment (independent of the introduction failing to convert the
174
        // error, we can't complete the payment if the last hop fails).
UNCOV
175
        if errSourceIdx == len(route.hops.Val) {
×
UNCOV
176
                i.finalFailureReason = &reasonError
×
UNCOV
177
        }
×
178
}
179

180
// processPaymentOutcomeSelf handles failures sent by ourselves.
181
func (i *interpretedResult) processPaymentOutcomeSelf(rt *mcRoute,
182
        failure lnwire.FailureMessage) {
3✔
183

3✔
184
        switch failure.(type) {
3✔
185

186
        // We receive a malformed htlc failure from our peer. We trust ourselves
187
        // to send the correct htlc, so our peer must be at fault.
188
        case *lnwire.FailInvalidOnionVersion,
189
                *lnwire.FailInvalidOnionHmac,
UNCOV
190
                *lnwire.FailInvalidOnionKey:
×
UNCOV
191

×
UNCOV
192
                i.failNode(rt, 1)
×
UNCOV
193

×
UNCOV
194
                // If this was a payment to a direct peer, we can stop trying.
×
UNCOV
195
                if len(rt.hops.Val) == 1 {
×
UNCOV
196
                        i.finalFailureReason = &reasonError
×
UNCOV
197
                }
×
198

199
        // Any other failure originating from ourselves should be temporary and
200
        // caused by changing conditions between path finding and execution of
201
        // the payment. We just retry and trust that the information locally
202
        // available in the link has been updated.
203
        default:
3✔
204
                log.Warnf("Routing failure for local channel %v occurred",
3✔
205
                        rt.hops.Val[0].channelID)
3✔
206
        }
207
}
208

209
// processPaymentOutcomeFinal handles failures sent by the final hop.
210
func (i *interpretedResult) processPaymentOutcomeFinal(route *mcRoute,
211
        failure lnwire.FailureMessage) {
3✔
212

3✔
213
        n := len(route.hops.Val)
3✔
214

3✔
215
        failNode := func() {
3✔
UNCOV
216
                i.failNode(route, n)
×
UNCOV
217

×
UNCOV
218
                // Other channels in the route forwarded correctly.
×
UNCOV
219
                if n > 1 {
×
UNCOV
220
                        i.successPairRange(route, 0, n-2)
×
UNCOV
221
                }
×
222

UNCOV
223
                i.finalFailureReason = &reasonError
×
224
        }
225

226
        // If a failure from the final node is received, we will fail the
227
        // payment in almost all cases. Only when the penultimate node sends an
228
        // incorrect htlc, we want to retry via another route. Invalid onion
229
        // failures are not expected, because the final node wouldn't be able to
230
        // encrypt that failure.
231
        switch failure.(type) {
3✔
232

233
        // Expiry or amount of the HTLC doesn't match the onion, try another
234
        // route.
235
        case *lnwire.FailFinalIncorrectCltvExpiry,
236
                *lnwire.FailFinalIncorrectHtlcAmount:
×
237

×
238
                // We trust ourselves. If this is a direct payment, we penalize
×
239
                // the final node and fail the payment.
×
240
                if n == 1 {
×
241
                        i.failNode(route, n)
×
242
                        i.finalFailureReason = &reasonError
×
243

×
244
                        return
×
245
                }
×
246

247
                // Otherwise penalize the last pair of the route and retry.
248
                // Either the final node is at fault, or it gets sent a bad htlc
249
                // from its predecessor.
250
                i.failPair(route, n-1)
×
251

×
252
                // The other hops relayed correctly, so assign those pairs a
×
253
                // success result. At this point, n >= 2.
×
254
                i.successPairRange(route, 0, n-2)
×
255

256
        // We are using wrong payment hash or amount, fail the payment.
257
        case *lnwire.FailIncorrectPaymentAmount,
258
                *lnwire.FailIncorrectDetails:
3✔
259

3✔
260
                // Assign all pairs a success result, as the payment reached the
3✔
261
                // destination correctly.
3✔
262
                i.successPairRange(route, 0, n-1)
3✔
263

3✔
264
                i.finalFailureReason = &reasonIncorrectDetails
3✔
265

266
        // The HTLC that was extended to the final hop expires too soon. Fail
267
        // the payment, because we may be using the wrong final cltv delta.
268
        case *lnwire.FailFinalExpiryTooSoon:
×
269
                // TODO(roasbeef): can happen to to race condition, try again
×
270
                // with recent block height
×
271

×
272
                // TODO(joostjager): can also happen because a node delayed
×
273
                // deliberately. What to penalize?
×
274
                i.finalFailureReason = &reasonIncorrectDetails
×
275

UNCOV
276
        case *lnwire.FailMPPTimeout:
×
UNCOV
277
                // Assign all pairs a success result, as the payment reached the
×
UNCOV
278
                // destination correctly. Continue the payment process.
×
UNCOV
279
                i.successPairRange(route, 0, n-1)
×
280

281
        // We do not expect to receive an invalid blinding error from the final
282
        // node in the route. This could erroneously happen in the following
283
        // cases:
284
        // 1. Unblinded node: misuses the error code.
285
        // 2. A receiving introduction node: erroneously sends the error code,
286
        //    as the spec indicates that receiving introduction nodes should
287
        //    use regular errors.
288
        //
289
        // Note that we expect the case where this error is sent from a node
290
        // after the introduction node to be handled elsewhere as this is part
291
        // of a more general class of errors where the introduction node has
292
        // failed to convert errors for the blinded route.
UNCOV
293
        case *lnwire.FailInvalidBlinding:
×
UNCOV
294
                failNode()
×
295

296
        // All other errors are considered terminal if coming from the
297
        // final hop. They indicate that something is wrong at the
298
        // recipient, so we do apply a penalty.
UNCOV
299
        default:
×
UNCOV
300
                failNode()
×
301
        }
302
}
303

304
// processPaymentOutcomeIntermediate handles failures sent by an intermediate
305
// hop.
306
//
307
//nolint:funlen
308
func (i *interpretedResult) processPaymentOutcomeIntermediate(route *mcRoute,
309
        errorSourceIdx int, failure lnwire.FailureMessage) {
3✔
310

3✔
311
        reportOutgoing := func() {
6✔
312
                i.failPair(
3✔
313
                        route, errorSourceIdx,
3✔
314
                )
3✔
315
        }
3✔
316

317
        reportOutgoingBalance := func() {
6✔
318
                i.failPairBalance(
3✔
319
                        route, errorSourceIdx,
3✔
320
                )
3✔
321

3✔
322
                // All nodes up to the failing pair must have forwarded
3✔
323
                // successfully.
3✔
324
                i.successPairRange(route, 0, errorSourceIdx-1)
3✔
325
        }
3✔
326

327
        reportIncoming := func() {
6✔
328
                // We trust ourselves. If the error comes from the first hop, we
3✔
329
                // can penalize the whole node. In that case there is no
3✔
330
                // uncertainty as to which node to blame.
3✔
331
                if errorSourceIdx == 1 {
6✔
332
                        i.failNode(route, errorSourceIdx)
3✔
333
                        return
3✔
334
                }
3✔
335

336
                // Otherwise report the incoming pair.
UNCOV
337
                i.failPair(
×
UNCOV
338
                        route, errorSourceIdx-1,
×
UNCOV
339
                )
×
UNCOV
340

×
UNCOV
341
                // All nodes up to the failing pair must have forwarded
×
UNCOV
342
                // successfully.
×
UNCOV
343
                if errorSourceIdx > 1 {
×
UNCOV
344
                        i.successPairRange(route, 0, errorSourceIdx-2)
×
UNCOV
345
                }
×
346
        }
347

348
        reportNode := func() {
3✔
UNCOV
349
                // Fail only the node that reported the failure.
×
UNCOV
350
                i.failNode(route, errorSourceIdx)
×
UNCOV
351

×
UNCOV
352
                // Other preceding channels in the route forwarded correctly.
×
UNCOV
353
                if errorSourceIdx > 1 {
×
UNCOV
354
                        i.successPairRange(route, 0, errorSourceIdx-2)
×
UNCOV
355
                }
×
356
        }
357

358
        reportAll := func() {
3✔
UNCOV
359
                // We trust ourselves. If the error comes from the first hop, we
×
UNCOV
360
                // can penalize the whole node. In that case there is no
×
UNCOV
361
                // uncertainty as to which node to blame.
×
UNCOV
362
                if errorSourceIdx == 1 {
×
UNCOV
363
                        i.failNode(route, errorSourceIdx)
×
UNCOV
364
                        return
×
UNCOV
365
                }
×
366

367
                // Otherwise penalize all pairs up to the error source. This
368
                // includes our own outgoing connection.
UNCOV
369
                i.failPairRange(
×
UNCOV
370
                        route, 0, errorSourceIdx-1,
×
UNCOV
371
                )
×
372
        }
373

374
        switch failure.(type) {
3✔
375

376
        // If a node reports onion payload corruption or an invalid version,
377
        // that node may be responsible, but it could also be that it is just
378
        // relaying a malformed htlc failure from it successor. By reporting the
379
        // outgoing channel set, we will surely hit the responsible node. At
380
        // this point, it is not possible that the node's predecessor corrupted
381
        // the onion blob. If the predecessor would have corrupted the payload,
382
        // the error source wouldn't have been able to encrypt this failure
383
        // message for us.
384
        case *lnwire.FailInvalidOnionVersion,
385
                *lnwire.FailInvalidOnionHmac,
386
                *lnwire.FailInvalidOnionKey:
3✔
387

3✔
388
                reportOutgoing()
3✔
389

390
        // If InvalidOnionPayload is received, we penalize only the reporting
391
        // node. We know the preceding hop didn't corrupt the onion, since the
392
        // reporting node is able to send the failure. We assume that we
393
        // constructed a valid onion payload and that the failure is most likely
394
        // an unknown required type or a bug in their implementation.
UNCOV
395
        case *lnwire.InvalidOnionPayload:
×
UNCOV
396
                reportNode()
×
397

398
        // If the next hop in the route wasn't known or offline, we'll only
399
        // penalize the channel set which we attempted to route over. This is
400
        // conservative, and it can handle faulty channels between nodes
401
        // properly. Additionally, this guards against routing nodes returning
402
        // errors in order to attempt to black list another node.
403
        case *lnwire.FailUnknownNextPeer:
3✔
404
                reportOutgoing()
3✔
405

406
        // Some implementations use this error when the next hop is offline, so we
407
        // do the same as FailUnknownNextPeer and also process the channel update.
408
        case *lnwire.FailChannelDisabled:
3✔
409

3✔
410
                // Set the node pair for which a channel update may be out of
3✔
411
                // date. The second chance logic uses the policyFailure field.
3✔
412
                i.policyFailure = &DirectedNodePair{
3✔
413
                        From: route.hops.Val[errorSourceIdx-1].pubKeyBytes.Val,
3✔
414
                        To:   route.hops.Val[errorSourceIdx].pubKeyBytes.Val,
3✔
415
                }
3✔
416

3✔
417
                reportOutgoing()
3✔
418

3✔
419
                // All nodes up to the failing pair must have forwarded
3✔
420
                // successfully.
3✔
421
                i.successPairRange(route, 0, errorSourceIdx-1)
3✔
422

423
        // If we get a permanent channel, we'll prune the channel set in both
424
        // directions and continue with the rest of the routes.
425
        case *lnwire.FailPermanentChannelFailure:
3✔
426
                reportOutgoing()
3✔
427

428
        // When an HTLC parameter is incorrect, the node sending the error may
429
        // be doing something wrong. But it could also be that its predecessor
430
        // is intentionally modifying the htlc parameters that we instructed it
431
        // via the hop payload. Therefore we penalize the incoming node pair. A
432
        // third cause of this error may be that we have an out of date channel
433
        // update. This is handled by the second chance logic up in mission
434
        // control.
435
        case *lnwire.FailAmountBelowMinimum,
436
                *lnwire.FailFeeInsufficient,
437
                *lnwire.FailIncorrectCltvExpiry:
3✔
438

3✔
439
                // Set the node pair for which a channel update may be out of
3✔
440
                // date. The second chance logic uses the policyFailure field.
3✔
441
                i.policyFailure = &DirectedNodePair{
3✔
442
                        From: route.hops.Val[errorSourceIdx-1].pubKeyBytes.Val,
3✔
443
                        To:   route.hops.Val[errorSourceIdx].pubKeyBytes.Val,
3✔
444
                }
3✔
445

3✔
446
                // We report incoming channel. If a second pair is granted in
3✔
447
                // mission control, this report is ignored.
3✔
448
                reportIncoming()
3✔
449

450
        // If the outgoing channel doesn't have enough capacity, we penalize.
451
        // But we penalize only in a single direction and only for amounts
452
        // greater than the attempted amount.
453
        case *lnwire.FailTemporaryChannelFailure:
3✔
454
                reportOutgoingBalance()
3✔
455

456
        // If FailExpiryTooSoon is received, there must have been some delay
457
        // along the path. We can't know which node is causing the delay, so we
458
        // penalize all of them up to the error source.
459
        //
460
        // Alternatively it could also be that we ourselves have fallen behind
461
        // somehow. We ignore that case for now.
UNCOV
462
        case *lnwire.FailExpiryTooSoon:
×
UNCOV
463
                reportAll()
×
464

465
        // We only expect to get FailInvalidBlinding from an introduction node
466
        // in a blinded route. The introduction node in a blinded route is
467
        // always responsible for reporting errors for the blinded portion of
468
        // the route (to protect the privacy of the members of the route), so
469
        // we need to be careful not to unfairly "shoot the messenger".
470
        //
471
        // The introduction node has no incentive to falsely report errors to
472
        // sabotage the blinded route because:
473
        //   1. Its ability to route this payment is strictly tied to the
474
        //      blinded route.
475
        //   2. The pubkeys in the blinded route are ephemeral, so doing so
476
        //      will have no impact on the nodes beyond the individual payment.
477
        //
478
        // Here we handle a few cases where we could unexpectedly receive this
479
        // error:
480
        // 1. Outside of a blinded route: erring node is not spec compliant.
481
        // 2. Before the introduction point: erring node is not spec compliant.
482
        //
483
        // Note that we expect the case where this error is sent from a node
484
        // after the introduction node to be handled elsewhere as this is part
485
        // of a more general class of errors where the introduction node has
486
        // failed to convert errors for the blinded route.
487
        case *lnwire.FailInvalidBlinding:
3✔
488
                introIdx, isBlinded := introductionPointIndex(route)
3✔
489

3✔
490
                // Deal with cases where a node has incorrectly returned a
3✔
491
                // blinding error:
3✔
492
                // 1. A node before the introduction point returned it.
3✔
493
                // 2. A node in a non-blinded route returned it.
3✔
494
                if errorSourceIdx < introIdx || !isBlinded {
3✔
UNCOV
495
                        reportNode()
×
UNCOV
496
                        return
×
UNCOV
497
                }
×
498

499
                // Otherwise, the error was at the introduction node. All
500
                // nodes up until the introduction node forwarded correctly,
501
                // so we award them as successful.
502
                if introIdx >= 1 {
6✔
503
                        i.successPairRange(route, 0, introIdx-1)
3✔
504
                }
3✔
505

506
                // If the hop after the introduction node that sent us an
507
                // error is the final recipient, then we finally fail the
508
                // payment because the receiver has generated a blinded route
509
                // that they're unable to use. We have this special case so
510
                // that we don't penalize the introduction node, and there is
511
                // no point in retrying the payment while LND only supports
512
                // one blinded route per payment.
513
                //
514
                // Note that if LND is extended to support multiple blinded
515
                // routes, this will terminate the payment without re-trying
516
                // the other routes.
517
                if introIdx == len(route.hops.Val)-1 {
3✔
UNCOV
518
                        i.finalFailureReason = &reasonError
×
519
                } else {
3✔
520
                        // We penalize the final hop of the blinded route which
3✔
521
                        // is sufficient to not reuse this route again and is
3✔
522
                        // also more memory efficient because the other hops
3✔
523
                        // of the blinded path are ephemeral and will only be
3✔
524
                        // used in conjunction with the final hop. Moreover we
3✔
525
                        // don't want to punish the introduction node because
3✔
526
                        // the blinded failure does not necessarily mean that
3✔
527
                        // the introduction node was at fault.
3✔
528
                        //
3✔
529
                        // TODO(ziggie): Make sure we only keep mc data for
3✔
530
                        // blinded paths, in both the success and failure case,
3✔
531
                        // in memory during the time of the payment and remove
3✔
532
                        // it afterwards. Blinded paths and their blinded hop
3✔
533
                        // keys are always changing per blinded route so there
3✔
534
                        // is no point in persisting this data.
3✔
535
                        i.failPairBalance(route, len(route.hops.Val)-1)
3✔
536
                }
3✔
537

538
        // In all other cases, we penalize the reporting node. These are all
539
        // failures that should not happen.
UNCOV
540
        default:
×
UNCOV
541
                i.failNode(route, errorSourceIdx)
×
542
        }
543
}
544

545
// introductionPointIndex returns the index of an introduction point in a
546
// route, using the same indexing in the route that we use for errorSourceIdx
547
// (i.e., that we consider our own node to be at index zero). A boolean is
548
// returned to indicate whether the route contains a blinded portion at all.
549
func introductionPointIndex(route *mcRoute) (int, bool) {
3✔
550
        for i, hop := range route.hops.Val {
6✔
551
                if hop.hasBlindingPoint.IsSome() {
6✔
552
                        return i + 1, true
3✔
553
                }
3✔
554
        }
555

556
        return 0, false
3✔
557
}
558

559
// processPaymentOutcomeUnknown processes a payment outcome for which no failure
560
// message or source is available.
UNCOV
561
func (i *interpretedResult) processPaymentOutcomeUnknown(route *mcRoute) {
×
UNCOV
562
        n := len(route.hops.Val)
×
UNCOV
563

×
UNCOV
564
        // If this is a direct payment, the destination must be at fault.
×
UNCOV
565
        if n == 1 {
×
566
                i.failNode(route, n)
×
567
                i.finalFailureReason = &reasonError
×
568
                return
×
569
        }
×
570

571
        // Otherwise penalize all channels in the route to make sure the
572
        // responsible node is at least hit too. We even penalize the connection
573
        // to our own peer, because that peer could also be responsible.
UNCOV
574
        i.failPairRange(route, 0, n-1)
×
575
}
576

577
// extractMCRoute extracts the fields required by MC from the Route struct to
578
// create the more minimal mcRoute struct.
579
func extractMCRoute(r *route.Route) *mcRoute {
3✔
580
        return &mcRoute{
3✔
581
                sourcePubKey: tlv.NewRecordT[tlv.TlvType0](r.SourcePubKey),
3✔
582
                totalAmount:  tlv.NewRecordT[tlv.TlvType1](r.TotalAmount),
3✔
583
                hops: tlv.NewRecordT[tlv.TlvType2](
3✔
584
                        extractMCHops(r.Hops),
3✔
585
                ),
3✔
586
        }
3✔
587
}
3✔
588

589
// extractMCHops extracts the Hop fields that MC actually uses from a slice of
590
// Hops.
591
func extractMCHops(hops []*route.Hop) mcHops {
3✔
592
        return fn.Map(extractMCHop, hops)
3✔
593
}
3✔
594

595
// extractMCHop extracts the Hop fields that MC actually uses from a Hop.
596
func extractMCHop(hop *route.Hop) *mcHop {
3✔
597
        h := mcHop{
3✔
598
                channelID: tlv.NewPrimitiveRecord[tlv.TlvType0](
3✔
599
                        hop.ChannelID,
3✔
600
                ),
3✔
601
                pubKeyBytes: tlv.NewRecordT[tlv.TlvType1](hop.PubKeyBytes),
3✔
602
                amtToFwd:    tlv.NewRecordT[tlv.TlvType2](hop.AmtToForward),
3✔
603
        }
3✔
604

3✔
605
        if hop.BlindingPoint != nil {
6✔
606
                h.hasBlindingPoint = tlv.SomeRecordT(
3✔
607
                        tlv.NewRecordT[tlv.TlvType3](lnwire.TrueBoolean{}),
3✔
608
                )
3✔
609
        }
3✔
610

611
        if hop.CustomRecords != nil {
6✔
612
                h.hasCustomRecords = tlv.SomeRecordT(
3✔
613
                        tlv.NewRecordT[tlv.TlvType4](lnwire.TrueBoolean{}),
3✔
614
                )
3✔
615
        }
3✔
616

617
        return &h
3✔
618
}
619

620
// mcRoute holds the bare minimum info about a payment attempt route that MC
621
// requires.
622
type mcRoute struct {
623
        sourcePubKey tlv.RecordT[tlv.TlvType0, route.Vertex]
624
        totalAmount  tlv.RecordT[tlv.TlvType1, lnwire.MilliSatoshi]
625
        hops         tlv.RecordT[tlv.TlvType2, mcHops]
626
}
627

628
// Record returns a TLV record that can be used to encode/decode an mcRoute
629
// to/from a TLV stream.
630
func (r *mcRoute) Record() tlv.Record {
3✔
631
        recordSize := func() uint64 {
6✔
632
                var (
3✔
633
                        b   bytes.Buffer
3✔
634
                        buf [8]byte
3✔
635
                )
3✔
636
                if err := encodeMCRoute(&b, r, &buf); err != nil {
3✔
637
                        panic(err)
×
638
                }
639

640
                return uint64(len(b.Bytes()))
3✔
641
        }
642

643
        return tlv.MakeDynamicRecord(
3✔
644
                0, r, recordSize, encodeMCRoute, decodeMCRoute,
3✔
645
        )
3✔
646
}
647

648
func encodeMCRoute(w io.Writer, val interface{}, _ *[8]byte) error {
3✔
649
        if v, ok := val.(*mcRoute); ok {
6✔
650
                return serializeRoute(w, v)
3✔
651
        }
3✔
652

653
        return tlv.NewTypeForEncodingErr(val, "routing.mcRoute")
×
654
}
655

656
func decodeMCRoute(r io.Reader, val interface{}, _ *[8]byte, l uint64) error {
3✔
657
        if v, ok := val.(*mcRoute); ok {
6✔
658
                route, err := deserializeRoute(io.LimitReader(r, int64(l)))
3✔
659
                if err != nil {
3✔
660
                        return err
×
661
                }
×
662

663
                *v = *route
3✔
664

3✔
665
                return nil
3✔
666
        }
667

668
        return tlv.NewTypeForDecodingErr(val, "routing.mcRoute", l, l)
×
669
}
670

671
// mcHops is a list of mcHop records.
672
type mcHops []*mcHop
673

674
// Record returns a TLV record that can be used to encode/decode a list of
675
// mcHop to/from a TLV stream.
676
func (h *mcHops) Record() tlv.Record {
3✔
677
        recordSize := func() uint64 {
6✔
678
                var (
3✔
679
                        b   bytes.Buffer
3✔
680
                        buf [8]byte
3✔
681
                )
3✔
682
                if err := encodeMCHops(&b, h, &buf); err != nil {
3✔
683
                        panic(err)
×
684
                }
685

686
                return uint64(len(b.Bytes()))
3✔
687
        }
688

689
        return tlv.MakeDynamicRecord(
3✔
690
                0, h, recordSize, encodeMCHops, decodeMCHops,
3✔
691
        )
3✔
692
}
693

694
func encodeMCHops(w io.Writer, val interface{}, buf *[8]byte) error {
3✔
695
        if v, ok := val.(*mcHops); ok {
6✔
696
                // Encode the number of hops as a var int.
3✔
697
                if err := tlv.WriteVarInt(w, uint64(len(*v)), buf); err != nil {
3✔
698
                        return err
×
699
                }
×
700

701
                // With that written out, we'll now encode the entries
702
                // themselves as a sub-TLV record, which includes its _own_
703
                // inner length prefix.
704
                for _, hop := range *v {
6✔
705
                        var hopBytes bytes.Buffer
3✔
706
                        if err := serializeHop(&hopBytes, hop); err != nil {
3✔
707
                                return err
×
708
                        }
×
709

710
                        // We encode the record with a varint length followed by
711
                        // the _raw_ TLV bytes.
712
                        tlvLen := uint64(len(hopBytes.Bytes()))
3✔
713
                        if err := tlv.WriteVarInt(w, tlvLen, buf); err != nil {
3✔
714
                                return err
×
715
                        }
×
716

717
                        if _, err := w.Write(hopBytes.Bytes()); err != nil {
3✔
718
                                return err
×
719
                        }
×
720
                }
721

722
                return nil
3✔
723
        }
724

725
        return tlv.NewTypeForEncodingErr(val, "routing.mcHops")
×
726
}
727

728
func decodeMCHops(r io.Reader, val interface{}, buf *[8]byte, l uint64) error {
3✔
729
        if v, ok := val.(*mcHops); ok {
6✔
730
                // First, we'll decode the varint that encodes how many hops
3✔
731
                // are encoded in the stream.
3✔
732
                numHops, err := tlv.ReadVarInt(r, buf)
3✔
733
                if err != nil {
3✔
734
                        return err
×
735
                }
×
736

737
                // Now that we know how many records we'll need to read, we can
738
                // iterate and read them all out in series.
739
                for i := uint64(0); i < numHops; i++ {
6✔
740
                        // Read out the varint that encodes the size of this
3✔
741
                        // inner TLV record.
3✔
742
                        hopSize, err := tlv.ReadVarInt(r, buf)
3✔
743
                        if err != nil {
3✔
744
                                return err
×
745
                        }
×
746

747
                        // Using this information, we'll create a new limited
748
                        // reader that'll return an EOF once the end has been
749
                        // reached so the stream stops consuming bytes.
750
                        innerTlvReader := &io.LimitedReader{
3✔
751
                                R: r,
3✔
752
                                N: int64(hopSize),
3✔
753
                        }
3✔
754

3✔
755
                        hop, err := deserializeHop(innerTlvReader)
3✔
756
                        if err != nil {
3✔
757
                                return err
×
758
                        }
×
759

760
                        *v = append(*v, hop)
3✔
761
                }
762

763
                return nil
3✔
764
        }
765

766
        return tlv.NewTypeForDecodingErr(val, "routing.mcHops", l, l)
×
767
}
768

769
// mcHop holds the bare minimum info about a payment attempt route hop that MC
770
// requires.
771
type mcHop struct {
772
        channelID        tlv.RecordT[tlv.TlvType0, uint64]
773
        pubKeyBytes      tlv.RecordT[tlv.TlvType1, route.Vertex]
774
        amtToFwd         tlv.RecordT[tlv.TlvType2, lnwire.MilliSatoshi]
775
        hasBlindingPoint tlv.OptionalRecordT[tlv.TlvType3, lnwire.TrueBoolean]
776
        hasCustomRecords tlv.OptionalRecordT[tlv.TlvType4, lnwire.TrueBoolean]
777
}
778

779
// failNode marks the node indicated by idx in the route as failed. It also
780
// marks the incoming and outgoing channels of the node as failed. This function
781
// intentionally panics when the self node is failed.
782
func (i *interpretedResult) failNode(rt *mcRoute, idx int) {
3✔
783
        // Mark the node as failing.
3✔
784
        i.nodeFailure = &rt.hops.Val[idx-1].pubKeyBytes.Val
3✔
785

3✔
786
        // Mark the incoming connection as failed for the node. We intent to
3✔
787
        // penalize as much as we can for a node level failure, including future
3✔
788
        // outgoing traffic for this connection. The pair as it is returned by
3✔
789
        // getPair is penalized in the original and the reversed direction. Note
3✔
790
        // that this will also affect the score of the failing node's peers.
3✔
791
        // This is necessary to prevent future routes from keep going into the
3✔
792
        // same node again.
3✔
793
        incomingChannelIdx := idx - 1
3✔
794
        inPair, _ := getPair(rt, incomingChannelIdx)
3✔
795
        i.pairResults[inPair] = failPairResult(0)
3✔
796
        i.pairResults[inPair.Reverse()] = failPairResult(0)
3✔
797

3✔
798
        // If not the ultimate node, mark the outgoing connection as failed for
3✔
799
        // the node.
3✔
800
        if idx < len(rt.hops.Val) {
6✔
801
                outgoingChannelIdx := idx
3✔
802
                outPair, _ := getPair(rt, outgoingChannelIdx)
3✔
803
                i.pairResults[outPair] = failPairResult(0)
3✔
804
                i.pairResults[outPair.Reverse()] = failPairResult(0)
3✔
805
        }
3✔
806
}
807

808
// failPairRange marks the node pairs from node fromIdx to node toIdx as failed
809
// in both direction.
UNCOV
810
func (i *interpretedResult) failPairRange(rt *mcRoute, fromIdx, toIdx int) {
×
UNCOV
811
        for idx := fromIdx; idx <= toIdx; idx++ {
×
UNCOV
812
                i.failPair(rt, idx)
×
UNCOV
813
        }
×
814
}
815

816
// failPair marks a pair as failed in both directions.
817
func (i *interpretedResult) failPair(rt *mcRoute, idx int) {
3✔
818
        pair, _ := getPair(rt, idx)
3✔
819

3✔
820
        // Report pair in both directions without a minimum penalization amount.
3✔
821
        i.pairResults[pair] = failPairResult(0)
3✔
822
        i.pairResults[pair.Reverse()] = failPairResult(0)
3✔
823
}
3✔
824

825
// failPairBalance marks a pair as failed with a minimum penalization amount.
826
func (i *interpretedResult) failPairBalance(rt *mcRoute, channelIdx int) {
3✔
827
        pair, amt := getPair(rt, channelIdx)
3✔
828

3✔
829
        i.pairResults[pair] = failPairResult(amt)
3✔
830
}
3✔
831

832
// successPairRange marks the node pairs from node fromIdx to node toIdx as
833
// succeeded.
834
func (i *interpretedResult) successPairRange(rt *mcRoute, fromIdx, toIdx int) {
3✔
835
        for idx := fromIdx; idx <= toIdx; idx++ {
6✔
836
                pair, amt := getPair(rt, idx)
3✔
837

3✔
838
                i.pairResults[pair] = successPairResult(amt)
3✔
839
        }
3✔
840
}
841

842
// getPair returns a node pair from the route and the amount passed between that
843
// pair.
844
func getPair(rt *mcRoute, channelIdx int) (DirectedNodePair,
845
        lnwire.MilliSatoshi) {
3✔
846

3✔
847
        nodeTo := rt.hops.Val[channelIdx].pubKeyBytes.Val
3✔
848
        var (
3✔
849
                nodeFrom route.Vertex
3✔
850
                amt      lnwire.MilliSatoshi
3✔
851
        )
3✔
852

3✔
853
        if channelIdx == 0 {
6✔
854
                nodeFrom = rt.sourcePubKey.Val
3✔
855
                amt = rt.totalAmount.Val
3✔
856
        } else {
6✔
857
                nodeFrom = rt.hops.Val[channelIdx-1].pubKeyBytes.Val
3✔
858
                amt = rt.hops.Val[channelIdx-1].amtToFwd.Val
3✔
859
        }
3✔
860

861
        pair := NewDirectedNodePair(nodeFrom, nodeTo)
3✔
862

3✔
863
        return pair, amt
3✔
864
}
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