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

lightningnetwork / lnd / 14350633513

09 Apr 2025 06:37AM UTC coverage: 58.642%. First build
14350633513

Pull #9690

github

web-flow
Merge 9f7b6f71c into ac052988c
Pull Request #9690: autopilot: thread contexts through in preparation for GraphSource methods taking a context

1 of 83 new or added lines in 13 files covered. (1.2%)

97190 of 165734 relevant lines covered (58.64%)

1.82 hits per line

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

0.0
/autopilot/agent.go
1
package autopilot
2

3
import (
4
        "bytes"
5
        "context"
6
        "fmt"
7
        "math/rand"
8
        "net"
9
        "sync"
10
        "time"
11

12
        "github.com/btcsuite/btcd/btcec/v2"
13
        "github.com/btcsuite/btcd/btcutil"
14
        "github.com/davecgh/go-spew/spew"
15
        "github.com/lightningnetwork/lnd/fn/v2"
16
        "github.com/lightningnetwork/lnd/lnwire"
17
)
18

19
// Config couples all the items that an autopilot agent needs to function.
20
// All items within the struct MUST be populated for the Agent to be able to
21
// carry out its duties.
22
type Config struct {
23
        // Self is the identity public key of the Lightning Network node that
24
        // is being driven by the agent. This is used to ensure that we don't
25
        // accidentally attempt to open a channel with ourselves.
26
        Self *btcec.PublicKey
27

28
        // Heuristic is an attachment heuristic which will govern to whom we
29
        // open channels to, and also what those channels look like in terms of
30
        // desired capacity. The Heuristic will take into account the current
31
        // state of the graph, our set of open channels, and the amount of
32
        // available funds when determining how channels are to be opened.
33
        // Additionally, a heuristic make also factor in extra-graph
34
        // information in order to make more pertinent recommendations.
35
        Heuristic AttachmentHeuristic
36

37
        // ChanController is an interface that is able to directly manage the
38
        // creation, closing and update of channels within the network.
39
        ChanController ChannelController
40

41
        // ConnectToPeer attempts to connect to the peer using one of its
42
        // advertised addresses. The boolean returned signals whether the peer
43
        // was already connected.
44
        ConnectToPeer func(*btcec.PublicKey, []net.Addr) (bool, error)
45

46
        // DisconnectPeer attempts to disconnect the peer with the given public
47
        // key.
48
        DisconnectPeer func(*btcec.PublicKey) error
49

50
        // WalletBalance is a function closure that should return the current
51
        // available balance of the backing wallet.
52
        WalletBalance func() (btcutil.Amount, error)
53

54
        // Graph is an abstract channel graph that the Heuristic and the Agent
55
        // will use to make decisions w.r.t channel allocation and placement
56
        // within the graph.
57
        Graph ChannelGraph
58

59
        // Constraints is the set of constraints the autopilot must adhere to
60
        // when opening channels.
61
        Constraints AgentConstraints
62

63
        // TODO(roasbeef): add additional signals from fee rates and revenue of
64
        // currently opened channels
65
}
66

67
// channelState is a type that represents the set of active channels of the
68
// backing LN node that the Agent should be aware of. This type contains a few
69
// helper utility methods.
70
type channelState map[lnwire.ShortChannelID]LocalChannel
71

72
// Channels returns a slice of all the active channels.
73
func (c channelState) Channels() []LocalChannel {
×
74
        chans := make([]LocalChannel, 0, len(c))
×
75
        for _, channel := range c {
×
76
                chans = append(chans, channel)
×
77
        }
×
78
        return chans
×
79
}
80

81
// ConnectedNodes returns the set of nodes we currently have a channel with.
82
// This information is needed as we want to avoid making repeated channels with
83
// any node.
84
func (c channelState) ConnectedNodes() map[NodeID]struct{} {
×
85
        nodes := make(map[NodeID]struct{})
×
86
        for _, channels := range c {
×
87
                nodes[channels.Node] = struct{}{}
×
88
        }
×
89

90
        // TODO(roasbeef): add outgoing, nodes, allow incoming and outgoing to
91
        // per node
92
        //  * only add node is chan as funding amt set
93

94
        return nodes
×
95
}
96

97
// Agent implements a closed-loop control system which seeks to autonomously
98
// optimize the allocation of satoshis within channels throughput the network's
99
// channel graph. An agent is configurable by swapping out different
100
// AttachmentHeuristic strategies. The agent uses external signals such as the
101
// wallet balance changing, or new channels being opened/closed for the local
102
// node as an indicator to re-examine its internal state, and the amount of
103
// available funds in order to make updated decisions w.r.t the channel graph.
104
// The Agent will automatically open, close, and splice in/out channel as
105
// necessary for it to step closer to its optimal state.
106
//
107
// TODO(roasbeef): prob re-word
108
type Agent struct {
109
        started sync.Once
110
        stopped sync.Once
111

112
        // cfg houses the configuration state of the Ant.
113
        cfg Config
114

115
        // chanState tracks the current set of open channels.
116
        chanState    channelState
117
        chanStateMtx sync.Mutex
118

119
        // stateUpdates is a channel that any external state updates that may
120
        // affect the heuristics of the agent will be sent over.
121
        stateUpdates chan interface{}
122

123
        // balanceUpdates is a channel where notifications about updates to the
124
        // wallet's balance will be sent. This channel will be buffered to
125
        // ensure we have at most one pending update of this type to handle at
126
        // a given time.
127
        balanceUpdates chan *balanceUpdate
128

129
        // nodeUpdates is a channel that changes to the graph node landscape
130
        // will be sent over. This channel will be buffered to ensure we have
131
        // at most one pending update of this type to handle at a given time.
132
        nodeUpdates chan *nodeUpdates
133

134
        // pendingOpenUpdates is a channel where updates about channel pending
135
        // opening will be sent. This channel will be buffered to ensure we
136
        // have at most one pending update of this type to handle at a given
137
        // time.
138
        pendingOpenUpdates chan *chanPendingOpenUpdate
139

140
        // chanOpenFailures is a channel where updates about channel open
141
        // failures will be sent. This channel will be buffered to ensure we
142
        // have at most one pending update of this type to handle at a given
143
        // time.
144
        chanOpenFailures chan *chanOpenFailureUpdate
145

146
        // heuristicUpdates is a channel where updates from active heuristics
147
        // will be sent.
148
        heuristicUpdates chan *heuristicUpdate
149

150
        // totalBalance is the total number of satoshis the backing wallet is
151
        // known to control at any given instance. This value will be updated
152
        // when the agent receives external balance update signals.
153
        totalBalance btcutil.Amount
154

155
        // failedNodes lists nodes that we've previously attempted to initiate
156
        // channels with, but didn't succeed.
157
        failedNodes map[NodeID]struct{}
158

159
        // pendingConns tracks the nodes that we are attempting to make
160
        // connections to. This prevents us from making duplicate connection
161
        // requests to the same node.
162
        pendingConns map[NodeID]struct{}
163

164
        // pendingOpens tracks the channels that we've requested to be
165
        // initiated, but haven't yet been confirmed as being fully opened.
166
        // This state is required as otherwise, we may go over our allotted
167
        // channel limit, or open multiple channels to the same node.
168
        pendingOpens map[NodeID]LocalChannel
169
        pendingMtx   sync.Mutex
170

171
        quit   chan struct{}
172
        wg     sync.WaitGroup
173
        cancel fn.Option[context.CancelFunc]
174
}
175

176
// New creates a new instance of the Agent instantiated using the passed
177
// configuration and initial channel state. The initial channel state slice
178
// should be populated with the set of Channels that are currently opened by
179
// the backing Lightning Node.
180
func New(cfg Config, initialState []LocalChannel) (*Agent, error) {
×
181
        a := &Agent{
×
182
                cfg:                cfg,
×
183
                chanState:          make(map[lnwire.ShortChannelID]LocalChannel),
×
184
                quit:               make(chan struct{}),
×
185
                stateUpdates:       make(chan interface{}),
×
186
                balanceUpdates:     make(chan *balanceUpdate, 1),
×
187
                nodeUpdates:        make(chan *nodeUpdates, 1),
×
188
                chanOpenFailures:   make(chan *chanOpenFailureUpdate, 1),
×
189
                heuristicUpdates:   make(chan *heuristicUpdate, 1),
×
190
                pendingOpenUpdates: make(chan *chanPendingOpenUpdate, 1),
×
191
                failedNodes:        make(map[NodeID]struct{}),
×
192
                pendingConns:       make(map[NodeID]struct{}),
×
193
                pendingOpens:       make(map[NodeID]LocalChannel),
×
194
        }
×
195

×
196
        for _, c := range initialState {
×
197
                a.chanState[c.ChanID] = c
×
198
        }
×
199

200
        return a, nil
×
201
}
202

203
// Start starts the agent along with any goroutines it needs to perform its
204
// normal duties.
NEW
205
func (a *Agent) Start(ctx context.Context) error {
×
206
        var err error
×
207
        a.started.Do(func() {
×
NEW
208
                ctx, cancel := context.WithCancel(ctx)
×
NEW
209
                a.cancel = fn.Some(cancel)
×
NEW
210

×
NEW
211
                err = a.start(ctx)
×
212
        })
×
213
        return err
×
214
}
215

NEW
216
func (a *Agent) start(ctx context.Context) error {
×
217
        rand.Seed(time.Now().Unix())
×
218
        log.Infof("Autopilot Agent starting")
×
219

×
220
        a.wg.Add(1)
×
NEW
221
        go a.controller(ctx)
×
222

×
223
        return nil
×
224
}
×
225

226
// Stop signals the Agent to gracefully shutdown. This function will block
227
// until all goroutines have exited.
228
func (a *Agent) Stop() error {
×
229
        var err error
×
230
        a.stopped.Do(func() {
×
231
                err = a.stop()
×
232
        })
×
233
        return err
×
234
}
235

236
func (a *Agent) stop() error {
×
237
        log.Infof("Autopilot Agent stopping")
×
238

×
NEW
239
        a.cancel.WhenSome(func(fn context.CancelFunc) { fn() })
×
240
        close(a.quit)
×
241
        a.wg.Wait()
×
242

×
243
        return nil
×
244
}
245

246
// balanceUpdate is a type of external state update that reflects an
247
// increase/decrease in the funds currently available to the wallet.
248
type balanceUpdate struct {
249
}
250

251
// nodeUpdates is a type of external state update that reflects an addition or
252
// modification in channel graph node membership.
253
type nodeUpdates struct{}
254

255
// chanOpenUpdate is a type of external state update that indicates a new
256
// channel has been opened, either by the Agent itself (within the main
257
// controller loop), or by an external user to the system.
258
type chanOpenUpdate struct {
259
        newChan LocalChannel
260
}
261

262
// chanPendingOpenUpdate is a type of external state update that indicates a new
263
// channel has been opened, either by the agent itself or an external subsystem,
264
// but is still pending.
265
type chanPendingOpenUpdate struct{}
266

267
// chanOpenFailureUpdate is a type of external state update that indicates
268
// a previous channel open failed, and that it might be possible to try again.
269
type chanOpenFailureUpdate struct{}
270

271
// heuristicUpdate is an update sent when one of the autopilot heuristics has
272
// changed, and prompts the agent to make a new attempt at opening more
273
// channels.
274
type heuristicUpdate struct {
275
        heuristic AttachmentHeuristic
276
}
277

278
// chanCloseUpdate is a type of external state update that indicates that the
279
// backing Lightning Node has closed a previously open channel.
280
type chanCloseUpdate struct {
281
        closedChans []lnwire.ShortChannelID
282
}
283

284
// OnBalanceChange is a callback that should be executed each time the balance
285
// of the backing wallet changes.
286
func (a *Agent) OnBalanceChange() {
×
287
        select {
×
288
        case a.balanceUpdates <- &balanceUpdate{}:
×
289
        default:
×
290
        }
291
}
292

293
// OnNodeUpdates is a callback that should be executed each time our channel
294
// graph has new nodes or their node announcements are updated.
295
func (a *Agent) OnNodeUpdates() {
×
296
        select {
×
297
        case a.nodeUpdates <- &nodeUpdates{}:
×
298
        default:
×
299
        }
300
}
301

302
// OnChannelOpen is a callback that should be executed each time a new channel
303
// is manually opened by the user or any system outside the autopilot agent.
304
func (a *Agent) OnChannelOpen(c LocalChannel) {
×
305
        a.wg.Add(1)
×
306
        go func() {
×
307
                defer a.wg.Done()
×
308

×
309
                select {
×
310
                case a.stateUpdates <- &chanOpenUpdate{newChan: c}:
×
311
                case <-a.quit:
×
312
                }
313
        }()
314
}
315

316
// OnChannelPendingOpen is a callback that should be executed each time a new
317
// channel is opened, either by the agent or an external subsystems, but is
318
// still pending.
319
func (a *Agent) OnChannelPendingOpen() {
×
320
        select {
×
321
        case a.pendingOpenUpdates <- &chanPendingOpenUpdate{}:
×
322
        default:
×
323
        }
324
}
325

326
// OnChannelOpenFailure is a callback that should be executed when the
327
// autopilot has attempted to open a channel, but failed. In this case we can
328
// retry channel creation with a different node.
329
func (a *Agent) OnChannelOpenFailure() {
×
330
        select {
×
331
        case a.chanOpenFailures <- &chanOpenFailureUpdate{}:
×
332
        default:
×
333
        }
334
}
335

336
// OnChannelClose is a callback that should be executed each time a prior
337
// channel has been closed for any reason. This includes regular
338
// closes, force closes, and channel breaches.
339
func (a *Agent) OnChannelClose(closedChans ...lnwire.ShortChannelID) {
×
340
        a.wg.Add(1)
×
341
        go func() {
×
342
                defer a.wg.Done()
×
343

×
344
                select {
×
345
                case a.stateUpdates <- &chanCloseUpdate{closedChans: closedChans}:
×
346
                case <-a.quit:
×
347
                }
348
        }()
349
}
350

351
// OnHeuristicUpdate is a method called when a heuristic has been updated, to
352
// trigger the agent to do a new state assessment.
353
func (a *Agent) OnHeuristicUpdate(h AttachmentHeuristic) {
×
354
        select {
×
355
        case a.heuristicUpdates <- &heuristicUpdate{
356
                heuristic: h,
357
        }:
×
358
        default:
×
359
        }
360
}
361

362
// mergeNodeMaps merges the Agent's set of nodes that it already has active
363
// channels open to, with the other sets of nodes that should be removed from
364
// consideration during heuristic selection. This ensures that the Agent doesn't
365
// attempt to open any "duplicate" channels to the same node.
366
func mergeNodeMaps(c map[NodeID]LocalChannel,
367
        skips ...map[NodeID]struct{}) map[NodeID]struct{} {
×
368

×
369
        numNodes := len(c)
×
370
        for _, skip := range skips {
×
371
                numNodes += len(skip)
×
372
        }
×
373

374
        res := make(map[NodeID]struct{}, numNodes)
×
375
        for nodeID := range c {
×
376
                res[nodeID] = struct{}{}
×
377
        }
×
378
        for _, skip := range skips {
×
379
                for nodeID := range skip {
×
380
                        res[nodeID] = struct{}{}
×
381
                }
×
382
        }
383

384
        return res
×
385
}
386

387
// mergeChanState merges the Agent's set of active channels, with the set of
388
// channels awaiting confirmation. This ensures that the agent doesn't go over
389
// the prescribed channel limit or fund allocation limit.
390
func mergeChanState(pendingChans map[NodeID]LocalChannel,
391
        activeChans channelState) []LocalChannel {
×
392

×
393
        numChans := len(pendingChans) + len(activeChans)
×
394
        totalChans := make([]LocalChannel, 0, numChans)
×
395

×
396
        totalChans = append(totalChans, activeChans.Channels()...)
×
397

×
398
        for _, pendingChan := range pendingChans {
×
399
                totalChans = append(totalChans, pendingChan)
×
400
        }
×
401

402
        return totalChans
×
403
}
404

405
// controller implements the closed-loop control system of the Agent. The
406
// controller will make a decision w.r.t channel placement within the graph
407
// based on: its current internal state of the set of active channels open,
408
// and external state changes as a result of decisions it makes w.r.t channel
409
// allocation, or attributes affecting its control loop being updated by the
410
// backing Lightning Node.
NEW
411
func (a *Agent) controller(ctx context.Context) {
×
412
        defer a.wg.Done()
×
413

×
414
        // We'll start off by assigning our starting balance, and injecting
×
415
        // that amount as an initial wake up to the main controller goroutine.
×
416
        a.OnBalanceChange()
×
417

×
418
        // TODO(roasbeef): do we in fact need to maintain order?
×
419
        //  * use sync.Cond if so
×
420
        updateBalance := func() {
×
421
                newBalance, err := a.cfg.WalletBalance()
×
422
                if err != nil {
×
423
                        log.Warnf("unable to update wallet balance: %v", err)
×
424
                        return
×
425
                }
×
426

427
                a.totalBalance = newBalance
×
428
        }
429

430
        // TODO(roasbeef): add 10-minute wake up timer
431
        for {
×
432
                select {
×
433
                // A new external signal has arrived. We'll use this to update
434
                // our internal state, then determine if we should trigger a
435
                // channel state modification (open/close, splice in/out).
436
                case signal := <-a.stateUpdates:
×
437
                        log.Infof("Processing new external signal")
×
438

×
439
                        switch update := signal.(type) {
×
440
                        // A new channel has been opened successfully. This was
441
                        // either opened by the Agent, or an external system
442
                        // that is able to drive the Lightning Node.
443
                        case *chanOpenUpdate:
×
444
                                log.Debugf("New channel successfully opened, "+
×
445
                                        "updating state with: %v",
×
446
                                        spew.Sdump(update.newChan))
×
447

×
448
                                newChan := update.newChan
×
449
                                a.chanStateMtx.Lock()
×
450
                                a.chanState[newChan.ChanID] = newChan
×
451
                                a.chanStateMtx.Unlock()
×
452

×
453
                                a.pendingMtx.Lock()
×
454
                                delete(a.pendingOpens, newChan.Node)
×
455
                                a.pendingMtx.Unlock()
×
456

×
457
                                updateBalance()
×
458
                        // A channel has been closed, this may free up an
459
                        // available slot, triggering a new channel update.
460
                        case *chanCloseUpdate:
×
461
                                log.Debugf("Applying closed channel "+
×
462
                                        "updates: %v",
×
463
                                        spew.Sdump(update.closedChans))
×
464

×
465
                                a.chanStateMtx.Lock()
×
466
                                for _, closedChan := range update.closedChans {
×
467
                                        delete(a.chanState, closedChan)
×
468
                                }
×
469
                                a.chanStateMtx.Unlock()
×
470

×
471
                                updateBalance()
×
472
                        }
473

474
                // A new channel has been opened by the agent or an external
475
                // subsystem, but is still pending confirmation.
476
                case <-a.pendingOpenUpdates:
×
477
                        updateBalance()
×
478

479
                // The balance of the backing wallet has changed, if more funds
480
                // are now available, we may attempt to open up an additional
481
                // channel, or splice in funds to an existing one.
482
                case <-a.balanceUpdates:
×
483
                        log.Debug("Applying external balance state update")
×
484

×
485
                        updateBalance()
×
486

487
                // The channel we tried to open previously failed for whatever
488
                // reason.
489
                case <-a.chanOpenFailures:
×
490
                        log.Debug("Retrying after previous channel open " +
×
491
                                "failure.")
×
492

×
493
                        updateBalance()
×
494

495
                // New nodes have been added to the graph or their node
496
                // announcements have been updated. We will consider opening
497
                // channels to these nodes if we haven't stabilized.
498
                case <-a.nodeUpdates:
×
499
                        log.Debugf("Node updates received, assessing " +
×
500
                                "need for more channels")
×
501

502
                // Any of the deployed heuristics has been updated, check
503
                // whether we have new channel candidates available.
504
                case upd := <-a.heuristicUpdates:
×
505
                        log.Debugf("Heuristic %v updated, assessing need for "+
×
506
                                "more channels", upd.heuristic.Name())
×
507

508
                // The agent has been signalled to exit, so we'll bail out
509
                // immediately.
510
                case <-a.quit:
×
511
                        return
×
512
                }
513

514
                a.pendingMtx.Lock()
×
515
                log.Debugf("Pending channels: %v", spew.Sdump(a.pendingOpens))
×
516
                a.pendingMtx.Unlock()
×
517

×
518
                // With all the updates applied, we'll obtain a set of the
×
519
                // current active channels (confirmed channels), and also
×
520
                // factor in our set of unconfirmed channels.
×
521
                a.chanStateMtx.Lock()
×
522
                a.pendingMtx.Lock()
×
523
                totalChans := mergeChanState(a.pendingOpens, a.chanState)
×
524
                a.pendingMtx.Unlock()
×
525
                a.chanStateMtx.Unlock()
×
526

×
527
                // Now that we've updated our internal state, we'll consult our
×
528
                // channel attachment heuristic to determine if we can open
×
529
                // up any additional channels while staying within our
×
530
                // constraints.
×
531
                availableFunds, numChans := a.cfg.Constraints.ChannelBudget(
×
532
                        totalChans, a.totalBalance,
×
533
                )
×
534
                switch {
×
535
                case numChans == 0:
×
536
                        continue
×
537

538
                // If the amount is too small, we don't want to attempt opening
539
                // another channel.
540
                case availableFunds == 0:
×
541
                        continue
×
542
                case availableFunds < a.cfg.Constraints.MinChanSize():
×
543
                        continue
×
544
                }
545

546
                log.Infof("Triggering attachment directive dispatch, "+
×
547
                        "total_funds=%v", a.totalBalance)
×
548

×
NEW
549
                err := a.openChans(ctx, availableFunds, numChans, totalChans)
×
550
                if err != nil {
×
551
                        log.Errorf("Unable to open channels: %v", err)
×
552
                }
×
553
        }
554
}
555

556
// openChans queries the agent's heuristic for a set of channel candidates, and
557
// attempts to open channels to them.
558
func (a *Agent) openChans(ctx context.Context, availableFunds btcutil.Amount,
NEW
559
        numChans uint32, totalChans []LocalChannel) error {
×
560

×
561
        // As channel size we'll use the maximum channel size available.
×
562
        chanSize := a.cfg.Constraints.MaxChanSize()
×
563
        if availableFunds < chanSize {
×
564
                chanSize = availableFunds
×
565
        }
×
566

567
        if chanSize < a.cfg.Constraints.MinChanSize() {
×
568
                return fmt.Errorf("not enough funds available to open a " +
×
569
                        "single channel")
×
570
        }
×
571

572
        // We're to attempt an attachment so we'll obtain the set of
573
        // nodes that we currently have channels with so we avoid
574
        // duplicate edges.
575
        a.chanStateMtx.Lock()
×
576
        connectedNodes := a.chanState.ConnectedNodes()
×
577
        a.chanStateMtx.Unlock()
×
578

×
579
        for nID := range connectedNodes {
×
580
                log.Tracef("Skipping node %x with open channel", nID[:])
×
581
        }
×
582

583
        a.pendingMtx.Lock()
×
584

×
585
        for nID := range a.pendingOpens {
×
586
                log.Tracef("Skipping node %x with pending channel open", nID[:])
×
587
        }
×
588

589
        for nID := range a.pendingConns {
×
590
                log.Tracef("Skipping node %x with pending connection", nID[:])
×
591
        }
×
592

593
        for nID := range a.failedNodes {
×
594
                log.Tracef("Skipping failed node %v", nID[:])
×
595
        }
×
596

597
        nodesToSkip := mergeNodeMaps(a.pendingOpens,
×
598
                a.pendingConns, connectedNodes, a.failedNodes,
×
599
        )
×
600

×
601
        a.pendingMtx.Unlock()
×
602

×
603
        // Gather the set of all nodes in the graph, except those we
×
604
        // want to skip.
×
605
        selfPubBytes := a.cfg.Self.SerializeCompressed()
×
606
        nodes := make(map[NodeID]struct{})
×
607
        addresses := make(map[NodeID][]net.Addr)
×
NEW
608
        if err := a.cfg.Graph.ForEachNode(ctx, func(_ context.Context,
×
NEW
609
                node Node) error {
×
NEW
610

×
611
                nID := NodeID(node.PubKey())
×
612

×
613
                // If we come across ourselves, them we'll continue in
×
614
                // order to avoid attempting to make a channel with
×
615
                // ourselves.
×
616
                if bytes.Equal(nID[:], selfPubBytes) {
×
617
                        log.Tracef("Skipping self node %x", nID[:])
×
618
                        return nil
×
619
                }
×
620

621
                // If the node has no known addresses, we cannot connect to it,
622
                // so we'll skip it.
623
                addrs := node.Addrs()
×
624
                if len(addrs) == 0 {
×
625
                        log.Tracef("Skipping node %x since no addresses known",
×
626
                                nID[:])
×
627
                        return nil
×
628
                }
×
629
                addresses[nID] = addrs
×
630

×
631
                // Additionally, if this node is in the blacklist, then
×
632
                // we'll skip it.
×
633
                if _, ok := nodesToSkip[nID]; ok {
×
634
                        log.Tracef("Skipping blacklisted node %x", nID[:])
×
635
                        return nil
×
636
                }
×
637

638
                nodes[nID] = struct{}{}
×
639
                return nil
×
640
        }); err != nil {
×
641
                return fmt.Errorf("unable to get graph nodes: %w", err)
×
642
        }
×
643

644
        // Use the heuristic to calculate a score for each node in the
645
        // graph.
646
        log.Debugf("Scoring %d nodes for chan_size=%v", len(nodes), chanSize)
×
647
        scores, err := a.cfg.Heuristic.NodeScores(
×
NEW
648
                ctx, a.cfg.Graph, totalChans, chanSize, nodes,
×
649
        )
×
650
        if err != nil {
×
651
                return fmt.Errorf("unable to calculate node scores : %w", err)
×
652
        }
×
653

654
        log.Debugf("Got scores for %d nodes", len(scores))
×
655

×
656
        // Now use the score to make a weighted choice which nodes to attempt
×
657
        // to open channels to.
×
658
        scores, err = chooseN(numChans, scores)
×
659
        if err != nil {
×
660
                return fmt.Errorf("unable to make weighted choice: %w",
×
661
                        err)
×
662
        }
×
663

664
        chanCandidates := make(map[NodeID]*AttachmentDirective)
×
665
        for nID := range scores {
×
666
                log.Tracef("Creating attachment directive for chosen node %x",
×
667
                        nID[:])
×
668

×
669
                // Track the available funds we have left.
×
670
                if availableFunds < chanSize {
×
671
                        chanSize = availableFunds
×
672
                }
×
673
                availableFunds -= chanSize
×
674

×
675
                // If we run out of funds, we can break early.
×
676
                if chanSize < a.cfg.Constraints.MinChanSize() {
×
677
                        log.Tracef("Chan size %v too small to satisfy min "+
×
678
                                "channel size %v, breaking", chanSize,
×
679
                                a.cfg.Constraints.MinChanSize())
×
680
                        break
×
681
                }
682

683
                chanCandidates[nID] = &AttachmentDirective{
×
684
                        NodeID:  nID,
×
685
                        ChanAmt: chanSize,
×
686
                        Addrs:   addresses[nID],
×
687
                }
×
688
        }
689

690
        if len(chanCandidates) == 0 {
×
691
                log.Infof("No eligible candidates to connect to")
×
692
                return nil
×
693
        }
×
694

695
        log.Infof("Attempting to execute channel attachment "+
×
696
                "directives: %v", spew.Sdump(chanCandidates))
×
697

×
698
        // Before proceeding, check to see if we have any slots
×
699
        // available to open channels. If there are any, we will attempt
×
700
        // to dispatch the retrieved directives since we can't be
×
701
        // certain which ones may actually succeed. If too many
×
702
        // connections succeed, they will be ignored and made
×
703
        // available to future heuristic selections.
×
704
        a.pendingMtx.Lock()
×
705
        defer a.pendingMtx.Unlock()
×
706
        if uint16(len(a.pendingOpens)) >= a.cfg.Constraints.MaxPendingOpens() {
×
707
                log.Debugf("Reached cap of %v pending "+
×
708
                        "channel opens, will retry "+
×
709
                        "after success/failure",
×
710
                        a.cfg.Constraints.MaxPendingOpens())
×
711
                return nil
×
712
        }
×
713

714
        // For each recommended attachment directive, we'll launch a
715
        // new goroutine to attempt to carry out the directive. If any
716
        // of these succeed, then we'll receive a new state update,
717
        // taking us back to the top of our controller loop.
718
        for _, chanCandidate := range chanCandidates {
×
719
                // Skip candidates which we are already trying
×
720
                // to establish a connection with.
×
721
                nodeID := chanCandidate.NodeID
×
722
                if _, ok := a.pendingConns[nodeID]; ok {
×
723
                        continue
×
724
                }
725
                a.pendingConns[nodeID] = struct{}{}
×
726

×
727
                a.wg.Add(1)
×
728
                go a.executeDirective(*chanCandidate)
×
729
        }
730
        return nil
×
731
}
732

733
// executeDirective attempts to connect to the channel candidate specified by
734
// the given attachment directive, and open a channel of the given size.
735
//
736
// NOTE: MUST be run as a goroutine.
737
func (a *Agent) executeDirective(directive AttachmentDirective) {
×
738
        defer a.wg.Done()
×
739

×
740
        // We'll start out by attempting to connect to the peer in order to
×
741
        // begin the funding workflow.
×
742
        nodeID := directive.NodeID
×
743
        pub, err := btcec.ParsePubKey(nodeID[:])
×
744
        if err != nil {
×
745
                log.Errorf("Unable to parse pubkey %x: %v", nodeID, err)
×
746
                return
×
747
        }
×
748

749
        connected := make(chan bool)
×
750
        errChan := make(chan error)
×
751

×
752
        // To ensure a call to ConnectToPeer doesn't block the agent from
×
753
        // shutting down, we'll launch it in a non-waitgrouped goroutine, that
×
754
        // will signal when a result is returned.
×
755
        // TODO(halseth): use DialContext to cancel on transport level.
×
756
        go func() {
×
757
                alreadyConnected, err := a.cfg.ConnectToPeer(
×
758
                        pub, directive.Addrs,
×
759
                )
×
760
                if err != nil {
×
761
                        select {
×
762
                        case errChan <- err:
×
763
                        case <-a.quit:
×
764
                        }
765
                        return
×
766
                }
767

768
                select {
×
769
                case connected <- alreadyConnected:
×
770
                case <-a.quit:
×
771
                        return
×
772
                }
773
        }()
774

775
        var alreadyConnected bool
×
776
        select {
×
777
        case alreadyConnected = <-connected:
×
778
        case err = <-errChan:
×
779
        case <-a.quit:
×
780
                return
×
781
        }
782

783
        if err != nil {
×
784
                log.Warnf("Unable to connect to %x: %v",
×
785
                        pub.SerializeCompressed(), err)
×
786

×
787
                // Since we failed to connect to them, we'll mark them as
×
788
                // failed so that we don't attempt to connect to them again.
×
789
                a.pendingMtx.Lock()
×
790
                delete(a.pendingConns, nodeID)
×
791
                a.failedNodes[nodeID] = struct{}{}
×
792
                a.pendingMtx.Unlock()
×
793

×
794
                // Finally, we'll trigger the agent to select new peers to
×
795
                // connect to.
×
796
                a.OnChannelOpenFailure()
×
797

×
798
                return
×
799
        }
×
800

801
        // The connection was successful, though before progressing we must
802
        // check that we have not already met our quota for max pending open
803
        // channels. This can happen if multiple directives were spawned but
804
        // fewer slots were available, and other successful attempts finished
805
        // first.
806
        a.pendingMtx.Lock()
×
807
        if uint16(len(a.pendingOpens)) >= a.cfg.Constraints.MaxPendingOpens() {
×
808
                // Since we've reached our max number of pending opens, we'll
×
809
                // disconnect this peer and exit. However, if we were
×
810
                // previously connected to them, then we'll make sure to
×
811
                // maintain the connection alive.
×
812
                if alreadyConnected {
×
813
                        // Since we succeeded in connecting, we won't add this
×
814
                        // peer to the failed nodes map, but we will remove it
×
815
                        // from a.pendingConns so that it can be retried in the
×
816
                        // future.
×
817
                        delete(a.pendingConns, nodeID)
×
818
                        a.pendingMtx.Unlock()
×
819
                        return
×
820
                }
×
821

822
                err = a.cfg.DisconnectPeer(pub)
×
823
                if err != nil {
×
824
                        log.Warnf("Unable to disconnect peer %x: %v",
×
825
                                pub.SerializeCompressed(), err)
×
826
                }
×
827

828
                // Now that we have disconnected, we can remove this node from
829
                // our pending conns map, permitting subsequent connection
830
                // attempts.
831
                delete(a.pendingConns, nodeID)
×
832
                a.pendingMtx.Unlock()
×
833
                return
×
834
        }
835

836
        // If we were successful, we'll track this peer in our set of pending
837
        // opens. We do this here to ensure we don't stall on selecting new
838
        // peers if the connection attempt happens to take too long.
839
        delete(a.pendingConns, nodeID)
×
840
        a.pendingOpens[nodeID] = LocalChannel{
×
841
                Balance: directive.ChanAmt,
×
842
                Node:    nodeID,
×
843
        }
×
844
        a.pendingMtx.Unlock()
×
845

×
846
        // We can then begin the funding workflow with this peer.
×
847
        err = a.cfg.ChanController.OpenChannel(pub, directive.ChanAmt)
×
848
        if err != nil {
×
849
                log.Warnf("Unable to open channel to %x of %v: %v",
×
850
                        pub.SerializeCompressed(), directive.ChanAmt, err)
×
851

×
852
                // As the attempt failed, we'll clear the peer from the set of
×
853
                // pending opens and mark them as failed so we don't attempt to
×
854
                // open a channel to them again.
×
855
                a.pendingMtx.Lock()
×
856
                delete(a.pendingOpens, nodeID)
×
857
                a.failedNodes[nodeID] = struct{}{}
×
858
                a.pendingMtx.Unlock()
×
859

×
860
                // Trigger the agent to re-evaluate everything and possibly
×
861
                // retry with a different node.
×
862
                a.OnChannelOpenFailure()
×
863

×
864
                // Finally, we should also disconnect the peer if we weren't
×
865
                // already connected to them beforehand by an external
×
866
                // subsystem.
×
867
                if alreadyConnected {
×
868
                        return
×
869
                }
×
870

871
                err = a.cfg.DisconnectPeer(pub)
×
872
                if err != nil {
×
873
                        log.Warnf("Unable to disconnect peer %x: %v",
×
874
                                pub.SerializeCompressed(), err)
×
875
                }
×
876
        }
877

878
        // Since the channel open was successful and is currently pending,
879
        // we'll trigger the autopilot agent to query for more peers.
880
        // TODO(halseth): this triggers a new loop before all the new channels
881
        // are added to the pending channels map. Should add before executing
882
        // directive in goroutine?
883
        a.OnChannelPendingOpen()
×
884
}
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