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

lightningnetwork / lnd / 10426952143

16 Aug 2024 10:17PM UTC coverage: 49.856% (+0.01%) from 49.843%
10426952143

Pull #8512

github

Roasbeef
lnwallet/chancloser: add unit tests for new rbf coop close
Pull Request #8512: [3/4] - lnwallet/chancloser: add new protofsm based RBF chan closer

6 of 1064 new or added lines in 6 files covered. (0.56%)

159 existing lines in 21 files now uncovered.

96167 of 192890 relevant lines covered (49.86%)

1.55 hits per line

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

71.97
/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 {
3✔
113
        // We add 7 to ensure that the integer division yields properly rounded
3✔
114
        // values.
3✔
115
        filterLen := (count + 7) / 8
3✔
116

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

123
// Count returns the number of elements represented by this PkgFilter.
124
func (f *PkgFilter) Count() uint16 {
×
125
        return f.count
×
126
}
×
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) {
3✔
131
        byt := i / 8
3✔
132
        bit := i % 8
3✔
133

3✔
134
        // Set the i-th bit in the filter.
3✔
135
        // TODO(conner): ignore if > count to prevent panic?
3✔
136
        f.filter[byt] |= byte(1 << (7 - bit))
3✔
137
}
3✔
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 {
3✔
142
        byt := i / 8
3✔
143
        bit := i % 8
3✔
144

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

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

159
        return bytes.Equal(f.filter, f2.filter)
×
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 {
3✔
165
        // Batch validate bytes that are fully used.
3✔
166
        for i := uint16(0); i < f.count/8; i++ {
6✔
167
                if f.filter[i] != 0xFF {
6✔
168
                        return false
3✔
169
                }
3✔
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
3✔
175
        for idx := f.count - rem; idx < f.count; idx++ {
6✔
176
                if !f.Contains(idx) {
6✔
177
                        return false
3✔
178
                }
3✔
179
        }
180

181
        return true
3✔
182
}
183

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

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

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

3✔
199
        return err
3✔
200
}
201

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

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

3✔
211
        return err
3✔
212
}
213

214
// String returns a human-readable string.
215
func (f *PkgFilter) String() string {
3✔
216
        return fmt.Sprintf("count=%v, filter=%v", f.count, f.filter)
3✔
217
}
3✔
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 {
3✔
273

3✔
274
        nAddUpdates := uint16(len(addUpdates))
3✔
275
        nSettleFailUpdates := uint16(len(settleFailUpdates))
3✔
276

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

289
// ID returns an unique identifier for this package, used to ensure that sphinx
290
// replay processing of this batch is idempotent.
291
func (f *FwdPkg) ID() []byte {
3✔
292
        var id = make([]byte, 16)
3✔
293
        byteOrder.PutUint64(id[:8], f.Source.ToUint64())
3✔
294
        byteOrder.PutUint64(id[8:], f.Height)
3✔
295
        return id
3✔
296
}
3✔
297

298
// String returns a human-readable description of the forwarding package.
299
func (f *FwdPkg) String() string {
×
300
        return fmt.Sprintf("%T(src=%v, height=%v, nadds=%v, nfailsettles=%v)",
×
301
                f, f.Source, f.Height, len(f.Adds), len(f.SettleFails))
×
302
}
×
303

304
// AddRef is used to identify a particular Add in a FwdPkg. The short channel ID
305
// is assumed to be that of the packager.
306
type AddRef struct {
307
        // Height is the remote commitment height that locked in the Add.
308
        Height uint64
309

310
        // Index is the index of the Add within the fwd pkg's Adds.
311
        //
312
        // NOTE: This index is static over the lifetime of a forwarding package.
313
        Index uint16
314
}
315

316
// Encode serializes the AddRef to the given io.Writer.
317
func (a *AddRef) Encode(w io.Writer) error {
3✔
318
        if err := binary.Write(w, binary.BigEndian, a.Height); err != nil {
3✔
319
                return err
×
320
        }
×
321

322
        return binary.Write(w, binary.BigEndian, a.Index)
3✔
323
}
324

325
// Decode deserializes the AddRef from the given io.Reader.
326
func (a *AddRef) Decode(r io.Reader) error {
3✔
327
        if err := binary.Read(r, binary.BigEndian, &a.Height); err != nil {
3✔
328
                return err
×
329
        }
×
330

331
        return binary.Read(r, binary.BigEndian, &a.Index)
3✔
332
}
333

334
// SettleFailRef is used to locate a Settle/Fail in another channel's FwdPkg. A
335
// channel does not remove its own Settle/Fail htlcs, so the source is provided
336
// to locate a db bucket belonging to another channel.
337
type SettleFailRef struct {
338
        // Source identifies the outgoing link that locked in the settle or
339
        // fail. This is then used by the *incoming* link to find the settle
340
        // fail in another link's forwarding packages.
341
        Source lnwire.ShortChannelID
342

343
        // Height is the remote commitment height that locked in this
344
        // Settle/Fail.
345
        Height uint64
346

347
        // Index is the index of the Add with the fwd pkg's SettleFails.
348
        //
349
        // NOTE: This index is static over the lifetime of a forwarding package.
350
        Index uint16
351
}
352

353
// SettleFailAcker is a generic interface providing the ability to acknowledge
354
// settle/fail HTLCs stored in forwarding packages.
355
type SettleFailAcker interface {
356
        // AckSettleFails atomically updates the settle-fail filters in *other*
357
        // channels' forwarding packages.
358
        AckSettleFails(tx kvdb.RwTx, settleFailRefs ...SettleFailRef) error
359
}
360

361
// GlobalFwdPkgReader is an interface used to retrieve the forwarding packages
362
// of any active channel.
363
type GlobalFwdPkgReader interface {
364
        // LoadChannelFwdPkgs loads all known forwarding packages for the given
365
        // channel.
366
        LoadChannelFwdPkgs(tx kvdb.RTx,
367
                source lnwire.ShortChannelID) ([]*FwdPkg, error)
368
}
369

370
// FwdOperator defines the interfaces for managing forwarding packages that are
371
// external to a particular channel. This interface is used by the switch to
372
// read forwarding packages from arbitrary channels, and acknowledge settles and
373
// fails for locally-sourced payments.
374
type FwdOperator interface {
375
        // GlobalFwdPkgReader provides read access to all known forwarding
376
        // packages
377
        GlobalFwdPkgReader
378

379
        // SettleFailAcker grants the ability to acknowledge settles or fails
380
        // residing in arbitrary forwarding packages.
381
        SettleFailAcker
382
}
383

384
// SwitchPackager is a concrete implementation of the FwdOperator interface.
385
// A SwitchPackager offers the ability to read any forwarding package, and ack
386
// arbitrary settle and fail HTLCs.
387
type SwitchPackager struct{}
388

389
// NewSwitchPackager instantiates a new SwitchPackager.
390
func NewSwitchPackager() *SwitchPackager {
3✔
391
        return &SwitchPackager{}
3✔
392
}
3✔
393

394
// AckSettleFails atomically updates the settle-fail filters in *other*
395
// channels' forwarding packages, to mark that the switch has received a settle
396
// or fail residing in the forwarding package of a link.
397
func (*SwitchPackager) AckSettleFails(tx kvdb.RwTx,
398
        settleFailRefs ...SettleFailRef) error {
3✔
399

3✔
400
        return ackSettleFails(tx, settleFailRefs)
3✔
401
}
3✔
402

403
// LoadChannelFwdPkgs loads all forwarding packages for a particular channel.
404
func (*SwitchPackager) LoadChannelFwdPkgs(tx kvdb.RTx,
405
        source lnwire.ShortChannelID) ([]*FwdPkg, error) {
3✔
406

3✔
407
        return loadChannelFwdPkgs(tx, source)
3✔
408
}
3✔
409

410
// FwdPackager supports all operations required to modify fwd packages, such as
411
// creation, updates, reading, and removal. The interfaces are broken down in
412
// this way to support future delegation of the subinterfaces.
413
type FwdPackager interface {
414
        // AddFwdPkg serializes and writes a FwdPkg for this channel at the
415
        // remote commitment height included in the forwarding package.
416
        AddFwdPkg(tx kvdb.RwTx, fwdPkg *FwdPkg) error
417

418
        // SetFwdFilter looks up the forwarding package at the remote `height`
419
        // and sets the `fwdFilter`, marking the Adds for which:
420
        // 1) We are not the exit node
421
        // 2) Passed all validation
422
        // 3) Should be forwarded to the switch immediately after a failure
423
        SetFwdFilter(tx kvdb.RwTx, height uint64, fwdFilter *PkgFilter) error
424

425
        // AckAddHtlcs atomically updates the add filters in this channel's
426
        // forwarding packages to mark the resolution of an Add that was
427
        // received from the remote party.
428
        AckAddHtlcs(tx kvdb.RwTx, addRefs ...AddRef) error
429

430
        // SettleFailAcker allows a link to acknowledge settle/fail HTLCs
431
        // belonging to other channels.
432
        SettleFailAcker
433

434
        // LoadFwdPkgs loads all known forwarding packages owned by this
435
        // channel.
436
        LoadFwdPkgs(tx kvdb.RTx) ([]*FwdPkg, error)
437

438
        // RemovePkg deletes a forwarding package owned by this channel at
439
        // the provided remote `height`.
440
        RemovePkg(tx kvdb.RwTx, height uint64) error
441

442
        // Wipe deletes all the forwarding packages owned by this channel.
443
        Wipe(tx kvdb.RwTx) error
444
}
445

446
// ChannelPackager is used by a channel to manage the lifecycle of its forwarding
447
// packages. The packager is tied to a particular source channel ID, allowing it
448
// to create and edit its own packages. Each packager also has the ability to
449
// remove fail/settle htlcs that correspond to an add contained in one of
450
// source's packages.
451
type ChannelPackager struct {
452
        source lnwire.ShortChannelID
453
}
454

455
// NewChannelPackager creates a new packager for a single channel.
456
func NewChannelPackager(source lnwire.ShortChannelID) *ChannelPackager {
3✔
457
        return &ChannelPackager{
3✔
458
                source: source,
3✔
459
        }
3✔
460
}
3✔
461

462
// AddFwdPkg writes a newly locked in forwarding package to disk.
463
func (*ChannelPackager) AddFwdPkg(tx kvdb.RwTx, fwdPkg *FwdPkg) error { // nolint: dupl
3✔
464
        fwdPkgBkt, err := tx.CreateTopLevelBucket(fwdPackagesKey)
3✔
465
        if err != nil {
3✔
466
                return err
×
467
        }
×
468

469
        source := makeLogKey(fwdPkg.Source.ToUint64())
3✔
470
        sourceBkt, err := fwdPkgBkt.CreateBucketIfNotExists(source[:])
3✔
471
        if err != nil {
3✔
472
                return err
×
473
        }
×
474

475
        heightKey := makeLogKey(fwdPkg.Height)
3✔
476
        heightBkt, err := sourceBkt.CreateBucketIfNotExists(heightKey[:])
3✔
477
        if err != nil {
3✔
478
                return err
×
479
        }
×
480

481
        // Write ADD updates we received at this commit height.
482
        addBkt, err := heightBkt.CreateBucketIfNotExists(addBucketKey)
3✔
483
        if err != nil {
3✔
484
                return err
×
485
        }
×
486

487
        // Write SETTLE/FAIL updates we received at this commit height.
488
        failSettleBkt, err := heightBkt.CreateBucketIfNotExists(failSettleBucketKey)
3✔
489
        if err != nil {
3✔
490
                return err
×
491
        }
×
492

493
        for i := range fwdPkg.Adds {
6✔
494
                err = putLogUpdate(addBkt, uint16(i), &fwdPkg.Adds[i])
3✔
495
                if err != nil {
3✔
496
                        return err
×
497
                }
×
498
        }
499

500
        // Persist the initialized pkg filter, which will be used to determine
501
        // when we can remove this forwarding package from disk.
502
        var ackFilterBuf bytes.Buffer
3✔
503
        if err := fwdPkg.AckFilter.Encode(&ackFilterBuf); err != nil {
3✔
504
                return err
×
505
        }
×
506

507
        if err := heightBkt.Put(ackFilterKey, ackFilterBuf.Bytes()); err != nil {
3✔
508
                return err
×
509
        }
×
510

511
        for i := range fwdPkg.SettleFails {
6✔
512
                err = putLogUpdate(failSettleBkt, uint16(i), &fwdPkg.SettleFails[i])
3✔
513
                if err != nil {
3✔
514
                        return err
×
515
                }
×
516
        }
517

518
        var settleFailFilterBuf bytes.Buffer
3✔
519
        err = fwdPkg.SettleFailFilter.Encode(&settleFailFilterBuf)
3✔
520
        if err != nil {
3✔
521
                return err
×
522
        }
×
523

524
        return heightBkt.Put(settleFailFilterKey, settleFailFilterBuf.Bytes())
3✔
525
}
526

527
// putLogUpdate writes an htlc to the provided `bkt`, using `index` as the key.
528
func putLogUpdate(bkt kvdb.RwBucket, idx uint16, htlc *LogUpdate) error {
3✔
529
        var b bytes.Buffer
3✔
530
        if err := serializeLogUpdate(&b, htlc); err != nil {
3✔
531
                return err
×
532
        }
×
533

534
        return bkt.Put(uint16Key(idx), b.Bytes())
3✔
535
}
536

537
// LoadFwdPkgs scans the forwarding log for any packages that haven't been
538
// processed, and returns their deserialized log updates in a map indexed by the
539
// remote commitment height at which the updates were locked in.
540
func (p *ChannelPackager) LoadFwdPkgs(tx kvdb.RTx) ([]*FwdPkg, error) {
3✔
541
        return loadChannelFwdPkgs(tx, p.source)
3✔
542
}
3✔
543

544
// loadChannelFwdPkgs loads all forwarding packages owned by `source`.
545
func loadChannelFwdPkgs(tx kvdb.RTx, source lnwire.ShortChannelID) ([]*FwdPkg, error) {
3✔
546
        fwdPkgBkt := tx.ReadBucket(fwdPackagesKey)
3✔
547
        if fwdPkgBkt == nil {
3✔
548
                return nil, nil
×
549
        }
×
550

551
        sourceKey := makeLogKey(source.ToUint64())
3✔
552
        sourceBkt := fwdPkgBkt.NestedReadBucket(sourceKey[:])
3✔
553
        if sourceBkt == nil {
6✔
554
                return nil, nil
3✔
555
        }
3✔
556

557
        var heights []uint64
3✔
558
        if err := sourceBkt.ForEach(func(k, _ []byte) error {
6✔
559
                if len(k) != 8 {
3✔
560
                        return ErrCorruptedFwdPkg
×
561
                }
×
562

563
                heights = append(heights, byteOrder.Uint64(k))
3✔
564

3✔
565
                return nil
3✔
566
        }); err != nil {
×
567
                return nil, err
×
568
        }
×
569

570
        // Load the forwarding package for each retrieved height.
571
        fwdPkgs := make([]*FwdPkg, 0, len(heights))
3✔
572
        for _, height := range heights {
6✔
573
                fwdPkg, err := loadFwdPkg(fwdPkgBkt, source, height)
3✔
574
                if err != nil {
3✔
575
                        return nil, err
×
576
                }
×
577

578
                fwdPkgs = append(fwdPkgs, fwdPkg)
3✔
579
        }
580

581
        return fwdPkgs, nil
3✔
582
}
583

584
// loadFwdPkg reads the packager's fwd pkg at a given height, and determines the
585
// appropriate FwdState.
586
func loadFwdPkg(fwdPkgBkt kvdb.RBucket, source lnwire.ShortChannelID,
587
        height uint64) (*FwdPkg, error) {
3✔
588

3✔
589
        sourceKey := makeLogKey(source.ToUint64())
3✔
590
        sourceBkt := fwdPkgBkt.NestedReadBucket(sourceKey[:])
3✔
591
        if sourceBkt == nil {
3✔
592
                return nil, ErrCorruptedFwdPkg
×
593
        }
×
594

595
        heightKey := makeLogKey(height)
3✔
596
        heightBkt := sourceBkt.NestedReadBucket(heightKey[:])
3✔
597
        if heightBkt == nil {
3✔
598
                return nil, ErrCorruptedFwdPkg
×
599
        }
×
600

601
        // Load ADDs from disk.
602
        addBkt := heightBkt.NestedReadBucket(addBucketKey)
3✔
603
        if addBkt == nil {
3✔
604
                return nil, ErrCorruptedFwdPkg
×
605
        }
×
606

607
        adds, err := loadHtlcs(addBkt)
3✔
608
        if err != nil {
3✔
609
                return nil, err
×
610
        }
×
611

612
        // Load ack filter from disk.
613
        ackFilterBytes := heightBkt.Get(ackFilterKey)
3✔
614
        if ackFilterBytes == nil {
3✔
615
                return nil, ErrCorruptedFwdPkg
×
616
        }
×
617
        ackFilterReader := bytes.NewReader(ackFilterBytes)
3✔
618

3✔
619
        ackFilter := &PkgFilter{}
3✔
620
        if err := ackFilter.Decode(ackFilterReader); err != nil {
3✔
621
                return nil, err
×
622
        }
×
623

624
        // Load SETTLE/FAILs from disk.
625
        failSettleBkt := heightBkt.NestedReadBucket(failSettleBucketKey)
3✔
626
        if failSettleBkt == nil {
3✔
627
                return nil, ErrCorruptedFwdPkg
×
628
        }
×
629

630
        failSettles, err := loadHtlcs(failSettleBkt)
3✔
631
        if err != nil {
3✔
632
                return nil, err
×
633
        }
×
634

635
        // Load settle fail filter from disk.
636
        settleFailFilterBytes := heightBkt.Get(settleFailFilterKey)
3✔
637
        if settleFailFilterBytes == nil {
3✔
638
                return nil, ErrCorruptedFwdPkg
×
639
        }
×
640
        settleFailFilterReader := bytes.NewReader(settleFailFilterBytes)
3✔
641

3✔
642
        settleFailFilter := &PkgFilter{}
3✔
643
        if err := settleFailFilter.Decode(settleFailFilterReader); err != nil {
3✔
644
                return nil, err
×
645
        }
×
646

647
        // Initialize the fwding package, which always starts in the
648
        // FwdStateLockedIn. We can determine what state the package was left in
649
        // by examining constraints on the information loaded from disk.
650
        fwdPkg := &FwdPkg{
3✔
651
                Source:           source,
3✔
652
                State:            FwdStateLockedIn,
3✔
653
                Height:           height,
3✔
654
                Adds:             adds,
3✔
655
                AckFilter:        ackFilter,
3✔
656
                SettleFails:      failSettles,
3✔
657
                SettleFailFilter: settleFailFilter,
3✔
658
        }
3✔
659

3✔
660
        // Check to see if we have written the set exported filter adds to
3✔
661
        // disk. If we haven't, processing of this package was never started, or
3✔
662
        // failed during the last attempt.
3✔
663
        fwdFilterBytes := heightBkt.Get(fwdFilterKey)
3✔
664
        if fwdFilterBytes == nil {
3✔
665
                nAdds := uint16(len(adds))
×
666
                fwdPkg.FwdFilter = NewPkgFilter(nAdds)
×
667
                return fwdPkg, nil
×
668
        }
×
669

670
        fwdFilterReader := bytes.NewReader(fwdFilterBytes)
3✔
671
        fwdPkg.FwdFilter = &PkgFilter{}
3✔
672
        if err := fwdPkg.FwdFilter.Decode(fwdFilterReader); err != nil {
3✔
673
                return nil, err
×
674
        }
×
675

676
        // Otherwise, a complete round of processing was completed, and we
677
        // advance the package to FwdStateProcessed.
678
        fwdPkg.State = FwdStateProcessed
3✔
679

3✔
680
        // If every add, settle, and fail has been fully acknowledged, we can
3✔
681
        // safely set the package's state to FwdStateCompleted, signalling that
3✔
682
        // it can be garbage collected.
3✔
683
        if fwdPkg.AckFilter.IsFull() && fwdPkg.SettleFailFilter.IsFull() {
6✔
684
                fwdPkg.State = FwdStateCompleted
3✔
685
        }
3✔
686

687
        return fwdPkg, nil
3✔
688
}
689

690
// loadHtlcs retrieves all serialized htlcs in a bucket, returning
691
// them in order of the indexes they were written under.
692
func loadHtlcs(bkt kvdb.RBucket) ([]LogUpdate, error) {
3✔
693
        var htlcs []LogUpdate
3✔
694
        if err := bkt.ForEach(func(_, v []byte) error {
6✔
695
                htlc, err := deserializeLogUpdate(bytes.NewReader(v))
3✔
696
                if err != nil {
3✔
697
                        return err
×
698
                }
×
699

700
                htlcs = append(htlcs, *htlc)
3✔
701

3✔
702
                return nil
3✔
703
        }); err != nil {
×
704
                return nil, err
×
705
        }
×
706

707
        return htlcs, nil
3✔
708
}
709

710
// SetFwdFilter writes the set of indexes corresponding to Adds at the
711
// `height` that are to be forwarded to the switch. Calling this method causes
712
// the forwarding package at `height` to be in FwdStateProcessed. We write this
713
// forwarding decision so that we always arrive at the same behavior for HTLCs
714
// leaving this channel. After a restart, we skip validation of these Adds,
715
// since they are assumed to have already been validated, and make the switch or
716
// outgoing link responsible for handling replays.
717
func (p *ChannelPackager) SetFwdFilter(tx kvdb.RwTx, height uint64,
718
        fwdFilter *PkgFilter) error {
3✔
719

3✔
720
        fwdPkgBkt := tx.ReadWriteBucket(fwdPackagesKey)
3✔
721
        if fwdPkgBkt == nil {
3✔
722
                return ErrCorruptedFwdPkg
×
723
        }
×
724

725
        source := makeLogKey(p.source.ToUint64())
3✔
726
        sourceBkt := fwdPkgBkt.NestedReadWriteBucket(source[:])
3✔
727
        if sourceBkt == nil {
3✔
728
                return ErrCorruptedFwdPkg
×
729
        }
×
730

731
        heightKey := makeLogKey(height)
3✔
732
        heightBkt := sourceBkt.NestedReadWriteBucket(heightKey[:])
3✔
733
        if heightBkt == nil {
3✔
734
                return ErrCorruptedFwdPkg
×
735
        }
×
736

737
        // If the fwd filter has already been written, we return early to avoid
738
        // modifying the persistent state.
739
        forwardedAddsBytes := heightBkt.Get(fwdFilterKey)
3✔
740
        if forwardedAddsBytes != nil {
3✔
741
                return nil
×
742
        }
×
743

744
        // Otherwise we serialize and write the provided fwd filter.
745
        var b bytes.Buffer
3✔
746
        if err := fwdFilter.Encode(&b); err != nil {
3✔
747
                return err
×
748
        }
×
749

750
        return heightBkt.Put(fwdFilterKey, b.Bytes())
3✔
751
}
752

753
// AckAddHtlcs accepts a list of references to add htlcs, and updates the
754
// AckAddFilter of those forwarding packages to indicate that a settle or fail
755
// has been received in response to the add.
756
func (p *ChannelPackager) AckAddHtlcs(tx kvdb.RwTx, addRefs ...AddRef) error {
3✔
757
        if len(addRefs) == 0 {
6✔
758
                return nil
3✔
759
        }
3✔
760

761
        fwdPkgBkt := tx.ReadWriteBucket(fwdPackagesKey)
3✔
762
        if fwdPkgBkt == nil {
3✔
763
                return ErrCorruptedFwdPkg
×
764
        }
×
765

766
        sourceKey := makeLogKey(p.source.ToUint64())
3✔
767
        sourceBkt := fwdPkgBkt.NestedReadWriteBucket(sourceKey[:])
3✔
768
        if sourceBkt == nil {
3✔
769
                return ErrCorruptedFwdPkg
×
770
        }
×
771

772
        // Organize the forward references such that we just get a single slice
773
        // of indexes for each unique height.
774
        heightDiffs := make(map[uint64][]uint16)
3✔
775
        for _, addRef := range addRefs {
6✔
776
                heightDiffs[addRef.Height] = append(
3✔
777
                        heightDiffs[addRef.Height],
3✔
778
                        addRef.Index,
3✔
779
                )
3✔
780
        }
3✔
781

782
        // Load each height bucket once and remove all acked htlcs at that
783
        // height.
784
        for height, indexes := range heightDiffs {
6✔
785
                err := ackAddHtlcsAtHeight(sourceBkt, height, indexes)
3✔
786
                if err != nil {
3✔
787
                        return err
×
788
                }
×
789
        }
790

791
        return nil
3✔
792
}
793

794
// ackAddHtlcsAtHeight updates the AddAckFilter of a single forwarding package
795
// with a list of indexes, writing the resulting filter back in its place.
796
func ackAddHtlcsAtHeight(sourceBkt kvdb.RwBucket, height uint64,
797
        indexes []uint16) error {
3✔
798

3✔
799
        heightKey := makeLogKey(height)
3✔
800
        heightBkt := sourceBkt.NestedReadWriteBucket(heightKey[:])
3✔
801
        if heightBkt == nil {
3✔
802
                // If the height bucket isn't found, this could be because the
×
803
                // forwarding package was already removed. We'll return nil to
×
804
                // signal that the operation is successful, as there is nothing
×
805
                // to ack.
×
806
                return nil
×
807
        }
×
808

809
        // Load ack filter from disk.
810
        ackFilterBytes := heightBkt.Get(ackFilterKey)
3✔
811
        if ackFilterBytes == nil {
3✔
812
                return ErrCorruptedFwdPkg
×
813
        }
×
814

815
        ackFilter := &PkgFilter{}
3✔
816
        ackFilterReader := bytes.NewReader(ackFilterBytes)
3✔
817
        if err := ackFilter.Decode(ackFilterReader); err != nil {
3✔
818
                return err
×
819
        }
×
820

821
        // Update the ack filter for this height.
822
        for _, index := range indexes {
6✔
823
                ackFilter.Set(index)
3✔
824
        }
3✔
825

826
        // Write the resulting filter to disk.
827
        var ackFilterBuf bytes.Buffer
3✔
828
        if err := ackFilter.Encode(&ackFilterBuf); err != nil {
3✔
829
                return err
×
830
        }
×
831

832
        return heightBkt.Put(ackFilterKey, ackFilterBuf.Bytes())
3✔
833
}
834

835
// AckSettleFails persistently acknowledges settles or fails from a remote forwarding
836
// package. This should only be called after the source of the Add has locked in
837
// the settle/fail, or it becomes otherwise safe to forgo retransmitting the
838
// settle/fail after a restart.
839
func (p *ChannelPackager) AckSettleFails(tx kvdb.RwTx, settleFailRefs ...SettleFailRef) error {
3✔
840
        return ackSettleFails(tx, settleFailRefs)
3✔
841
}
3✔
842

843
// ackSettleFails persistently acknowledges a batch of settle fail references.
844
func ackSettleFails(tx kvdb.RwTx, settleFailRefs []SettleFailRef) error {
3✔
845
        if len(settleFailRefs) == 0 {
6✔
846
                return nil
3✔
847
        }
3✔
848

849
        fwdPkgBkt := tx.ReadWriteBucket(fwdPackagesKey)
3✔
850
        if fwdPkgBkt == nil {
3✔
851
                return ErrCorruptedFwdPkg
×
852
        }
×
853

854
        // Organize the forward references such that we just get a single slice
855
        // of indexes for each unique destination-height pair.
856
        destHeightDiffs := make(map[lnwire.ShortChannelID]map[uint64][]uint16)
3✔
857
        for _, settleFailRef := range settleFailRefs {
6✔
858
                destHeights, ok := destHeightDiffs[settleFailRef.Source]
3✔
859
                if !ok {
6✔
860
                        destHeights = make(map[uint64][]uint16)
3✔
861
                        destHeightDiffs[settleFailRef.Source] = destHeights
3✔
862
                }
3✔
863

864
                destHeights[settleFailRef.Height] = append(
3✔
865
                        destHeights[settleFailRef.Height],
3✔
866
                        settleFailRef.Index,
3✔
867
                )
3✔
868
        }
869

870
        // With the references organized by destination and height, we now load
871
        // each remote bucket, and update the settle fail filter for any
872
        // settle/fail htlcs.
873
        for dest, destHeights := range destHeightDiffs {
6✔
874
                destKey := makeLogKey(dest.ToUint64())
3✔
875
                destBkt := fwdPkgBkt.NestedReadWriteBucket(destKey[:])
3✔
876
                if destBkt == nil {
6✔
877
                        // If the destination bucket is not found, this is
3✔
878
                        // likely the result of the destination channel being
3✔
879
                        // closed and having it's forwarding packages wiped. We
3✔
880
                        // won't treat this as an error, because the response
3✔
881
                        // will no longer be retransmitted internally.
3✔
882
                        continue
3✔
883
                }
884

885
                for height, indexes := range destHeights {
6✔
886
                        err := ackSettleFailsAtHeight(destBkt, height, indexes)
3✔
887
                        if err != nil {
3✔
888
                                return err
×
889
                        }
×
890
                }
891
        }
892

893
        return nil
3✔
894
}
895

896
// ackSettleFailsAtHeight given a destination bucket, acks the provided indexes
897
// at particular a height by updating the settle fail filter.
898
func ackSettleFailsAtHeight(destBkt kvdb.RwBucket, height uint64,
899
        indexes []uint16) error {
3✔
900

3✔
901
        heightKey := makeLogKey(height)
3✔
902
        heightBkt := destBkt.NestedReadWriteBucket(heightKey[:])
3✔
903
        if heightBkt == nil {
3✔
904
                // If the height bucket isn't found, this could be because the
×
905
                // forwarding package was already removed. We'll return nil to
×
906
                // signal that the operation is as there is nothing to ack.
×
907
                return nil
×
908
        }
×
909

910
        // Load ack filter from disk.
911
        settleFailFilterBytes := heightBkt.Get(settleFailFilterKey)
3✔
912
        if settleFailFilterBytes == nil {
3✔
913
                return ErrCorruptedFwdPkg
×
914
        }
×
915

916
        settleFailFilter := &PkgFilter{}
3✔
917
        settleFailFilterReader := bytes.NewReader(settleFailFilterBytes)
3✔
918
        if err := settleFailFilter.Decode(settleFailFilterReader); err != nil {
3✔
919
                return err
×
920
        }
×
921

922
        // Update the ack filter for this height.
923
        for _, index := range indexes {
6✔
924
                settleFailFilter.Set(index)
3✔
925
        }
3✔
926

927
        // Write the resulting filter to disk.
928
        var settleFailFilterBuf bytes.Buffer
3✔
929
        if err := settleFailFilter.Encode(&settleFailFilterBuf); err != nil {
3✔
930
                return err
×
931
        }
×
932

933
        return heightBkt.Put(settleFailFilterKey, settleFailFilterBuf.Bytes())
3✔
934
}
935

936
// RemovePkg deletes the forwarding package at the given height from the
937
// packager's source bucket.
938
func (p *ChannelPackager) RemovePkg(tx kvdb.RwTx, height uint64) error {
3✔
939
        fwdPkgBkt := tx.ReadWriteBucket(fwdPackagesKey)
3✔
940
        if fwdPkgBkt == nil {
3✔
941
                return nil
×
942
        }
×
943

944
        sourceBytes := makeLogKey(p.source.ToUint64())
3✔
945
        sourceBkt := fwdPkgBkt.NestedReadWriteBucket(sourceBytes[:])
3✔
946
        if sourceBkt == nil {
3✔
UNCOV
947
                return ErrCorruptedFwdPkg
×
UNCOV
948
        }
×
949

950
        heightKey := makeLogKey(height)
3✔
951

3✔
952
        return sourceBkt.DeleteNestedBucket(heightKey[:])
3✔
953
}
954

955
// Wipe deletes all the channel's forwarding packages, if any.
956
func (p *ChannelPackager) Wipe(tx kvdb.RwTx) error {
3✔
957
        // If the root bucket doesn't exist, there's no need to delete.
3✔
958
        fwdPkgBkt := tx.ReadWriteBucket(fwdPackagesKey)
3✔
959
        if fwdPkgBkt == nil {
3✔
960
                return nil
×
961
        }
×
962

963
        sourceBytes := makeLogKey(p.source.ToUint64())
3✔
964

3✔
965
        // If the nested bucket doesn't exist, there's no need to delete.
3✔
966
        if fwdPkgBkt.NestedReadWriteBucket(sourceBytes[:]) == nil {
6✔
967
                return nil
3✔
968
        }
3✔
969

970
        return fwdPkgBkt.DeleteNestedBucket(sourceBytes[:])
3✔
971
}
972

973
// uint16Key writes the provided 16-bit unsigned integer to a 2-byte slice.
974
func uint16Key(i uint16) []byte {
3✔
975
        key := make([]byte, 2)
3✔
976
        byteOrder.PutUint16(key, i)
3✔
977
        return key
3✔
978
}
3✔
979

980
// Compile-time constraint to ensure that ChannelPackager implements the public
981
// FwdPackager interface.
982
var _ FwdPackager = (*ChannelPackager)(nil)
983

984
// Compile-time constraint to ensure that SwitchPackager implements the public
985
// FwdOperator interface.
986
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