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

lightningnetwork / lnd / 16802564426

07 Aug 2025 10:58AM UTC coverage: 57.437% (-9.5%) from 66.938%
16802564426

Pull #9871

github

web-flow
Merge 0e84b7dbb into 8a2128ba4
Pull Request #9871: Add `NoopAdd` HTLCs

48 of 147 new or added lines in 3 files covered. (32.65%)

28319 existing lines in 455 files now uncovered.

99037 of 172428 relevant lines covered (57.44%)

1.78 hits per line

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

36.42
/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, reset func()) 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(
3✔
156
                ctx, processChan,
3✔
157
                func() {
6✔
158
                        failedUpdates = nil
3✔
159
                        edgesToUpdate = nil
3✔
160
                        clear(policiesToUpdate)
3✔
161
                },
3✔
162
        )
163
        if err != nil {
3✔
164
                return nil, err
×
165
        }
×
166

167
        // Construct a list of failed policy updates.
168
        for chanPoint := range unprocessedChans {
3✔
UNCOV
169
                channel, err := r.FetchChannel(chanPoint)
×
UNCOV
170
                switch {
×
UNCOV
171
                case errors.Is(err, channeldb.ErrChannelNotFound):
×
UNCOV
172
                        failedUpdates = append(failedUpdates,
×
UNCOV
173
                                makeFailureItem(chanPoint,
×
UNCOV
174
                                        lnrpc.UpdateFailure_UPDATE_FAILURE_NOT_FOUND,
×
UNCOV
175
                                        "not found",
×
UNCOV
176
                                ))
×
177

178
                case err != nil:
×
179
                        failedUpdates = append(failedUpdates,
×
180
                                makeFailureItem(chanPoint,
×
181
                                        lnrpc.UpdateFailure_UPDATE_FAILURE_INTERNAL_ERR,
×
182
                                        err.Error(),
×
183
                                ))
×
184

185
                case channel.IsPending:
×
186
                        failedUpdates = append(failedUpdates,
×
187
                                makeFailureItem(chanPoint,
×
188
                                        lnrpc.UpdateFailure_UPDATE_FAILURE_PENDING,
×
189
                                        "not yet confirmed",
×
190
                                ))
×
191

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

×
UNCOV
204
                        info, edge, failedUpdate := r.createMissingEdge(
×
UNCOV
205
                                ctx, channel, newSchema,
×
UNCOV
206
                        )
×
UNCOV
207
                        if failedUpdate == nil {
×
UNCOV
208
                                err = processChan(info, edge)
×
UNCOV
209
                                if err != nil {
×
210
                                        return nil, err
×
211
                                }
×
212
                        } else {
×
213
                                failedUpdates = append(
×
214
                                        failedUpdates, failedUpdate,
×
215
                                )
×
216
                        }
×
217

UNCOV
218
                default:
×
UNCOV
219
                        log.Warnf("Missing edge for active channel (%s) "+
×
UNCOV
220
                                "during policy update. Could not update "+
×
UNCOV
221
                                "policy.", channel.FundingOutpoint.String())
×
UNCOV
222

×
UNCOV
223
                        failedUpdates = append(failedUpdates,
×
UNCOV
224
                                makeFailureItem(chanPoint,
×
UNCOV
225
                                        lnrpc.UpdateFailure_UPDATE_FAILURE_UNKNOWN,
×
UNCOV
226
                                        "could not update policies",
×
UNCOV
227
                                ))
×
228
                }
229
        }
230

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

241
        // Update active links.
242
        r.UpdateForwardingPolicies(policiesToUpdate)
3✔
243

3✔
244
        return failedUpdates, nil
3✔
245
}
246

247
func (r *Manager) createMissingEdge(ctx context.Context,
248
        channel *channeldb.OpenChannel,
249
        newSchema routing.ChannelPolicy) (*models.ChannelEdgeInfo,
UNCOV
250
        *models.ChannelEdgePolicy, *lnrpc.FailedUpdate) {
×
UNCOV
251

×
UNCOV
252
        info, edge, err := r.createEdge(channel, time.Now())
×
UNCOV
253
        if err != nil {
×
254
                log.Errorf("Failed to recreate missing edge "+
×
255
                        "for channel (%s): %v",
×
256
                        channel.FundingOutpoint.String(), err)
×
257

×
258
                return nil, nil, makeFailureItem(
×
259
                        channel.FundingOutpoint,
×
260
                        lnrpc.UpdateFailure_UPDATE_FAILURE_UNKNOWN,
×
261
                        "could not update policies",
×
262
                )
×
263
        }
×
264

265
        // Validate the newly created edge policy with the user defined new
266
        // schema before adding the edge to the database.
UNCOV
267
        err = r.updateEdge(channel.FundingOutpoint, edge, newSchema)
×
UNCOV
268
        if err != nil {
×
269
                return nil, nil, makeFailureItem(
×
270
                        info.ChannelPoint,
×
271
                        lnrpc.UpdateFailure_UPDATE_FAILURE_INVALID_PARAMETER,
×
272
                        err.Error(),
×
273
                )
×
274
        }
×
275

276
        // Insert the edge into the database to avoid `edge not
277
        // found` errors during policy update propagation.
UNCOV
278
        err = r.AddEdge(ctx, info)
×
UNCOV
279
        if err != nil {
×
280
                log.Errorf("Attempt to add missing edge for "+
×
281
                        "channel (%s) errored with: %v",
×
282
                        channel.FundingOutpoint.String(), err)
×
283

×
284
                return nil, nil, makeFailureItem(
×
285
                        channel.FundingOutpoint,
×
286
                        lnrpc.UpdateFailure_UPDATE_FAILURE_UNKNOWN,
×
287
                        "could not add edge",
×
288
                )
×
289
        }
×
290

UNCOV
291
        return info, edge, nil
×
292
}
293

294
// createEdge recreates an edge and policy from an open channel in-memory.
295
func (r *Manager) createEdge(channel *channeldb.OpenChannel,
296
        timestamp time.Time) (*models.ChannelEdgeInfo,
UNCOV
297
        *models.ChannelEdgePolicy, error) {
×
UNCOV
298

×
UNCOV
299
        nodeKey1Bytes := r.SelfPub.SerializeCompressed()
×
UNCOV
300
        nodeKey2Bytes := channel.IdentityPub.SerializeCompressed()
×
UNCOV
301
        bitcoinKey1Bytes := channel.LocalChanCfg.MultiSigKey.PubKey.
×
UNCOV
302
                SerializeCompressed()
×
UNCOV
303
        bitcoinKey2Bytes := channel.RemoteChanCfg.MultiSigKey.PubKey.
×
UNCOV
304
                SerializeCompressed()
×
UNCOV
305
        channelFlags := lnwire.ChanUpdateChanFlags(0)
×
UNCOV
306

×
UNCOV
307
        // Make it such that node_id_1 is the lexicographically-lesser of the
×
UNCOV
308
        // two compressed keys sorted in ascending lexicographic order.
×
UNCOV
309
        if bytes.Compare(nodeKey2Bytes, nodeKey1Bytes) < 0 {
×
UNCOV
310
                nodeKey1Bytes, nodeKey2Bytes = nodeKey2Bytes, nodeKey1Bytes
×
UNCOV
311
                bitcoinKey1Bytes, bitcoinKey2Bytes = bitcoinKey2Bytes,
×
UNCOV
312
                        bitcoinKey1Bytes
×
UNCOV
313
                channelFlags = 1
×
UNCOV
314
        }
×
315

316
        // We need to make sure we use the real scid for public confirmed
317
        // zero-conf channels.
UNCOV
318
        shortChanID := channel.ShortChanID()
×
UNCOV
319
        isPublic := channel.ChannelFlags&lnwire.FFAnnounceChannel != 0
×
UNCOV
320
        if isPublic && channel.IsZeroConf() && channel.ZeroConfConfirmed() {
×
321
                shortChanID = channel.ZeroConfRealScid()
×
322
        }
×
323

UNCOV
324
        info := &models.ChannelEdgeInfo{
×
UNCOV
325
                ChannelID:    shortChanID.ToUint64(),
×
UNCOV
326
                ChainHash:    channel.ChainHash,
×
UNCOV
327
                Features:     lnwire.EmptyFeatureVector(),
×
UNCOV
328
                Capacity:     channel.Capacity,
×
UNCOV
329
                ChannelPoint: channel.FundingOutpoint,
×
UNCOV
330
        }
×
UNCOV
331

×
UNCOV
332
        copy(info.NodeKey1Bytes[:], nodeKey1Bytes)
×
UNCOV
333
        copy(info.NodeKey2Bytes[:], nodeKey2Bytes)
×
UNCOV
334
        copy(info.BitcoinKey1Bytes[:], bitcoinKey1Bytes)
×
UNCOV
335
        copy(info.BitcoinKey2Bytes[:], bitcoinKey2Bytes)
×
UNCOV
336

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

×
UNCOV
352
        copy(edge.ToNode[:], channel.IdentityPub.SerializeCompressed())
×
UNCOV
353

×
UNCOV
354
        return info, edge, nil
×
355
}
356

357
// updateEdge updates the given edge with the new schema.
358
func (r *Manager) updateEdge(chanPoint wire.OutPoint,
359
        edge *models.ChannelEdgePolicy,
360
        newSchema routing.ChannelPolicy) error {
3✔
361

3✔
362
        channel, err := r.FetchChannel(chanPoint)
3✔
363
        if err != nil {
3✔
364
                return err
×
365
        }
×
366

367
        // Update forwarding fee scheme and required time lock delta.
368
        edge.FeeBaseMSat = newSchema.BaseFee
3✔
369
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(
3✔
370
                newSchema.FeeRate,
3✔
371
        )
3✔
372

3✔
373
        // If inbound fees are set, we update the edge with them.
3✔
374
        err = fn.MapOptionZ(newSchema.InboundFee,
3✔
375
                func(f models.InboundFee) error {
6✔
376
                        inboundWireFee := f.ToWire()
3✔
377
                        edge.InboundFee = fn.Some(inboundWireFee)
3✔
378

3✔
379
                        return edge.ExtraOpaqueData.PackRecords(
3✔
380
                                &inboundWireFee,
3✔
381
                        )
3✔
382
                })
3✔
383
        if err != nil {
3✔
384
                return err
×
385
        }
×
386

387
        edge.TimeLockDelta = uint16(newSchema.TimeLockDelta)
3✔
388

3✔
389
        // Retrieve negotiated channel htlc amt limits.
3✔
390
        amtMin, amtMax, err := r.getHtlcAmtLimits(channel)
3✔
391
        if err != nil {
3✔
392
                return err
×
393
        }
×
394

395
        // We now update the edge max htlc value.
396
        switch {
3✔
397
        // If a non-zero max htlc was specified, use it to update the edge.
398
        // Otherwise keep the value unchanged.
399
        case newSchema.MaxHTLC != 0:
3✔
400
                edge.MaxHTLC = newSchema.MaxHTLC
3✔
401

402
        // If this edge still doesn't have a max htlc set, set it to the max.
403
        // This is an on-the-fly migration.
404
        case !edge.MessageFlags.HasMaxHtlc():
×
405
                edge.MaxHTLC = amtMax
×
406

407
        // If this edge has a max htlc that exceeds what the channel can
408
        // actually carry, correct it now. This can happen, because we
409
        // previously set the max htlc to the channel capacity.
410
        case edge.MaxHTLC > amtMax:
×
411
                edge.MaxHTLC = amtMax
×
412
        }
413

414
        // If a new min htlc is specified, update the edge.
415
        if newSchema.MinHTLC != nil {
3✔
416
                edge.MinHTLC = *newSchema.MinHTLC
×
417
        }
×
418

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

3✔
422
        // Validate htlc amount constraints.
3✔
423
        switch {
3✔
424
        case edge.MinHTLC < amtMin:
×
425
                return fmt.Errorf(
×
426
                        "min htlc amount of %v is below min htlc parameter of %v",
×
427
                        edge.MinHTLC, amtMin,
×
428
                )
×
429

430
        case edge.MaxHTLC > amtMax:
×
431
                return fmt.Errorf(
×
432
                        "max htlc size of %v is above max pending amount of %v",
×
433
                        edge.MaxHTLC, amtMax,
×
434
                )
×
435

436
        case edge.MinHTLC > edge.MaxHTLC:
×
437
                return fmt.Errorf(
×
438
                        "min_htlc %v greater than max_htlc %v",
×
439
                        edge.MinHTLC, edge.MaxHTLC,
×
440
                )
×
441
        }
442

443
        // Clear signature to help prevent usage of the previous signature.
444
        edge.SetSigBytes(nil)
3✔
445

3✔
446
        return nil
3✔
447
}
448

449
// getHtlcAmtLimits retrieves the negotiated channel min and max htlc amount
450
// constraints.
451
func (r *Manager) getHtlcAmtLimits(ch *channeldb.OpenChannel) (
452
        lnwire.MilliSatoshi, lnwire.MilliSatoshi, error) {
3✔
453

3✔
454
        // The max htlc policy field must be less than or equal to the channel
3✔
455
        // capacity AND less than or equal to the max in-flight HTLC value.
3✔
456
        // Since the latter is always less than or equal to the former, just
3✔
457
        // return the max in-flight value.
3✔
458
        maxAmt := ch.LocalChanCfg.ChannelStateBounds.MaxPendingAmount
3✔
459

3✔
460
        return ch.LocalChanCfg.MinHTLC, maxAmt, nil
3✔
461
}
3✔
462

463
// makeFailureItem creates a lnrpc.FailedUpdate object.
464
func makeFailureItem(outPoint wire.OutPoint, updateFailure lnrpc.UpdateFailure,
UNCOV
465
        errStr string) *lnrpc.FailedUpdate {
×
UNCOV
466

×
UNCOV
467
        outpoint := lnrpc.MarshalOutPoint(&outPoint)
×
UNCOV
468

×
UNCOV
469
        return &lnrpc.FailedUpdate{
×
UNCOV
470
                Outpoint:    outpoint,
×
UNCOV
471
                Reason:      updateFailure,
×
UNCOV
472
                UpdateError: errStr,
×
UNCOV
473
        }
×
UNCOV
474
}
×
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