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

lightningnetwork / lnd / 16200178152

10 Jul 2025 04:04PM UTC coverage: 57.65% (-9.8%) from 67.417%
16200178152

Pull #10065

github

web-flow
Merge 944c68c38 into 04a2be29d
Pull Request #10065: graph/db: async graph cache population

28 of 38 new or added lines in 3 files covered. (73.68%)

28436 existing lines in 456 files now uncovered.

98585 of 171006 relevant lines covered (57.65%)

1.79 hits per line

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

35.18
/routing/localchans/manager.go
1
package localchans
2

3
import (
4
        "bytes"
5
        "context"
6
        "errors"
7
        "fmt"
8
        "sync"
9
        "time"
10

11
        "github.com/btcsuite/btcd/btcec/v2"
12
        "github.com/btcsuite/btcd/wire"
13
        "github.com/lightningnetwork/lnd/channeldb"
14
        "github.com/lightningnetwork/lnd/discovery"
15
        "github.com/lightningnetwork/lnd/fn/v2"
16
        "github.com/lightningnetwork/lnd/graph/db/models"
17
        "github.com/lightningnetwork/lnd/lnrpc"
18
        "github.com/lightningnetwork/lnd/lnwire"
19
        "github.com/lightningnetwork/lnd/routing"
20
)
21

22
// Manager manages the node's local channels. The only operation that is
23
// currently implemented is updating forwarding policies.
24
type Manager struct {
25
        // SelfPub contains the public key of the local node.
26
        SelfPub *btcec.PublicKey
27

28
        // DefaultRoutingPolicy is the default routing policy.
29
        DefaultRoutingPolicy models.ForwardingPolicy
30

31
        // UpdateForwardingPolicies is used by the manager to update active
32
        // links with a new policy.
33
        UpdateForwardingPolicies func(
34
                chanPolicies map[wire.OutPoint]models.ForwardingPolicy)
35

36
        // PropagateChanPolicyUpdate is called to persist a new policy to disk
37
        // and broadcast it to the network.
38
        PropagateChanPolicyUpdate func(
39
                edgesToUpdate []discovery.EdgeWithInfo) error
40

41
        // ForAllOutgoingChannels is required to iterate over all our local
42
        // channels. The ChannelEdgePolicy parameter may be nil.
43
        ForAllOutgoingChannels func(ctx context.Context,
44
                cb func(*models.ChannelEdgeInfo,
45
                        *models.ChannelEdgePolicy) error) error
46

47
        // FetchChannel is used to query local channel parameters. Optionally an
48
        // existing db tx can be supplied.
49
        FetchChannel func(chanPoint wire.OutPoint) (*channeldb.OpenChannel,
50
                error)
51

52
        // AddEdge is used to add edge/channel to the topology of the router.
53
        AddEdge func(ctx context.Context, edge *models.ChannelEdgeInfo) error
54

55
        // policyUpdateLock ensures that the database and the link do not fall
56
        // out of sync if there are concurrent fee update calls. Without it,
57
        // there is a chance that policy A updates the database, then policy B
58
        // updates the database, then policy B updates the link, then policy A
59
        // updates the link.
60
        policyUpdateLock sync.Mutex
61
}
62

63
// UpdatePolicy updates the policy for the specified channels on disk and in
64
// the active links.
65
func (r *Manager) UpdatePolicy(ctx context.Context,
66
        newSchema routing.ChannelPolicy,
67
        createMissingEdge bool, chanPoints ...wire.OutPoint) (
68
        []*lnrpc.FailedUpdate, error) {
3✔
69

3✔
70
        r.policyUpdateLock.Lock()
3✔
71
        defer r.policyUpdateLock.Unlock()
3✔
72

3✔
73
        // First, we'll construct a set of all the channels that we are
3✔
74
        // trying to update.
3✔
75
        unprocessedChans := make(map[wire.OutPoint]struct{})
3✔
76
        for _, chanPoint := range chanPoints {
6✔
77
                unprocessedChans[chanPoint] = struct{}{}
3✔
78
        }
3✔
79

80
        haveChanFilter := len(unprocessedChans) != 0
3✔
81

3✔
82
        var failedUpdates []*lnrpc.FailedUpdate
3✔
83
        var edgesToUpdate []discovery.EdgeWithInfo
3✔
84
        policiesToUpdate := make(map[wire.OutPoint]models.ForwardingPolicy)
3✔
85

3✔
86
        // NOTE: edge may be nil when this function is called.
3✔
87
        processChan := func(info *models.ChannelEdgeInfo,
3✔
88
                edge *models.ChannelEdgePolicy) error {
6✔
89

3✔
90
                // If we have a channel filter, and this channel isn't a part
3✔
91
                // of it, then we'll skip it.
3✔
92
                _, ok := unprocessedChans[info.ChannelPoint]
3✔
93
                if !ok && haveChanFilter {
6✔
94
                        return nil
3✔
95
                }
3✔
96

97
                // Mark this channel as found by removing it. unprocessedChans
98
                // will be used to report invalid channels later on.
99
                delete(unprocessedChans, info.ChannelPoint)
3✔
100

3✔
101
                if edge == nil {
3✔
102
                        log.Errorf("Got nil channel edge policy when updating "+
×
103
                                "a channel. Channel point: %v",
×
104
                                info.ChannelPoint.String())
×
105

×
106
                        failedUpdates = append(failedUpdates, makeFailureItem(
×
107
                                info.ChannelPoint,
×
108
                                lnrpc.UpdateFailure_UPDATE_FAILURE_NOT_FOUND,
×
109
                                "edge policy not found",
×
110
                        ))
×
111

×
112
                        return nil
×
113
                }
×
114

115
                // Apply the new policy to the edge.
116
                err := r.updateEdge(info.ChannelPoint, edge, newSchema)
3✔
117
                if err != nil {
3✔
118
                        failedUpdates = append(failedUpdates,
×
119
                                makeFailureItem(info.ChannelPoint,
×
120
                                        lnrpc.UpdateFailure_UPDATE_FAILURE_INVALID_PARAMETER,
×
121
                                        err.Error(),
×
122
                                ))
×
123

×
124
                        return nil
×
125
                }
×
126

127
                // Add updated edge to list of edges to send to gossiper.
128
                edgesToUpdate = append(edgesToUpdate, discovery.EdgeWithInfo{
3✔
129
                        Info: info,
3✔
130
                        Edge: edge,
3✔
131
                })
3✔
132

3✔
133
                var inboundWireFee lnwire.Fee
3✔
134
                edge.InboundFee.WhenSome(func(fee lnwire.Fee) {
6✔
135
                        inboundWireFee = fee
3✔
136
                })
3✔
137
                inboundFee := models.NewInboundFeeFromWire(inboundWireFee)
3✔
138

3✔
139
                // Add updated policy to list of policies to send to switch.
3✔
140
                policiesToUpdate[info.ChannelPoint] = models.ForwardingPolicy{
3✔
141
                        BaseFee:       edge.FeeBaseMSat,
3✔
142
                        FeeRate:       edge.FeeProportionalMillionths,
3✔
143
                        TimeLockDelta: uint32(edge.TimeLockDelta),
3✔
144
                        MinHTLCOut:    edge.MinHTLC,
3✔
145
                        MaxHTLC:       edge.MaxHTLC,
3✔
146
                        InboundFee:    inboundFee,
3✔
147
                }
3✔
148

3✔
149
                return nil
3✔
150
        }
151

152
        // Next, we'll loop over all the outgoing channels the router knows of.
153
        // If we have a filter then we'll only collect those channels, otherwise
154
        // we'll collect them all.
155
        err := r.ForAllOutgoingChannels(ctx, processChan)
3✔
156
        if err != nil {
3✔
157
                return nil, err
×
158
        }
×
159

160
        // Construct a list of failed policy updates.
161
        for chanPoint := range unprocessedChans {
3✔
UNCOV
162
                channel, err := r.FetchChannel(chanPoint)
×
UNCOV
163
                switch {
×
UNCOV
164
                case errors.Is(err, channeldb.ErrChannelNotFound):
×
UNCOV
165
                        failedUpdates = append(failedUpdates,
×
UNCOV
166
                                makeFailureItem(chanPoint,
×
UNCOV
167
                                        lnrpc.UpdateFailure_UPDATE_FAILURE_NOT_FOUND,
×
UNCOV
168
                                        "not found",
×
UNCOV
169
                                ))
×
170

171
                case err != nil:
×
172
                        failedUpdates = append(failedUpdates,
×
173
                                makeFailureItem(chanPoint,
×
174
                                        lnrpc.UpdateFailure_UPDATE_FAILURE_INTERNAL_ERR,
×
175
                                        err.Error(),
×
176
                                ))
×
177

178
                case channel.IsPending:
×
179
                        failedUpdates = append(failedUpdates,
×
180
                                makeFailureItem(chanPoint,
×
181
                                        lnrpc.UpdateFailure_UPDATE_FAILURE_PENDING,
×
182
                                        "not yet confirmed",
×
183
                                ))
×
184

185
                // If the edge was not found, but the channel is found, that
186
                // means the edge is missing in the graph database and should be
187
                // recreated. The edge and policy are created in-memory. The
188
                // edge is inserted in createEdge below and the policy will be
189
                // added to the graph in the PropagateChanPolicyUpdate call
190
                // below.
UNCOV
191
                case createMissingEdge:
×
UNCOV
192
                        log.Warnf("Missing edge for active channel (%s) "+
×
UNCOV
193
                                "during policy update. Recreating edge with "+
×
UNCOV
194
                                "default policy.",
×
UNCOV
195
                                channel.FundingOutpoint.String())
×
UNCOV
196

×
UNCOV
197
                        info, edge, failedUpdate := r.createMissingEdge(
×
UNCOV
198
                                ctx, channel, newSchema,
×
UNCOV
199
                        )
×
UNCOV
200
                        if failedUpdate == nil {
×
UNCOV
201
                                err = processChan(info, edge)
×
UNCOV
202
                                if err != nil {
×
203
                                        return nil, err
×
204
                                }
×
205
                        } else {
×
206
                                failedUpdates = append(
×
207
                                        failedUpdates, failedUpdate,
×
208
                                )
×
209
                        }
×
210

UNCOV
211
                default:
×
UNCOV
212
                        log.Warnf("Missing edge for active channel (%s) "+
×
UNCOV
213
                                "during policy update. Could not update "+
×
UNCOV
214
                                "policy.", channel.FundingOutpoint.String())
×
UNCOV
215

×
UNCOV
216
                        failedUpdates = append(failedUpdates,
×
UNCOV
217
                                makeFailureItem(chanPoint,
×
UNCOV
218
                                        lnrpc.UpdateFailure_UPDATE_FAILURE_UNKNOWN,
×
UNCOV
219
                                        "could not update policies",
×
UNCOV
220
                                ))
×
221
                }
222
        }
223

224
        // Commit the policy updates to disk and broadcast to the network. We
225
        // validated the new policy above, so we expect no validation errors. If
226
        // this would happen because of a bug, the link policy will be
227
        // desynchronized. It is currently not possible to atomically commit
228
        // multiple edge updates.
229
        err = r.PropagateChanPolicyUpdate(edgesToUpdate)
3✔
230
        if err != nil {
3✔
231
                return nil, err
×
232
        }
×
233

234
        // Update active links.
235
        r.UpdateForwardingPolicies(policiesToUpdate)
3✔
236

3✔
237
        return failedUpdates, nil
3✔
238
}
239

240
func (r *Manager) createMissingEdge(ctx context.Context,
241
        channel *channeldb.OpenChannel,
242
        newSchema routing.ChannelPolicy) (*models.ChannelEdgeInfo,
UNCOV
243
        *models.ChannelEdgePolicy, *lnrpc.FailedUpdate) {
×
UNCOV
244

×
UNCOV
245
        info, edge, err := r.createEdge(channel, time.Now())
×
UNCOV
246
        if err != nil {
×
247
                log.Errorf("Failed to recreate missing edge "+
×
248
                        "for channel (%s): %v",
×
249
                        channel.FundingOutpoint.String(), err)
×
250

×
251
                return nil, nil, makeFailureItem(
×
252
                        channel.FundingOutpoint,
×
253
                        lnrpc.UpdateFailure_UPDATE_FAILURE_UNKNOWN,
×
254
                        "could not update policies",
×
255
                )
×
256
        }
×
257

258
        // Validate the newly created edge policy with the user defined new
259
        // schema before adding the edge to the database.
UNCOV
260
        err = r.updateEdge(channel.FundingOutpoint, edge, newSchema)
×
UNCOV
261
        if err != nil {
×
262
                return nil, nil, makeFailureItem(
×
263
                        info.ChannelPoint,
×
264
                        lnrpc.UpdateFailure_UPDATE_FAILURE_INVALID_PARAMETER,
×
265
                        err.Error(),
×
266
                )
×
267
        }
×
268

269
        // Insert the edge into the database to avoid `edge not
270
        // found` errors during policy update propagation.
UNCOV
271
        err = r.AddEdge(ctx, info)
×
UNCOV
272
        if err != nil {
×
273
                log.Errorf("Attempt to add missing edge for "+
×
274
                        "channel (%s) errored with: %v",
×
275
                        channel.FundingOutpoint.String(), err)
×
276

×
277
                return nil, nil, makeFailureItem(
×
278
                        channel.FundingOutpoint,
×
279
                        lnrpc.UpdateFailure_UPDATE_FAILURE_UNKNOWN,
×
280
                        "could not add edge",
×
281
                )
×
282
        }
×
283

UNCOV
284
        return info, edge, nil
×
285
}
286

287
// createEdge recreates an edge and policy from an open channel in-memory.
288
func (r *Manager) createEdge(channel *channeldb.OpenChannel,
289
        timestamp time.Time) (*models.ChannelEdgeInfo,
UNCOV
290
        *models.ChannelEdgePolicy, error) {
×
UNCOV
291

×
UNCOV
292
        nodeKey1Bytes := r.SelfPub.SerializeCompressed()
×
UNCOV
293
        nodeKey2Bytes := channel.IdentityPub.SerializeCompressed()
×
UNCOV
294
        bitcoinKey1Bytes := channel.LocalChanCfg.MultiSigKey.PubKey.
×
UNCOV
295
                SerializeCompressed()
×
UNCOV
296
        bitcoinKey2Bytes := channel.RemoteChanCfg.MultiSigKey.PubKey.
×
UNCOV
297
                SerializeCompressed()
×
UNCOV
298
        channelFlags := lnwire.ChanUpdateChanFlags(0)
×
UNCOV
299

×
UNCOV
300
        // Make it such that node_id_1 is the lexicographically-lesser of the
×
UNCOV
301
        // two compressed keys sorted in ascending lexicographic order.
×
UNCOV
302
        if bytes.Compare(nodeKey2Bytes, nodeKey1Bytes) < 0 {
×
UNCOV
303
                nodeKey1Bytes, nodeKey2Bytes = nodeKey2Bytes, nodeKey1Bytes
×
UNCOV
304
                bitcoinKey1Bytes, bitcoinKey2Bytes = bitcoinKey2Bytes,
×
UNCOV
305
                        bitcoinKey1Bytes
×
UNCOV
306
                channelFlags = 1
×
UNCOV
307
        }
×
308

309
        // We need to make sure we use the real scid for public confirmed
310
        // zero-conf channels.
UNCOV
311
        shortChanID := channel.ShortChanID()
×
UNCOV
312
        isPublic := channel.ChannelFlags&lnwire.FFAnnounceChannel != 0
×
UNCOV
313
        if isPublic && channel.IsZeroConf() && channel.ZeroConfConfirmed() {
×
314
                shortChanID = channel.ZeroConfRealScid()
×
315
        }
×
316

UNCOV
317
        info := &models.ChannelEdgeInfo{
×
UNCOV
318
                ChannelID:    shortChanID.ToUint64(),
×
UNCOV
319
                ChainHash:    channel.ChainHash,
×
UNCOV
320
                Features:     lnwire.EmptyFeatureVector(),
×
UNCOV
321
                Capacity:     channel.Capacity,
×
UNCOV
322
                ChannelPoint: channel.FundingOutpoint,
×
UNCOV
323
        }
×
UNCOV
324

×
UNCOV
325
        copy(info.NodeKey1Bytes[:], nodeKey1Bytes)
×
UNCOV
326
        copy(info.NodeKey2Bytes[:], nodeKey2Bytes)
×
UNCOV
327
        copy(info.BitcoinKey1Bytes[:], bitcoinKey1Bytes)
×
UNCOV
328
        copy(info.BitcoinKey2Bytes[:], bitcoinKey2Bytes)
×
UNCOV
329

×
UNCOV
330
        // Construct a dummy channel edge policy with default values that will
×
UNCOV
331
        // be updated with the new values in the call to processChan below.
×
UNCOV
332
        timeLockDelta := uint16(r.DefaultRoutingPolicy.TimeLockDelta)
×
UNCOV
333
        edge := &models.ChannelEdgePolicy{
×
UNCOV
334
                ChannelID:                 shortChanID.ToUint64(),
×
UNCOV
335
                LastUpdate:                timestamp,
×
UNCOV
336
                TimeLockDelta:             timeLockDelta,
×
UNCOV
337
                ChannelFlags:              channelFlags,
×
UNCOV
338
                MessageFlags:              lnwire.ChanUpdateRequiredMaxHtlc,
×
UNCOV
339
                FeeBaseMSat:               r.DefaultRoutingPolicy.BaseFee,
×
UNCOV
340
                FeeProportionalMillionths: r.DefaultRoutingPolicy.FeeRate,
×
UNCOV
341
                MinHTLC:                   r.DefaultRoutingPolicy.MinHTLCOut,
×
UNCOV
342
                MaxHTLC:                   r.DefaultRoutingPolicy.MaxHTLC,
×
UNCOV
343
        }
×
UNCOV
344

×
UNCOV
345
        copy(edge.ToNode[:], channel.IdentityPub.SerializeCompressed())
×
UNCOV
346

×
UNCOV
347
        return info, edge, nil
×
348
}
349

350
// updateEdge updates the given edge with the new schema.
351
func (r *Manager) updateEdge(chanPoint wire.OutPoint,
352
        edge *models.ChannelEdgePolicy,
353
        newSchema routing.ChannelPolicy) error {
3✔
354

3✔
355
        channel, err := r.FetchChannel(chanPoint)
3✔
356
        if err != nil {
3✔
357
                return err
×
358
        }
×
359

360
        // Update forwarding fee scheme and required time lock delta.
361
        edge.FeeBaseMSat = newSchema.BaseFee
3✔
362
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(
3✔
363
                newSchema.FeeRate,
3✔
364
        )
3✔
365

3✔
366
        // If inbound fees are set, we update the edge with them.
3✔
367
        err = fn.MapOptionZ(newSchema.InboundFee,
3✔
368
                func(f models.InboundFee) error {
6✔
369
                        inboundWireFee := f.ToWire()
3✔
370
                        edge.InboundFee = fn.Some(inboundWireFee)
3✔
371

3✔
372
                        return edge.ExtraOpaqueData.PackRecords(
3✔
373
                                &inboundWireFee,
3✔
374
                        )
3✔
375
                })
3✔
376
        if err != nil {
3✔
377
                return err
×
378
        }
×
379

380
        edge.TimeLockDelta = uint16(newSchema.TimeLockDelta)
3✔
381

3✔
382
        // Retrieve negotiated channel htlc amt limits.
3✔
383
        amtMin, amtMax, err := r.getHtlcAmtLimits(channel)
3✔
384
        if err != nil {
3✔
385
                return err
×
386
        }
×
387

388
        // We now update the edge max htlc value.
389
        switch {
3✔
390
        // If a non-zero max htlc was specified, use it to update the edge.
391
        // Otherwise keep the value unchanged.
392
        case newSchema.MaxHTLC != 0:
3✔
393
                edge.MaxHTLC = newSchema.MaxHTLC
3✔
394

395
        // If this edge still doesn't have a max htlc set, set it to the max.
396
        // This is an on-the-fly migration.
397
        case !edge.MessageFlags.HasMaxHtlc():
×
398
                edge.MaxHTLC = amtMax
×
399

400
        // If this edge has a max htlc that exceeds what the channel can
401
        // actually carry, correct it now. This can happen, because we
402
        // previously set the max htlc to the channel capacity.
403
        case edge.MaxHTLC > amtMax:
×
404
                edge.MaxHTLC = amtMax
×
405
        }
406

407
        // If a new min htlc is specified, update the edge.
408
        if newSchema.MinHTLC != nil {
3✔
409
                edge.MinHTLC = *newSchema.MinHTLC
×
410
        }
×
411

412
        // If the MaxHtlc flag wasn't already set, we can set it now.
413
        edge.MessageFlags |= lnwire.ChanUpdateRequiredMaxHtlc
3✔
414

3✔
415
        // Validate htlc amount constraints.
3✔
416
        switch {
3✔
417
        case edge.MinHTLC < amtMin:
×
418
                return fmt.Errorf(
×
419
                        "min htlc amount of %v is below min htlc parameter of %v",
×
420
                        edge.MinHTLC, amtMin,
×
421
                )
×
422

423
        case edge.MaxHTLC > amtMax:
×
424
                return fmt.Errorf(
×
425
                        "max htlc size of %v is above max pending amount of %v",
×
426
                        edge.MaxHTLC, amtMax,
×
427
                )
×
428

429
        case edge.MinHTLC > edge.MaxHTLC:
×
430
                return fmt.Errorf(
×
431
                        "min_htlc %v greater than max_htlc %v",
×
432
                        edge.MinHTLC, edge.MaxHTLC,
×
433
                )
×
434
        }
435

436
        // Clear signature to help prevent usage of the previous signature.
437
        edge.SetSigBytes(nil)
3✔
438

3✔
439
        return nil
3✔
440
}
441

442
// getHtlcAmtLimits retrieves the negotiated channel min and max htlc amount
443
// constraints.
444
func (r *Manager) getHtlcAmtLimits(ch *channeldb.OpenChannel) (
445
        lnwire.MilliSatoshi, lnwire.MilliSatoshi, error) {
3✔
446

3✔
447
        // The max htlc policy field must be less than or equal to the channel
3✔
448
        // capacity AND less than or equal to the max in-flight HTLC value.
3✔
449
        // Since the latter is always less than or equal to the former, just
3✔
450
        // return the max in-flight value.
3✔
451
        maxAmt := ch.LocalChanCfg.ChannelStateBounds.MaxPendingAmount
3✔
452

3✔
453
        return ch.LocalChanCfg.MinHTLC, maxAmt, nil
3✔
454
}
3✔
455

456
// makeFailureItem creates a lnrpc.FailedUpdate object.
457
func makeFailureItem(outPoint wire.OutPoint, updateFailure lnrpc.UpdateFailure,
UNCOV
458
        errStr string) *lnrpc.FailedUpdate {
×
UNCOV
459

×
UNCOV
460
        outpoint := lnrpc.MarshalOutPoint(&outPoint)
×
UNCOV
461

×
UNCOV
462
        return &lnrpc.FailedUpdate{
×
UNCOV
463
                Outpoint:    outpoint,
×
UNCOV
464
                Reason:      updateFailure,
×
UNCOV
465
                UpdateError: errStr,
×
UNCOV
466
        }
×
UNCOV
467
}
×
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