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

lightningnetwork / lnd / 12312390362

13 Dec 2024 08:44AM UTC coverage: 57.458% (+8.5%) from 48.92%
12312390362

Pull #9343

github

ellemouton
fn: rework the ContextGuard and add tests

In this commit, the ContextGuard struct is re-worked such that the
context that its new main WithCtx method provides is cancelled in sync
with a parent context being cancelled or with it's quit channel being
cancelled. Tests are added to assert the behaviour. In order for the
close of the quit channel to be consistent with the cancelling of the
derived context, the quit channel _must_ be contained internal to the
ContextGuard so that callers are only able to close the channel via the
exposed Quit method which will then take care to first cancel any
derived context that depend on the quit channel before returning.
Pull Request #9343: fn: expand the ContextGuard and add tests

101853 of 177264 relevant lines covered (57.46%)

24972.93 hits per line

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

81.3
/lnwire/onion_error.go
1
package lnwire
2

3
import (
4
        "bufio"
5
        "bytes"
6
        "crypto/sha256"
7
        "encoding/binary"
8
        "fmt"
9
        "io"
10

11
        "github.com/davecgh/go-spew/spew"
12
        "github.com/go-errors/errors"
13
        "github.com/lightningnetwork/lnd/fn/v2"
14
        "github.com/lightningnetwork/lnd/tlv"
15
)
16

17
// FailureMessage represents the onion failure object identified by its unique
18
// failure code.
19
type FailureMessage interface {
20
        // Code returns a failure code describing the exact nature of the
21
        // error.
22
        Code() FailCode
23

24
        // Error returns a human readable string describing the error. With
25
        // this method, the FailureMessage interface meets the built-in error
26
        // interface.
27
        Error() string
28
}
29

30
// FailureMessageLength is the size of the failure message plus the size of
31
// padding. The FailureMessage message should always be EXACTLY this size.
32
const FailureMessageLength = 256
33

34
const (
35
        // FlagBadOnion error flag describes an unparsable, encrypted by
36
        // previous node.
37
        FlagBadOnion FailCode = 0x8000
38

39
        // FlagPerm error flag indicates a permanent failure.
40
        FlagPerm FailCode = 0x4000
41

42
        // FlagNode error flag indicates a node failure.
43
        FlagNode FailCode = 0x2000
44

45
        // FlagUpdate error flag indicates a new channel update is enclosed
46
        // within the error.
47
        FlagUpdate FailCode = 0x1000
48
)
49

50
// FailCode specifies the precise reason that an upstream HTLC was canceled.
51
// Each UpdateFailHTLC message carries a FailCode which is to be passed
52
// backwards, encrypted at each step back to the source of the HTLC within the
53
// route.
54
type FailCode uint16
55

56
// The currently defined onion failure types within this current version of the
57
// Lightning protocol.
58
const (
59
        CodeNone                             FailCode = 0
60
        CodeInvalidRealm                              = FlagBadOnion | 1
61
        CodeTemporaryNodeFailure                      = FlagNode | 2
62
        CodePermanentNodeFailure                      = FlagPerm | FlagNode | 2
63
        CodeRequiredNodeFeatureMissing                = FlagPerm | FlagNode | 3
64
        CodeInvalidOnionVersion                       = FlagBadOnion | FlagPerm | 4
65
        CodeInvalidOnionHmac                          = FlagBadOnion | FlagPerm | 5
66
        CodeInvalidOnionKey                           = FlagBadOnion | FlagPerm | 6
67
        CodeTemporaryChannelFailure                   = FlagUpdate | 7
68
        CodePermanentChannelFailure                   = FlagPerm | 8
69
        CodeRequiredChannelFeatureMissing             = FlagPerm | 9
70
        CodeUnknownNextPeer                           = FlagPerm | 10
71
        CodeAmountBelowMinimum                        = FlagUpdate | 11
72
        CodeFeeInsufficient                           = FlagUpdate | 12
73
        CodeIncorrectCltvExpiry                       = FlagUpdate | 13
74
        CodeExpiryTooSoon                             = FlagUpdate | 14
75
        CodeChannelDisabled                           = FlagUpdate | 20
76
        CodeIncorrectOrUnknownPaymentDetails          = FlagPerm | 15
77
        CodeIncorrectPaymentAmount                    = FlagPerm | 16
78
        CodeFinalExpiryTooSoon               FailCode = 17
79
        CodeFinalIncorrectCltvExpiry         FailCode = 18
80
        CodeFinalIncorrectHtlcAmount         FailCode = 19
81
        CodeExpiryTooFar                     FailCode = 21
82
        CodeInvalidOnionPayload                       = FlagPerm | 22
83
        CodeMPPTimeout                       FailCode = 23
84
        CodeInvalidBlinding                           = FlagBadOnion | FlagPerm | 24 //nolint:ll
85
)
86

87
// String returns the string representation of the failure code.
88
func (c FailCode) String() string {
44✔
89
        switch c {
44✔
90
        case CodeInvalidRealm:
1✔
91
                return "InvalidRealm"
1✔
92

93
        case CodeTemporaryNodeFailure:
1✔
94
                return "TemporaryNodeFailure"
1✔
95

96
        case CodePermanentNodeFailure:
1✔
97
                return "PermanentNodeFailure"
1✔
98

99
        case CodeRequiredNodeFeatureMissing:
1✔
100
                return "RequiredNodeFeatureMissing"
1✔
101

102
        case CodeInvalidOnionVersion:
1✔
103
                return "InvalidOnionVersion"
1✔
104

105
        case CodeInvalidOnionHmac:
1✔
106
                return "InvalidOnionHmac"
1✔
107

108
        case CodeInvalidOnionKey:
1✔
109
                return "InvalidOnionKey"
1✔
110

111
        case CodeTemporaryChannelFailure:
11✔
112
                return "TemporaryChannelFailure"
11✔
113

114
        case CodePermanentChannelFailure:
1✔
115
                return "PermanentChannelFailure"
1✔
116

117
        case CodeRequiredChannelFeatureMissing:
1✔
118
                return "RequiredChannelFeatureMissing"
1✔
119

120
        case CodeUnknownNextPeer:
5✔
121
                return "UnknownNextPeer"
5✔
122

123
        case CodeAmountBelowMinimum:
1✔
124
                return "AmountBelowMinimum"
1✔
125

126
        case CodeFeeInsufficient:
1✔
127
                return "FeeInsufficient"
1✔
128

129
        case CodeIncorrectCltvExpiry:
1✔
130
                return "IncorrectCltvExpiry"
1✔
131

132
        case CodeIncorrectPaymentAmount:
1✔
133
                return "IncorrectPaymentAmount"
1✔
134

135
        case CodeExpiryTooSoon:
1✔
136
                return "ExpiryTooSoon"
1✔
137

138
        case CodeChannelDisabled:
1✔
139
                return "ChannelDisabled"
1✔
140

141
        case CodeIncorrectOrUnknownPaymentDetails:
5✔
142
                return "IncorrectOrUnknownPaymentDetails"
5✔
143

144
        case CodeFinalExpiryTooSoon:
1✔
145
                return "FinalExpiryTooSoon"
1✔
146

147
        case CodeFinalIncorrectCltvExpiry:
1✔
148
                return "FinalIncorrectCltvExpiry"
1✔
149

150
        case CodeFinalIncorrectHtlcAmount:
1✔
151
                return "FinalIncorrectHtlcAmount"
1✔
152

153
        case CodeExpiryTooFar:
×
154
                return "ExpiryTooFar"
×
155

156
        case CodeInvalidOnionPayload:
1✔
157
                return "InvalidOnionPayload"
1✔
158

159
        case CodeMPPTimeout:
1✔
160
                return "MPPTimeout"
1✔
161

162
        case CodeInvalidBlinding:
1✔
163
                return "InvalidBlinding"
1✔
164

165
        default:
2✔
166
                return "<unknown>"
2✔
167
        }
168
}
169

170
// FailInvalidRealm is returned if the realm byte is unknown.
171
//
172
// NOTE: May be returned by any node in the payment route.
173
type FailInvalidRealm struct{}
174

175
// Returns a human readable string describing the target FailureMessage.
176
//
177
// NOTE: Implements the error interface.
178
func (f *FailInvalidRealm) Error() string {
×
179
        return f.Code().String()
×
180
}
×
181

182
// Code returns the failure unique code.
183
//
184
// NOTE: Part of the FailureMessage interface.
185
func (f *FailInvalidRealm) Code() FailCode {
3✔
186
        return CodeInvalidRealm
3✔
187
}
3✔
188

189
// FailTemporaryNodeFailure is returned if an otherwise unspecified transient
190
// error occurs for the entire node.
191
//
192
// NOTE: May be returned by any node in the payment route.
193
type FailTemporaryNodeFailure struct{}
194

195
// Code returns the failure unique code.
196
// NOTE: Part of the FailureMessage interface.
197
func (f *FailTemporaryNodeFailure) Code() FailCode {
38✔
198
        return CodeTemporaryNodeFailure
38✔
199
}
38✔
200

201
// Returns a human readable string describing the target FailureMessage.
202
//
203
// NOTE: Implements the error interface.
204
func (f *FailTemporaryNodeFailure) Error() string {
×
205
        return f.Code().String()
×
206
}
×
207

208
// FailPermanentNodeFailure is returned if an otherwise unspecified permanent
209
// error occurs for the entire node.
210
//
211
// NOTE: May be returned by any node in the payment route.
212
type FailPermanentNodeFailure struct{}
213

214
// Code returns the failure unique code.
215
//
216
// NOTE: Part of the FailureMessage interface.
217
func (f *FailPermanentNodeFailure) Code() FailCode {
3✔
218
        return CodePermanentNodeFailure
3✔
219
}
3✔
220

221
// Returns a human readable string describing the target FailureMessage.
222
//
223
// NOTE: Implements the error interface.
224
func (f *FailPermanentNodeFailure) Error() string {
×
225
        return f.Code().String()
×
226
}
×
227

228
// FailRequiredNodeFeatureMissing is returned if a node has requirement
229
// advertised in its node_announcement features which were not present in the
230
// onion.
231
//
232
// NOTE: May be returned by any node in the payment route.
233
type FailRequiredNodeFeatureMissing struct{}
234

235
// Code returns the failure unique code.
236
//
237
// NOTE: Part of the FailureMessage interface.
238
func (f *FailRequiredNodeFeatureMissing) Code() FailCode {
3✔
239
        return CodeRequiredNodeFeatureMissing
3✔
240
}
3✔
241

242
// Returns a human readable string describing the target FailureMessage.
243
//
244
// NOTE: Implements the error interface.
245
func (f *FailRequiredNodeFeatureMissing) Error() string {
×
246
        return f.Code().String()
×
247
}
×
248

249
// FailPermanentChannelFailure is return if an otherwise unspecified permanent
250
// error occurs for the outgoing channel (eg. channel (recently).
251
//
252
// NOTE: May be returned by any node in the payment route.
253
type FailPermanentChannelFailure struct{}
254

255
// Code returns the failure unique code.
256
//
257
// NOTE: Part of the FailureMessage interface.
258
func (f *FailPermanentChannelFailure) Code() FailCode {
3✔
259
        return CodePermanentChannelFailure
3✔
260
}
3✔
261

262
// Returns a human readable string describing the target FailureMessage.
263
//
264
// NOTE: Implements the error interface.
265
func (f *FailPermanentChannelFailure) Error() string {
×
266
        return f.Code().String()
×
267
}
×
268

269
// FailRequiredChannelFeatureMissing is returned if the outgoing channel has a
270
// requirement advertised in its channel announcement features which were not
271
// present in the onion.
272
//
273
// NOTE: May only be returned by intermediate nodes.
274
type FailRequiredChannelFeatureMissing struct{}
275

276
// Code returns the failure unique code.
277
//
278
// NOTE: Part of the FailureMessage interface.
279
func (f *FailRequiredChannelFeatureMissing) Code() FailCode {
3✔
280
        return CodeRequiredChannelFeatureMissing
3✔
281
}
3✔
282

283
// Returns a human readable string describing the target FailureMessage.
284
//
285
// NOTE: Implements the error interface.
286
func (f *FailRequiredChannelFeatureMissing) Error() string {
×
287
        return f.Code().String()
×
288
}
×
289

290
// FailUnknownNextPeer is returned if the next peer specified by the onion is
291
// not known.
292
//
293
// NOTE: May only be returned by intermediate nodes.
294
type FailUnknownNextPeer struct{}
295

296
// Code returns the failure unique code.
297
//
298
// NOTE: Part of the FailureMessage interface.
299
func (f *FailUnknownNextPeer) Code() FailCode {
14✔
300
        return CodeUnknownNextPeer
14✔
301
}
14✔
302

303
// Returns a human readable string describing the target FailureMessage.
304
//
305
// NOTE: Implements the error interface.
306
func (f *FailUnknownNextPeer) Error() string {
4✔
307
        return f.Code().String()
4✔
308
}
4✔
309

310
// FailIncorrectPaymentAmount is returned if the amount paid is less than the
311
// amount expected, the final node MUST fail the HTLC. If the amount paid is
312
// more than twice the amount expected, the final node SHOULD fail the HTLC.
313
// This allows the sender to reduce information leakage by altering the amount,
314
// without allowing accidental gross overpayment.
315
//
316
// NOTE: May only be returned by the final node in the path.
317
type FailIncorrectPaymentAmount struct{}
318

319
// Code returns the failure unique code.
320
//
321
// NOTE: Part of the FailureMessage interface.
322
func (f *FailIncorrectPaymentAmount) Code() FailCode {
3✔
323
        return CodeIncorrectPaymentAmount
3✔
324
}
3✔
325

326
// Returns a human readable string describing the target FailureMessage.
327
//
328
// NOTE: Implements the error interface.
329
func (f *FailIncorrectPaymentAmount) Error() string {
×
330
        return f.Code().String()
×
331
}
×
332

333
// FailIncorrectDetails is returned for two reasons:
334
//
335
// 1) if the payment hash has already been paid, the final node MAY treat the
336
// payment hash as unknown, or may succeed in accepting the HTLC. If the
337
// payment hash is unknown, the final node MUST fail the HTLC.
338
//
339
// 2) if the amount paid is less than the amount expected, the final node MUST
340
// fail the HTLC. If the amount paid is more than twice the amount expected,
341
// the final node SHOULD fail the HTLC. This allows the sender to reduce
342
// information leakage by altering the amount, without allowing accidental
343
// gross overpayment.
344
//
345
// NOTE: May only be returned by the final node in the path.
346
type FailIncorrectDetails struct {
347
        // amount is the value of the extended HTLC.
348
        amount MilliSatoshi
349

350
        // height is the block height when the htlc was received.
351
        height uint32
352

353
        // extraOpaqueData contains additional failure message tlv data.
354
        extraOpaqueData ExtraOpaqueData
355
}
356

357
// NewFailIncorrectDetails makes a new instance of the FailIncorrectDetails
358
// error bound to the specified HTLC amount and acceptance height.
359
func NewFailIncorrectDetails(amt MilliSatoshi,
360
        height uint32) *FailIncorrectDetails {
11✔
361

11✔
362
        return &FailIncorrectDetails{
11✔
363
                amount:          amt,
11✔
364
                height:          height,
11✔
365
                extraOpaqueData: []byte{},
11✔
366
        }
11✔
367
}
11✔
368

369
// Amount is the value of the extended HTLC.
370
func (f *FailIncorrectDetails) Amount() MilliSatoshi {
×
371
        return f.amount
×
372
}
×
373

374
// Height is the block height when the htlc was received.
375
func (f *FailIncorrectDetails) Height() uint32 {
×
376
        return f.height
×
377
}
×
378

379
// ExtraOpaqueData returns additional failure message tlv data.
380
func (f *FailIncorrectDetails) ExtraOpaqueData() ExtraOpaqueData {
1✔
381
        return f.extraOpaqueData
1✔
382
}
1✔
383

384
// Code returns the failure unique code.
385
//
386
// NOTE: Part of the FailureMessage interface.
387
func (f *FailIncorrectDetails) Code() FailCode {
103✔
388
        return CodeIncorrectOrUnknownPaymentDetails
103✔
389
}
103✔
390

391
// Returns a human readable string describing the target FailureMessage.
392
//
393
// NOTE: Implements the error interface.
394
func (f *FailIncorrectDetails) Error() string {
4✔
395
        return fmt.Sprintf(
4✔
396
                "%v(amt=%v, height=%v)", CodeIncorrectOrUnknownPaymentDetails,
4✔
397
                f.amount, f.height,
4✔
398
        )
4✔
399
}
4✔
400

401
// Decode decodes the failure from bytes stream.
402
//
403
// NOTE: Part of the Serializable interface.
404
func (f *FailIncorrectDetails) Decode(r io.Reader, pver uint32) error {
72✔
405
        err := ReadElement(r, &f.amount)
72✔
406
        switch {
72✔
407
        // This is an optional tack on that was added later in the protocol. As
408
        // a result, older nodes may not include this value. We'll account for
409
        // this by checking for io.EOF here which means that no bytes were read
410
        // at all.
411
        case err == io.EOF:
2✔
412
                return nil
2✔
413

414
        case err != nil:
1✔
415
                return err
1✔
416
        }
417

418
        // At a later stage, the height field was also tacked on. We need to
419
        // check for io.EOF here as well.
420
        err = ReadElement(r, &f.height)
69✔
421
        switch {
69✔
422
        case err == io.EOF:
2✔
423
                return nil
2✔
424

425
        case err != nil:
1✔
426
                return err
1✔
427
        }
428

429
        return f.extraOpaqueData.Decode(r)
66✔
430
}
431

432
// Encode writes the failure in bytes stream.
433
//
434
// NOTE: Part of the Serializable interface.
435
func (f *FailIncorrectDetails) Encode(w *bytes.Buffer, pver uint32) error {
99✔
436
        if err := WriteMilliSatoshi(w, f.amount); err != nil {
99✔
437
                return err
×
438
        }
×
439

440
        if err := WriteUint32(w, f.height); err != nil {
99✔
441
                return err
×
442
        }
×
443

444
        return f.extraOpaqueData.Encode(w)
99✔
445
}
446

447
// FailFinalExpiryTooSoon is returned if the cltv_expiry is too low, the final
448
// node MUST fail the HTLC.
449
//
450
// NOTE: May only be returned by the final node in the path.
451
type FailFinalExpiryTooSoon struct{}
452

453
// Code returns the failure unique code.
454
//
455
// NOTE: Part of the FailureMessage interface.
456
func (f *FailFinalExpiryTooSoon) Code() FailCode {
3✔
457
        return CodeFinalExpiryTooSoon
3✔
458
}
3✔
459

460
// Returns a human readable string describing the target FailureMessage.
461
//
462
// NOTE: Implements the error interface.
463
func (f *FailFinalExpiryTooSoon) Error() string {
×
464
        return f.Code().String()
×
465
}
×
466

467
// NewFinalExpiryTooSoon creates new instance of the FailFinalExpiryTooSoon.
468
func NewFinalExpiryTooSoon() *FailFinalExpiryTooSoon {
×
469
        return &FailFinalExpiryTooSoon{}
×
470
}
×
471

472
// FailInvalidOnionVersion is returned if the onion version byte is unknown.
473
//
474
// NOTE: May be returned only by intermediate nodes.
475
type FailInvalidOnionVersion struct {
476
        // OnionSHA256 hash of the onion blob which haven't been proceeded.
477
        OnionSHA256 [sha256.Size]byte
478
}
479

480
// Returns a human readable string describing the target FailureMessage.
481
//
482
// NOTE: Implements the error interface.
483
func (f *FailInvalidOnionVersion) Error() string {
×
484
        return fmt.Sprintf("InvalidOnionVersion(onion_sha=%x)", f.OnionSHA256[:])
×
485
}
×
486

487
// NewInvalidOnionVersion creates new instance of the FailInvalidOnionVersion.
488
func NewInvalidOnionVersion(onion []byte) *FailInvalidOnionVersion {
1✔
489
        return &FailInvalidOnionVersion{OnionSHA256: sha256.Sum256(onion)}
1✔
490
}
1✔
491

492
// Code returns the failure unique code.
493
//
494
// NOTE: Part of the FailureMessage interface.
495
func (f *FailInvalidOnionVersion) Code() FailCode {
6✔
496
        return CodeInvalidOnionVersion
6✔
497
}
6✔
498

499
// Decode decodes the failure from bytes stream.
500
//
501
// NOTE: Part of the Serializable interface.
502
func (f *FailInvalidOnionVersion) Decode(r io.Reader, pver uint32) error {
8✔
503
        return ReadElement(r, f.OnionSHA256[:])
8✔
504
}
8✔
505

506
// Encode writes the failure in bytes stream.
507
//
508
// NOTE: Part of the Serializable interface.
509
func (f *FailInvalidOnionVersion) Encode(w *bytes.Buffer, pver uint32) error {
5✔
510
        return WriteBytes(w, f.OnionSHA256[:])
5✔
511
}
5✔
512

513
// FailInvalidOnionHmac is return if the onion HMAC is incorrect.
514
//
515
// NOTE: May only be returned by intermediate nodes.
516
type FailInvalidOnionHmac struct {
517
        // OnionSHA256 hash of the onion blob which haven't been proceeded.
518
        OnionSHA256 [sha256.Size]byte
519
}
520

521
// NewInvalidOnionHmac creates new instance of the FailInvalidOnionHmac.
522
func NewInvalidOnionHmac(onion []byte) *FailInvalidOnionHmac {
1✔
523
        return &FailInvalidOnionHmac{OnionSHA256: sha256.Sum256(onion)}
1✔
524
}
1✔
525

526
// Code returns the failure unique code.
527
//
528
// NOTE: Part of the FailureMessage interface.
529
func (f *FailInvalidOnionHmac) Code() FailCode {
5✔
530
        return CodeInvalidOnionHmac
5✔
531
}
5✔
532

533
// Decode decodes the failure from bytes stream.
534
//
535
// NOTE: Part of the Serializable interface.
536
func (f *FailInvalidOnionHmac) Decode(r io.Reader, pver uint32) error {
7✔
537
        return ReadElement(r, f.OnionSHA256[:])
7✔
538
}
7✔
539

540
// Encode writes the failure in bytes stream.
541
//
542
// NOTE: Part of the Serializable interface.
543
func (f *FailInvalidOnionHmac) Encode(w *bytes.Buffer, pver uint32) error {
4✔
544
        return WriteBytes(w, f.OnionSHA256[:])
4✔
545
}
4✔
546

547
// Returns a human readable string describing the target FailureMessage.
548
//
549
// NOTE: Implements the error interface.
550
func (f *FailInvalidOnionHmac) Error() string {
×
551
        return fmt.Sprintf("InvalidOnionHMAC(onion_sha=%x)", f.OnionSHA256[:])
×
552
}
×
553

554
// FailInvalidOnionKey is return if the ephemeral key in the onion is
555
// unparsable.
556
//
557
// NOTE: May only be returned by intermediate nodes.
558
type FailInvalidOnionKey struct {
559
        // OnionSHA256 hash of the onion blob which haven't been proceeded.
560
        OnionSHA256 [sha256.Size]byte
561
}
562

563
// NewInvalidOnionKey creates new instance of the FailInvalidOnionKey.
564
func NewInvalidOnionKey(onion []byte) *FailInvalidOnionKey {
3✔
565
        return &FailInvalidOnionKey{OnionSHA256: sha256.Sum256(onion)}
3✔
566
}
3✔
567

568
// Code returns the failure unique code.
569
//
570
// NOTE: Part of the FailureMessage interface.
571
func (f *FailInvalidOnionKey) Code() FailCode {
8✔
572
        return CodeInvalidOnionKey
8✔
573
}
8✔
574

575
// Decode decodes the failure from bytes stream.
576
//
577
// NOTE: Part of the Serializable interface.
578
func (f *FailInvalidOnionKey) Decode(r io.Reader, pver uint32) error {
10✔
579
        return ReadElement(r, f.OnionSHA256[:])
10✔
580
}
10✔
581

582
// Encode writes the failure in bytes stream.
583
//
584
// NOTE: Part of the Serializable interface.
585
func (f *FailInvalidOnionKey) Encode(w *bytes.Buffer, pver uint32) error {
7✔
586
        return WriteBytes(w, f.OnionSHA256[:])
7✔
587
}
7✔
588

589
// Returns a human readable string describing the target FailureMessage.
590
//
591
// NOTE: Implements the error interface.
592
func (f *FailInvalidOnionKey) Error() string {
×
593
        return fmt.Sprintf("InvalidOnionKey(onion_sha=%x)", f.OnionSHA256[:])
×
594
}
×
595

596
// parseChannelUpdateCompatibilityMode will attempt to parse a channel updated
597
// encoded into an onion error payload in two ways. First, we'll try the
598
// compatibility oriented version wherein we'll _skip_ the length prefixing on
599
// the channel update message. Older versions of c-lighting do this so we'll
600
// attempt to parse these messages in order to retain compatibility. If we're
601
// unable to pull out a fully valid version, then we'll fall back to the
602
// regular parsing mechanism which includes the length prefix an NO type byte.
603
func parseChannelUpdateCompatibilityMode(reader io.Reader, length uint16,
604
        chanUpdate *ChannelUpdate1, pver uint32) error {
419✔
605

419✔
606
        // Instantiate a LimitReader because there may be additional data
419✔
607
        // present after the channel update. Without limiting the stream, the
419✔
608
        // additional data would be interpreted as channel update tlv data.
419✔
609
        limitReader := io.LimitReader(reader, int64(length))
419✔
610

419✔
611
        r := bufio.NewReader(limitReader)
419✔
612

419✔
613
        // We'll peek out two bytes from the buffer without advancing the
419✔
614
        // buffer so we can decide how to parse the remainder of it.
419✔
615
        maybeTypeBytes, err := r.Peek(2)
419✔
616
        if err != nil {
442✔
617
                return err
23✔
618
        }
23✔
619

620
        // Some nodes well prefix an additional set of bytes in front of their
621
        // channel updates. These bytes will _almost_ always be 258 or the type
622
        // of the ChannelUpdate message.
623
        typeInt := binary.BigEndian.Uint16(maybeTypeBytes)
396✔
624
        if typeInt == MsgChannelUpdate {
588✔
625
                // At this point it's likely the case that this is a channel
192✔
626
                // update message with its type prefixed, so we'll snip off the
192✔
627
                // first two bytes and parse it as normal.
192✔
628
                var throwAwayTypeBytes [2]byte
192✔
629
                _, err := r.Read(throwAwayTypeBytes[:])
192✔
630
                if err != nil {
192✔
631
                        return err
×
632
                }
×
633
        }
634

635
        // At this pint, we've either decided to keep the entire thing, or snip
636
        // off the first two bytes. In either case, we can just read it as
637
        // normal.
638
        return chanUpdate.Decode(r, pver)
396✔
639
}
640

641
// FailTemporaryChannelFailure is if an otherwise unspecified transient error
642
// occurs for the outgoing channel (eg. channel capacity reached, too many
643
// in-flight htlcs)
644
//
645
// NOTE: May only be returned by intermediate nodes.
646
type FailTemporaryChannelFailure struct {
647
        // Update is used to update information about state of the channel
648
        // which caused the failure.
649
        //
650
        // NOTE: This field is optional.
651
        Update *ChannelUpdate1
652
}
653

654
// NewTemporaryChannelFailure creates new instance of the FailTemporaryChannelFailure.
655
func NewTemporaryChannelFailure(
656
        update *ChannelUpdate1) *FailTemporaryChannelFailure {
69✔
657

69✔
658
        return &FailTemporaryChannelFailure{Update: update}
69✔
659
}
69✔
660

661
// Code returns the failure unique code.
662
//
663
// NOTE: Part of the FailureMessage interface.
664
func (f *FailTemporaryChannelFailure) Code() FailCode {
120✔
665
        return CodeTemporaryChannelFailure
120✔
666
}
120✔
667

668
// Returns a human readable string describing the target FailureMessage.
669
//
670
// NOTE: Implements the error interface.
671
func (f *FailTemporaryChannelFailure) Error() string {
9✔
672
        if f.Update == nil {
18✔
673
                return f.Code().String()
9✔
674
        }
9✔
675

676
        return fmt.Sprintf("TemporaryChannelFailure(update=%v)",
×
677
                spew.Sdump(f.Update))
×
678
}
679

680
// Decode decodes the failure from bytes stream.
681
//
682
// NOTE: Part of the Serializable interface.
683
func (f *FailTemporaryChannelFailure) Decode(r io.Reader, pver uint32) error {
88✔
684
        var length uint16
88✔
685
        err := ReadElement(r, &length)
88✔
686
        if err != nil {
89✔
687
                return err
1✔
688
        }
1✔
689

690
        if length != 0 {
166✔
691
                f.Update = &ChannelUpdate1{}
79✔
692

79✔
693
                return parseChannelUpdateCompatibilityMode(
79✔
694
                        r, length, f.Update, pver,
79✔
695
                )
79✔
696
        }
79✔
697

698
        return nil
8✔
699
}
700

701
// Encode writes the failure in bytes stream.
702
//
703
// NOTE: Part of the Serializable interface.
704
func (f *FailTemporaryChannelFailure) Encode(w *bytes.Buffer,
705
        pver uint32) error {
102✔
706

102✔
707
        if f.Update != nil {
173✔
708
                return writeOnionErrorChanUpdate(w, f.Update, pver)
71✔
709
        }
71✔
710

711
        // Write zero length to indicate no channel_update is present.
712
        return WriteUint16(w, 0)
31✔
713
}
714

715
// FailAmountBelowMinimum is returned if the HTLC does not reach the current
716
// minimum amount, we tell them the amount of the incoming HTLC and the current
717
// channel setting for the outgoing channel.
718
//
719
// NOTE: May only be returned by the intermediate nodes in the path.
720
type FailAmountBelowMinimum struct {
721
        // HtlcMsat is the wrong amount of the incoming HTLC.
722
        HtlcMsat MilliSatoshi
723

724
        // Update is used to update information about state of the channel
725
        // which caused the failure.
726
        Update ChannelUpdate1
727
}
728

729
// NewAmountBelowMinimum creates new instance of the FailAmountBelowMinimum.
730
func NewAmountBelowMinimum(htlcMsat MilliSatoshi,
731
        update ChannelUpdate1) *FailAmountBelowMinimum {
9✔
732

9✔
733
        return &FailAmountBelowMinimum{
9✔
734
                HtlcMsat: htlcMsat,
9✔
735
                Update:   update,
9✔
736
        }
9✔
737
}
9✔
738

739
// Code returns the failure unique code.
740
//
741
// NOTE: Part of the FailureMessage interface.
742
func (f *FailAmountBelowMinimum) Code() FailCode {
57✔
743
        return CodeAmountBelowMinimum
57✔
744
}
57✔
745

746
// Returns a human readable string describing the target FailureMessage.
747
//
748
// NOTE: Implements the error interface.
749
func (f *FailAmountBelowMinimum) Error() string {
6✔
750
        return fmt.Sprintf("AmountBelowMinimum(amt=%v, update=%v", f.HtlcMsat,
6✔
751
                spew.Sdump(f.Update))
6✔
752
}
6✔
753

754
// Decode decodes the failure from bytes stream.
755
//
756
// NOTE: Part of the Serializable interface.
757
func (f *FailAmountBelowMinimum) Decode(r io.Reader, pver uint32) error {
73✔
758
        if err := ReadElement(r, &f.HtlcMsat); err != nil {
74✔
759
                return err
1✔
760
        }
1✔
761

762
        var length uint16
72✔
763
        if err := ReadElement(r, &length); err != nil {
73✔
764
                return err
1✔
765
        }
1✔
766

767
        f.Update = ChannelUpdate1{}
71✔
768

71✔
769
        return parseChannelUpdateCompatibilityMode(
71✔
770
                r, length, &f.Update, pver,
71✔
771
        )
71✔
772
}
773

774
// Encode writes the failure in bytes stream.
775
//
776
// NOTE: Part of the Serializable interface.
777
func (f *FailAmountBelowMinimum) Encode(w *bytes.Buffer, pver uint32) error {
56✔
778
        if err := WriteMilliSatoshi(w, f.HtlcMsat); err != nil {
56✔
779
                return err
×
780
        }
×
781

782
        return writeOnionErrorChanUpdate(w, &f.Update, pver)
56✔
783
}
784

785
// FailFeeInsufficient is returned if the HTLC does not pay sufficient fee, we
786
// tell them the amount of the incoming HTLC and the current channel setting
787
// for the outgoing channel.
788
//
789
// NOTE: May only be returned by intermediate nodes.
790
type FailFeeInsufficient struct {
791
        // HtlcMsat is the wrong amount of the incoming HTLC.
792
        HtlcMsat MilliSatoshi
793

794
        // Update is used to update information about state of the channel
795
        // which caused the failure.
796
        Update ChannelUpdate1
797
}
798

799
// NewFeeInsufficient creates new instance of the FailFeeInsufficient.
800
func NewFeeInsufficient(htlcMsat MilliSatoshi,
801
        update ChannelUpdate1) *FailFeeInsufficient {
10✔
802
        return &FailFeeInsufficient{
10✔
803
                HtlcMsat: htlcMsat,
10✔
804
                Update:   update,
10✔
805
        }
10✔
806
}
10✔
807

808
// Code returns the failure unique code.
809
//
810
// NOTE: Part of the FailureMessage interface.
811
func (f *FailFeeInsufficient) Code() FailCode {
48✔
812
        return CodeFeeInsufficient
48✔
813
}
48✔
814

815
// Returns a human readable string describing the target FailureMessage.
816
//
817
// NOTE: Implements the error interface.
818
func (f *FailFeeInsufficient) Error() string {
3✔
819
        return fmt.Sprintf("FeeInsufficient(htlc_amt==%v, update=%v", f.HtlcMsat,
3✔
820
                spew.Sdump(f.Update))
3✔
821
}
3✔
822

823
// Decode decodes the failure from bytes stream.
824
//
825
// NOTE: Part of the Serializable interface.
826
func (f *FailFeeInsufficient) Decode(r io.Reader, pver uint32) error {
69✔
827
        if err := ReadElement(r, &f.HtlcMsat); err != nil {
70✔
828
                return err
1✔
829
        }
1✔
830

831
        var length uint16
68✔
832
        if err := ReadElement(r, &length); err != nil {
70✔
833
                return err
2✔
834
        }
2✔
835

836
        f.Update = ChannelUpdate1{}
66✔
837

66✔
838
        return parseChannelUpdateCompatibilityMode(
66✔
839
                r, length, &f.Update, pver,
66✔
840
        )
66✔
841
}
842

843
// Encode writes the failure in bytes stream.
844
//
845
// NOTE: Part of the Serializable interface.
846
func (f *FailFeeInsufficient) Encode(w *bytes.Buffer, pver uint32) error {
47✔
847
        if err := WriteMilliSatoshi(w, f.HtlcMsat); err != nil {
47✔
848
                return err
×
849
        }
×
850

851
        return writeOnionErrorChanUpdate(w, &f.Update, pver)
47✔
852
}
853

854
// FailIncorrectCltvExpiry is returned if outgoing cltv value does not match
855
// the update add htlc's cltv expiry minus cltv expiry delta for the outgoing
856
// channel, we tell them the cltv expiry and the current channel setting for
857
// the outgoing channel.
858
//
859
// NOTE: May only be returned by intermediate nodes.
860
type FailIncorrectCltvExpiry struct {
861
        // CltvExpiry is the wrong absolute timeout in blocks, after which
862
        // outgoing HTLC expires.
863
        CltvExpiry uint32
864

865
        // Update is used to update information about state of the channel
866
        // which caused the failure.
867
        Update ChannelUpdate1
868
}
869

870
// NewIncorrectCltvExpiry creates new instance of the FailIncorrectCltvExpiry.
871
func NewIncorrectCltvExpiry(cltvExpiry uint32,
872
        update ChannelUpdate1) *FailIncorrectCltvExpiry {
3✔
873

3✔
874
        return &FailIncorrectCltvExpiry{
3✔
875
                CltvExpiry: cltvExpiry,
3✔
876
                Update:     update,
3✔
877
        }
3✔
878
}
3✔
879

880
// Code returns the failure unique code.
881
//
882
// NOTE: Part of the FailureMessage interface.
883
func (f *FailIncorrectCltvExpiry) Code() FailCode {
50✔
884
        return CodeIncorrectCltvExpiry
50✔
885
}
50✔
886

887
func (f *FailIncorrectCltvExpiry) Error() string {
1✔
888
        return fmt.Sprintf("IncorrectCltvExpiry(expiry=%v, update=%v",
1✔
889
                f.CltvExpiry, spew.Sdump(f.Update))
1✔
890
}
1✔
891

892
// Decode decodes the failure from bytes stream.
893
//
894
// NOTE: Part of the Serializable interface.
895
func (f *FailIncorrectCltvExpiry) Decode(r io.Reader, pver uint32) error {
71✔
896
        if err := ReadElement(r, &f.CltvExpiry); err != nil {
72✔
897
                return err
1✔
898
        }
1✔
899

900
        var length uint16
70✔
901
        if err := ReadElement(r, &length); err != nil {
72✔
902
                return err
2✔
903
        }
2✔
904

905
        f.Update = ChannelUpdate1{}
68✔
906

68✔
907
        return parseChannelUpdateCompatibilityMode(
68✔
908
                r, length, &f.Update, pver,
68✔
909
        )
68✔
910
}
911

912
// Encode writes the failure in bytes stream.
913
//
914
// NOTE: Part of the Serializable interface.
915
func (f *FailIncorrectCltvExpiry) Encode(w *bytes.Buffer, pver uint32) error {
49✔
916
        if err := WriteUint32(w, f.CltvExpiry); err != nil {
49✔
917
                return err
×
918
        }
×
919

920
        return writeOnionErrorChanUpdate(w, &f.Update, pver)
49✔
921
}
922

923
// FailExpiryTooSoon is returned if the ctlv-expiry is too near, we tell them
924
// the current channel setting for the outgoing channel.
925
//
926
// NOTE: May only be returned by intermediate nodes.
927
type FailExpiryTooSoon struct {
928
        // Update is used to update information about state of the channel
929
        // which caused the failure.
930
        Update ChannelUpdate1
931
}
932

933
// NewExpiryTooSoon creates new instance of the FailExpiryTooSoon.
934
func NewExpiryTooSoon(update ChannelUpdate1) *FailExpiryTooSoon {
6✔
935
        return &FailExpiryTooSoon{
6✔
936
                Update: update,
6✔
937
        }
6✔
938
}
6✔
939

940
// Code returns the failure unique code.
941
//
942
// NOTE: Part of the FailureMessage interface.
943
func (f *FailExpiryTooSoon) Code() FailCode {
51✔
944
        return CodeExpiryTooSoon
51✔
945
}
51✔
946

947
// Returns a human readable string describing the target FailureMessage.
948
//
949
// NOTE: Implements the error interface.
950
func (f *FailExpiryTooSoon) Error() string {
1✔
951
        return fmt.Sprintf("ExpiryTooSoon(update=%v", spew.Sdump(f.Update))
1✔
952
}
1✔
953

954
// Decode decodes the failure from l stream.
955
//
956
// NOTE: Part of the Serializable interface.
957
func (f *FailExpiryTooSoon) Decode(r io.Reader, pver uint32) error {
71✔
958
        var length uint16
71✔
959
        if err := ReadElement(r, &length); err != nil {
72✔
960
                return err
1✔
961
        }
1✔
962

963
        f.Update = ChannelUpdate1{}
70✔
964

70✔
965
        return parseChannelUpdateCompatibilityMode(
70✔
966
                r, length, &f.Update, pver,
70✔
967
        )
70✔
968
}
969

970
// Encode writes the failure in bytes stream.
971
//
972
// NOTE: Part of the Serializable interface.
973
func (f *FailExpiryTooSoon) Encode(w *bytes.Buffer, pver uint32) error {
50✔
974
        return writeOnionErrorChanUpdate(w, &f.Update, pver)
50✔
975
}
50✔
976

977
// FailChannelDisabled is returned if the channel is disabled, we tell them the
978
// current channel setting for the outgoing channel.
979
//
980
// NOTE: May only be returned by intermediate nodes.
981
type FailChannelDisabled struct {
982
        // Flags least-significant bit must be set to 0 if the creating node
983
        // corresponds to the first node in the previously sent channel
984
        // announcement and 1 otherwise.
985
        Flags uint16
986

987
        // Update is used to update information about state of the channel
988
        // which caused the failure.
989
        Update ChannelUpdate1
990
}
991

992
// NewChannelDisabled creates new instance of the FailChannelDisabled.
993
func NewChannelDisabled(flags uint16,
994
        update ChannelUpdate1) *FailChannelDisabled {
1✔
995

1✔
996
        return &FailChannelDisabled{
1✔
997
                Flags:  flags,
1✔
998
                Update: update,
1✔
999
        }
1✔
1000
}
1✔
1001

1002
// Code returns the failure unique code.
1003
//
1004
// NOTE: Part of the FailureMessage interface.
1005
func (f *FailChannelDisabled) Code() FailCode {
46✔
1006
        return CodeChannelDisabled
46✔
1007
}
46✔
1008

1009
// Returns a human readable string describing the target FailureMessage.
1010
//
1011
// NOTE: Implements the error interface.
1012
func (f *FailChannelDisabled) Error() string {
×
1013
        return fmt.Sprintf("ChannelDisabled(flags=%v, update=%v", f.Flags,
×
1014
                spew.Sdump(f.Update))
×
1015
}
×
1016

1017
// Decode decodes the failure from bytes stream.
1018
//
1019
// NOTE: Part of the Serializable interface.
1020
func (f *FailChannelDisabled) Decode(r io.Reader, pver uint32) error {
65✔
1021
        if err := ReadElement(r, &f.Flags); err != nil {
66✔
1022
                return err
1✔
1023
        }
1✔
1024

1025
        var length uint16
64✔
1026
        if err := ReadElement(r, &length); err != nil {
65✔
1027
                return err
1✔
1028
        }
1✔
1029

1030
        f.Update = ChannelUpdate1{}
63✔
1031

63✔
1032
        return parseChannelUpdateCompatibilityMode(
63✔
1033
                r, length, &f.Update, pver,
63✔
1034
        )
63✔
1035
}
1036

1037
// Encode writes the failure in bytes stream.
1038
//
1039
// NOTE: Part of the Serializable interface.
1040
func (f *FailChannelDisabled) Encode(w *bytes.Buffer, pver uint32) error {
45✔
1041
        if err := WriteUint16(w, f.Flags); err != nil {
45✔
1042
                return err
×
1043
        }
×
1044

1045
        return writeOnionErrorChanUpdate(w, &f.Update, pver)
45✔
1046
}
1047

1048
// FailFinalIncorrectCltvExpiry is returned if the outgoing_cltv_value does not
1049
// match the ctlv_expiry of the HTLC at the final hop.
1050
//
1051
// NOTE: might be returned by final node only.
1052
type FailFinalIncorrectCltvExpiry struct {
1053
        // CltvExpiry is the wrong absolute timeout in blocks, after which
1054
        // outgoing HTLC expires.
1055
        CltvExpiry uint32
1056
}
1057

1058
// Returns a human readable string describing the target FailureMessage.
1059
//
1060
// NOTE: Implements the error interface.
1061
func (f *FailFinalIncorrectCltvExpiry) Error() string {
1✔
1062
        return fmt.Sprintf("FinalIncorrectCltvExpiry(expiry=%v)", f.CltvExpiry)
1✔
1063
}
1✔
1064

1065
// NewFinalIncorrectCltvExpiry creates new instance of the
1066
// FailFinalIncorrectCltvExpiry.
1067
func NewFinalIncorrectCltvExpiry(cltvExpiry uint32) *FailFinalIncorrectCltvExpiry {
4✔
1068
        return &FailFinalIncorrectCltvExpiry{
4✔
1069
                CltvExpiry: cltvExpiry,
4✔
1070
        }
4✔
1071
}
4✔
1072

1073
// Code returns the failure unique code.
1074
//
1075
// NOTE: Part of the FailureMessage interface.
1076
func (f *FailFinalIncorrectCltvExpiry) Code() FailCode {
8✔
1077
        return CodeFinalIncorrectCltvExpiry
8✔
1078
}
8✔
1079

1080
// Decode decodes the failure from bytes stream.
1081
//
1082
// NOTE: Part of the Serializable interface.
1083
func (f *FailFinalIncorrectCltvExpiry) Decode(r io.Reader, pver uint32) error {
7✔
1084
        return ReadElement(r, &f.CltvExpiry)
7✔
1085
}
7✔
1086

1087
// Encode writes the failure in bytes stream.
1088
//
1089
// NOTE: Part of the Serializable interface.
1090
func (f *FailFinalIncorrectCltvExpiry) Encode(w *bytes.Buffer,
1091
        pver uint32) error {
6✔
1092

6✔
1093
        return WriteUint32(w, f.CltvExpiry)
6✔
1094
}
6✔
1095

1096
// FailFinalIncorrectHtlcAmount is returned if the amt_to_forward is higher
1097
// than incoming_htlc_amt of the HTLC at the final hop.
1098
//
1099
// NOTE: May only be returned by the final node.
1100
type FailFinalIncorrectHtlcAmount struct {
1101
        // IncomingHTLCAmount is the wrong forwarded htlc amount.
1102
        IncomingHTLCAmount MilliSatoshi
1103
}
1104

1105
// Returns a human readable string describing the target FailureMessage.
1106
//
1107
// NOTE: Implements the error interface.
1108
func (f *FailFinalIncorrectHtlcAmount) Error() string {
×
1109
        return fmt.Sprintf("FinalIncorrectHtlcAmount(amt=%v)",
×
1110
                f.IncomingHTLCAmount)
×
1111
}
×
1112

1113
// NewFinalIncorrectHtlcAmount creates new instance of the
1114
// FailFinalIncorrectHtlcAmount.
1115
func NewFinalIncorrectHtlcAmount(amount MilliSatoshi) *FailFinalIncorrectHtlcAmount {
101✔
1116
        return &FailFinalIncorrectHtlcAmount{
101✔
1117
                IncomingHTLCAmount: amount,
101✔
1118
        }
101✔
1119
}
101✔
1120

1121
// Code returns the failure unique code.
1122
//
1123
// NOTE: Part of the FailureMessage interface.
1124
func (f *FailFinalIncorrectHtlcAmount) Code() FailCode {
205✔
1125
        return CodeFinalIncorrectHtlcAmount
205✔
1126
}
205✔
1127

1128
// Decode decodes the failure from bytes stream.
1129
//
1130
// NOTE: Part of the Serializable interface.
1131
func (f *FailFinalIncorrectHtlcAmount) Decode(r io.Reader, pver uint32) error {
107✔
1132
        return ReadElement(r, &f.IncomingHTLCAmount)
107✔
1133
}
107✔
1134

1135
// Encode writes the failure in bytes stream.
1136
//
1137
// NOTE: Part of the Serializable interface.
1138
func (f *FailFinalIncorrectHtlcAmount) Encode(w *bytes.Buffer,
1139
        pver uint32) error {
104✔
1140

104✔
1141
        return WriteMilliSatoshi(w, f.IncomingHTLCAmount)
104✔
1142
}
104✔
1143

1144
// FailExpiryTooFar is returned if the CLTV expiry in the HTLC is too far in the
1145
// future.
1146
//
1147
// NOTE: May be returned by any node in the payment route.
1148
type FailExpiryTooFar struct{}
1149

1150
// Code returns the failure unique code.
1151
//
1152
// NOTE: Part of the FailureMessage interface.
1153
func (f *FailExpiryTooFar) Code() FailCode {
×
1154
        return CodeExpiryTooFar
×
1155
}
×
1156

1157
// Returns a human readable string describing the target FailureMessage.
1158
//
1159
// NOTE: Implements the error interface.
1160
func (f *FailExpiryTooFar) Error() string {
×
1161
        return f.Code().String()
×
1162
}
×
1163

1164
// InvalidOnionPayload is returned if the hop could not process the TLV payload
1165
// enclosed in the onion.
1166
type InvalidOnionPayload struct {
1167
        // Type is the TLV type that caused the specific failure.
1168
        Type uint64
1169

1170
        // Offset is the byte offset within the payload where the failure
1171
        // occurred.
1172
        Offset uint16
1173
}
1174

1175
// NewInvalidOnionPayload initializes a new InvalidOnionPayload failure.
1176
func NewInvalidOnionPayload(typ uint64, offset uint16) *InvalidOnionPayload {
5✔
1177
        return &InvalidOnionPayload{
5✔
1178
                Type:   typ,
5✔
1179
                Offset: offset,
5✔
1180
        }
5✔
1181
}
5✔
1182

1183
// Code returns the failure unique code.
1184
//
1185
// NOTE: Part of the FailureMessage interface.
1186
func (f *InvalidOnionPayload) Code() FailCode {
11✔
1187
        return CodeInvalidOnionPayload
11✔
1188
}
11✔
1189

1190
// Returns a human readable string describing the target FailureMessage.
1191
//
1192
// NOTE: Implements the error interface.
1193
func (f *InvalidOnionPayload) Error() string {
×
1194
        return fmt.Sprintf("%v(type=%v, offset=%d)",
×
1195
                f.Code(), f.Type, f.Offset)
×
1196
}
×
1197

1198
// Decode decodes the failure from bytes stream.
1199
//
1200
// NOTE: Part of the Serializable interface.
1201
func (f *InvalidOnionPayload) Decode(r io.Reader, pver uint32) error {
28✔
1202
        var buf [8]byte
28✔
1203
        typ, err := tlv.ReadVarInt(r, &buf)
28✔
1204
        if err != nil {
37✔
1205
                return err
9✔
1206
        }
9✔
1207
        f.Type = typ
19✔
1208

19✔
1209
        return ReadElements(r, &f.Offset)
19✔
1210
}
1211

1212
// Encode writes the failure in bytes stream.
1213
//
1214
// NOTE: Part of the Serializable interface.
1215
func (f *InvalidOnionPayload) Encode(w *bytes.Buffer, pver uint32) error {
10✔
1216
        var buf [8]byte
10✔
1217
        if err := tlv.WriteVarInt(w, f.Type, &buf); err != nil {
10✔
1218
                return err
×
1219
        }
×
1220

1221
        return WriteUint16(w, f.Offset)
10✔
1222
}
1223

1224
// FailMPPTimeout is returned if the complete amount for a multi part payment
1225
// was not received within a reasonable time.
1226
//
1227
// NOTE: May only be returned by the final node in the path.
1228
type FailMPPTimeout struct{}
1229

1230
// Code returns the failure unique code.
1231
//
1232
// NOTE: Part of the FailureMessage interface.
1233
func (f *FailMPPTimeout) Code() FailCode {
11✔
1234
        return CodeMPPTimeout
11✔
1235
}
11✔
1236

1237
// Returns a human readable string describing the target FailureMessage.
1238
//
1239
// NOTE: Implements the error interface.
1240
func (f *FailMPPTimeout) Error() string {
×
1241
        return f.Code().String()
×
1242
}
×
1243

1244
// FailInvalidBlinding is returned if there has been a route blinding related
1245
// error.
1246
type FailInvalidBlinding struct {
1247
        OnionSHA256 [sha256.Size]byte
1248
}
1249

1250
// Code returns the failure unique code.
1251
//
1252
// NOTE: Part of the FailureMessage interface.
1253
func (f *FailInvalidBlinding) Code() FailCode {
3✔
1254
        return CodeInvalidBlinding
3✔
1255
}
3✔
1256

1257
// Returns a human readable string describing the target FailureMessage.
1258
//
1259
// NOTE: Implements the error interface.
1260
func (f *FailInvalidBlinding) Error() string {
×
1261
        return f.Code().String()
×
1262
}
×
1263

1264
// Decode decodes the failure from bytes stream.
1265
//
1266
// NOTE: Part of the Serializable interface.
1267
func (f *FailInvalidBlinding) Decode(r io.Reader, _ uint32) error {
2✔
1268
        return ReadElement(r, f.OnionSHA256[:])
2✔
1269
}
2✔
1270

1271
// Encode writes the failure in bytes stream.
1272
//
1273
// NOTE: Part of the Serializable interface.
1274
func (f *FailInvalidBlinding) Encode(w *bytes.Buffer, _ uint32) error {
2✔
1275
        return WriteBytes(w, f.OnionSHA256[:])
2✔
1276
}
2✔
1277

1278
// NewInvalidBlinding creates new instance of FailInvalidBlinding.
1279
func NewInvalidBlinding(
1280
        onion fn.Option[[OnionPacketSize]byte]) *FailInvalidBlinding {
1✔
1281
        // The spec allows empty onion hashes for invalid blinding, so we only
1✔
1282
        // include our onion hash if it's provided.
1✔
1283
        if onion.IsNone() {
1✔
1284
                return &FailInvalidBlinding{}
×
1285
        }
×
1286

1287
        shaSum := fn.MapOptionZ(onion, func(o [OnionPacketSize]byte) [32]byte {
2✔
1288
                return sha256.Sum256(o[:])
1✔
1289
        })
1✔
1290

1291
        return &FailInvalidBlinding{OnionSHA256: shaSum}
1✔
1292
}
1293

1294
// DecodeFailure decodes, validates, and parses the lnwire onion failure, for
1295
// the provided protocol version.
1296
func DecodeFailure(r io.Reader, pver uint32) (FailureMessage, error) {
201✔
1297
        // First, we'll parse out the encapsulated failure message itself. This
201✔
1298
        // is a 2 byte length followed by the payload itself.
201✔
1299
        var failureLength uint16
201✔
1300
        if err := ReadElement(r, &failureLength); err != nil {
202✔
1301
                return nil, fmt.Errorf("unable to read failure len: %w", err)
1✔
1302
        }
1✔
1303

1304
        failureData := make([]byte, failureLength)
200✔
1305
        if _, err := io.ReadFull(r, failureData); err != nil {
200✔
1306
                return nil, fmt.Errorf("unable to full read payload of "+
×
1307
                        "%v: %w", failureLength, err)
×
1308
        }
×
1309

1310
        // Read the padding.
1311
        var padLength uint16
200✔
1312
        if err := ReadElement(r, &padLength); err != nil {
200✔
1313
                return nil, fmt.Errorf("unable to read pad len: %w", err)
×
1314
        }
×
1315

1316
        if _, err := io.CopyN(io.Discard, r, int64(padLength)); err != nil {
200✔
1317
                return nil, fmt.Errorf("unable to read padding %w", err)
×
1318
        }
×
1319

1320
        // Verify that we are at the end of the stream now.
1321
        scratch := make([]byte, 1)
200✔
1322
        _, err := r.Read(scratch)
200✔
1323
        if err != io.EOF {
200✔
1324
                return nil, fmt.Errorf("unexpected failure bytes")
×
1325
        }
×
1326

1327
        // Check the total length. Convert to 32 bits to prevent overflow.
1328
        totalLength := uint32(padLength) + uint32(failureLength)
200✔
1329
        if totalLength < FailureMessageLength {
200✔
1330
                return nil, fmt.Errorf("failure message too short: "+
×
1331
                        "msg=%v, pad=%v, total=%v",
×
1332
                        failureLength, padLength, totalLength)
×
1333
        }
×
1334

1335
        // Decode the failure message.
1336
        dataReader := bytes.NewReader(failureData)
200✔
1337

200✔
1338
        return DecodeFailureMessage(dataReader, pver)
200✔
1339
}
1340

1341
// DecodeFailureMessage decodes just the failure message, ignoring any padding
1342
// that may be present at the end.
1343
func DecodeFailureMessage(r io.Reader, pver uint32) (FailureMessage, error) {
701✔
1344
        // Once we have the failure data, we can obtain the failure code from
701✔
1345
        // the first two bytes of the buffer.
701✔
1346
        var codeBytes [2]byte
701✔
1347
        if _, err := io.ReadFull(r, codeBytes[:]); err != nil {
701✔
1348
                return nil, fmt.Errorf("unable to read failure code: %w", err)
×
1349
        }
×
1350
        failCode := FailCode(binary.BigEndian.Uint16(codeBytes[:]))
701✔
1351

701✔
1352
        // Create the empty failure by given code and populate the failure with
701✔
1353
        // additional data if needed.
701✔
1354
        failure, err := makeEmptyOnionError(failCode)
701✔
1355
        if err != nil {
701✔
1356
                return nil, fmt.Errorf("unable to make empty error: %w", err)
×
1357
        }
×
1358

1359
        // Finally, if this failure has a payload, then we'll read that now as
1360
        // well.
1361
        switch f := failure.(type) {
701✔
1362
        case Serializable:
678✔
1363
                if err := f.Decode(r, pver); err != nil {
805✔
1364
                        return nil, fmt.Errorf("unable to decode error "+
127✔
1365
                                "update (type=%T): %v", failure, err)
127✔
1366
                }
127✔
1367
        }
1368

1369
        return failure, nil
574✔
1370
}
1371

1372
// EncodeFailure encodes, including the necessary onion failure header
1373
// information.
1374
func EncodeFailure(w *bytes.Buffer, failure FailureMessage, pver uint32) error {
379✔
1375
        var failureMessageBuffer bytes.Buffer
379✔
1376

379✔
1377
        err := EncodeFailureMessage(&failureMessageBuffer, failure, pver)
379✔
1378
        if err != nil {
379✔
1379
                return err
×
1380
        }
×
1381

1382
        // The combined size of this message must be below the max allowed
1383
        // failure message length.
1384
        failureMessage := failureMessageBuffer.Bytes()
379✔
1385
        if len(failureMessage) > FailureMessageLength {
496✔
1386
                return fmt.Errorf("failure message exceed max "+
117✔
1387
                        "available size: %v", len(failureMessage))
117✔
1388
        }
117✔
1389

1390
        // Finally, we'll add some padding in order to ensure that all failure
1391
        // messages are fixed size.
1392
        pad := make([]byte, FailureMessageLength-len(failureMessage))
262✔
1393

262✔
1394
        if err := WriteUint16(w, uint16(len(failureMessage))); err != nil {
262✔
1395
                return err
×
1396
        }
×
1397

1398
        if err := WriteBytes(w, failureMessage); err != nil {
262✔
1399
                return err
×
1400
        }
×
1401
        if err := WriteUint16(w, uint16(len(pad))); err != nil {
262✔
1402
                return err
×
1403
        }
×
1404

1405
        return WriteBytes(w, pad)
262✔
1406
}
1407

1408
// EncodeFailureMessage encodes just the failure message without adding a length
1409
// and padding the message for the onion protocol.
1410
func EncodeFailureMessage(w *bytes.Buffer,
1411
        failure FailureMessage, pver uint32) error {
656✔
1412

656✔
1413
        // First, we'll write out the error code itself into the failure
656✔
1414
        // buffer.
656✔
1415
        var codeBytes [2]byte
656✔
1416
        code := uint16(failure.Code())
656✔
1417
        binary.BigEndian.PutUint16(codeBytes[:], code)
656✔
1418
        _, err := w.Write(codeBytes[:])
656✔
1419
        if err != nil {
656✔
1420
                return err
×
1421
        }
×
1422

1423
        // Next, some message have an additional message payload, if this is
1424
        // one of those types, then we'll also encode the error payload as
1425
        // well.
1426
        switch failure := failure.(type) {
656✔
1427
        case Serializable:
587✔
1428
                if err := failure.Encode(w, pver); err != nil {
587✔
1429
                        return err
×
1430
                }
×
1431
        }
1432

1433
        return nil
656✔
1434
}
1435

1436
// makeEmptyOnionError creates a new empty onion error  of the proper concrete
1437
// type based on the passed failure code.
1438
func makeEmptyOnionError(code FailCode) (FailureMessage, error) {
701✔
1439
        switch code {
701✔
1440
        case CodeInvalidRealm:
2✔
1441
                return &FailInvalidRealm{}, nil
2✔
1442

1443
        case CodeTemporaryNodeFailure:
2✔
1444
                return &FailTemporaryNodeFailure{}, nil
2✔
1445

1446
        case CodePermanentNodeFailure:
2✔
1447
                return &FailPermanentNodeFailure{}, nil
2✔
1448

1449
        case CodeRequiredNodeFeatureMissing:
2✔
1450
                return &FailRequiredNodeFeatureMissing{}, nil
2✔
1451

1452
        case CodePermanentChannelFailure:
2✔
1453
                return &FailPermanentChannelFailure{}, nil
2✔
1454

1455
        case CodeRequiredChannelFeatureMissing:
2✔
1456
                return &FailRequiredChannelFeatureMissing{}, nil
2✔
1457

1458
        case CodeUnknownNextPeer:
3✔
1459
                return &FailUnknownNextPeer{}, nil
3✔
1460

1461
        case CodeIncorrectOrUnknownPaymentDetails:
72✔
1462
                return &FailIncorrectDetails{}, nil
72✔
1463

1464
        case CodeIncorrectPaymentAmount:
2✔
1465
                return &FailIncorrectPaymentAmount{}, nil
2✔
1466

1467
        case CodeFinalExpiryTooSoon:
2✔
1468
                return &FailFinalExpiryTooSoon{}, nil
2✔
1469

1470
        case CodeInvalidOnionVersion:
8✔
1471
                return &FailInvalidOnionVersion{}, nil
8✔
1472

1473
        case CodeInvalidOnionHmac:
7✔
1474
                return &FailInvalidOnionHmac{}, nil
7✔
1475

1476
        case CodeInvalidOnionKey:
10✔
1477
                return &FailInvalidOnionKey{}, nil
10✔
1478

1479
        case CodeTemporaryChannelFailure:
88✔
1480
                return &FailTemporaryChannelFailure{}, nil
88✔
1481

1482
        case CodeAmountBelowMinimum:
73✔
1483
                return &FailAmountBelowMinimum{}, nil
73✔
1484

1485
        case CodeFeeInsufficient:
69✔
1486
                return &FailFeeInsufficient{}, nil
69✔
1487

1488
        case CodeIncorrectCltvExpiry:
71✔
1489
                return &FailIncorrectCltvExpiry{}, nil
71✔
1490

1491
        case CodeExpiryTooSoon:
71✔
1492
                return &FailExpiryTooSoon{}, nil
71✔
1493

1494
        case CodeChannelDisabled:
65✔
1495
                return &FailChannelDisabled{}, nil
65✔
1496

1497
        case CodeFinalIncorrectCltvExpiry:
7✔
1498
                return &FailFinalIncorrectCltvExpiry{}, nil
7✔
1499

1500
        case CodeFinalIncorrectHtlcAmount:
107✔
1501
                return &FailFinalIncorrectHtlcAmount{}, nil
107✔
1502

1503
        case CodeExpiryTooFar:
×
1504
                return &FailExpiryTooFar{}, nil
×
1505

1506
        case CodeInvalidOnionPayload:
28✔
1507
                return &InvalidOnionPayload{}, nil
28✔
1508

1509
        case CodeMPPTimeout:
4✔
1510
                return &FailMPPTimeout{}, nil
4✔
1511

1512
        case CodeInvalidBlinding:
2✔
1513
                return &FailInvalidBlinding{}, nil
2✔
1514

1515
        default:
×
1516
                return nil, errors.Errorf("unknown error code: %v", code)
×
1517
        }
1518
}
1519

1520
// writeOnionErrorChanUpdate writes out a ChannelUpdate using the onion error
1521
// format. The format is that we first write out the true serialized length of
1522
// the channel update, followed by the serialized channel update itself.
1523
func writeOnionErrorChanUpdate(w *bytes.Buffer, chanUpdate *ChannelUpdate1,
1524
        pver uint32) error {
319✔
1525

319✔
1526
        // First, we encode the channel update in a temporary buffer in order
319✔
1527
        // to get the exact serialized size.
319✔
1528
        var b bytes.Buffer
319✔
1529
        updateLen, err := WriteMessage(&b, chanUpdate, pver)
319✔
1530
        if err != nil {
319✔
1531
                return err
×
1532
        }
×
1533

1534
        // Now that we know the size, we can write the length out in the main
1535
        // writer.
1536
        if err := WriteUint16(w, uint16(updateLen)); err != nil {
319✔
1537
                return err
×
1538
        }
×
1539

1540
        // With the length written, we'll then write out the serialized channel
1541
        // update.
1542
        if _, err := w.Write(b.Bytes()); err != nil {
319✔
1543
                return err
×
1544
        }
×
1545

1546
        return nil
319✔
1547
}
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