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

lightningnetwork / lnd / 16171981582

09 Jul 2025 02:22PM UTC coverage: 55.32% (-2.3%) from 57.62%
16171981582

Pull #10059

github

web-flow
Merge b62793ada into ea32aac77
Pull Request #10059: .gemini: add styleguide.md

108496 of 196123 relevant lines covered (55.32%)

22301.4 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/lightningnetwork/lnd/fn/v2"
13
        "github.com/lightningnetwork/lnd/tlv"
14
)
15

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

443
        return f.extraOpaqueData.Encode(w)
71✔
444
}
445

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

284✔
610
        r := bufio.NewReader(limitReader)
284✔
611

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

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

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

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

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

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

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

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

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

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

689
        if length != 0 {
116✔
690
                f.Update = &ChannelUpdate1{}
54✔
691

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

697
        return nil
8✔
698
}
699

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

46✔
706
        if f.Update != nil {
73✔
707
                return writeOnionErrorChanUpdate(w, f.Update, pver)
27✔
708
        }
27✔
709

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

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

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

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

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

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

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

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

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

766
        f.Update = ChannelUpdate1{}
45✔
767

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

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

781
        return writeOnionErrorChanUpdate(w, &f.Update, pver)
12✔
782
}
783

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

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

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

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

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

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

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

835
        f.Update = ChannelUpdate1{}
44✔
836

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

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

850
        return writeOnionErrorChanUpdate(w, &f.Update, pver)
9✔
851
}
852

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

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

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

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

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

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

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

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

904
        f.Update = ChannelUpdate1{}
47✔
905

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

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

919
        return writeOnionErrorChanUpdate(w, &f.Update, pver)
9✔
920
}
921

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

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

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

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

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

962
        f.Update = ChannelUpdate1{}
48✔
963

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

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

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

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

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

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

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

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

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

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

1029
        f.Update = ChannelUpdate1{}
44✔
1030

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

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

1044
        return writeOnionErrorChanUpdate(w, &f.Update, pver)
9✔
1045
}
1046

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

187✔
1337
        return DecodeFailureMessage(dataReader, pver)
187✔
1338
}
1339

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

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

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

1368
        return failure, nil
321✔
1369
}
1370

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

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

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

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

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

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

1404
        return WriteBytes(w, pad)
249✔
1405
}
1406

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

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

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

1432
        return nil
372✔
1433
}
1434

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

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

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

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

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

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

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

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

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

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

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

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

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

1478
        case CodeTemporaryChannelFailure:
63✔
1479
                return &FailTemporaryChannelFailure{}, nil
63✔
1480

1481
        case CodeAmountBelowMinimum:
47✔
1482
                return &FailAmountBelowMinimum{}, nil
47✔
1483

1484
        case CodeFeeInsufficient:
47✔
1485
                return &FailFeeInsufficient{}, nil
47✔
1486

1487
        case CodeIncorrectCltvExpiry:
50✔
1488
                return &FailIncorrectCltvExpiry{}, nil
50✔
1489

1490
        case CodeExpiryTooSoon:
49✔
1491
                return &FailExpiryTooSoon{}, nil
49✔
1492

1493
        case CodeChannelDisabled:
46✔
1494
                return &FailChannelDisabled{}, nil
46✔
1495

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

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

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

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

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

1511
        case CodeInvalidBlinding:
7✔
1512
                return &FailInvalidBlinding{}, nil
7✔
1513

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

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

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

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

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

1545
        return nil
77✔
1546
}
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