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

lightningnetwork / lnd / 15736109134

18 Jun 2025 02:46PM UTC coverage: 58.197% (-10.1%) from 68.248%
15736109134

Pull #9752

github

web-flow
Merge d2634a68c into 31c74f20f
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

28331 existing lines in 455 files now uncovered.

97860 of 168153 relevant lines covered (58.2%)

1.81 hits per line

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

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

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

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

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

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

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

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

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

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

50
        // AddEdge is used to add edge/channel to the topology of the router.
51
        AddEdge func(edge *models.ChannelEdgeInfo) error
52

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

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

3✔
67
        r.policyUpdateLock.Lock()
3✔
68
        defer r.policyUpdateLock.Unlock()
3✔
69

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

77
        haveChanFilter := len(unprocessedChans) != 0
3✔
78

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

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

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

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

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

×
103
                        failedUpdates = append(failedUpdates, makeFailureItem(
×
104
                                info.ChannelPoint,
×
105
                                lnrpc.UpdateFailure_UPDATE_FAILURE_NOT_FOUND,
×
106
                                "edge policy not found",
×
107
                        ))
×
108

×
109
                        return nil
×
110
                }
×
111

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

×
121
                        return nil
×
122
                }
×
123

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

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

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

3✔
146
                return nil
3✔
147
        }
148

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

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

168
                case err != nil:
×
169
                        failedUpdates = append(failedUpdates,
×
170
                                makeFailureItem(chanPoint,
×
171
                                        lnrpc.UpdateFailure_UPDATE_FAILURE_INTERNAL_ERR,
×
172
                                        err.Error(),
×
173
                                ))
×
174

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

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

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

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

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

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

231
        // Update active links.
232
        r.UpdateForwardingPolicies(policiesToUpdate)
3✔
233

3✔
234
        return failedUpdates, nil
3✔
235
}
236

237
func (r *Manager) createMissingEdge(channel *channeldb.OpenChannel,
238
        newSchema routing.ChannelPolicy) (*models.ChannelEdgeInfo,
UNCOV
239
        *models.ChannelEdgePolicy, *lnrpc.FailedUpdate) {
×
UNCOV
240

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

×
247
                return nil, nil, makeFailureItem(
×
248
                        channel.FundingOutpoint,
×
249
                        lnrpc.UpdateFailure_UPDATE_FAILURE_UNKNOWN,
×
250
                        "could not update policies",
×
251
                )
×
252
        }
×
253

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

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

×
273
                return nil, nil, makeFailureItem(
×
274
                        channel.FundingOutpoint,
×
275
                        lnrpc.UpdateFailure_UPDATE_FAILURE_UNKNOWN,
×
276
                        "could not add edge",
×
277
                )
×
278
        }
×
279

UNCOV
280
        return info, edge, nil
×
281
}
282

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

×
UNCOV
288
        nodeKey1Bytes := r.SelfPub.SerializeCompressed()
×
UNCOV
289
        nodeKey2Bytes := channel.IdentityPub.SerializeCompressed()
×
UNCOV
290
        bitcoinKey1Bytes := channel.LocalChanCfg.MultiSigKey.PubKey.
×
UNCOV
291
                SerializeCompressed()
×
UNCOV
292
        bitcoinKey2Bytes := channel.RemoteChanCfg.MultiSigKey.PubKey.
×
UNCOV
293
                SerializeCompressed()
×
UNCOV
294
        channelFlags := lnwire.ChanUpdateChanFlags(0)
×
UNCOV
295

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

UNCOV
305
        var featureBuf bytes.Buffer
×
UNCOV
306
        err := lnwire.NewRawFeatureVector().Encode(&featureBuf)
×
UNCOV
307
        if err != nil {
×
308
                return nil, nil, fmt.Errorf("unable to encode features: %w",
×
309
                        err)
×
310
        }
×
311

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

UNCOV
320
        info := &models.ChannelEdgeInfo{
×
UNCOV
321
                ChannelID:    shortChanID.ToUint64(),
×
UNCOV
322
                ChainHash:    channel.ChainHash,
×
UNCOV
323
                Features:     featureBuf.Bytes(),
×
UNCOV
324
                Capacity:     channel.Capacity,
×
UNCOV
325
                ChannelPoint: channel.FundingOutpoint,
×
UNCOV
326
        }
×
UNCOV
327

×
UNCOV
328
        copy(info.NodeKey1Bytes[:], nodeKey1Bytes)
×
UNCOV
329
        copy(info.NodeKey2Bytes[:], nodeKey2Bytes)
×
UNCOV
330
        copy(info.BitcoinKey1Bytes[:], bitcoinKey1Bytes)
×
UNCOV
331
        copy(info.BitcoinKey2Bytes[:], bitcoinKey2Bytes)
×
UNCOV
332

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

×
UNCOV
348
        copy(edge.ToNode[:], channel.IdentityPub.SerializeCompressed())
×
UNCOV
349

×
UNCOV
350
        return info, edge, nil
×
351
}
352

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

3✔
358
        channel, err := r.FetchChannel(chanPoint)
3✔
359
        if err != nil {
3✔
360
                return err
×
361
        }
×
362

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

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

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

383
        edge.TimeLockDelta = uint16(newSchema.TimeLockDelta)
3✔
384

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

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

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

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

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

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

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

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

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

439
        // Clear signature to help prevent usage of the previous signature.
440
        edge.SetSigBytes(nil)
3✔
441

3✔
442
        return nil
3✔
443
}
444

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

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

3✔
456
        return ch.LocalChanCfg.MinHTLC, maxAmt, nil
3✔
457
}
3✔
458

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

×
UNCOV
463
        outpoint := lnrpc.MarshalOutPoint(&outPoint)
×
UNCOV
464

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