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

lightningnetwork / lnd / 19155841408

07 Nov 2025 02:03AM UTC coverage: 66.675% (-0.04%) from 66.712%
19155841408

Pull #10352

github

web-flow
Merge e4313eba8 into 096ab65b1
Pull Request #10352: [WIP] chainrpc: return Unavailable while notifier starts

137328 of 205965 relevant lines covered (66.68%)

21333.36 hits per line

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

90.1
/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) {
6✔
138

6✔
139
        // First, we'll subscribe to the latest set of channel updates given
6✔
140
        // the set of channels we already know of.
6✔
141
        knownChans := make(map[wire.OutPoint]struct{})
6✔
142
        for _, chanBackup := range startingChans {
12✔
143
                knownChans[chanBackup.FundingOutpoint] = struct{}{}
6✔
144
        }
6✔
145
        chanEvents, err := chanNotifier.SubscribeChans(ctx, knownChans)
6✔
146
        if err != nil {
7✔
147
                return nil, err
1✔
148
        }
1✔
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)
5✔
153
        for _, chanBackup := range startingChans {
11✔
154
                backupState[chanBackup.FundingOutpoint] = chanBackup
6✔
155
        }
6✔
156

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

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

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

×
180
                        return
×
181
                }
×
182

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

187
        return startErr
6✔
188
}
189

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

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

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

203
        return nil
6✔
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 {
5✔
210
        if !s.isActive.Load() {
5✔
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)
5✔
219

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

5✔
226
        select {
5✔
227
        case s.manualUpdates <- update:
5✔
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 {
5✔
234
        case err := <-errChan:
5✔
235
                if err != nil {
9✔
236
                        return fmt.Errorf("processing of manual update "+
4✔
237
                                "failed: %w", err)
4✔
238
                }
4✔
239

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

244
        // Success.
245
        return nil
4✔
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 {
9✔
252
        // Before we pack the new set of SCBs, we'll first decode what we
9✔
253
        // already have on-disk, to make sure we can decode it (proper seed)
9✔
254
        // and that we're able to combine it with our new data.
9✔
255
        diskMulti, err := s.Swapper.ExtractMulti(s.keyRing)
9✔
256

9✔
257
        // If the file doesn't exist on disk, then that's OK as it was never
9✔
258
        // created. In this case we'll continue onwards as it isn't a critical
9✔
259
        // error.
9✔
260
        if err != nil && !os.IsNotExist(err) {
9✔
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)
9✔
272
        if diskMulti != nil {
18✔
273
                for _, diskChannel := range diskMulti.StaticBackups {
36✔
274
                        chanPoint := diskChannel.FundingOutpoint
27✔
275
                        combinedBackup[chanPoint] = diskChannel
27✔
276
                }
27✔
277
        }
278
        for _, memChannel := range s.backupState {
30✔
279
                chanPoint := memChannel.FundingOutpoint
21✔
280
                if _, ok := combinedBackup[chanPoint]; ok {
37✔
281
                        log.Warnf("Replacing disk backup for ChannelPoint(%v) "+
16✔
282
                                "w/ newer version", chanPoint)
16✔
283
                }
16✔
284

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

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

293
        // With our updated channel state obtained, we'll create a new multi
294
        // from our series of singles.
295
        var newMulti Multi
9✔
296
        for _, backup := range combinedBackup {
40✔
297
                newMulti.StaticBackups = append(
31✔
298
                        newMulti.StaticBackups, backup,
31✔
299
                )
31✔
300
        }
31✔
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
9✔
305
        err = newMulti.PackToWriter(&b, s.keyRing)
9✔
306
        if err != nil {
9✔
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()))
9✔
314
        if err != nil {
13✔
315
                return fmt.Errorf("unable to update multi backup: %w", err)
4✔
316
        }
4✔
317

318
        return nil
8✔
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() {
5✔
327
        // Ensure that once we exit, we'll cancel our active channel
5✔
328
        // subscription.
5✔
329
        defer s.chanEvents.Cancel()
5✔
330
        defer s.wg.Done()
5✔
331

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

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

5✔
337
        for {
14✔
338
                select {
9✔
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:
5✔
343
                        oldStateSize := len(s.backupState)
5✔
344

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

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

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

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

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

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

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

5✔
378
                        // Without new state constructed, we'll, atomically
5✔
379
                        // update the on-disk backup state.
5✔
380
                        if err := s.updateBackupFile(closedChans...); err != nil {
5✔
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:
5✔
387
                        oldStateSize := len(s.backupState)
5✔
388

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

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

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

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

5✔
404
                        // Without new state constructed, we'll, atomically
5✔
405
                        // update the on-disk backup state.
5✔
406
                        err := s.updateBackupFile()
5✔
407
                        if err != nil {
9✔
408
                                log.Errorf("unable to update backup file: %v",
4✔
409
                                        err)
4✔
410
                        }
4✔
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
5✔
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:
5✔
422
                        return
5✔
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