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

lightningnetwork / lnd / 17027244024

17 Aug 2025 11:32PM UTC coverage: 57.287% (-9.5%) from 66.765%
17027244024

Pull #10167

github

web-flow
Merge fcb4f4303 into fb1adfc21
Pull Request #10167: multi: bump Go to 1.24.6

3 of 18 new or added lines in 6 files covered. (16.67%)

28537 existing lines in 457 files now uncovered.

99094 of 172978 relevant lines covered (57.29%)

1.78 hits per line

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

89.11
/chanbackup/pubsub.go
1
package chanbackup
2

3
import (
4
        "bytes"
5
        "context"
6
        "fmt"
7
        "net"
8
        "os"
9
        "sync"
10
        "sync/atomic"
11

12
        "github.com/btcsuite/btcd/wire"
13
        "github.com/lightningnetwork/lnd/channeldb"
14
        "github.com/lightningnetwork/lnd/keychain"
15
        "github.com/lightningnetwork/lnd/lnutils"
16
)
17

18
// Swapper is an interface that allows the chanbackup.SubSwapper to update the
19
// main multi backup location once it learns of new channels or that prior
20
// channels have been closed.
21
type Swapper interface {
22
        // UpdateAndSwap attempts to atomically update the main multi back up
23
        // file location with the new fully packed multi-channel backup.
24
        UpdateAndSwap(newBackup PackedMulti) error
25

26
        // ExtractMulti attempts to obtain and decode the current SCB instance
27
        // stored by the Swapper instance.
28
        ExtractMulti(keychain keychain.KeyRing) (*Multi, error)
29
}
30

31
// ChannelWithAddrs bundles an open channel along with all the addresses for
32
// the channel peer.
33
type ChannelWithAddrs struct {
34
        *channeldb.OpenChannel
35

36
        // Addrs is the set of addresses that we can use to reach the target
37
        // peer.
38
        Addrs []net.Addr
39
}
40

41
// ChannelEvent packages a new update of new channels since subscription, and
42
// channels that have been opened since prior channel event.
43
type ChannelEvent struct {
44
        // ClosedChans are the set of channels that have been closed since the
45
        // last event.
46
        ClosedChans []wire.OutPoint
47

48
        // NewChans is the set of channels that have been opened since the last
49
        // event.
50
        NewChans []ChannelWithAddrs
51
}
52

53
// manualUpdate holds a group of channel state updates and an error channel
54
// to send back an error happened upon update processing or file updating.
55
type manualUpdate struct {
56
        // singles hold channels backups. They can be either new or known
57
        // channels in the Swapper.
58
        singles []Single
59

60
        // errChan is the channel to send an error back. If the update handling
61
        // and the subsequent file updating succeeds, nil is sent.
62
        // The channel must have capacity of 1 to prevent Swapper blocking.
63
        errChan chan error
64
}
65

66
// ChannelSubscription represents an intent to be notified of any updates to
67
// the primary channel state.
68
type ChannelSubscription struct {
69
        // ChanUpdates is a channel that will be sent upon once the primary
70
        // channel state is updated.
71
        ChanUpdates chan ChannelEvent
72

73
        // Cancel is a closure that allows the caller to cancel their
74
        // subscription and free up any resources allocated.
75
        Cancel func()
76
}
77

78
// ChannelNotifier represents a system that allows the chanbackup.SubSwapper to
79
// be notified of any changes to the primary channel state.
80
type ChannelNotifier interface {
81
        // SubscribeChans requests a new channel subscription relative to the
82
        // initial set of known channels. We use the knownChans as a
83
        // synchronization point to ensure that the chanbackup.SubSwapper does
84
        // not miss any channel open or close events in the period between when
85
        // it's created, and when it requests the channel subscription.
86
        SubscribeChans(context.Context,
87
                map[wire.OutPoint]struct{}) (*ChannelSubscription, error)
88
}
89

90
// SubSwapper subscribes to new updates to the open channel state, and then
91
// swaps out the on-disk channel backup state in response.  This sub-system
92
// that will ensure that the multi chan backup file on disk will always be
93
// updated with the latest channel back up state. We'll receive new
94
// opened/closed channels from the ChannelNotifier, then use the Swapper to
95
// update the file state on disk with the new set of open channels.  This can
96
// be used to implement a system that always keeps the multi-chan backup file
97
// on disk in a consistent state for safety purposes.
98
type SubSwapper struct {
99
        // started tracks whether the SubSwapper has been started and ensures
100
        // it can only be started once.
101
        started sync.Once
102

103
        // stopped tracks whether the SubSwapper has been stopped and ensures
104
        // it can only be stopped once.
105
        stopped sync.Once
106

107
        // backupState are the set of SCBs for all open channels we know of.
108
        backupState map[wire.OutPoint]Single
109

110
        // chanEvents is an active subscription to receive new channel state
111
        // over.
112
        chanEvents *ChannelSubscription
113

114
        manualUpdates chan manualUpdate
115

116
        // keyRing is the main key ring that will allow us to pack the new
117
        // multi backup.
118
        keyRing keychain.KeyRing
119

120
        Swapper
121

122
        quit chan struct{}
123
        wg   sync.WaitGroup
124

125
        // isActive tracks whether the SubSwapper is active and ready to receive
126
        // messages. It is used to prevent manual updates from being sent to the
127
        // SubSwapper after it has been stopped or not yet started.
128
        isActive atomic.Bool
129
}
130

131
// NewSubSwapper creates a new instance of the SubSwapper given the starting
132
// set of channels, and the required interfaces to be notified of new channel
133
// updates, pack a multi backup, and swap the current best backup from its
134
// storage location.
135
func NewSubSwapper(ctx context.Context, startingChans []Single,
136
        chanNotifier ChannelNotifier, keyRing keychain.KeyRing,
137
        backupSwapper Swapper) (*SubSwapper, error) {
3✔
138

3✔
139
        // First, we'll subscribe to the latest set of channel updates given
3✔
140
        // the set of channels we already know of.
3✔
141
        knownChans := make(map[wire.OutPoint]struct{})
3✔
142
        for _, chanBackup := range startingChans {
6✔
143
                knownChans[chanBackup.FundingOutpoint] = struct{}{}
3✔
144
        }
3✔
145
        chanEvents, err := chanNotifier.SubscribeChans(ctx, knownChans)
3✔
146
        if err != nil {
3✔
UNCOV
147
                return nil, err
×
UNCOV
148
        }
×
149

150
        // Next, we'll construct our own backup state so we can add/remove
151
        // channels that have been opened and closed.
152
        backupState := make(map[wire.OutPoint]Single)
3✔
153
        for _, chanBackup := range startingChans {
6✔
154
                backupState[chanBackup.FundingOutpoint] = chanBackup
3✔
155
        }
3✔
156

157
        return &SubSwapper{
3✔
158
                backupState:   backupState,
3✔
159
                chanEvents:    chanEvents,
3✔
160
                keyRing:       keyRing,
3✔
161
                Swapper:       backupSwapper,
3✔
162
                quit:          make(chan struct{}),
3✔
163
                manualUpdates: make(chan manualUpdate),
3✔
164
        }, nil
3✔
165
}
166

167
// Start starts the chanbackup.SubSwapper.
168
func (s *SubSwapper) Start() error {
3✔
169
        var startErr error
3✔
170
        s.started.Do(func() {
6✔
171
                log.Infof("chanbackup.SubSwapper starting")
3✔
172

3✔
173
                // Before we enter our main loop, we'll update the on-disk
3✔
174
                // state with the latest Single state, as nodes may have new
3✔
175
                // advertised addresses.
3✔
176
                if err := s.updateBackupFile(); err != nil {
3✔
177
                        startErr = fmt.Errorf("unable to refresh backup "+
×
178
                                "file: %v", err)
×
179

×
180
                        return
×
181
                }
×
182

183
                s.wg.Add(1)
3✔
184
                go s.backupUpdater()
3✔
185
        })
186

187
        return startErr
3✔
188
}
189

190
// Stop signals the SubSwapper to being a graceful shutdown.
191
func (s *SubSwapper) Stop() error {
3✔
192
        s.stopped.Do(func() {
6✔
193
                log.Infof("chanbackup.SubSwapper shutting down...")
3✔
194
                defer log.Debug("chanbackup.SubSwapper shutdown complete")
3✔
195

3✔
196
                // Mark the SubSwapper as not running.
3✔
197
                s.isActive.Store(false)
3✔
198

3✔
199
                close(s.quit)
3✔
200
                s.wg.Wait()
3✔
201
        })
3✔
202

203
        return nil
3✔
204
}
205

206
// ManualUpdate inserts/updates channel states into the swapper. The updates
207
// are processed in another goroutine. The method waits for the updates to be
208
// fully processed and the file to be updated on-disk before returning.
209
func (s *SubSwapper) ManualUpdate(singles []Single) error {
3✔
210
        if !s.isActive.Load() {
3✔
211
                return fmt.Errorf("swapper is not active, cannot perform " +
×
212
                        "manual update")
×
213
        }
×
214

215
        // Create the channel to send an error back. If the update handling
216
        // and the subsequent file updating succeeds, nil is sent.
217
        // The channel must have capacity of 1 to prevent Swapper blocking.
218
        errChan := make(chan error, 1)
3✔
219

3✔
220
        // Create the update object to insert into the processing loop.
3✔
221
        update := manualUpdate{
3✔
222
                singles: singles,
3✔
223
                errChan: errChan,
3✔
224
        }
3✔
225

3✔
226
        select {
3✔
227
        case s.manualUpdates <- update:
3✔
228
        case <-s.quit:
×
229
                return fmt.Errorf("swapper stopped when sending manual update")
×
230
        }
231

232
        // Wait for processing, block on errChan.
233
        select {
3✔
234
        case err := <-errChan:
3✔
235
                if err != nil {
6✔
236
                        return fmt.Errorf("processing of manual update "+
3✔
237
                                "failed: %w", err)
3✔
238
                }
3✔
239

240
        case <-s.quit:
×
241
                return fmt.Errorf("swapper stopped when waiting for outcome")
×
242
        }
243

244
        // Success.
245
        return nil
3✔
246
}
247

248
// updateBackupFile updates the backup file in place given the current state of
249
// the SubSwapper. We accept the set of channels that were closed between this
250
// update and the last to make sure we leave them out of our backup set union.
251
func (s *SubSwapper) updateBackupFile(closedChans ...wire.OutPoint) error {
3✔
252
        // Before we pack the new set of SCBs, we'll first decode what we
3✔
253
        // already have on-disk, to make sure we can decode it (proper seed)
3✔
254
        // and that we're able to combine it with our new data.
3✔
255
        diskMulti, err := s.Swapper.ExtractMulti(s.keyRing)
3✔
256

3✔
257
        // If the file doesn't exist on disk, then that's OK as it was never
3✔
258
        // created. In this case we'll continue onwards as it isn't a critical
3✔
259
        // error.
3✔
260
        if err != nil && !os.IsNotExist(err) {
3✔
261
                return fmt.Errorf("unable to extract on disk encrypted "+
×
262
                        "SCB: %v", err)
×
263
        }
×
264

265
        // Now that we have channels stored on-disk, we'll create a new set of
266
        // the combined old and new channels to make sure we retain what's
267
        // already on-disk.
268
        //
269
        // NOTE: The ordering of this operations means that our in-memory
270
        // structure will replace what we read from disk.
271
        combinedBackup := make(map[wire.OutPoint]Single)
3✔
272
        if diskMulti != nil {
6✔
273
                for _, diskChannel := range diskMulti.StaticBackups {
6✔
274
                        chanPoint := diskChannel.FundingOutpoint
3✔
275
                        combinedBackup[chanPoint] = diskChannel
3✔
276
                }
3✔
277
        }
278
        for _, memChannel := range s.backupState {
6✔
279
                chanPoint := memChannel.FundingOutpoint
3✔
280
                if _, ok := combinedBackup[chanPoint]; ok {
6✔
281
                        log.Warnf("Replacing disk backup for ChannelPoint(%v) "+
3✔
282
                                "w/ newer version", chanPoint)
3✔
283
                }
3✔
284

285
                combinedBackup[chanPoint] = memChannel
3✔
286
        }
287

288
        // Remove the set of closed channels from the final set of backups.
289
        for _, closedChan := range closedChans {
6✔
290
                delete(combinedBackup, closedChan)
3✔
291
        }
3✔
292

293
        // With our updated channel state obtained, we'll create a new multi
294
        // from our series of singles.
295
        var newMulti Multi
3✔
296
        for _, backup := range combinedBackup {
6✔
297
                newMulti.StaticBackups = append(
3✔
298
                        newMulti.StaticBackups, backup,
3✔
299
                )
3✔
300
        }
3✔
301

302
        // Now that our multi has been assembled, we'll attempt to pack
303
        // (encrypt+encode) the new channel state to our target reader.
304
        var b bytes.Buffer
3✔
305
        err = newMulti.PackToWriter(&b, s.keyRing)
3✔
306
        if err != nil {
3✔
307
                return fmt.Errorf("unable to pack multi backup: %w", err)
×
308
        }
×
309

310
        // Finally, we'll swap out the old backup for this new one in a single
311
        // atomic step, combining the file already on-disk with this set of new
312
        // channels.
313
        err = s.Swapper.UpdateAndSwap(PackedMulti(b.Bytes()))
3✔
314
        if err != nil {
6✔
315
                return fmt.Errorf("unable to update multi backup: %w", err)
3✔
316
        }
3✔
317

318
        return nil
3✔
319
}
320

321
// backupFileUpdater is the primary goroutine of the SubSwapper which is
322
// responsible for listening for changes to the channel, and updating the
323
// persistent multi backup state with a new packed multi of the latest channel
324
// state. Once active, it will process subscription updates and manual updates
325
// until the SubSwapper is stopped.
326
func (s *SubSwapper) backupUpdater() {
3✔
327
        // Ensure that once we exit, we'll cancel our active channel
3✔
328
        // subscription.
3✔
329
        defer s.chanEvents.Cancel()
3✔
330
        defer s.wg.Done()
3✔
331

3✔
332
        log.Debugf("SubSwapper's backupUpdater is active!")
3✔
333

3✔
334
        // Mark the SubSwapper as active.
3✔
335
        s.isActive.Store(true)
3✔
336

3✔
337
        for {
6✔
338
                select {
3✔
339
                // The channel state has been modified! We'll evaluate all
340
                // changes, and swap out the old packed multi with a new one
341
                // with the latest channel state.
342
                case chanUpdate := <-s.chanEvents.ChanUpdates:
3✔
343
                        oldStateSize := len(s.backupState)
3✔
344

3✔
345
                        // For all new open channels, we'll create a new SCB
3✔
346
                        // given the required information.
3✔
347
                        for _, newChan := range chanUpdate.NewChans {
6✔
348
                                log.Debugf("Adding channel %v to backup state",
3✔
349
                                        newChan.FundingOutpoint)
3✔
350

3✔
351
                                single := NewSingle(
3✔
352
                                        newChan.OpenChannel, newChan.Addrs,
3✔
353
                                )
3✔
354
                                s.backupState[newChan.FundingOutpoint] = single
3✔
355
                        }
3✔
356

357
                        // For all closed channels, we'll remove the prior
358
                        // backup state.
359
                        closedChans := make(
3✔
360
                                []wire.OutPoint, 0, len(chanUpdate.ClosedChans),
3✔
361
                        )
3✔
362
                        for i, closedChan := range chanUpdate.ClosedChans {
6✔
363
                                log.Debugf("Removing channel %v from backup "+
3✔
364
                                        "state", lnutils.NewLogClosure(
3✔
365
                                        chanUpdate.ClosedChans[i].String))
3✔
366

3✔
367
                                delete(s.backupState, closedChan)
3✔
368

3✔
369
                                closedChans = append(closedChans, closedChan)
3✔
370
                        }
3✔
371

372
                        newStateSize := len(s.backupState)
3✔
373

3✔
374
                        log.Infof("Updating on-disk multi SCB backup: "+
3✔
375
                                "num_old_chans=%v, num_new_chans=%v",
3✔
376
                                oldStateSize, newStateSize)
3✔
377

3✔
378
                        // Without new state constructed, we'll, atomically
3✔
379
                        // update the on-disk backup state.
3✔
380
                        if err := s.updateBackupFile(closedChans...); err != nil {
3✔
381
                                log.Errorf("unable to update backup file: %v",
×
382
                                        err)
×
383
                        }
×
384

385
                // We received a manual update. Handle it and update the file.
386
                case manualUpdate := <-s.manualUpdates:
3✔
387
                        oldStateSize := len(s.backupState)
3✔
388

3✔
389
                        // For all open channels, we'll create a new SCB given
3✔
390
                        // the required information.
3✔
391
                        for _, single := range manualUpdate.singles {
6✔
392
                                log.Debugf("Manual update of channel %v",
3✔
393
                                        single.FundingOutpoint)
3✔
394

3✔
395
                                s.backupState[single.FundingOutpoint] = single
3✔
396
                        }
3✔
397

398
                        newStateSize := len(s.backupState)
3✔
399

3✔
400
                        log.Infof("Updating on-disk multi SCB backup: "+
3✔
401
                                "num_old_chans=%v, num_new_chans=%v",
3✔
402
                                oldStateSize, newStateSize)
3✔
403

3✔
404
                        // Without new state constructed, we'll, atomically
3✔
405
                        // update the on-disk backup state.
3✔
406
                        err := s.updateBackupFile()
3✔
407
                        if err != nil {
6✔
408
                                log.Errorf("unable to update backup file: %v",
3✔
409
                                        err)
3✔
410
                        }
3✔
411

412
                        // Send the error (or nil) to the caller of
413
                        // ManualUpdate. The error channel must have capacity of
414
                        // 1 not to block here.
415
                        manualUpdate.errChan <- err
3✔
416

417
                // TODO(roasbeef): refresh periodically on a time basis due to
418
                // possible addr changes from node
419

420
                // Exit at once if a quit signal is detected.
421
                case <-s.quit:
3✔
422
                        return
3✔
423
                }
424
        }
425
}
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