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

lightningnetwork / lnd / 12231552240

09 Dec 2024 08:17AM UTC coverage: 58.955% (+0.02%) from 58.933%
12231552240

Pull #9242

github

aakselrod
go.mod: update btcwallet to latest to eliminate waddrmgr deadlock
Pull Request #9242: Reapply #8644

24 of 40 new or added lines in 3 files covered. (60.0%)

89 existing lines in 18 files now uncovered.

133525 of 226485 relevant lines covered (58.96%)

19398.62 hits per line

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

75.76
/channeldb/forwarding_package.go
1
package channeldb
2

3
import (
4
        "bytes"
5
        "encoding/binary"
6
        "errors"
7
        "fmt"
8
        "io"
9

10
        "github.com/lightningnetwork/lnd/kvdb"
11
        "github.com/lightningnetwork/lnd/lnwire"
12
)
13

14
// ErrCorruptedFwdPkg signals that the on-disk structure of the forwarding
15
// package has potentially been mangled.
16
var ErrCorruptedFwdPkg = errors.New("fwding package db has been corrupted")
17

18
// FwdState is an enum used to describe the lifecycle of a FwdPkg.
19
type FwdState byte
20

21
const (
22
        // FwdStateLockedIn is the starting state for all forwarding packages.
23
        // Packages in this state have not yet committed to the exact set of
24
        // Adds to forward to the switch.
25
        FwdStateLockedIn FwdState = iota
26

27
        // FwdStateProcessed marks the state in which all Adds have been
28
        // locally processed and the forwarding decision to the switch has been
29
        // persisted.
30
        FwdStateProcessed
31

32
        // FwdStateCompleted signals that all Adds have been acked, and that all
33
        // settles and fails have been delivered to their sources. Packages in
34
        // this state can be removed permanently.
35
        FwdStateCompleted
36
)
37

38
var (
39
        // fwdPackagesKey is the root-level bucket that all forwarding packages
40
        // are written. This bucket is further subdivided based on the short
41
        // channel ID of each channel.
42
        //
43
        // Bucket hierarchy:
44
        //
45
        // fwdPackagesKey(root-bucket)
46
        //             |
47
        //             |-- <shortChannelID>
48
        //             |       |
49
        //             |       |-- <height>
50
        //             |       |       |-- ackFilterKey: <encoded bytes of PkgFilter>
51
        //             |       |       |-- settleFailFilterKey: <encoded bytes of PkgFilter>
52
        //             |       |       |-- fwdFilterKey: <encoded bytes of PkgFilter>
53
        //             |       |       |
54
        //             |       |       |-- addBucketKey
55
        //             |       |       |        |-- <index of LogUpdate>: <encoded bytes of LogUpdate>
56
        //             |       |       |        |-- <index of LogUpdate>: <encoded bytes of LogUpdate>
57
        //             |       |       |        ...
58
        //             |       |       |
59
        //             |       |       |-- failSettleBucketKey
60
        //             |       |                |-- <index of LogUpdate>: <encoded bytes of LogUpdate>
61
        //             |       |                |-- <index of LogUpdate>: <encoded bytes of LogUpdate>
62
        //             |       |                ...
63
        //             |       |
64
        //             |       |-- <height>
65
        //             |       |       |
66
        //             |       ...     ...
67
        //             |
68
        //             |
69
        //             |-- <shortChannelID>
70
        //             |       |
71
        //        |       ...
72
        //         ...
73
        //
74
        fwdPackagesKey = []byte("fwd-packages")
75

76
        // addBucketKey is the bucket to which all Add log updates are written.
77
        addBucketKey = []byte("add-updates")
78

79
        // failSettleBucketKey is the bucket to which all Settle/Fail log
80
        // updates are written.
81
        failSettleBucketKey = []byte("fail-settle-updates")
82

83
        // fwdFilterKey is a key used to write the set of Adds that passed
84
        // validation and are to be forwarded to the switch.
85
        // NOTE: The presence of this key within a forwarding package indicates
86
        // that the package has reached FwdStateProcessed.
87
        fwdFilterKey = []byte("fwd-filter-key")
88

89
        // ackFilterKey is a key used to access the PkgFilter indicating which
90
        // Adds have received a Settle/Fail. This response may come from a
91
        // number of sources, including: exitHop settle/fails, switch failures,
92
        // chain arbiter interjections, as well as settle/fails from the
93
        // next hop in the route.
94
        ackFilterKey = []byte("ack-filter-key")
95

96
        // settleFailFilterKey is a key used to access the PkgFilter indicating
97
        // which Settles/Fails in have been received and processed by the link
98
        // that originally received the Add.
99
        settleFailFilterKey = []byte("settle-fail-filter-key")
100
)
101

102
// PkgFilter is used to compactly represent a particular subset of the Adds in a
103
// forwarding package. Each filter is represented as a simple, statically-sized
104
// bitvector, where the elements are intended to be the indices of the Adds as
105
// they are written in the FwdPkg.
106
type PkgFilter struct {
107
        count  uint16
108
        filter []byte
109
}
110

111
// NewPkgFilter initializes an empty PkgFilter supporting `count` elements.
112
func NewPkgFilter(count uint16) *PkgFilter {
6,895✔
113
        // We add 7 to ensure that the integer division yields properly rounded
6,895✔
114
        // values.
6,895✔
115
        filterLen := (count + 7) / 8
6,895✔
116

6,895✔
117
        return &PkgFilter{
6,895✔
118
                count:  count,
6,895✔
119
                filter: make([]byte, filterLen),
6,895✔
120
        }
6,895✔
121
}
6,895✔
122

123
// Count returns the number of elements represented by this PkgFilter.
124
func (f *PkgFilter) Count() uint16 {
1,004✔
125
        return f.count
1,004✔
126
}
1,004✔
127

128
// Set marks the `i`-th element as included by this filter.
129
// NOTE: It is assumed that i is always less than count.
130
func (f *PkgFilter) Set(i uint16) {
500,029✔
131
        byt := i / 8
500,029✔
132
        bit := i % 8
500,029✔
133

500,029✔
134
        // Set the i-th bit in the filter.
500,029✔
135
        // TODO(conner): ignore if > count to prevent panic?
500,029✔
136
        f.filter[byt] |= byte(1 << (7 - bit))
500,029✔
137
}
500,029✔
138

139
// Contains queries the filter for membership of index `i`.
140
// NOTE: It is assumed that i is always less than count.
141
func (f *PkgFilter) Contains(i uint16) bool {
1,013,452✔
142
        byt := i / 8
1,013,452✔
143
        bit := i % 8
1,013,452✔
144

1,013,452✔
145
        // Read the i-th bit in the filter.
1,013,452✔
146
        // TODO(conner): ignore if > count to prevent panic?
1,013,452✔
147
        return f.filter[byt]&(1<<(7-bit)) != 0
1,013,452✔
148
}
1,013,452✔
149

150
// Equal checks two PkgFilters for equality.
151
func (f *PkgFilter) Equal(f2 *PkgFilter) bool {
501,534✔
152
        if f == f2 {
501,534✔
153
                return true
×
154
        }
×
155
        if f.count != f2.count {
501,534✔
156
                return false
×
157
        }
×
158

159
        return bytes.Equal(f.filter, f2.filter)
501,534✔
160
}
161

162
// IsFull returns true if every element in the filter has been Set, and false
163
// otherwise.
164
func (f *PkgFilter) IsFull() bool {
499,626✔
165
        // Batch validate bytes that are fully used.
499,626✔
166
        for i := uint16(0); i < f.count/8; i++ {
21,609,655✔
167
                if f.filter[i] != 0xFF {
21,605,056✔
168
                        return false
495,027✔
169
                }
495,027✔
170
        }
171

172
        // If the count is not a multiple of 8, check that the filter contains
173
        // all remaining bits.
174
        rem := f.count % 8
4,603✔
175
        for idx := f.count - rem; idx < f.count; idx++ {
18,696✔
176
                if !f.Contains(idx) {
17,634✔
177
                        return false
3,541✔
178
                }
3,541✔
179
        }
180

181
        return true
1,066✔
182
}
183

184
// Size returns number of bytes produced when the PkgFilter is serialized.
185
func (f *PkgFilter) Size() uint16 {
1,003,673✔
186
        // 2 bytes for uint16 `count`, then round up number of bytes required to
1,003,673✔
187
        // represent `count` bits.
1,003,673✔
188
        return 2 + (f.count+7)/8
1,003,673✔
189
}
1,003,673✔
190

191
// Encode writes the filter to the provided io.Writer.
192
func (f *PkgFilter) Encode(w io.Writer) error {
507,092✔
193
        if err := binary.Write(w, binary.BigEndian, f.count); err != nil {
507,092✔
194
                return err
×
195
        }
×
196

197
        _, err := w.Write(f.filter)
507,092✔
198

507,092✔
199
        return err
507,092✔
200
}
201

202
// Decode reads the filter from the provided io.Reader.
203
func (f *PkgFilter) Decode(r io.Reader) error {
502,139✔
204
        if err := binary.Read(r, binary.BigEndian, &f.count); err != nil {
502,139✔
205
                return err
×
206
        }
×
207

208
        f.filter = make([]byte, f.Size()-2)
502,139✔
209
        _, err := io.ReadFull(r, f.filter)
502,139✔
210

502,139✔
211
        return err
502,139✔
212
}
213

214
// String returns a human-readable string.
215
func (f *PkgFilter) String() string {
4✔
216
        return fmt.Sprintf("count=%v, filter=%v", f.count, f.filter)
4✔
217
}
4✔
218

219
// FwdPkg records all adds, settles, and fails that were locked in as a result
220
// of the remote peer sending us a revocation. Each package is identified by
221
// the short chanid and remote commitment height corresponding to the revocation
222
// that locked in the HTLCs. For everything except a locally initiated payment,
223
// settles and fails in a forwarding package must have a corresponding Add in
224
// another package, and can be removed individually once the source link has
225
// received the fail/settle.
226
//
227
// Adds cannot be removed, as we need to present the same batch of Adds to
228
// properly handle replay protection. Instead, we use a PkgFilter to mark that
229
// we have finished processing a particular Add. A FwdPkg should only be deleted
230
// after the AckFilter is full and all settles and fails have been persistently
231
// removed.
232
type FwdPkg struct {
233
        // Source identifies the channel that wrote this forwarding package.
234
        Source lnwire.ShortChannelID
235

236
        // Height is the height of the remote commitment chain that locked in
237
        // this forwarding package.
238
        Height uint64
239

240
        // State signals the persistent condition of the package and directs how
241
        // to reprocess the package in the event of failures.
242
        State FwdState
243

244
        // Adds contains all add messages which need to be processed and
245
        // forwarded to the switch. Adds does not change over the life of a
246
        // forwarding package.
247
        Adds []LogUpdate
248

249
        // FwdFilter is a filter containing the indices of all Adds that were
250
        // forwarded to the switch.
251
        FwdFilter *PkgFilter
252

253
        // AckFilter is a filter containing the indices of all Adds for which
254
        // the source has received a settle or fail and is reflected in the next
255
        // commitment txn. A package should not be removed until IsFull()
256
        // returns true.
257
        AckFilter *PkgFilter
258

259
        // SettleFails contains all settle and fail messages that should be
260
        // forwarded to the switch.
261
        SettleFails []LogUpdate
262

263
        // SettleFailFilter is a filter containing the indices of all Settle or
264
        // Fails originating in this package that have been received and locked
265
        // into the incoming link's commitment state.
266
        SettleFailFilter *PkgFilter
267
}
268

269
// NewFwdPkg initializes a new forwarding package in FwdStateLockedIn. This
270
// should be used to create a package at the time we receive a revocation.
271
func NewFwdPkg(source lnwire.ShortChannelID, height uint64,
272
        addUpdates, settleFailUpdates []LogUpdate) *FwdPkg {
1,963✔
273

1,963✔
274
        nAddUpdates := uint16(len(addUpdates))
1,963✔
275
        nSettleFailUpdates := uint16(len(settleFailUpdates))
1,963✔
276

1,963✔
277
        return &FwdPkg{
1,963✔
278
                Source:           source,
1,963✔
279
                Height:           height,
1,963✔
280
                State:            FwdStateLockedIn,
1,963✔
281
                Adds:             addUpdates,
1,963✔
282
                FwdFilter:        NewPkgFilter(nAddUpdates),
1,963✔
283
                AckFilter:        NewPkgFilter(nAddUpdates),
1,963✔
284
                SettleFails:      settleFailUpdates,
1,963✔
285
                SettleFailFilter: NewPkgFilter(nSettleFailUpdates),
1,963✔
286
        }
1,963✔
287
}
1,963✔
288

289
// SourceRef is a convenience method that returns an AddRef to this forwarding
290
// package for the index in the argument. It is the caller's responsibility
291
// to ensure that the index is in bounds.
292
func (f *FwdPkg) SourceRef(i uint16) AddRef {
453✔
293
        return AddRef{
453✔
294
                Height: f.Height,
453✔
295
                Index:  i,
453✔
296
        }
453✔
297
}
453✔
298

299
// DestRef is a convenience method that returns a SettleFailRef to this
300
// forwarding package for the index in the argument. It is the caller's
301
// responsibility to ensure that the index is in bounds.
302
func (f *FwdPkg) DestRef(i uint16) SettleFailRef {
318✔
303
        return SettleFailRef{
318✔
304
                Source: f.Source,
318✔
305
                Height: f.Height,
318✔
306
                Index:  i,
318✔
307
        }
318✔
308
}
318✔
309

310
// ID returns an unique identifier for this package, used to ensure that sphinx
311
// replay processing of this batch is idempotent.
312
func (f *FwdPkg) ID() []byte {
1,176✔
313
        var id = make([]byte, 16)
1,176✔
314
        byteOrder.PutUint64(id[:8], f.Source.ToUint64())
1,176✔
315
        byteOrder.PutUint64(id[8:], f.Height)
1,176✔
316
        return id
1,176✔
317
}
1,176✔
318

319
// String returns a human-readable description of the forwarding package.
320
func (f *FwdPkg) String() string {
×
321
        return fmt.Sprintf("%T(src=%v, height=%v, nadds=%v, nfailsettles=%v)",
×
322
                f, f.Source, f.Height, len(f.Adds), len(f.SettleFails))
×
323
}
×
324

325
// AddRef is used to identify a particular Add in a FwdPkg. The short channel ID
326
// is assumed to be that of the packager.
327
type AddRef struct {
328
        // Height is the remote commitment height that locked in the Add.
329
        Height uint64
330

331
        // Index is the index of the Add within the fwd pkg's Adds.
332
        //
333
        // NOTE: This index is static over the lifetime of a forwarding package.
334
        Index uint16
335
}
336

337
// Encode serializes the AddRef to the given io.Writer.
338
func (a *AddRef) Encode(w io.Writer) error {
587✔
339
        if err := binary.Write(w, binary.BigEndian, a.Height); err != nil {
587✔
340
                return err
×
341
        }
×
342

343
        return binary.Write(w, binary.BigEndian, a.Index)
587✔
344
}
345

346
// Decode deserializes the AddRef from the given io.Reader.
347
func (a *AddRef) Decode(r io.Reader) error {
106✔
348
        if err := binary.Read(r, binary.BigEndian, &a.Height); err != nil {
106✔
349
                return err
×
350
        }
×
351

352
        return binary.Read(r, binary.BigEndian, &a.Index)
106✔
353
}
354

355
// SettleFailRef is used to locate a Settle/Fail in another channel's FwdPkg. A
356
// channel does not remove its own Settle/Fail htlcs, so the source is provided
357
// to locate a db bucket belonging to another channel.
358
type SettleFailRef struct {
359
        // Source identifies the outgoing link that locked in the settle or
360
        // fail. This is then used by the *incoming* link to find the settle
361
        // fail in another link's forwarding packages.
362
        Source lnwire.ShortChannelID
363

364
        // Height is the remote commitment height that locked in this
365
        // Settle/Fail.
366
        Height uint64
367

368
        // Index is the index of the Add with the fwd pkg's SettleFails.
369
        //
370
        // NOTE: This index is static over the lifetime of a forwarding package.
371
        Index uint16
372
}
373

374
// SettleFailAcker is a generic interface providing the ability to acknowledge
375
// settle/fail HTLCs stored in forwarding packages.
376
type SettleFailAcker interface {
377
        // AckSettleFails atomically updates the settle-fail filters in *other*
378
        // channels' forwarding packages.
379
        AckSettleFails(tx kvdb.RwTx, settleFailRefs ...SettleFailRef) error
380
}
381

382
// GlobalFwdPkgReader is an interface used to retrieve the forwarding packages
383
// of any active channel.
384
type GlobalFwdPkgReader interface {
385
        // LoadChannelFwdPkgs loads all known forwarding packages for the given
386
        // channel.
387
        LoadChannelFwdPkgs(tx kvdb.RTx,
388
                source lnwire.ShortChannelID) ([]*FwdPkg, error)
389
}
390

391
// FwdOperator defines the interfaces for managing forwarding packages that are
392
// external to a particular channel. This interface is used by the switch to
393
// read forwarding packages from arbitrary channels, and acknowledge settles and
394
// fails for locally-sourced payments.
395
type FwdOperator interface {
396
        // GlobalFwdPkgReader provides read access to all known forwarding
397
        // packages
398
        GlobalFwdPkgReader
399

400
        // SettleFailAcker grants the ability to acknowledge settles or fails
401
        // residing in arbitrary forwarding packages.
402
        SettleFailAcker
403
}
404

405
// SwitchPackager is a concrete implementation of the FwdOperator interface.
406
// A SwitchPackager offers the ability to read any forwarding package, and ack
407
// arbitrary settle and fail HTLCs.
408
type SwitchPackager struct{}
409

410
// NewSwitchPackager instantiates a new SwitchPackager.
411
func NewSwitchPackager() *SwitchPackager {
345✔
412
        return &SwitchPackager{}
345✔
413
}
345✔
414

415
// AckSettleFails atomically updates the settle-fail filters in *other*
416
// channels' forwarding packages, to mark that the switch has received a settle
417
// or fail residing in the forwarding package of a link.
418
func (*SwitchPackager) AckSettleFails(tx kvdb.RwTx,
419
        settleFailRefs ...SettleFailRef) error {
122✔
420

122✔
421
        return ackSettleFails(tx, settleFailRefs)
122✔
422
}
122✔
423

424
// LoadChannelFwdPkgs loads all forwarding packages for a particular channel.
425
func (*SwitchPackager) LoadChannelFwdPkgs(tx kvdb.RTx,
426
        source lnwire.ShortChannelID) ([]*FwdPkg, error) {
133✔
427

133✔
428
        return loadChannelFwdPkgs(tx, source)
133✔
429
}
133✔
430

431
// FwdPackager supports all operations required to modify fwd packages, such as
432
// creation, updates, reading, and removal. The interfaces are broken down in
433
// this way to support future delegation of the subinterfaces.
434
type FwdPackager interface {
435
        // AddFwdPkg serializes and writes a FwdPkg for this channel at the
436
        // remote commitment height included in the forwarding package.
437
        AddFwdPkg(tx kvdb.RwTx, fwdPkg *FwdPkg) error
438

439
        // SetFwdFilter looks up the forwarding package at the remote `height`
440
        // and sets the `fwdFilter`, marking the Adds for which:
441
        // 1) We are not the exit node
442
        // 2) Passed all validation
443
        // 3) Should be forwarded to the switch immediately after a failure
444
        SetFwdFilter(tx kvdb.RwTx, height uint64, fwdFilter *PkgFilter) error
445

446
        // AckAddHtlcs atomically updates the add filters in this channel's
447
        // forwarding packages to mark the resolution of an Add that was
448
        // received from the remote party.
449
        AckAddHtlcs(tx kvdb.RwTx, addRefs ...AddRef) error
450

451
        // SettleFailAcker allows a link to acknowledge settle/fail HTLCs
452
        // belonging to other channels.
453
        SettleFailAcker
454

455
        // LoadFwdPkgs loads all known forwarding packages owned by this
456
        // channel.
457
        LoadFwdPkgs(tx kvdb.RTx) ([]*FwdPkg, error)
458

459
        // RemovePkg deletes a forwarding package owned by this channel at
460
        // the provided remote `height`.
461
        RemovePkg(tx kvdb.RwTx, height uint64) error
462

463
        // Wipe deletes all the forwarding packages owned by this channel.
464
        Wipe(tx kvdb.RwTx) error
465
}
466

467
// ChannelPackager is used by a channel to manage the lifecycle of its forwarding
468
// packages. The packager is tied to a particular source channel ID, allowing it
469
// to create and edit its own packages. Each packager also has the ability to
470
// remove fail/settle htlcs that correspond to an add contained in one of
471
// source's packages.
472
type ChannelPackager struct {
473
        source lnwire.ShortChannelID
474
}
475

476
// NewChannelPackager creates a new packager for a single channel.
477
func NewChannelPackager(source lnwire.ShortChannelID) *ChannelPackager {
15,183✔
478
        return &ChannelPackager{
15,183✔
479
                source: source,
15,183✔
480
        }
15,183✔
481
}
15,183✔
482

483
// AddFwdPkg writes a newly locked in forwarding package to disk.
484
func (*ChannelPackager) AddFwdPkg(tx kvdb.RwTx, fwdPkg *FwdPkg) error { // nolint: dupl
1,962✔
485
        fwdPkgBkt, err := tx.CreateTopLevelBucket(fwdPackagesKey)
1,962✔
486
        if err != nil {
1,962✔
487
                return err
×
488
        }
×
489

490
        source := makeLogKey(fwdPkg.Source.ToUint64())
1,962✔
491
        sourceBkt, err := fwdPkgBkt.CreateBucketIfNotExists(source[:])
1,962✔
492
        if err != nil {
1,962✔
493
                return err
×
494
        }
×
495

496
        heightKey := makeLogKey(fwdPkg.Height)
1,962✔
497
        heightBkt, err := sourceBkt.CreateBucketIfNotExists(heightKey[:])
1,962✔
498
        if err != nil {
1,962✔
499
                return err
×
500
        }
×
501

502
        // Write ADD updates we received at this commit height.
503
        addBkt, err := heightBkt.CreateBucketIfNotExists(addBucketKey)
1,962✔
504
        if err != nil {
1,962✔
505
                return err
×
506
        }
×
507

508
        // Write SETTLE/FAIL updates we received at this commit height.
509
        failSettleBkt, err := heightBkt.CreateBucketIfNotExists(failSettleBucketKey)
1,962✔
510
        if err != nil {
1,962✔
511
                return err
×
512
        }
×
513

514
        for i := range fwdPkg.Adds {
2,786✔
515
                err = putLogUpdate(addBkt, uint16(i), &fwdPkg.Adds[i])
824✔
516
                if err != nil {
824✔
517
                        return err
×
518
                }
×
519
        }
520

521
        // Persist the initialized pkg filter, which will be used to determine
522
        // when we can remove this forwarding package from disk.
523
        var ackFilterBuf bytes.Buffer
1,962✔
524
        if err := fwdPkg.AckFilter.Encode(&ackFilterBuf); err != nil {
1,962✔
525
                return err
×
526
        }
×
527

528
        if err := heightBkt.Put(ackFilterKey, ackFilterBuf.Bytes()); err != nil {
1,962✔
529
                return err
×
530
        }
×
531

532
        for i := range fwdPkg.SettleFails {
2,391✔
533
                err = putLogUpdate(failSettleBkt, uint16(i), &fwdPkg.SettleFails[i])
429✔
534
                if err != nil {
429✔
535
                        return err
×
536
                }
×
537
        }
538

539
        var settleFailFilterBuf bytes.Buffer
1,962✔
540
        err = fwdPkg.SettleFailFilter.Encode(&settleFailFilterBuf)
1,962✔
541
        if err != nil {
1,962✔
542
                return err
×
543
        }
×
544

545
        return heightBkt.Put(settleFailFilterKey, settleFailFilterBuf.Bytes())
1,962✔
546
}
547

548
// putLogUpdate writes an htlc to the provided `bkt`, using `index` as the key.
549
func putLogUpdate(bkt kvdb.RwBucket, idx uint16, htlc *LogUpdate) error {
1,249✔
550
        var b bytes.Buffer
1,249✔
551
        if err := serializeLogUpdate(&b, htlc); err != nil {
1,249✔
552
                return err
×
553
        }
×
554

555
        return bkt.Put(uint16Key(idx), b.Bytes())
1,249✔
556
}
557

558
// LoadFwdPkgs scans the forwarding log for any packages that haven't been
559
// processed, and returns their deserialized log updates in a map indexed by the
560
// remote commitment height at which the updates were locked in.
561
func (p *ChannelPackager) LoadFwdPkgs(tx kvdb.RTx) ([]*FwdPkg, error) {
471✔
562
        return loadChannelFwdPkgs(tx, p.source)
471✔
563
}
471✔
564

565
// loadChannelFwdPkgs loads all forwarding packages owned by `source`.
566
func loadChannelFwdPkgs(tx kvdb.RTx, source lnwire.ShortChannelID) ([]*FwdPkg, error) {
600✔
567
        fwdPkgBkt := tx.ReadBucket(fwdPackagesKey)
600✔
568
        if fwdPkgBkt == nil {
606✔
569
                return nil, nil
6✔
570
        }
6✔
571

572
        sourceKey := makeLogKey(source.ToUint64())
594✔
573
        sourceBkt := fwdPkgBkt.NestedReadBucket(sourceKey[:])
594✔
574
        if sourceBkt == nil {
1,140✔
575
                return nil, nil
546✔
576
        }
546✔
577

578
        var heights []uint64
52✔
579
        if err := sourceBkt.ForEach(func(k, _ []byte) error {
106✔
580
                if len(k) != 8 {
54✔
581
                        return ErrCorruptedFwdPkg
×
582
                }
×
583

584
                heights = append(heights, byteOrder.Uint64(k))
54✔
585

54✔
586
                return nil
54✔
587
        }); err != nil {
×
588
                return nil, err
×
589
        }
×
590

591
        // Load the forwarding package for each retrieved height.
592
        fwdPkgs := make([]*FwdPkg, 0, len(heights))
52✔
593
        for _, height := range heights {
106✔
594
                fwdPkg, err := loadFwdPkg(fwdPkgBkt, source, height)
54✔
595
                if err != nil {
54✔
596
                        return nil, err
×
597
                }
×
598

599
                fwdPkgs = append(fwdPkgs, fwdPkg)
54✔
600
        }
601

602
        return fwdPkgs, nil
52✔
603
}
604

605
// loadFwdPkg reads the packager's fwd pkg at a given height, and determines the
606
// appropriate FwdState.
607
func loadFwdPkg(fwdPkgBkt kvdb.RBucket, source lnwire.ShortChannelID,
608
        height uint64) (*FwdPkg, error) {
54✔
609

54✔
610
        sourceKey := makeLogKey(source.ToUint64())
54✔
611
        sourceBkt := fwdPkgBkt.NestedReadBucket(sourceKey[:])
54✔
612
        if sourceBkt == nil {
54✔
613
                return nil, ErrCorruptedFwdPkg
×
614
        }
×
615

616
        heightKey := makeLogKey(height)
54✔
617
        heightBkt := sourceBkt.NestedReadBucket(heightKey[:])
54✔
618
        if heightBkt == nil {
54✔
619
                return nil, ErrCorruptedFwdPkg
×
620
        }
×
621

622
        // Load ADDs from disk.
623
        addBkt := heightBkt.NestedReadBucket(addBucketKey)
54✔
624
        if addBkt == nil {
54✔
625
                return nil, ErrCorruptedFwdPkg
×
626
        }
×
627

628
        adds, err := loadHtlcs(addBkt)
54✔
629
        if err != nil {
54✔
630
                return nil, err
×
631
        }
×
632

633
        // Load ack filter from disk.
634
        ackFilterBytes := heightBkt.Get(ackFilterKey)
54✔
635
        if ackFilterBytes == nil {
54✔
636
                return nil, ErrCorruptedFwdPkg
×
637
        }
×
638
        ackFilterReader := bytes.NewReader(ackFilterBytes)
54✔
639

54✔
640
        ackFilter := &PkgFilter{}
54✔
641
        if err := ackFilter.Decode(ackFilterReader); err != nil {
54✔
642
                return nil, err
×
643
        }
×
644

645
        // Load SETTLE/FAILs from disk.
646
        failSettleBkt := heightBkt.NestedReadBucket(failSettleBucketKey)
54✔
647
        if failSettleBkt == nil {
54✔
648
                return nil, ErrCorruptedFwdPkg
×
649
        }
×
650

651
        failSettles, err := loadHtlcs(failSettleBkt)
54✔
652
        if err != nil {
54✔
653
                return nil, err
×
654
        }
×
655

656
        // Load settle fail filter from disk.
657
        settleFailFilterBytes := heightBkt.Get(settleFailFilterKey)
54✔
658
        if settleFailFilterBytes == nil {
54✔
659
                return nil, ErrCorruptedFwdPkg
×
660
        }
×
661
        settleFailFilterReader := bytes.NewReader(settleFailFilterBytes)
54✔
662

54✔
663
        settleFailFilter := &PkgFilter{}
54✔
664
        if err := settleFailFilter.Decode(settleFailFilterReader); err != nil {
54✔
665
                return nil, err
×
666
        }
×
667

668
        // Initialize the fwding package, which always starts in the
669
        // FwdStateLockedIn. We can determine what state the package was left in
670
        // by examining constraints on the information loaded from disk.
671
        fwdPkg := &FwdPkg{
54✔
672
                Source:           source,
54✔
673
                State:            FwdStateLockedIn,
54✔
674
                Height:           height,
54✔
675
                Adds:             adds,
54✔
676
                AckFilter:        ackFilter,
54✔
677
                SettleFails:      failSettles,
54✔
678
                SettleFailFilter: settleFailFilter,
54✔
679
        }
54✔
680

54✔
681
        // Check to see if we have written the set exported filter adds to
54✔
682
        // disk. If we haven't, processing of this package was never started, or
54✔
683
        // failed during the last attempt.
54✔
684
        fwdFilterBytes := heightBkt.Get(fwdFilterKey)
54✔
685
        if fwdFilterBytes == nil {
71✔
686
                nAdds := uint16(len(adds))
17✔
687
                fwdPkg.FwdFilter = NewPkgFilter(nAdds)
17✔
688
                return fwdPkg, nil
17✔
689
        }
17✔
690

691
        fwdFilterReader := bytes.NewReader(fwdFilterBytes)
41✔
692
        fwdPkg.FwdFilter = &PkgFilter{}
41✔
693
        if err := fwdPkg.FwdFilter.Decode(fwdFilterReader); err != nil {
41✔
694
                return nil, err
×
695
        }
×
696

697
        // Otherwise, a complete round of processing was completed, and we
698
        // advance the package to FwdStateProcessed.
699
        fwdPkg.State = FwdStateProcessed
41✔
700

41✔
701
        // If every add, settle, and fail has been fully acknowledged, we can
41✔
702
        // safely set the package's state to FwdStateCompleted, signalling that
41✔
703
        // it can be garbage collected.
41✔
704
        if fwdPkg.AckFilter.IsFull() && fwdPkg.SettleFailFilter.IsFull() {
60✔
705
                fwdPkg.State = FwdStateCompleted
19✔
706
        }
19✔
707

708
        return fwdPkg, nil
41✔
709
}
710

711
// loadHtlcs retrieves all serialized htlcs in a bucket, returning
712
// them in order of the indexes they were written under.
713
func loadHtlcs(bkt kvdb.RBucket) ([]LogUpdate, error) {
104✔
714
        var htlcs []LogUpdate
104✔
715
        if err := bkt.ForEach(func(_, v []byte) error {
191✔
716
                htlc, err := deserializeLogUpdate(bytes.NewReader(v))
87✔
717
                if err != nil {
87✔
718
                        return err
×
719
                }
×
720

721
                htlcs = append(htlcs, *htlc)
87✔
722

87✔
723
                return nil
87✔
724
        }); err != nil {
×
725
                return nil, err
×
726
        }
×
727

728
        return htlcs, nil
104✔
729
}
730

731
// SetFwdFilter writes the set of indexes corresponding to Adds at the
732
// `height` that are to be forwarded to the switch. Calling this method causes
733
// the forwarding package at `height` to be in FwdStateProcessed. We write this
734
// forwarding decision so that we always arrive at the same behavior for HTLCs
735
// leaving this channel. After a restart, we skip validation of these Adds,
736
// since they are assumed to have already been validated, and make the switch or
737
// outgoing link responsible for handling replays.
738
func (p *ChannelPackager) SetFwdFilter(tx kvdb.RwTx, height uint64,
739
        fwdFilter *PkgFilter) error {
1,178✔
740

1,178✔
741
        fwdPkgBkt := tx.ReadWriteBucket(fwdPackagesKey)
1,178✔
742
        if fwdPkgBkt == nil {
1,178✔
743
                return ErrCorruptedFwdPkg
×
744
        }
×
745

746
        source := makeLogKey(p.source.ToUint64())
1,178✔
747
        sourceBkt := fwdPkgBkt.NestedReadWriteBucket(source[:])
1,178✔
748
        if sourceBkt == nil {
1,178✔
749
                return ErrCorruptedFwdPkg
×
750
        }
×
751

752
        heightKey := makeLogKey(height)
1,178✔
753
        heightBkt := sourceBkt.NestedReadWriteBucket(heightKey[:])
1,178✔
754
        if heightBkt == nil {
1,178✔
755
                return ErrCorruptedFwdPkg
×
756
        }
×
757

758
        // If the fwd filter has already been written, we return early to avoid
759
        // modifying the persistent state.
760
        forwardedAddsBytes := heightBkt.Get(fwdFilterKey)
1,178✔
761
        if forwardedAddsBytes != nil {
1,178✔
762
                return nil
×
763
        }
×
764

765
        // Otherwise we serialize and write the provided fwd filter.
766
        var b bytes.Buffer
1,178✔
767
        if err := fwdFilter.Encode(&b); err != nil {
1,178✔
768
                return err
×
769
        }
×
770

771
        return heightBkt.Put(fwdFilterKey, b.Bytes())
1,178✔
772
}
773

774
// AckAddHtlcs accepts a list of references to add htlcs, and updates the
775
// AckAddFilter of those forwarding packages to indicate that a settle or fail
776
// has been received in response to the add.
777
func (p *ChannelPackager) AckAddHtlcs(tx kvdb.RwTx, addRefs ...AddRef) error {
2,050✔
778
        if len(addRefs) == 0 {
3,760✔
779
                return nil
1,710✔
780
        }
1,710✔
781

782
        fwdPkgBkt := tx.ReadWriteBucket(fwdPackagesKey)
344✔
783
        if fwdPkgBkt == nil {
344✔
784
                return ErrCorruptedFwdPkg
×
785
        }
×
786

787
        sourceKey := makeLogKey(p.source.ToUint64())
344✔
788
        sourceBkt := fwdPkgBkt.NestedReadWriteBucket(sourceKey[:])
344✔
789
        if sourceBkt == nil {
344✔
790
                return ErrCorruptedFwdPkg
×
791
        }
×
792

793
        // Organize the forward references such that we just get a single slice
794
        // of indexes for each unique height.
795
        heightDiffs := make(map[uint64][]uint16)
344✔
796
        for _, addRef := range addRefs {
696✔
797
                heightDiffs[addRef.Height] = append(
352✔
798
                        heightDiffs[addRef.Height],
352✔
799
                        addRef.Index,
352✔
800
                )
352✔
801
        }
352✔
802

803
        // Load each height bucket once and remove all acked htlcs at that
804
        // height.
805
        for height, indexes := range heightDiffs {
688✔
806
                err := ackAddHtlcsAtHeight(sourceBkt, height, indexes)
344✔
807
                if err != nil {
344✔
808
                        return err
×
809
                }
×
810
        }
811

812
        return nil
344✔
813
}
814

815
// ackAddHtlcsAtHeight updates the AddAckFilter of a single forwarding package
816
// with a list of indexes, writing the resulting filter back in its place.
817
func ackAddHtlcsAtHeight(sourceBkt kvdb.RwBucket, height uint64,
818
        indexes []uint16) error {
344✔
819

344✔
820
        heightKey := makeLogKey(height)
344✔
821
        heightBkt := sourceBkt.NestedReadWriteBucket(heightKey[:])
344✔
822
        if heightBkt == nil {
344✔
823
                // If the height bucket isn't found, this could be because the
×
824
                // forwarding package was already removed. We'll return nil to
×
825
                // signal that the operation is successful, as there is nothing
×
826
                // to ack.
×
827
                return nil
×
828
        }
×
829

830
        // Load ack filter from disk.
831
        ackFilterBytes := heightBkt.Get(ackFilterKey)
344✔
832
        if ackFilterBytes == nil {
344✔
833
                return ErrCorruptedFwdPkg
×
834
        }
×
835

836
        ackFilter := &PkgFilter{}
344✔
837
        ackFilterReader := bytes.NewReader(ackFilterBytes)
344✔
838
        if err := ackFilter.Decode(ackFilterReader); err != nil {
344✔
839
                return err
×
840
        }
×
841

842
        // Update the ack filter for this height.
843
        for _, index := range indexes {
696✔
844
                ackFilter.Set(index)
352✔
845
        }
352✔
846

847
        // Write the resulting filter to disk.
848
        var ackFilterBuf bytes.Buffer
344✔
849
        if err := ackFilter.Encode(&ackFilterBuf); err != nil {
344✔
850
                return err
×
851
        }
×
852

853
        return heightBkt.Put(ackFilterKey, ackFilterBuf.Bytes())
344✔
854
}
855

856
// AckSettleFails persistently acknowledges settles or fails from a remote forwarding
857
// package. This should only be called after the source of the Add has locked in
858
// the settle/fail, or it becomes otherwise safe to forgo retransmitting the
859
// settle/fail after a restart.
860
func (p *ChannelPackager) AckSettleFails(tx kvdb.RwTx, settleFailRefs ...SettleFailRef) error {
2,049✔
861
        return ackSettleFails(tx, settleFailRefs)
2,049✔
862
}
2,049✔
863

864
// ackSettleFails persistently acknowledges a batch of settle fail references.
865
func ackSettleFails(tx kvdb.RwTx, settleFailRefs []SettleFailRef) error {
2,167✔
866
        if len(settleFailRefs) == 0 {
4,207✔
867
                return nil
2,040✔
868
        }
2,040✔
869

870
        fwdPkgBkt := tx.ReadWriteBucket(fwdPackagesKey)
131✔
871
        if fwdPkgBkt == nil {
131✔
872
                return ErrCorruptedFwdPkg
×
873
        }
×
874

875
        // Organize the forward references such that we just get a single slice
876
        // of indexes for each unique destination-height pair.
877
        destHeightDiffs := make(map[lnwire.ShortChannelID]map[uint64][]uint16)
131✔
878
        for _, settleFailRef := range settleFailRefs {
262✔
879
                destHeights, ok := destHeightDiffs[settleFailRef.Source]
131✔
880
                if !ok {
262✔
881
                        destHeights = make(map[uint64][]uint16)
131✔
882
                        destHeightDiffs[settleFailRef.Source] = destHeights
131✔
883
                }
131✔
884

885
                destHeights[settleFailRef.Height] = append(
131✔
886
                        destHeights[settleFailRef.Height],
131✔
887
                        settleFailRef.Index,
131✔
888
                )
131✔
889
        }
890

891
        // With the references organized by destination and height, we now load
892
        // each remote bucket, and update the settle fail filter for any
893
        // settle/fail htlcs.
894
        for dest, destHeights := range destHeightDiffs {
262✔
895
                destKey := makeLogKey(dest.ToUint64())
131✔
896
                destBkt := fwdPkgBkt.NestedReadWriteBucket(destKey[:])
131✔
897
                if destBkt == nil {
138✔
898
                        // If the destination bucket is not found, this is
7✔
899
                        // likely the result of the destination channel being
7✔
900
                        // closed and having it's forwarding packages wiped. We
7✔
901
                        // won't treat this as an error, because the response
7✔
902
                        // will no longer be retransmitted internally.
7✔
903
                        continue
7✔
904
                }
905

906
                for height, indexes := range destHeights {
256✔
907
                        err := ackSettleFailsAtHeight(destBkt, height, indexes)
128✔
908
                        if err != nil {
128✔
909
                                return err
×
910
                        }
×
911
                }
912
        }
913

914
        return nil
131✔
915
}
916

917
// ackSettleFailsAtHeight given a destination bucket, acks the provided indexes
918
// at particular a height by updating the settle fail filter.
919
func ackSettleFailsAtHeight(destBkt kvdb.RwBucket, height uint64,
920
        indexes []uint16) error {
128✔
921

128✔
922
        heightKey := makeLogKey(height)
128✔
923
        heightBkt := destBkt.NestedReadWriteBucket(heightKey[:])
128✔
924
        if heightBkt == nil {
128✔
925
                // If the height bucket isn't found, this could be because the
×
926
                // forwarding package was already removed. We'll return nil to
×
927
                // signal that the operation is as there is nothing to ack.
×
928
                return nil
×
929
        }
×
930

931
        // Load ack filter from disk.
932
        settleFailFilterBytes := heightBkt.Get(settleFailFilterKey)
128✔
933
        if settleFailFilterBytes == nil {
128✔
934
                return ErrCorruptedFwdPkg
×
935
        }
×
936

937
        settleFailFilter := &PkgFilter{}
128✔
938
        settleFailFilterReader := bytes.NewReader(settleFailFilterBytes)
128✔
939
        if err := settleFailFilter.Decode(settleFailFilterReader); err != nil {
128✔
940
                return err
×
941
        }
×
942

943
        // Update the ack filter for this height.
944
        for _, index := range indexes {
256✔
945
                settleFailFilter.Set(index)
128✔
946
        }
128✔
947

948
        // Write the resulting filter to disk.
949
        var settleFailFilterBuf bytes.Buffer
128✔
950
        if err := settleFailFilter.Encode(&settleFailFilterBuf); err != nil {
128✔
951
                return err
×
952
        }
×
953

954
        return heightBkt.Put(settleFailFilterKey, settleFailFilterBuf.Bytes())
128✔
955
}
956

957
// RemovePkg deletes the forwarding package at the given height from the
958
// packager's source bucket.
959
func (p *ChannelPackager) RemovePkg(tx kvdb.RwTx, height uint64) error {
10✔
960
        fwdPkgBkt := tx.ReadWriteBucket(fwdPackagesKey)
10✔
961
        if fwdPkgBkt == nil {
10✔
962
                return nil
×
963
        }
×
964

965
        sourceBytes := makeLogKey(p.source.ToUint64())
10✔
966
        sourceBkt := fwdPkgBkt.NestedReadWriteBucket(sourceBytes[:])
10✔
967
        if sourceBkt == nil {
10✔
UNCOV
968
                return ErrCorruptedFwdPkg
×
UNCOV
969
        }
×
970

971
        heightKey := makeLogKey(height)
10✔
972

10✔
973
        return sourceBkt.DeleteNestedBucket(heightKey[:])
10✔
974
}
975

976
// Wipe deletes all the channel's forwarding packages, if any.
977
func (p *ChannelPackager) Wipe(tx kvdb.RwTx) error {
120✔
978
        // If the root bucket doesn't exist, there's no need to delete.
120✔
979
        fwdPkgBkt := tx.ReadWriteBucket(fwdPackagesKey)
120✔
980
        if fwdPkgBkt == nil {
121✔
981
                return nil
1✔
982
        }
1✔
983

984
        sourceBytes := makeLogKey(p.source.ToUint64())
119✔
985

119✔
986
        // If the nested bucket doesn't exist, there's no need to delete.
119✔
987
        if fwdPkgBkt.NestedReadWriteBucket(sourceBytes[:]) == nil {
232✔
988
                return nil
113✔
989
        }
113✔
990

991
        return fwdPkgBkt.DeleteNestedBucket(sourceBytes[:])
10✔
992
}
993

994
// uint16Key writes the provided 16-bit unsigned integer to a 2-byte slice.
995
func uint16Key(i uint16) []byte {
1,249✔
996
        key := make([]byte, 2)
1,249✔
997
        byteOrder.PutUint16(key, i)
1,249✔
998
        return key
1,249✔
999
}
1,249✔
1000

1001
// Compile-time constraint to ensure that ChannelPackager implements the public
1002
// FwdPackager interface.
1003
var _ FwdPackager = (*ChannelPackager)(nil)
1004

1005
// Compile-time constraint to ensure that SwitchPackager implements the public
1006
// FwdOperator interface.
1007
var _ FwdOperator = (*SwitchPackager)(nil)
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