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

lightningnetwork / lnd / 15248061147

26 May 2025 06:45AM UTC coverage: 56.774% (-1.8%) from 58.596%
15248061147

Pull #9807

github

web-flow
Merge c65cf7ffd into dc946ae7e
Pull Request #9807: make: allow skipping the vendor and source packaging

107749 of 189787 relevant lines covered (56.77%)

22587.19 hits per line

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

55.1
/accessman.go
1
package lnd
2

3
import (
4
        "context"
5
        "fmt"
6
        "maps"
7
        "sync"
8

9
        "github.com/btcsuite/btcd/btcec/v2"
10
        "github.com/btcsuite/btclog/v2"
11
        "github.com/lightningnetwork/lnd/channeldb"
12
        "github.com/lightningnetwork/lnd/lnutils"
13
)
14

15
// accessMan is responsible for managing the server's access permissions.
16
type accessMan struct {
17
        cfg *accessManConfig
18

19
        // banScoreMtx is used for the server's ban tracking. If the server
20
        // mutex is also going to be locked, ensure that this is locked after
21
        // the server mutex.
22
        banScoreMtx sync.RWMutex
23

24
        // peerCounts is a mapping from remote public key to {bool, uint64}
25
        // where the bool indicates that we have an open/closed channel with
26
        // the peer and where the uint64 indicates the number of pending-open
27
        // channels we currently have with them. This mapping will be used to
28
        // determine access permissions for the peer. The map key is the
29
        // string-version of the serialized public key.
30
        //
31
        // NOTE: This MUST be accessed with the banScoreMtx held.
32
        peerCounts map[string]channeldb.ChanCount
33

34
        // peerScores stores each connected peer's access status. The map key
35
        // is the string-version of the serialized public key.
36
        //
37
        // NOTE: This MUST be accessed with the banScoreMtx held.
38
        peerScores map[string]peerSlotStatus
39

40
        // numRestricted tracks the number of peers with restricted access in
41
        // peerScores. This MUST be accessed with the banScoreMtx held.
42
        numRestricted int64
43
}
44

45
type accessManConfig struct {
46
        // initAccessPerms checks the channeldb for initial access permissions
47
        // and then populates the peerCounts and peerScores maps.
48
        initAccessPerms func() (map[string]channeldb.ChanCount, error)
49

50
        // shouldDisconnect determines whether we should disconnect a peer or
51
        // not.
52
        shouldDisconnect func(*btcec.PublicKey) (bool, error)
53

54
        // maxRestrictedSlots is the number of restricted slots we'll allocate.
55
        maxRestrictedSlots int64
56
}
57

58
func newAccessMan(cfg *accessManConfig) (*accessMan, error) {
1✔
59
        a := &accessMan{
1✔
60
                cfg:        cfg,
1✔
61
                peerCounts: make(map[string]channeldb.ChanCount),
1✔
62
                peerScores: make(map[string]peerSlotStatus),
1✔
63
        }
1✔
64

1✔
65
        counts, err := a.cfg.initAccessPerms()
1✔
66
        if err != nil {
1✔
67
                return nil, err
×
68
        }
×
69

70
        // We'll populate the server's peerCounts map with the counts fetched
71
        // via initAccessPerms. Also note that we haven't yet connected to the
72
        // peers.
73
        maps.Copy(a.peerCounts, counts)
1✔
74

1✔
75
        acsmLog.Info("Access Manager initialized")
1✔
76

1✔
77
        return a, nil
1✔
78
}
79

80
// assignPeerPerms assigns a new peer its permissions. This does not track the
81
// access in the maps. This is intentional.
82
func (a *accessMan) assignPeerPerms(remotePub *btcec.PublicKey) (
83
        peerAccessStatus, error) {
5✔
84

5✔
85
        ctx := btclog.WithCtx(
5✔
86
                context.TODO(), lnutils.LogPubKey("peer", remotePub),
5✔
87
        )
5✔
88

5✔
89
        peerMapKey := string(remotePub.SerializeCompressed())
5✔
90

5✔
91
        acsmLog.DebugS(ctx, "Assigning permissions")
5✔
92

5✔
93
        // Default is restricted unless the below filters say otherwise.
5✔
94
        access := peerStatusRestricted
5✔
95

5✔
96
        shouldDisconnect, err := a.cfg.shouldDisconnect(remotePub)
5✔
97
        if err != nil {
5✔
98
                acsmLog.ErrorS(ctx, "Error checking disconnect status", err)
×
99

×
100
                // Access is restricted here.
×
101
                return access, err
×
102
        }
×
103

104
        if shouldDisconnect {
5✔
105
                acsmLog.WarnS(ctx, "Peer is banned, assigning restricted access",
×
106
                        ErrGossiperBan)
×
107

×
108
                // Access is restricted here.
×
109
                return access, ErrGossiperBan
×
110
        }
×
111

112
        // Lock banScoreMtx for reading so that we can update the banning maps
113
        // below.
114
        a.banScoreMtx.RLock()
5✔
115
        defer a.banScoreMtx.RUnlock()
5✔
116

5✔
117
        if count, found := a.peerCounts[peerMapKey]; found {
8✔
118
                if count.HasOpenOrClosedChan {
5✔
119
                        acsmLog.DebugS(ctx, "Peer has open/closed channel, "+
2✔
120
                                "assigning protected access")
2✔
121

2✔
122
                        access = peerStatusProtected
2✔
123
                } else if count.PendingOpenCount != 0 {
4✔
124
                        acsmLog.DebugS(ctx, "Peer has pending channel(s), "+
1✔
125
                                "assigning temporary access")
1✔
126

1✔
127
                        access = peerStatusTemporary
1✔
128
                }
1✔
129
        }
130

131
        // If we've reached this point and access hasn't changed from
132
        // restricted, then we need to check if we even have a slot for this
133
        // peer.
134
        if access == peerStatusRestricted {
7✔
135
                acsmLog.DebugS(ctx, "Peer has no channels, assigning "+
2✔
136
                        "restricted access")
2✔
137

2✔
138
                if a.numRestricted >= a.cfg.maxRestrictedSlots {
2✔
139
                        acsmLog.WarnS(ctx, "No more restricted slots "+
×
140
                                "available, denying peer",
×
141
                                ErrNoMoreRestrictedAccessSlots,
×
142
                                "num_restricted", a.numRestricted,
×
143
                                "max_restricted", a.cfg.maxRestrictedSlots)
×
144

×
145
                        return access, ErrNoMoreRestrictedAccessSlots
×
146
                }
×
147
        }
148

149
        return access, nil
5✔
150
}
151

152
// newPendingOpenChan is called after the pending-open channel has been
153
// committed to the database. This may transition a restricted-access peer to a
154
// temporary-access peer.
155
func (a *accessMan) newPendingOpenChan(remotePub *btcec.PublicKey) error {
1✔
156
        a.banScoreMtx.Lock()
1✔
157
        defer a.banScoreMtx.Unlock()
1✔
158

1✔
159
        ctx := btclog.WithCtx(
1✔
160
                context.TODO(), lnutils.LogPubKey("peer", remotePub),
1✔
161
        )
1✔
162

1✔
163
        acsmLog.DebugS(ctx, "Processing new pending open channel")
1✔
164

1✔
165
        peerMapKey := string(remotePub.SerializeCompressed())
1✔
166

1✔
167
        // Fetch the peer's access status from peerScores.
1✔
168
        status, found := a.peerScores[peerMapKey]
1✔
169
        if !found {
1✔
170
                acsmLog.ErrorS(ctx, "Peer score not found", ErrNoPeerScore)
×
171

×
172
                // If we didn't find the peer, we'll return an error.
×
173
                return ErrNoPeerScore
×
174
        }
×
175

176
        switch status.state {
1✔
177
        case peerStatusProtected:
×
178
                acsmLog.DebugS(ctx, "Peer already protected, no change")
×
179

×
180
                // If this peer's access status is protected, we don't need to
×
181
                // do anything.
×
182
                return nil
×
183

184
        case peerStatusTemporary:
×
185
                // If this peer's access status is temporary, we'll need to
×
186
                // update the peerCounts map. The peer's access status will stay
×
187
                // temporary.
×
188
                peerCount, found := a.peerCounts[peerMapKey]
×
189
                if !found {
×
190
                        // Error if we did not find any info in peerCounts.
×
191
                        acsmLog.ErrorS(ctx, "Pending peer info not found",
×
192
                                ErrNoPendingPeerInfo)
×
193

×
194
                        return ErrNoPendingPeerInfo
×
195
                }
×
196

197
                // Increment the pending channel amount.
198
                peerCount.PendingOpenCount += 1
×
199
                a.peerCounts[peerMapKey] = peerCount
×
200

×
201
                acsmLog.DebugS(ctx, "Peer is temporary, incremented "+
×
202
                        "pending count",
×
203
                        "pending_count", peerCount.PendingOpenCount)
×
204

205
        case peerStatusRestricted:
1✔
206
                // If the peer's access status is restricted, then we can
1✔
207
                // transition it to a temporary-access peer. We'll need to
1✔
208
                // update numRestricted and also peerScores. We'll also need to
1✔
209
                // update peerCounts.
1✔
210
                peerCount := channeldb.ChanCount{
1✔
211
                        HasOpenOrClosedChan: false,
1✔
212
                        PendingOpenCount:    1,
1✔
213
                }
1✔
214

1✔
215
                a.peerCounts[peerMapKey] = peerCount
1✔
216

1✔
217
                // A restricted-access slot has opened up.
1✔
218
                oldRestricted := a.numRestricted
1✔
219
                a.numRestricted -= 1
1✔
220

1✔
221
                a.peerScores[peerMapKey] = peerSlotStatus{
1✔
222
                        state: peerStatusTemporary,
1✔
223
                }
1✔
224

1✔
225
                acsmLog.InfoS(ctx, "Peer transitioned restricted -> "+
1✔
226
                        "temporary (pending open)",
1✔
227
                        "old_restricted", oldRestricted,
1✔
228
                        "new_restricted", a.numRestricted)
1✔
229

230
        default:
×
231
                // This should not be possible.
×
232
                err := fmt.Errorf("invalid peer access status %v for %x",
×
233
                        status.state, peerMapKey)
×
234
                acsmLog.ErrorS(ctx, "Invalid peer access status", err)
×
235

×
236
                return err
×
237
        }
238

239
        return nil
1✔
240
}
241

242
// newPendingCloseChan is called when a pending-open channel prematurely closes
243
// before the funding transaction has confirmed. This potentially demotes a
244
// temporary-access peer to a restricted-access peer. If no restricted-access
245
// slots are available, the peer will be disconnected.
246
func (a *accessMan) newPendingCloseChan(remotePub *btcec.PublicKey) error {
1✔
247
        a.banScoreMtx.Lock()
1✔
248
        defer a.banScoreMtx.Unlock()
1✔
249

1✔
250
        ctx := btclog.WithCtx(
1✔
251
                context.TODO(), lnutils.LogPubKey("peer", remotePub),
1✔
252
        )
1✔
253

1✔
254
        acsmLog.DebugS(ctx, "Processing pending channel close")
1✔
255

1✔
256
        peerMapKey := string(remotePub.SerializeCompressed())
1✔
257

1✔
258
        // Fetch the peer's access status from peerScores.
1✔
259
        status, found := a.peerScores[peerMapKey]
1✔
260
        if !found {
1✔
261
                acsmLog.ErrorS(ctx, "Peer score not found", ErrNoPeerScore)
×
262

×
263
                return ErrNoPeerScore
×
264
        }
×
265

266
        switch status.state {
1✔
267
        case peerStatusProtected:
×
268
                // If this peer is protected, we don't do anything.
×
269
                acsmLog.DebugS(ctx, "Peer is protected, no change")
×
270

×
271
                return nil
×
272

273
        case peerStatusTemporary:
1✔
274
                // If this peer is temporary, we need to check if it will
1✔
275
                // revert to a restricted-access peer.
1✔
276
                peerCount, found := a.peerCounts[peerMapKey]
1✔
277
                if !found {
1✔
278
                        acsmLog.ErrorS(ctx, "Pending peer info not found",
×
279
                                ErrNoPendingPeerInfo)
×
280

×
281
                        // Error if we did not find any info in peerCounts.
×
282
                        return ErrNoPendingPeerInfo
×
283
                }
×
284

285
                currentNumPending := peerCount.PendingOpenCount - 1
1✔
286

1✔
287
                acsmLog.DebugS(ctx, "Peer is temporary, decrementing "+
1✔
288
                        "pending count",
1✔
289
                        "pending_count", currentNumPending)
1✔
290

1✔
291
                if currentNumPending == 0 {
2✔
292
                        // Remove the entry from peerCounts.
1✔
293
                        delete(a.peerCounts, peerMapKey)
1✔
294

1✔
295
                        // If this is the only pending-open channel for this
1✔
296
                        // peer and it's getting removed, attempt to demote
1✔
297
                        // this peer to a restricted peer.
1✔
298
                        if a.numRestricted == a.cfg.maxRestrictedSlots {
2✔
299
                                // There are no available restricted slots, so
1✔
300
                                // we need to disconnect this peer. We leave
1✔
301
                                // this up to the caller.
1✔
302
                                acsmLog.WarnS(ctx, "Peer last pending "+
1✔
303
                                        "channel closed: ",
1✔
304
                                        ErrNoMoreRestrictedAccessSlots,
1✔
305
                                        "num_restricted", a.numRestricted,
1✔
306
                                        "max_restricted", a.cfg.maxRestrictedSlots)
1✔
307

1✔
308
                                return ErrNoMoreRestrictedAccessSlots
1✔
309
                        }
1✔
310

311
                        // Otherwise, there is an available restricted-access
312
                        // slot, so we can demote this peer.
313
                        a.peerScores[peerMapKey] = peerSlotStatus{
×
314
                                state: peerStatusRestricted,
×
315
                        }
×
316

×
317
                        // Update numRestricted.
×
318
                        oldRestricted := a.numRestricted
×
319
                        a.numRestricted++
×
320

×
321
                        acsmLog.InfoS(ctx, "Peer transitioned "+
×
322
                                "temporary -> restricted "+
×
323
                                "(last pending closed)",
×
324
                                "old_restricted", oldRestricted,
×
325
                                "new_restricted", a.numRestricted)
×
326

×
327
                        return nil
×
328
                }
329

330
                // Else, we don't need to demote this peer since it has other
331
                // pending-open channels with us.
332
                peerCount.PendingOpenCount = currentNumPending
×
333
                a.peerCounts[peerMapKey] = peerCount
×
334

×
335
                acsmLog.DebugS(ctx, "Peer still has other pending channels",
×
336
                        "pending_count", currentNumPending)
×
337

×
338
                return nil
×
339

340
        case peerStatusRestricted:
×
341
                // This should not be possible. This indicates an error.
×
342
                err := fmt.Errorf("invalid peer access state transition: "+
×
343
                        "pending close for restricted peer %x", peerMapKey)
×
344
                acsmLog.ErrorS(ctx, "Invalid peer access state transition", err)
×
345

×
346
                return err
×
347

348
        default:
×
349
                // This should not be possible.
×
350
                err := fmt.Errorf("invalid peer access status %v for %x",
×
351
                        status.state, peerMapKey)
×
352
                acsmLog.ErrorS(ctx, "Invalid peer access status", err)
×
353

×
354
                return err
×
355
        }
356
}
357

358
// newOpenChan is called when a pending-open channel becomes an open channel
359
// (i.e. the funding transaction has confirmed). If the remote peer is a
360
// temporary-access peer, it will be promoted to a protected-access peer.
361
func (a *accessMan) newOpenChan(remotePub *btcec.PublicKey) error {
1✔
362
        a.banScoreMtx.Lock()
1✔
363
        defer a.banScoreMtx.Unlock()
1✔
364

1✔
365
        ctx := btclog.WithCtx(
1✔
366
                context.TODO(), lnutils.LogPubKey("peer", remotePub),
1✔
367
        )
1✔
368

1✔
369
        acsmLog.DebugS(ctx, "Processing new open channel")
1✔
370

1✔
371
        peerMapKey := string(remotePub.SerializeCompressed())
1✔
372

1✔
373
        // Fetch the peer's access status from peerScores.
1✔
374
        status, found := a.peerScores[peerMapKey]
1✔
375
        if !found {
1✔
376
                // If we didn't find the peer, we'll return an error.
×
377
                acsmLog.ErrorS(ctx, "Peer score not found", ErrNoPeerScore)
×
378

×
379
                return ErrNoPeerScore
×
380
        }
×
381

382
        switch status.state {
1✔
383
        case peerStatusProtected:
×
384
                acsmLog.DebugS(ctx, "Peer already protected, no change")
×
385

×
386
                // If the peer's state is already protected, we don't need to do
×
387
                // anything more.
×
388
                return nil
×
389

390
        case peerStatusTemporary:
1✔
391
                // If the peer's state is temporary, we'll upgrade the peer to
1✔
392
                // a protected peer.
1✔
393
                peerCount, found := a.peerCounts[peerMapKey]
1✔
394
                if !found {
1✔
395
                        // Error if we did not find any info in peerCounts.
×
396
                        acsmLog.ErrorS(ctx, "Pending peer info not found",
×
397
                                ErrNoPendingPeerInfo)
×
398

×
399
                        return ErrNoPendingPeerInfo
×
400
                }
×
401

402
                peerCount.HasOpenOrClosedChan = true
1✔
403
                a.peerCounts[peerMapKey] = peerCount
1✔
404

1✔
405
                newStatus := peerSlotStatus{
1✔
406
                        state: peerStatusProtected,
1✔
407
                }
1✔
408
                a.peerScores[peerMapKey] = newStatus
1✔
409

1✔
410
                acsmLog.InfoS(ctx, "Peer transitioned temporary -> "+
1✔
411
                        "protected (channel opened)")
1✔
412

1✔
413
                return nil
1✔
414

415
        case peerStatusRestricted:
×
416
                // This should not be possible. For the server to receive a
×
417
                // state-transition event via NewOpenChan, the server must have
×
418
                // previously granted this peer "temporary" access. This
×
419
                // temporary access would not have been revoked or downgraded
×
420
                // without `CloseChannel` being called with the pending
×
421
                // argument set to true. This means that an open-channel state
×
422
                // transition would be impossible. Therefore, we can return an
×
423
                // error.
×
424
                err := fmt.Errorf("invalid peer access status: new open "+
×
425
                        "channel for restricted peer %x", peerMapKey)
×
426

×
427
                acsmLog.ErrorS(ctx, "Invalid peer access status", err)
×
428

×
429
                return err
×
430

431
        default:
×
432
                // This should not be possible.
×
433
                err := fmt.Errorf("invalid peer access status %v for %x",
×
434
                        status.state, peerMapKey)
×
435

×
436
                acsmLog.ErrorS(ctx, "Invalid peer access status", err)
×
437

×
438
                return err
×
439
        }
440
}
441

442
// checkIncomingConnBanScore checks whether, given the remote's public hex-
443
// encoded key, we should not accept this incoming connection or immediately
444
// disconnect. This does not assign to the server's peerScores maps. This is
445
// just an inbound filter that the brontide listeners use.
446
func (a *accessMan) checkIncomingConnBanScore(remotePub *btcec.PublicKey) (
447
        bool, error) {
5✔
448

5✔
449
        ctx := btclog.WithCtx(
5✔
450
                context.TODO(), lnutils.LogPubKey("peer", remotePub),
5✔
451
        )
5✔
452

5✔
453
        peerMapKey := string(remotePub.SerializeCompressed())
5✔
454

5✔
455
        acsmLog.TraceS(ctx, "Checking incoming connection ban score")
5✔
456

5✔
457
        a.banScoreMtx.RLock()
5✔
458
        defer a.banScoreMtx.RUnlock()
5✔
459

5✔
460
        if _, found := a.peerCounts[peerMapKey]; !found {
7✔
461
                acsmLog.DebugS(ctx, "Peer not found in counts, "+
2✔
462
                        "checking restricted slots")
2✔
463

2✔
464
                // Check numRestricted to see if there is an available slot. In
2✔
465
                // the future, it's possible to add better heuristics.
2✔
466
                if a.numRestricted < a.cfg.maxRestrictedSlots {
4✔
467
                        // There is an available slot.
2✔
468
                        acsmLog.DebugS(ctx, "Restricted slot available, "+
2✔
469
                                "accepting",
2✔
470
                                "num_restricted", a.numRestricted,
2✔
471
                                "max_restricted", a.cfg.maxRestrictedSlots)
2✔
472

2✔
473
                        return true, nil
2✔
474
                }
2✔
475

476
                // If there are no slots left, then we reject this connection.
477
                acsmLog.WarnS(ctx, "No restricted slots available, "+
×
478
                        "rejecting",
×
479
                        ErrNoMoreRestrictedAccessSlots,
×
480
                        "num_restricted", a.numRestricted,
×
481
                        "max_restricted", a.cfg.maxRestrictedSlots)
×
482

×
483
                return false, ErrNoMoreRestrictedAccessSlots
×
484
        }
485

486
        // Else, the peer is either protected or temporary.
487
        acsmLog.DebugS(ctx, "Peer found (protected/temporary), accepting")
3✔
488

3✔
489
        return true, nil
3✔
490
}
491

492
// addPeerAccess tracks a peer's access in the maps. This should be called when
493
// the peer has fully connected.
494
func (a *accessMan) addPeerAccess(remotePub *btcec.PublicKey,
495
        access peerAccessStatus) {
5✔
496

5✔
497
        ctx := btclog.WithCtx(
5✔
498
                context.TODO(), lnutils.LogPubKey("peer", remotePub),
5✔
499
        )
5✔
500

5✔
501
        acsmLog.DebugS(ctx, "Adding peer access", "access", access)
5✔
502

5✔
503
        // Add the remote public key to peerScores.
5✔
504
        a.banScoreMtx.Lock()
5✔
505
        defer a.banScoreMtx.Unlock()
5✔
506

5✔
507
        peerMapKey := string(remotePub.SerializeCompressed())
5✔
508

5✔
509
        a.peerScores[peerMapKey] = peerSlotStatus{state: access}
5✔
510

5✔
511
        // Increment numRestricted.
5✔
512
        if access == peerStatusRestricted {
7✔
513
                oldRestricted := a.numRestricted
2✔
514
                a.numRestricted++
2✔
515

2✔
516
                acsmLog.DebugS(ctx, "Incremented restricted slots",
2✔
517
                        "old_restricted", oldRestricted,
2✔
518
                        "new_restricted", a.numRestricted)
2✔
519
        }
2✔
520
}
521

522
// removePeerAccess removes the peer's access from the maps. This should be
523
// called when the peer has been disconnected.
524
func (a *accessMan) removePeerAccess(remotePub *btcec.PublicKey) {
×
525
        a.banScoreMtx.Lock()
×
526
        defer a.banScoreMtx.Unlock()
×
527

×
528
        ctx := btclog.WithCtx(
×
529
                context.TODO(), lnutils.LogPubKey("peer", remotePub),
×
530
        )
×
531

×
532
        acsmLog.DebugS(ctx, "Removing peer access")
×
533

×
534
        peerMapKey := string(remotePub.SerializeCompressed())
×
535

×
536
        status, found := a.peerScores[peerMapKey]
×
537
        if !found {
×
538
                acsmLog.InfoS(ctx, "Peer score not found during removal")
×
539
                return
×
540
        }
×
541

542
        if status.state == peerStatusRestricted {
×
543
                // If the status is restricted, then we decrement from
×
544
                // numRestrictedSlots.
×
545
                oldRestricted := a.numRestricted
×
546
                a.numRestricted--
×
547

×
548
                acsmLog.DebugS(ctx, "Decremented restricted slots",
×
549
                        "old_restricted", oldRestricted,
×
550
                        "new_restricted", a.numRestricted)
×
551
        }
×
552

553
        acsmLog.TraceS(ctx, "Deleting peer from peerScores")
×
554

×
555
        delete(a.peerScores, peerMapKey)
×
556
}
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