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

lightningnetwork / lnd / 11294395806

11 Oct 2024 02:38PM UTC coverage: 49.177% (-0.002%) from 49.179%
11294395806

Pull #9175

github

ellemouton
lnwire: update AnnounceSigs2 to use pure TLV
Pull Request #9175: lnwire+netann: update structure of g175 messages to be pure TLV

0 of 207 new or added lines in 7 files covered. (0.0%)

73 existing lines in 17 files now uncovered.

97421 of 198103 relevant lines covered (49.18%)

1.04 hits per line

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

63.58
/server.go
1
package lnd
2

3
import (
4
        "bytes"
5
        "context"
6
        "crypto/rand"
7
        "encoding/hex"
8
        "fmt"
9
        "math/big"
10
        prand "math/rand"
11
        "net"
12
        "strconv"
13
        "strings"
14
        "sync"
15
        "sync/atomic"
16
        "time"
17

18
        "github.com/btcsuite/btcd/btcec/v2"
19
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
20
        "github.com/btcsuite/btcd/btcutil"
21
        "github.com/btcsuite/btcd/chaincfg"
22
        "github.com/btcsuite/btcd/chaincfg/chainhash"
23
        "github.com/btcsuite/btcd/connmgr"
24
        "github.com/btcsuite/btcd/txscript"
25
        "github.com/btcsuite/btcd/wire"
26
        "github.com/go-errors/errors"
27
        sphinx "github.com/lightningnetwork/lightning-onion"
28
        "github.com/lightningnetwork/lnd/aliasmgr"
29
        "github.com/lightningnetwork/lnd/autopilot"
30
        "github.com/lightningnetwork/lnd/brontide"
31
        "github.com/lightningnetwork/lnd/chainreg"
32
        "github.com/lightningnetwork/lnd/chanacceptor"
33
        "github.com/lightningnetwork/lnd/chanbackup"
34
        "github.com/lightningnetwork/lnd/chanfitness"
35
        "github.com/lightningnetwork/lnd/channeldb"
36
        "github.com/lightningnetwork/lnd/channeldb/graphsession"
37
        "github.com/lightningnetwork/lnd/channeldb/models"
38
        "github.com/lightningnetwork/lnd/channelnotifier"
39
        "github.com/lightningnetwork/lnd/clock"
40
        "github.com/lightningnetwork/lnd/cluster"
41
        "github.com/lightningnetwork/lnd/contractcourt"
42
        "github.com/lightningnetwork/lnd/discovery"
43
        "github.com/lightningnetwork/lnd/feature"
44
        "github.com/lightningnetwork/lnd/fn"
45
        "github.com/lightningnetwork/lnd/funding"
46
        "github.com/lightningnetwork/lnd/graph"
47
        "github.com/lightningnetwork/lnd/healthcheck"
48
        "github.com/lightningnetwork/lnd/htlcswitch"
49
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
50
        "github.com/lightningnetwork/lnd/input"
51
        "github.com/lightningnetwork/lnd/invoices"
52
        "github.com/lightningnetwork/lnd/keychain"
53
        "github.com/lightningnetwork/lnd/kvdb"
54
        "github.com/lightningnetwork/lnd/lncfg"
55
        "github.com/lightningnetwork/lnd/lnencrypt"
56
        "github.com/lightningnetwork/lnd/lnpeer"
57
        "github.com/lightningnetwork/lnd/lnrpc"
58
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
59
        "github.com/lightningnetwork/lnd/lnwallet"
60
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
61
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
62
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
63
        "github.com/lightningnetwork/lnd/lnwire"
64
        "github.com/lightningnetwork/lnd/nat"
65
        "github.com/lightningnetwork/lnd/netann"
66
        "github.com/lightningnetwork/lnd/peer"
67
        "github.com/lightningnetwork/lnd/peernotifier"
68
        "github.com/lightningnetwork/lnd/pool"
69
        "github.com/lightningnetwork/lnd/queue"
70
        "github.com/lightningnetwork/lnd/routing"
71
        "github.com/lightningnetwork/lnd/routing/localchans"
72
        "github.com/lightningnetwork/lnd/routing/route"
73
        "github.com/lightningnetwork/lnd/subscribe"
74
        "github.com/lightningnetwork/lnd/sweep"
75
        "github.com/lightningnetwork/lnd/ticker"
76
        "github.com/lightningnetwork/lnd/tor"
77
        "github.com/lightningnetwork/lnd/walletunlocker"
78
        "github.com/lightningnetwork/lnd/watchtower/blob"
79
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
80
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
81
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
82
)
83

84
const (
85
        // defaultMinPeers is the minimum number of peers nodes should always be
86
        // connected to.
87
        defaultMinPeers = 3
88

89
        // defaultStableConnDuration is a floor under which all reconnection
90
        // attempts will apply exponential randomized backoff. Connections
91
        // durations exceeding this value will be eligible to have their
92
        // backoffs reduced.
93
        defaultStableConnDuration = 10 * time.Minute
94

95
        // numInstantInitReconnect specifies how many persistent peers we should
96
        // always attempt outbound connections to immediately. After this value
97
        // is surpassed, the remaining peers will be randomly delayed using
98
        // maxInitReconnectDelay.
99
        numInstantInitReconnect = 10
100

101
        // maxInitReconnectDelay specifies the maximum delay in seconds we will
102
        // apply in attempting to reconnect to persistent peers on startup. The
103
        // value used or a particular peer will be chosen between 0s and this
104
        // value.
105
        maxInitReconnectDelay = 30
106

107
        // multiAddrConnectionStagger is the number of seconds to wait between
108
        // attempting to a peer with each of its advertised addresses.
109
        multiAddrConnectionStagger = 10 * time.Second
110
)
111

112
var (
113
        // ErrPeerNotConnected signals that the server has no connection to the
114
        // given peer.
115
        ErrPeerNotConnected = errors.New("peer is not connected")
116

117
        // ErrServerNotActive indicates that the server has started but hasn't
118
        // fully finished the startup process.
119
        ErrServerNotActive = errors.New("server is still in the process of " +
120
                "starting")
121

122
        // ErrServerShuttingDown indicates that the server is in the process of
123
        // gracefully exiting.
124
        ErrServerShuttingDown = errors.New("server is shutting down")
125

126
        // MaxFundingAmount is a soft-limit of the maximum channel size
127
        // currently accepted within the Lightning Protocol. This is
128
        // defined in BOLT-0002, and serves as an initial precautionary limit
129
        // while implementations are battle tested in the real world.
130
        //
131
        // At the moment, this value depends on which chain is active. It is set
132
        // to the value under the Bitcoin chain as default.
133
        //
134
        // TODO(roasbeef): add command line param to modify.
135
        MaxFundingAmount = funding.MaxBtcFundingAmount
136
)
137

138
// errPeerAlreadyConnected is an error returned by the server when we're
139
// commanded to connect to a peer, but they're already connected.
140
type errPeerAlreadyConnected struct {
141
        peer *peer.Brontide
142
}
143

144
// Error returns the human readable version of this error type.
145
//
146
// NOTE: Part of the error interface.
147
func (e *errPeerAlreadyConnected) Error() string {
2✔
148
        return fmt.Sprintf("already connected to peer: %v", e.peer)
2✔
149
}
2✔
150

151
// server is the main server of the Lightning Network Daemon. The server houses
152
// global state pertaining to the wallet, database, and the rpcserver.
153
// Additionally, the server is also used as a central messaging bus to interact
154
// with any of its companion objects.
155
type server struct {
156
        active   int32 // atomic
157
        stopping int32 // atomic
158

159
        start sync.Once
160
        stop  sync.Once
161

162
        cfg *Config
163

164
        implCfg *ImplementationCfg
165

166
        // identityECDH is an ECDH capable wrapper for the private key used
167
        // to authenticate any incoming connections.
168
        identityECDH keychain.SingleKeyECDH
169

170
        // identityKeyLoc is the key locator for the above wrapped identity key.
171
        identityKeyLoc keychain.KeyLocator
172

173
        // nodeSigner is an implementation of the MessageSigner implementation
174
        // that's backed by the identity private key of the running lnd node.
175
        nodeSigner *netann.NodeSigner
176

177
        chanStatusMgr *netann.ChanStatusManager
178

179
        // listenAddrs is the list of addresses the server is currently
180
        // listening on.
181
        listenAddrs []net.Addr
182

183
        // torController is a client that will communicate with a locally
184
        // running Tor server. This client will handle initiating and
185
        // authenticating the connection to the Tor server, automatically
186
        // creating and setting up onion services, etc.
187
        torController *tor.Controller
188

189
        // natTraversal is the specific NAT traversal technique used to
190
        // automatically set up port forwarding rules in order to advertise to
191
        // the network that the node is accepting inbound connections.
192
        natTraversal nat.Traversal
193

194
        // lastDetectedIP is the last IP detected by the NAT traversal technique
195
        // above. This IP will be watched periodically in a goroutine in order
196
        // to handle dynamic IP changes.
197
        lastDetectedIP net.IP
198

199
        mu         sync.RWMutex
200
        peersByPub map[string]*peer.Brontide
201

202
        inboundPeers  map[string]*peer.Brontide
203
        outboundPeers map[string]*peer.Brontide
204

205
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
206
        peerDisconnectedListeners map[string][]chan<- struct{}
207

208
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
209
        // will continue to send messages even if there are no active channels
210
        // and the value below is false. Once it's pruned, all its connections
211
        // will be closed, thus the Brontide.Start will return an error.
212
        persistentPeers        map[string]bool
213
        persistentPeersBackoff map[string]time.Duration
214
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
215
        persistentConnReqs     map[string][]*connmgr.ConnReq
216
        persistentRetryCancels map[string]chan struct{}
217

218
        // peerErrors keeps a set of peer error buffers for peers that have
219
        // disconnected from us. This allows us to track historic peer errors
220
        // over connections. The string of the peer's compressed pubkey is used
221
        // as a key for this map.
222
        peerErrors map[string]*queue.CircularBuffer
223

224
        // ignorePeerTermination tracks peers for which the server has initiated
225
        // a disconnect. Adding a peer to this map causes the peer termination
226
        // watcher to short circuit in the event that peers are purposefully
227
        // disconnected.
228
        ignorePeerTermination map[*peer.Brontide]struct{}
229

230
        // scheduledPeerConnection maps a pubkey string to a callback that
231
        // should be executed in the peerTerminationWatcher the prior peer with
232
        // the same pubkey exits.  This allows the server to wait until the
233
        // prior peer has cleaned up successfully, before adding the new peer
234
        // intended to replace it.
235
        scheduledPeerConnection map[string]func()
236

237
        // pongBuf is a shared pong reply buffer we'll use across all active
238
        // peer goroutines. We know the max size of a pong message
239
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
240
        // avoid allocations each time we need to send a pong message.
241
        pongBuf []byte
242

243
        cc *chainreg.ChainControl
244

245
        fundingMgr *funding.Manager
246

247
        graphDB *channeldb.ChannelGraph
248

249
        chanStateDB *channeldb.ChannelStateDB
250

251
        addrSource chanbackup.AddressSource
252

253
        // miscDB is the DB that contains all "other" databases within the main
254
        // channel DB that haven't been separated out yet.
255
        miscDB *channeldb.DB
256

257
        invoicesDB invoices.InvoiceDB
258

259
        aliasMgr *aliasmgr.Manager
260

261
        htlcSwitch *htlcswitch.Switch
262

263
        interceptableSwitch *htlcswitch.InterceptableSwitch
264

265
        invoices *invoices.InvoiceRegistry
266

267
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
268

269
        channelNotifier *channelnotifier.ChannelNotifier
270

271
        peerNotifier *peernotifier.PeerNotifier
272

273
        htlcNotifier *htlcswitch.HtlcNotifier
274

275
        witnessBeacon contractcourt.WitnessBeacon
276

277
        breachArbitrator *contractcourt.BreachArbitrator
278

279
        missionController *routing.MissionController
280
        defaultMC         *routing.MissionControl
281

282
        graphBuilder *graph.Builder
283

284
        chanRouter *routing.ChannelRouter
285

286
        controlTower routing.ControlTower
287

288
        authGossiper *discovery.AuthenticatedGossiper
289

290
        localChanMgr *localchans.Manager
291

292
        utxoNursery *contractcourt.UtxoNursery
293

294
        sweeper *sweep.UtxoSweeper
295

296
        chainArb *contractcourt.ChainArbitrator
297

298
        sphinx *hop.OnionProcessor
299

300
        towerClientMgr *wtclient.Manager
301

302
        connMgr *connmgr.ConnManager
303

304
        sigPool *lnwallet.SigPool
305

306
        writePool *pool.Write
307

308
        readPool *pool.Read
309

310
        tlsManager *TLSManager
311

312
        // featureMgr dispatches feature vectors for various contexts within the
313
        // daemon.
314
        featureMgr *feature.Manager
315

316
        // currentNodeAnn is the node announcement that has been broadcast to
317
        // the network upon startup, if the attributes of the node (us) has
318
        // changed since last start.
319
        currentNodeAnn *lnwire.NodeAnnouncement
320

321
        // chansToRestore is the set of channels that upon starting, the server
322
        // should attempt to restore/recover.
323
        chansToRestore walletunlocker.ChannelsToRecover
324

325
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
326
        // backups are consistent at all times. It interacts with the
327
        // channelNotifier to be notified of newly opened and closed channels.
328
        chanSubSwapper *chanbackup.SubSwapper
329

330
        // chanEventStore tracks the behaviour of channels and their remote peers to
331
        // provide insights into their health and performance.
332
        chanEventStore *chanfitness.ChannelEventStore
333

334
        hostAnn *netann.HostAnnouncer
335

336
        // livenessMonitor monitors that lnd has access to critical resources.
337
        livenessMonitor *healthcheck.Monitor
338

339
        customMessageServer *subscribe.Server
340

341
        // txPublisher is a publisher with fee-bumping capability.
342
        txPublisher *sweep.TxPublisher
343

344
        quit chan struct{}
345

346
        wg sync.WaitGroup
347
}
348

349
// updatePersistentPeerAddrs subscribes to topology changes and stores
350
// advertised addresses for any NodeAnnouncements from our persisted peers.
351
func (s *server) updatePersistentPeerAddrs() error {
2✔
352
        graphSub, err := s.graphBuilder.SubscribeTopology()
2✔
353
        if err != nil {
2✔
354
                return err
×
355
        }
×
356

357
        s.wg.Add(1)
2✔
358
        go func() {
4✔
359
                defer func() {
4✔
360
                        graphSub.Cancel()
2✔
361
                        s.wg.Done()
2✔
362
                }()
2✔
363

364
                for {
4✔
365
                        select {
2✔
366
                        case <-s.quit:
2✔
367
                                return
2✔
368

369
                        case topChange, ok := <-graphSub.TopologyChanges:
2✔
370
                                // If the router is shutting down, then we will
2✔
371
                                // as well.
2✔
372
                                if !ok {
2✔
373
                                        return
×
374
                                }
×
375

376
                                for _, update := range topChange.NodeUpdates {
4✔
377
                                        pubKeyStr := string(
2✔
378
                                                update.IdentityKey.
2✔
379
                                                        SerializeCompressed(),
2✔
380
                                        )
2✔
381

2✔
382
                                        // We only care about updates from
2✔
383
                                        // our persistentPeers.
2✔
384
                                        s.mu.RLock()
2✔
385
                                        _, ok := s.persistentPeers[pubKeyStr]
2✔
386
                                        s.mu.RUnlock()
2✔
387
                                        if !ok {
4✔
388
                                                continue
2✔
389
                                        }
390

391
                                        addrs := make([]*lnwire.NetAddress, 0,
2✔
392
                                                len(update.Addresses))
2✔
393

2✔
394
                                        for _, addr := range update.Addresses {
4✔
395
                                                addrs = append(addrs,
2✔
396
                                                        &lnwire.NetAddress{
2✔
397
                                                                IdentityKey: update.IdentityKey,
2✔
398
                                                                Address:     addr,
2✔
399
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
2✔
400
                                                        },
2✔
401
                                                )
2✔
402
                                        }
2✔
403

404
                                        s.mu.Lock()
2✔
405

2✔
406
                                        // Update the stored addresses for this
2✔
407
                                        // to peer to reflect the new set.
2✔
408
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
2✔
409

2✔
410
                                        // If there are no outstanding
2✔
411
                                        // connection requests for this peer
2✔
412
                                        // then our work is done since we are
2✔
413
                                        // not currently trying to connect to
2✔
414
                                        // them.
2✔
415
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
4✔
416
                                                s.mu.Unlock()
2✔
417
                                                continue
2✔
418
                                        }
419

420
                                        s.mu.Unlock()
2✔
421

2✔
422
                                        s.connectToPersistentPeer(pubKeyStr)
2✔
423
                                }
424
                        }
425
                }
426
        }()
427

428
        return nil
2✔
429
}
430

431
// CustomMessage is a custom message that is received from a peer.
432
type CustomMessage struct {
433
        // Peer is the peer pubkey
434
        Peer [33]byte
435

436
        // Msg is the custom wire message.
437
        Msg *lnwire.Custom
438
}
439

440
// parseAddr parses an address from its string format to a net.Addr.
441
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
2✔
442
        var (
2✔
443
                host string
2✔
444
                port int
2✔
445
        )
2✔
446

2✔
447
        // Split the address into its host and port components.
2✔
448
        h, p, err := net.SplitHostPort(address)
2✔
449
        if err != nil {
2✔
450
                // If a port wasn't specified, we'll assume the address only
×
451
                // contains the host so we'll use the default port.
×
452
                host = address
×
453
                port = defaultPeerPort
×
454
        } else {
2✔
455
                // Otherwise, we'll note both the host and ports.
2✔
456
                host = h
2✔
457
                portNum, err := strconv.Atoi(p)
2✔
458
                if err != nil {
2✔
459
                        return nil, err
×
460
                }
×
461
                port = portNum
2✔
462
        }
463

464
        if tor.IsOnionHost(host) {
2✔
465
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
466
        }
×
467

468
        // If the host is part of a TCP address, we'll use the network
469
        // specific ResolveTCPAddr function in order to resolve these
470
        // addresses over Tor in order to prevent leaking your real IP
471
        // address.
472
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
2✔
473
        return netCfg.ResolveTCPAddr("tcp", hostPort)
2✔
474
}
475

476
// noiseDial is a factory function which creates a connmgr compliant dialing
477
// function by returning a closure which includes the server's identity key.
478
func noiseDial(idKey keychain.SingleKeyECDH,
479
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
2✔
480

2✔
481
        return func(a net.Addr) (net.Conn, error) {
4✔
482
                lnAddr := a.(*lnwire.NetAddress)
2✔
483
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
2✔
484
        }
2✔
485
}
486

487
// newServer creates a new instance of the server which is to listen using the
488
// passed listener address.
489
func newServer(cfg *Config, listenAddrs []net.Addr,
490
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
491
        nodeKeyDesc *keychain.KeyDescriptor,
492
        chansToRestore walletunlocker.ChannelsToRecover,
493
        chanPredicate chanacceptor.ChannelAcceptor,
494
        torController *tor.Controller, tlsManager *TLSManager,
495
        leaderElector cluster.LeaderElector,
496
        implCfg *ImplementationCfg) (*server, error) {
2✔
497

2✔
498
        var (
2✔
499
                err         error
2✔
500
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
2✔
501

2✔
502
                // We just derived the full descriptor, so we know the public
2✔
503
                // key is set on it.
2✔
504
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
2✔
505
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
2✔
506
                )
2✔
507
        )
2✔
508

2✔
509
        listeners := make([]net.Listener, len(listenAddrs))
2✔
510
        for i, listenAddr := range listenAddrs {
4✔
511
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
2✔
512
                // doesn't need to call the general lndResolveTCP function
2✔
513
                // since we are resolving a local address.
2✔
514
                listeners[i], err = brontide.NewListener(
2✔
515
                        nodeKeyECDH, listenAddr.String(),
2✔
516
                )
2✔
517
                if err != nil {
2✔
518
                        return nil, err
×
519
                }
×
520
        }
521

522
        var serializedPubKey [33]byte
2✔
523
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
2✔
524

2✔
525
        netParams := cfg.ActiveNetParams.Params
2✔
526

2✔
527
        // Initialize the sphinx router.
2✔
528
        replayLog := htlcswitch.NewDecayedLog(
2✔
529
                dbs.DecayedLogDB, cc.ChainNotifier,
2✔
530
        )
2✔
531
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
2✔
532

2✔
533
        writeBufferPool := pool.NewWriteBuffer(
2✔
534
                pool.DefaultWriteBufferGCInterval,
2✔
535
                pool.DefaultWriteBufferExpiryInterval,
2✔
536
        )
2✔
537

2✔
538
        writePool := pool.NewWrite(
2✔
539
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
2✔
540
        )
2✔
541

2✔
542
        readBufferPool := pool.NewReadBuffer(
2✔
543
                pool.DefaultReadBufferGCInterval,
2✔
544
                pool.DefaultReadBufferExpiryInterval,
2✔
545
        )
2✔
546

2✔
547
        readPool := pool.NewRead(
2✔
548
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
2✔
549
        )
2✔
550

2✔
551
        // If the taproot overlay flag is set, but we don't have an aux funding
2✔
552
        // controller, then we'll exit as this is incompatible.
2✔
553
        if cfg.ProtocolOptions.TaprootOverlayChans &&
2✔
554
                implCfg.AuxFundingController.IsNone() {
2✔
555

×
556
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
557
                        "aux controllers")
×
558
        }
×
559

560
        //nolint:lll
561
        featureMgr, err := feature.NewManager(feature.Config{
2✔
562
                NoTLVOnion:               cfg.ProtocolOptions.LegacyOnion(),
2✔
563
                NoStaticRemoteKey:        cfg.ProtocolOptions.NoStaticRemoteKey(),
2✔
564
                NoAnchors:                cfg.ProtocolOptions.NoAnchorCommitments(),
2✔
565
                NoWumbo:                  !cfg.ProtocolOptions.Wumbo(),
2✔
566
                NoScriptEnforcementLease: cfg.ProtocolOptions.NoScriptEnforcementLease(),
2✔
567
                NoKeysend:                !cfg.AcceptKeySend,
2✔
568
                NoOptionScidAlias:        !cfg.ProtocolOptions.ScidAlias(),
2✔
569
                NoZeroConf:               !cfg.ProtocolOptions.ZeroConf(),
2✔
570
                NoAnySegwit:              cfg.ProtocolOptions.NoAnySegwit(),
2✔
571
                CustomFeatures:           cfg.ProtocolOptions.CustomFeatures(),
2✔
572
                NoTaprootChans:           !cfg.ProtocolOptions.TaprootChans,
2✔
573
                NoTaprootOverlay:         !cfg.ProtocolOptions.TaprootOverlayChans,
2✔
574
                NoRouteBlinding:          cfg.ProtocolOptions.NoRouteBlinding(),
2✔
575
        })
2✔
576
        if err != nil {
2✔
577
                return nil, err
×
578
        }
×
579

580
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
2✔
581
        registryConfig := invoices.RegistryConfig{
2✔
582
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
2✔
583
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
2✔
584
                Clock:                       clock.NewDefaultClock(),
2✔
585
                AcceptKeySend:               cfg.AcceptKeySend,
2✔
586
                AcceptAMP:                   cfg.AcceptAMP,
2✔
587
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
2✔
588
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
2✔
589
                KeysendHoldTime:             cfg.KeysendHoldTime,
2✔
590
                HtlcInterceptor:             invoiceHtlcModifier,
2✔
591
        }
2✔
592

2✔
593
        s := &server{
2✔
594
                cfg:            cfg,
2✔
595
                implCfg:        implCfg,
2✔
596
                graphDB:        dbs.GraphDB.ChannelGraph(),
2✔
597
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
2✔
598
                addrSource:     dbs.ChanStateDB,
2✔
599
                miscDB:         dbs.ChanStateDB,
2✔
600
                invoicesDB:     dbs.InvoiceDB,
2✔
601
                cc:             cc,
2✔
602
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
2✔
603
                writePool:      writePool,
2✔
604
                readPool:       readPool,
2✔
605
                chansToRestore: chansToRestore,
2✔
606

2✔
607
                channelNotifier: channelnotifier.New(
2✔
608
                        dbs.ChanStateDB.ChannelStateDB(),
2✔
609
                ),
2✔
610

2✔
611
                identityECDH:   nodeKeyECDH,
2✔
612
                identityKeyLoc: nodeKeyDesc.KeyLocator,
2✔
613
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
2✔
614

2✔
615
                listenAddrs: listenAddrs,
2✔
616

2✔
617
                // TODO(roasbeef): derive proper onion key based on rotation
2✔
618
                // schedule
2✔
619
                sphinx: hop.NewOnionProcessor(sphinxRouter),
2✔
620

2✔
621
                torController: torController,
2✔
622

2✔
623
                persistentPeers:         make(map[string]bool),
2✔
624
                persistentPeersBackoff:  make(map[string]time.Duration),
2✔
625
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
2✔
626
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
2✔
627
                persistentRetryCancels:  make(map[string]chan struct{}),
2✔
628
                peerErrors:              make(map[string]*queue.CircularBuffer),
2✔
629
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
2✔
630
                scheduledPeerConnection: make(map[string]func()),
2✔
631
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
2✔
632

2✔
633
                peersByPub:                make(map[string]*peer.Brontide),
2✔
634
                inboundPeers:              make(map[string]*peer.Brontide),
2✔
635
                outboundPeers:             make(map[string]*peer.Brontide),
2✔
636
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
2✔
637
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
2✔
638

2✔
639
                invoiceHtlcModifier: invoiceHtlcModifier,
2✔
640

2✔
641
                customMessageServer: subscribe.NewServer(),
2✔
642

2✔
643
                tlsManager: tlsManager,
2✔
644

2✔
645
                featureMgr: featureMgr,
2✔
646
                quit:       make(chan struct{}),
2✔
647
        }
2✔
648

2✔
649
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
2✔
650
        if err != nil {
2✔
651
                return nil, err
×
652
        }
×
653

654
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
2✔
655
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
2✔
656
                uint32(currentHeight), currentHash, cc.ChainNotifier,
2✔
657
        )
2✔
658
        s.invoices = invoices.NewRegistry(
2✔
659
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
2✔
660
        )
2✔
661

2✔
662
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
2✔
663

2✔
664
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
2✔
665
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
2✔
666

2✔
667
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
4✔
668
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
2✔
669
                if err != nil {
2✔
670
                        return err
×
671
                }
×
672

673
                s.htlcSwitch.UpdateLinkAliases(link)
2✔
674

2✔
675
                return nil
2✔
676
        }
677

678
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
2✔
679
        if err != nil {
2✔
680
                return nil, err
×
681
        }
×
682

683
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
2✔
684
                DB:                   dbs.ChanStateDB,
2✔
685
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
2✔
686
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
2✔
687
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
2✔
688
                LocalChannelClose: func(pubKey []byte,
2✔
689
                        request *htlcswitch.ChanClose) {
4✔
690

2✔
691
                        peer, err := s.FindPeerByPubStr(string(pubKey))
2✔
692
                        if err != nil {
2✔
693
                                srvrLog.Errorf("unable to close channel, peer"+
×
694
                                        " with %v id can't be found: %v",
×
695
                                        pubKey, err,
×
696
                                )
×
697
                                return
×
698
                        }
×
699

700
                        peer.HandleLocalCloseChanReqs(request)
2✔
701
                },
702
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
703
                SwitchPackager:         channeldb.NewSwitchPackager(),
704
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
705
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
706
                Notifier:               s.cc.ChainNotifier,
707
                HtlcNotifier:           s.htlcNotifier,
708
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
709
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
710
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
711
                AllowCircularRoute:     cfg.AllowCircularRoute,
712
                RejectHTLC:             cfg.RejectHTLC,
713
                Clock:                  clock.NewDefaultClock(),
714
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
715
                MaxFeeExposure:         thresholdMSats,
716
                SignAliasUpdate:        s.signAliasUpdate,
717
                IsAlias:                aliasmgr.IsAlias,
718
        }, uint32(currentHeight))
719
        if err != nil {
2✔
720
                return nil, err
×
721
        }
×
722
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
2✔
723
                &htlcswitch.InterceptableSwitchConfig{
2✔
724
                        Switch:             s.htlcSwitch,
2✔
725
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
2✔
726
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
2✔
727
                        RequireInterceptor: s.cfg.RequireInterceptor,
2✔
728
                        Notifier:           s.cc.ChainNotifier,
2✔
729
                },
2✔
730
        )
2✔
731
        if err != nil {
2✔
732
                return nil, err
×
733
        }
×
734

735
        s.witnessBeacon = newPreimageBeacon(
2✔
736
                dbs.ChanStateDB.NewWitnessCache(),
2✔
737
                s.interceptableSwitch.ForwardPacket,
2✔
738
        )
2✔
739

2✔
740
        chanStatusMgrCfg := &netann.ChanStatusConfig{
2✔
741
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
2✔
742
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
2✔
743
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
2✔
744
                OurPubKey:                nodeKeyDesc.PubKey,
2✔
745
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
2✔
746
                MessageSigner:            s.nodeSigner,
2✔
747
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
2✔
748
                ApplyChannelUpdate:       s.applyChannelUpdate,
2✔
749
                DB:                       s.chanStateDB,
2✔
750
                Graph:                    dbs.GraphDB.ChannelGraph(),
2✔
751
        }
2✔
752

2✔
753
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
2✔
754
        if err != nil {
2✔
755
                return nil, err
×
756
        }
×
757
        s.chanStatusMgr = chanStatusMgr
2✔
758

2✔
759
        // If enabled, use either UPnP or NAT-PMP to automatically configure
2✔
760
        // port forwarding for users behind a NAT.
2✔
761
        if cfg.NAT {
2✔
762
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
763

×
764
                discoveryTimeout := time.Duration(10 * time.Second)
×
765

×
766
                ctx, cancel := context.WithTimeout(
×
767
                        context.Background(), discoveryTimeout,
×
768
                )
×
769
                defer cancel()
×
770
                upnp, err := nat.DiscoverUPnP(ctx)
×
771
                if err == nil {
×
772
                        s.natTraversal = upnp
×
773
                } else {
×
774
                        // If we were not able to discover a UPnP enabled device
×
775
                        // on the local network, we'll fall back to attempting
×
776
                        // to discover a NAT-PMP enabled device.
×
777
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
778
                                "device on the local network: %v", err)
×
779

×
780
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
781
                                "enabled device")
×
782

×
783
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
784
                        if err != nil {
×
785
                                err := fmt.Errorf("unable to discover a "+
×
786
                                        "NAT-PMP enabled device on the local "+
×
787
                                        "network: %v", err)
×
788
                                srvrLog.Error(err)
×
789
                                return nil, err
×
790
                        }
×
791

792
                        s.natTraversal = pmp
×
793
                }
794
        }
795

796
        // If we were requested to automatically configure port forwarding,
797
        // we'll use the ports that the server will be listening on.
798
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
2✔
799
        for idx, ip := range cfg.ExternalIPs {
4✔
800
                externalIPStrings[idx] = ip.String()
2✔
801
        }
2✔
802
        if s.natTraversal != nil {
2✔
803
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
804
                for _, listenAddr := range listenAddrs {
×
805
                        // At this point, the listen addresses should have
×
806
                        // already been normalized, so it's safe to ignore the
×
807
                        // errors.
×
808
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
809
                        port, _ := strconv.Atoi(portStr)
×
810

×
811
                        listenPorts = append(listenPorts, uint16(port))
×
812
                }
×
813

814
                ips, err := s.configurePortForwarding(listenPorts...)
×
815
                if err != nil {
×
816
                        srvrLog.Errorf("Unable to automatically set up port "+
×
817
                                "forwarding using %s: %v",
×
818
                                s.natTraversal.Name(), err)
×
819
                } else {
×
820
                        srvrLog.Infof("Automatically set up port forwarding "+
×
821
                                "using %s to advertise external IP",
×
822
                                s.natTraversal.Name())
×
823
                        externalIPStrings = append(externalIPStrings, ips...)
×
824
                }
×
825
        }
826

827
        // If external IP addresses have been specified, add those to the list
828
        // of this server's addresses.
829
        externalIPs, err := lncfg.NormalizeAddresses(
2✔
830
                externalIPStrings, strconv.Itoa(defaultPeerPort),
2✔
831
                cfg.net.ResolveTCPAddr,
2✔
832
        )
2✔
833
        if err != nil {
2✔
834
                return nil, err
×
835
        }
×
836

837
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
2✔
838
        selfAddrs = append(selfAddrs, externalIPs...)
2✔
839

2✔
840
        // As the graph can be obtained at anytime from the network, we won't
2✔
841
        // replicate it, and instead it'll only be stored locally.
2✔
842
        chanGraph := dbs.GraphDB.ChannelGraph()
2✔
843

2✔
844
        // We'll now reconstruct a node announcement based on our current
2✔
845
        // configuration so we can send it out as a sort of heart beat within
2✔
846
        // the network.
2✔
847
        //
2✔
848
        // We'll start by parsing the node color from configuration.
2✔
849
        color, err := lncfg.ParseHexColor(cfg.Color)
2✔
850
        if err != nil {
2✔
851
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
852
                return nil, err
×
853
        }
×
854

855
        // If no alias is provided, default to first 10 characters of public
856
        // key.
857
        alias := cfg.Alias
2✔
858
        if alias == "" {
4✔
859
                alias = hex.EncodeToString(serializedPubKey[:10])
2✔
860
        }
2✔
861
        nodeAlias, err := lnwire.NewNodeAlias(alias)
2✔
862
        if err != nil {
2✔
863
                return nil, err
×
864
        }
×
865
        selfNode := &channeldb.LightningNode{
2✔
866
                HaveNodeAnnouncement: true,
2✔
867
                LastUpdate:           time.Now(),
2✔
868
                Addresses:            selfAddrs,
2✔
869
                Alias:                nodeAlias.String(),
2✔
870
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
2✔
871
                Color:                color,
2✔
872
        }
2✔
873
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
2✔
874

2✔
875
        // Based on the disk representation of the node announcement generated
2✔
876
        // above, we'll generate a node announcement that can go out on the
2✔
877
        // network so we can properly sign it.
2✔
878
        nodeAnn, err := selfNode.NodeAnnouncement(false)
2✔
879
        if err != nil {
2✔
880
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
881
        }
×
882

883
        // With the announcement generated, we'll sign it to properly
884
        // authenticate the message on the network.
885
        authSig, err := netann.SignAnnouncement(
2✔
886
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
2✔
887
        )
2✔
888
        if err != nil {
2✔
889
                return nil, fmt.Errorf("unable to generate signature for "+
×
890
                        "self node announcement: %v", err)
×
891
        }
×
892
        selfNode.AuthSigBytes = authSig.Serialize()
2✔
893
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
2✔
894
                selfNode.AuthSigBytes,
2✔
895
        )
2✔
896
        if err != nil {
2✔
897
                return nil, err
×
898
        }
×
899

900
        // Finally, we'll update the representation on disk, and update our
901
        // cached in-memory version as well.
902
        if err := chanGraph.SetSourceNode(selfNode); err != nil {
2✔
903
                return nil, fmt.Errorf("can't set self node: %w", err)
×
904
        }
×
905
        s.currentNodeAnn = nodeAnn
2✔
906

2✔
907
        // The router will get access to the payment ID sequencer, such that it
2✔
908
        // can generate unique payment IDs.
2✔
909
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
2✔
910
        if err != nil {
2✔
911
                return nil, err
×
912
        }
×
913

914
        // Instantiate mission control with config from the sub server.
915
        //
916
        // TODO(joostjager): When we are further in the process of moving to sub
917
        // servers, the mission control instance itself can be moved there too.
918
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
2✔
919

2✔
920
        // We only initialize a probability estimator if there's no custom one.
2✔
921
        var estimator routing.Estimator
2✔
922
        if cfg.Estimator != nil {
2✔
923
                estimator = cfg.Estimator
×
924
        } else {
2✔
925
                switch routingConfig.ProbabilityEstimatorType {
2✔
926
                case routing.AprioriEstimatorName:
2✔
927
                        aCfg := routingConfig.AprioriConfig
2✔
928
                        aprioriConfig := routing.AprioriConfig{
2✔
929
                                AprioriHopProbability: aCfg.HopProbability,
2✔
930
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
2✔
931
                                AprioriWeight:         aCfg.Weight,
2✔
932
                                CapacityFraction:      aCfg.CapacityFraction,
2✔
933
                        }
2✔
934

2✔
935
                        estimator, err = routing.NewAprioriEstimator(
2✔
936
                                aprioriConfig,
2✔
937
                        )
2✔
938
                        if err != nil {
2✔
939
                                return nil, err
×
940
                        }
×
941

942
                case routing.BimodalEstimatorName:
×
943
                        bCfg := routingConfig.BimodalConfig
×
944
                        bimodalConfig := routing.BimodalConfig{
×
945
                                BimodalNodeWeight: bCfg.NodeWeight,
×
946
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
947
                                        bCfg.Scale,
×
948
                                ),
×
949
                                BimodalDecayTime: bCfg.DecayTime,
×
950
                        }
×
951

×
952
                        estimator, err = routing.NewBimodalEstimator(
×
953
                                bimodalConfig,
×
954
                        )
×
955
                        if err != nil {
×
956
                                return nil, err
×
957
                        }
×
958

959
                default:
×
960
                        return nil, fmt.Errorf("unknown estimator type %v",
×
961
                                routingConfig.ProbabilityEstimatorType)
×
962
                }
963
        }
964

965
        mcCfg := &routing.MissionControlConfig{
2✔
966
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
2✔
967
                Estimator:               estimator,
2✔
968
                MaxMcHistory:            routingConfig.MaxMcHistory,
2✔
969
                McFlushInterval:         routingConfig.McFlushInterval,
2✔
970
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
2✔
971
        }
2✔
972

2✔
973
        s.missionController, err = routing.NewMissionController(
2✔
974
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
2✔
975
        )
2✔
976
        if err != nil {
2✔
977
                return nil, fmt.Errorf("can't create mission control "+
×
978
                        "manager: %w", err)
×
979
        }
×
980
        s.defaultMC, err = s.missionController.GetNamespacedStore(
2✔
981
                routing.DefaultMissionControlNamespace,
2✔
982
        )
2✔
983
        if err != nil {
2✔
984
                return nil, fmt.Errorf("can't create mission control in the "+
×
985
                        "default namespace: %w", err)
×
986
        }
×
987

988
        srvrLog.Debugf("Instantiating payment session source with config: "+
2✔
989
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
2✔
990
                int64(routingConfig.AttemptCost),
2✔
991
                float64(routingConfig.AttemptCostPPM)/10000,
2✔
992
                routingConfig.MinRouteProbability)
2✔
993

2✔
994
        pathFindingConfig := routing.PathFindingConfig{
2✔
995
                AttemptCost: lnwire.NewMSatFromSatoshis(
2✔
996
                        routingConfig.AttemptCost,
2✔
997
                ),
2✔
998
                AttemptCostPPM: routingConfig.AttemptCostPPM,
2✔
999
                MinProbability: routingConfig.MinRouteProbability,
2✔
1000
        }
2✔
1001

2✔
1002
        sourceNode, err := chanGraph.SourceNode()
2✔
1003
        if err != nil {
2✔
1004
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1005
        }
×
1006
        paymentSessionSource := &routing.SessionSource{
2✔
1007
                GraphSessionFactory: graphsession.NewGraphSessionFactory(
2✔
1008
                        chanGraph,
2✔
1009
                ),
2✔
1010
                SourceNode:        sourceNode,
2✔
1011
                MissionControl:    s.defaultMC,
2✔
1012
                GetLink:           s.htlcSwitch.GetLinkByShortID,
2✔
1013
                PathFindingConfig: pathFindingConfig,
2✔
1014
        }
2✔
1015

2✔
1016
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
2✔
1017

2✔
1018
        s.controlTower = routing.NewControlTower(paymentControl)
2✔
1019

2✔
1020
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
2✔
1021
                cfg.Routing.StrictZombiePruning
2✔
1022

2✔
1023
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
2✔
1024
                SelfNode:            selfNode.PubKeyBytes,
2✔
1025
                Graph:               chanGraph,
2✔
1026
                Chain:               cc.ChainIO,
2✔
1027
                ChainView:           cc.ChainView,
2✔
1028
                Notifier:            cc.ChainNotifier,
2✔
1029
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
2✔
1030
                GraphPruneInterval:  time.Hour,
2✔
1031
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
2✔
1032
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
2✔
1033
                StrictZombiePruning: strictPruning,
2✔
1034
                IsAlias:             aliasmgr.IsAlias,
2✔
1035
        })
2✔
1036
        if err != nil {
2✔
1037
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1038
        }
×
1039

1040
        s.chanRouter, err = routing.New(routing.Config{
2✔
1041
                SelfNode:           selfNode.PubKeyBytes,
2✔
1042
                RoutingGraph:       graphsession.NewRoutingGraph(chanGraph),
2✔
1043
                Chain:              cc.ChainIO,
2✔
1044
                Payer:              s.htlcSwitch,
2✔
1045
                Control:            s.controlTower,
2✔
1046
                MissionControl:     s.defaultMC,
2✔
1047
                SessionSource:      paymentSessionSource,
2✔
1048
                GetLink:            s.htlcSwitch.GetLinkByShortID,
2✔
1049
                NextPaymentID:      sequencer.NextID,
2✔
1050
                PathFindingConfig:  pathFindingConfig,
2✔
1051
                Clock:              clock.NewDefaultClock(),
2✔
1052
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
2✔
1053
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
2✔
1054
                TrafficShaper:      implCfg.TrafficShaper,
2✔
1055
        })
2✔
1056
        if err != nil {
2✔
1057
                return nil, fmt.Errorf("can't create router: %w", err)
×
1058
        }
×
1059

1060
        chanSeries := discovery.NewChanSeries(s.graphDB)
2✔
1061
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
2✔
1062
        if err != nil {
2✔
1063
                return nil, err
×
1064
        }
×
1065
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
2✔
1066
        if err != nil {
2✔
1067
                return nil, err
×
1068
        }
×
1069

1070
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
2✔
1071

2✔
1072
        s.authGossiper = discovery.New(discovery.Config{
2✔
1073
                Graph:                 s.graphBuilder,
2✔
1074
                ChainIO:               s.cc.ChainIO,
2✔
1075
                Notifier:              s.cc.ChainNotifier,
2✔
1076
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
2✔
1077
                Broadcast:             s.BroadcastMessage,
2✔
1078
                ChanSeries:            chanSeries,
2✔
1079
                NotifyWhenOnline:      s.NotifyWhenOnline,
2✔
1080
                NotifyWhenOffline:     s.NotifyWhenOffline,
2✔
1081
                FetchSelfAnnouncement: s.getNodeAnnouncement,
2✔
1082
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
2✔
1083
                        error) {
2✔
1084

×
1085
                        return s.genNodeAnnouncement(nil)
×
1086
                },
×
1087
                ProofMatureDelta:        0,
1088
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1089
                RetransmitTicker:        ticker.New(time.Minute * 30),
1090
                RebroadcastInterval:     time.Hour * 24,
1091
                WaitingProofStore:       waitingProofStore,
1092
                MessageStore:            gossipMessageStore,
1093
                AnnSigner:               s.nodeSigner,
1094
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1095
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1096
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1097
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:lll
1098
                MinimumBatchSize:        10,
1099
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1100
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1101
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1102
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1103
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1104
                IsAlias:                 aliasmgr.IsAlias,
1105
                SignAliasUpdate:         s.signAliasUpdate,
1106
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1107
                GetAlias:                s.aliasMgr.GetPeerAlias,
1108
                FindChannel:             s.findChannel,
1109
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1110
                ScidCloser:              scidCloserMan,
1111
        }, nodeKeyDesc)
1112

1113
        //nolint:lll
1114
        s.localChanMgr = &localchans.Manager{
2✔
1115
                ForAllOutgoingChannels:    s.graphBuilder.ForAllOutgoingChannels,
2✔
1116
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
2✔
1117
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
2✔
1118
                FetchChannel:              s.chanStateDB.FetchChannel,
2✔
1119
        }
2✔
1120

2✔
1121
        utxnStore, err := contractcourt.NewNurseryStore(
2✔
1122
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
2✔
1123
        )
2✔
1124
        if err != nil {
2✔
1125
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1126
                return nil, err
×
1127
        }
×
1128

1129
        sweeperStore, err := sweep.NewSweeperStore(
2✔
1130
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
2✔
1131
        )
2✔
1132
        if err != nil {
2✔
1133
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1134
                return nil, err
×
1135
        }
×
1136

1137
        aggregator := sweep.NewBudgetAggregator(
2✔
1138
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
2✔
1139
                s.implCfg.AuxSweeper,
2✔
1140
        )
2✔
1141

2✔
1142
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
2✔
1143
                Signer:     cc.Wallet.Cfg.Signer,
2✔
1144
                Wallet:     cc.Wallet,
2✔
1145
                Estimator:  cc.FeeEstimator,
2✔
1146
                Notifier:   cc.ChainNotifier,
2✔
1147
                AuxSweeper: s.implCfg.AuxSweeper,
2✔
1148
        })
2✔
1149

2✔
1150
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
2✔
1151
                FeeEstimator: cc.FeeEstimator,
2✔
1152
                GenSweepScript: newSweepPkScriptGen(
2✔
1153
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
2✔
1154
                ),
2✔
1155
                Signer:               cc.Wallet.Cfg.Signer,
2✔
1156
                Wallet:               newSweeperWallet(cc.Wallet),
2✔
1157
                Mempool:              cc.MempoolNotifier,
2✔
1158
                Notifier:             cc.ChainNotifier,
2✔
1159
                Store:                sweeperStore,
2✔
1160
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
2✔
1161
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
2✔
1162
                Aggregator:           aggregator,
2✔
1163
                Publisher:            s.txPublisher,
2✔
1164
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
2✔
1165
        })
2✔
1166

2✔
1167
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
2✔
1168
                ChainIO:             cc.ChainIO,
2✔
1169
                ConfDepth:           1,
2✔
1170
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
2✔
1171
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
2✔
1172
                Notifier:            cc.ChainNotifier,
2✔
1173
                PublishTransaction:  cc.Wallet.PublishTransaction,
2✔
1174
                Store:               utxnStore,
2✔
1175
                SweepInput:          s.sweeper.SweepInput,
2✔
1176
                Budget:              s.cfg.Sweeper.Budget,
2✔
1177
        })
2✔
1178

2✔
1179
        // Construct a closure that wraps the htlcswitch's CloseLink method.
2✔
1180
        closeLink := func(chanPoint *wire.OutPoint,
2✔
1181
                closureType contractcourt.ChannelCloseType) {
4✔
1182
                // TODO(conner): Properly respect the update and error channels
2✔
1183
                // returned by CloseLink.
2✔
1184

2✔
1185
                // Instruct the switch to close the channel.  Provide no close out
2✔
1186
                // delivery script or target fee per kw because user input is not
2✔
1187
                // available when the remote peer closes the channel.
2✔
1188
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
2✔
1189
        }
2✔
1190

1191
        // We will use the following channel to reliably hand off contract
1192
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1193
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
2✔
1194

2✔
1195
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
2✔
1196
                &contractcourt.BreachConfig{
2✔
1197
                        CloseLink: closeLink,
2✔
1198
                        DB:        s.chanStateDB,
2✔
1199
                        Estimator: s.cc.FeeEstimator,
2✔
1200
                        GenSweepScript: newSweepPkScriptGen(
2✔
1201
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
2✔
1202
                        ),
2✔
1203
                        Notifier:           cc.ChainNotifier,
2✔
1204
                        PublishTransaction: cc.Wallet.PublishTransaction,
2✔
1205
                        ContractBreaches:   contractBreaches,
2✔
1206
                        Signer:             cc.Wallet.Cfg.Signer,
2✔
1207
                        Store: contractcourt.NewRetributionStore(
2✔
1208
                                dbs.ChanStateDB,
2✔
1209
                        ),
2✔
1210
                        AuxSweeper: s.implCfg.AuxSweeper,
2✔
1211
                },
2✔
1212
        )
2✔
1213

2✔
1214
        //nolint:lll
2✔
1215
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
2✔
1216
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
2✔
1217
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
2✔
1218
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
2✔
1219
                NewSweepAddr: func() ([]byte, error) {
2✔
1220
                        addr, err := newSweepPkScriptGen(
×
1221
                                cc.Wallet, netParams,
×
1222
                        )().Unpack()
×
1223
                        if err != nil {
×
1224
                                return nil, err
×
1225
                        }
×
1226

1227
                        return addr.DeliveryAddress, nil
×
1228
                },
1229
                PublishTx: cc.Wallet.PublishTransaction,
1230
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
2✔
1231
                        for _, msg := range msgs {
4✔
1232
                                err := s.htlcSwitch.ProcessContractResolution(msg)
2✔
1233
                                if err != nil {
2✔
1234
                                        return err
×
1235
                                }
×
1236
                        }
1237
                        return nil
2✔
1238
                },
1239
                IncubateOutputs: func(chanPoint wire.OutPoint,
1240
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1241
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1242
                        broadcastHeight uint32,
1243
                        deadlineHeight fn.Option[int32]) error {
2✔
1244

2✔
1245
                        return s.utxoNursery.IncubateOutputs(
2✔
1246
                                chanPoint, outHtlcRes, inHtlcRes,
2✔
1247
                                broadcastHeight, deadlineHeight,
2✔
1248
                        )
2✔
1249
                },
2✔
1250
                PreimageDB:   s.witnessBeacon,
1251
                Notifier:     cc.ChainNotifier,
1252
                Mempool:      cc.MempoolNotifier,
1253
                Signer:       cc.Wallet.Cfg.Signer,
1254
                FeeEstimator: cc.FeeEstimator,
1255
                ChainIO:      cc.ChainIO,
1256
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
2✔
1257
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
1258
                        s.htlcSwitch.RemoveLink(chanID)
2✔
1259
                        return nil
2✔
1260
                },
2✔
1261
                IsOurAddress: cc.Wallet.IsOurAddress,
1262
                ContractBreach: func(chanPoint wire.OutPoint,
1263
                        breachRet *lnwallet.BreachRetribution) error {
2✔
1264

2✔
1265
                        // processACK will handle the BreachArbitrator ACKing
2✔
1266
                        // the event.
2✔
1267
                        finalErr := make(chan error, 1)
2✔
1268
                        processACK := func(brarErr error) {
4✔
1269
                                if brarErr != nil {
2✔
1270
                                        finalErr <- brarErr
×
1271
                                        return
×
1272
                                }
×
1273

1274
                                // If the BreachArbitrator successfully handled
1275
                                // the event, we can signal that the handoff
1276
                                // was successful.
1277
                                finalErr <- nil
2✔
1278
                        }
1279

1280
                        event := &contractcourt.ContractBreachEvent{
2✔
1281
                                ChanPoint:         chanPoint,
2✔
1282
                                ProcessACK:        processACK,
2✔
1283
                                BreachRetribution: breachRet,
2✔
1284
                        }
2✔
1285

2✔
1286
                        // Send the contract breach event to the
2✔
1287
                        // BreachArbitrator.
2✔
1288
                        select {
2✔
1289
                        case contractBreaches <- event:
2✔
1290
                        case <-s.quit:
×
1291
                                return ErrServerShuttingDown
×
1292
                        }
1293

1294
                        // We'll wait for a final error to be available from
1295
                        // the BreachArbitrator.
1296
                        select {
2✔
1297
                        case err := <-finalErr:
2✔
1298
                                return err
2✔
1299
                        case <-s.quit:
×
1300
                                return ErrServerShuttingDown
×
1301
                        }
1302
                },
1303
                DisableChannel: func(chanPoint wire.OutPoint) error {
2✔
1304
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
2✔
1305
                },
2✔
1306
                Sweeper:                       s.sweeper,
1307
                Registry:                      s.invoices,
1308
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1309
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1310
                OnionProcessor:                s.sphinx,
1311
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1312
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1313
                Clock:                         clock.NewDefaultClock(),
1314
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1315
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1316
                HtlcNotifier:                  s.htlcNotifier,
1317
                Budget:                        *s.cfg.Sweeper.Budget,
1318

1319
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1320
                QueryIncomingCircuit: func(
1321
                        circuit models.CircuitKey) *models.CircuitKey {
2✔
1322

2✔
1323
                        // Get the circuit map.
2✔
1324
                        circuits := s.htlcSwitch.CircuitLookup()
2✔
1325

2✔
1326
                        // Lookup the outgoing circuit.
2✔
1327
                        pc := circuits.LookupOpenCircuit(circuit)
2✔
1328
                        if pc == nil {
4✔
1329
                                return nil
2✔
1330
                        }
2✔
1331

1332
                        return &pc.Incoming
2✔
1333
                },
1334
                AuxLeafStore: implCfg.AuxLeafStore,
1335
                AuxSigner:    implCfg.AuxSigner,
1336
                AuxResolver:  implCfg.AuxContractResolver,
1337
        }, dbs.ChanStateDB)
1338

1339
        // Select the configuration and funding parameters for Bitcoin.
1340
        chainCfg := cfg.Bitcoin
2✔
1341
        minRemoteDelay := funding.MinBtcRemoteDelay
2✔
1342
        maxRemoteDelay := funding.MaxBtcRemoteDelay
2✔
1343

2✔
1344
        var chanIDSeed [32]byte
2✔
1345
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
2✔
1346
                return nil, err
×
1347
        }
×
1348

1349
        // Wrap the DeleteChannelEdges method so that the funding manager can
1350
        // use it without depending on several layers of indirection.
1351
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
2✔
1352
                *models.ChannelEdgePolicy, error) {
4✔
1353

2✔
1354
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
2✔
1355
                        scid.ToUint64(),
2✔
1356
                )
2✔
1357
                if errors.Is(err, channeldb.ErrEdgeNotFound) {
2✔
1358
                        // This is unlikely but there is a slim chance of this
×
1359
                        // being hit if lnd was killed via SIGKILL and the
×
1360
                        // funding manager was stepping through the delete
×
1361
                        // alias edge logic.
×
1362
                        return nil, nil
×
1363
                } else if err != nil {
2✔
1364
                        return nil, err
×
1365
                }
×
1366

1367
                // Grab our key to find our policy.
1368
                var ourKey [33]byte
2✔
1369
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
2✔
1370

2✔
1371
                var ourPolicy *models.ChannelEdgePolicy
2✔
1372
                if info != nil && info.NodeKey1Bytes == ourKey {
4✔
1373
                        ourPolicy = e1
2✔
1374
                } else {
4✔
1375
                        ourPolicy = e2
2✔
1376
                }
2✔
1377

1378
                if ourPolicy == nil {
2✔
1379
                        // Something is wrong, so return an error.
×
1380
                        return nil, fmt.Errorf("we don't have an edge")
×
1381
                }
×
1382

1383
                err = s.graphDB.DeleteChannelEdges(
2✔
1384
                        false, false, scid.ToUint64(),
2✔
1385
                )
2✔
1386
                return ourPolicy, err
2✔
1387
        }
1388

1389
        // For the reservationTimeout and the zombieSweeperInterval different
1390
        // values are set in case we are in a dev environment so enhance test
1391
        // capacilities.
1392
        reservationTimeout := chanfunding.DefaultReservationTimeout
2✔
1393
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
2✔
1394

2✔
1395
        // Get the development config for funding manager. If we are not in
2✔
1396
        // development mode, this would be nil.
2✔
1397
        var devCfg *funding.DevConfig
2✔
1398
        if lncfg.IsDevBuild() {
4✔
1399
                devCfg = &funding.DevConfig{
2✔
1400
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
2✔
1401
                }
2✔
1402

2✔
1403
                reservationTimeout = cfg.Dev.GetReservationTimeout()
2✔
1404
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
2✔
1405

2✔
1406
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
2✔
1407
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
2✔
1408
                        devCfg, reservationTimeout, zombieSweeperInterval)
2✔
1409
        }
2✔
1410

1411
        //nolint:lll
1412
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
2✔
1413
                Dev:                devCfg,
2✔
1414
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
2✔
1415
                IDKey:              nodeKeyDesc.PubKey,
2✔
1416
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
2✔
1417
                Wallet:             cc.Wallet,
2✔
1418
                PublishTransaction: cc.Wallet.PublishTransaction,
2✔
1419
                UpdateLabel: func(hash chainhash.Hash, label string) error {
4✔
1420
                        return cc.Wallet.LabelTransaction(hash, label, true)
2✔
1421
                },
2✔
1422
                Notifier:     cc.ChainNotifier,
1423
                ChannelDB:    s.chanStateDB,
1424
                FeeEstimator: cc.FeeEstimator,
1425
                SignMessage:  cc.MsgSigner.SignMessage,
1426
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1427
                        error) {
2✔
1428

2✔
1429
                        return s.genNodeAnnouncement(nil)
2✔
1430
                },
2✔
1431
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1432
                NotifyWhenOnline:     s.NotifyWhenOnline,
1433
                TempChanIDSeed:       chanIDSeed,
1434
                FindChannel:          s.findChannel,
1435
                DefaultRoutingPolicy: cc.RoutingPolicy,
1436
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1437
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1438
                        pushAmt lnwire.MilliSatoshi) uint16 {
2✔
1439
                        // For large channels we increase the number
2✔
1440
                        // of confirmations we require for the
2✔
1441
                        // channel to be considered open. As it is
2✔
1442
                        // always the responder that gets to choose
2✔
1443
                        // value, the pushAmt is value being pushed
2✔
1444
                        // to us. This means we have more to lose
2✔
1445
                        // in the case this gets re-orged out, and
2✔
1446
                        // we will require more confirmations before
2✔
1447
                        // we consider it open.
2✔
1448

2✔
1449
                        // In case the user has explicitly specified
2✔
1450
                        // a default value for the number of
2✔
1451
                        // confirmations, we use it.
2✔
1452
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
2✔
1453
                        if defaultConf != 0 {
4✔
1454
                                return defaultConf
2✔
1455
                        }
2✔
1456

1457
                        minConf := uint64(3)
×
1458
                        maxConf := uint64(6)
×
1459

×
1460
                        // If this is a wumbo channel, then we'll require the
×
1461
                        // max amount of confirmations.
×
1462
                        if chanAmt > MaxFundingAmount {
×
1463
                                return uint16(maxConf)
×
1464
                        }
×
1465

1466
                        // If not we return a value scaled linearly
1467
                        // between 3 and 6, depending on channel size.
1468
                        // TODO(halseth): Use 1 as minimum?
1469
                        maxChannelSize := uint64(
×
1470
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1471
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1472
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1473
                        if conf < minConf {
×
1474
                                conf = minConf
×
1475
                        }
×
1476
                        if conf > maxConf {
×
1477
                                conf = maxConf
×
1478
                        }
×
1479
                        return uint16(conf)
×
1480
                },
1481
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
2✔
1482
                        // We scale the remote CSV delay (the time the
2✔
1483
                        // remote have to claim funds in case of a unilateral
2✔
1484
                        // close) linearly from minRemoteDelay blocks
2✔
1485
                        // for small channels, to maxRemoteDelay blocks
2✔
1486
                        // for channels of size MaxFundingAmount.
2✔
1487

2✔
1488
                        // In case the user has explicitly specified
2✔
1489
                        // a default value for the remote delay, we
2✔
1490
                        // use it.
2✔
1491
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
2✔
1492
                        if defaultDelay > 0 {
4✔
1493
                                return defaultDelay
2✔
1494
                        }
2✔
1495

1496
                        // If this is a wumbo channel, then we'll require the
1497
                        // max value.
1498
                        if chanAmt > MaxFundingAmount {
×
1499
                                return maxRemoteDelay
×
1500
                        }
×
1501

1502
                        // If not we scale according to channel size.
1503
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1504
                                chanAmt / MaxFundingAmount)
×
1505
                        if delay < minRemoteDelay {
×
1506
                                delay = minRemoteDelay
×
1507
                        }
×
1508
                        if delay > maxRemoteDelay {
×
1509
                                delay = maxRemoteDelay
×
1510
                        }
×
1511
                        return delay
×
1512
                },
1513
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1514
                        peerKey *btcec.PublicKey) error {
2✔
1515

2✔
1516
                        // First, we'll mark this new peer as a persistent peer
2✔
1517
                        // for re-connection purposes. If the peer is not yet
2✔
1518
                        // tracked or the user hasn't requested it to be perm,
2✔
1519
                        // we'll set false to prevent the server from continuing
2✔
1520
                        // to connect to this peer even if the number of
2✔
1521
                        // channels with this peer is zero.
2✔
1522
                        s.mu.Lock()
2✔
1523
                        pubStr := string(peerKey.SerializeCompressed())
2✔
1524
                        if _, ok := s.persistentPeers[pubStr]; !ok {
4✔
1525
                                s.persistentPeers[pubStr] = false
2✔
1526
                        }
2✔
1527
                        s.mu.Unlock()
2✔
1528

2✔
1529
                        // With that taken care of, we'll send this channel to
2✔
1530
                        // the chain arb so it can react to on-chain events.
2✔
1531
                        return s.chainArb.WatchNewChannel(channel)
2✔
1532
                },
1533
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
2✔
1534
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
2✔
1535
                        return s.htlcSwitch.UpdateShortChanID(cid)
2✔
1536
                },
2✔
1537
                RequiredRemoteChanReserve: func(chanAmt,
1538
                        dustLimit btcutil.Amount) btcutil.Amount {
2✔
1539

2✔
1540
                        // By default, we'll require the remote peer to maintain
2✔
1541
                        // at least 1% of the total channel capacity at all
2✔
1542
                        // times. If this value ends up dipping below the dust
2✔
1543
                        // limit, then we'll use the dust limit itself as the
2✔
1544
                        // reserve as required by BOLT #2.
2✔
1545
                        reserve := chanAmt / 100
2✔
1546
                        if reserve < dustLimit {
4✔
1547
                                reserve = dustLimit
2✔
1548
                        }
2✔
1549

1550
                        return reserve
2✔
1551
                },
1552
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
2✔
1553
                        // By default, we'll allow the remote peer to fully
2✔
1554
                        // utilize the full bandwidth of the channel, minus our
2✔
1555
                        // required reserve.
2✔
1556
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
2✔
1557
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
2✔
1558
                },
2✔
1559
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
2✔
1560
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
4✔
1561
                                return cfg.DefaultRemoteMaxHtlcs
2✔
1562
                        }
2✔
1563

1564
                        // By default, we'll permit them to utilize the full
1565
                        // channel bandwidth.
1566
                        return uint16(input.MaxHTLCNumber / 2)
×
1567
                },
1568
                ZombieSweeperInterval:         zombieSweeperInterval,
1569
                ReservationTimeout:            reservationTimeout,
1570
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1571
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1572
                MaxPendingChannels:            cfg.MaxPendingChannels,
1573
                RejectPush:                    cfg.RejectPush,
1574
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1575
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1576
                OpenChannelPredicate:          chanPredicate,
1577
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1578
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1579
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1580
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1581
                DeleteAliasEdge:      deleteAliasEdge,
1582
                AliasManager:         s.aliasMgr,
1583
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1584
                AuxFundingController: implCfg.AuxFundingController,
1585
                AuxSigner:            implCfg.AuxSigner,
1586
                AuxResolver:          implCfg.AuxContractResolver,
1587
        })
1588
        if err != nil {
2✔
1589
                return nil, err
×
1590
        }
×
1591

1592
        // Next, we'll assemble the sub-system that will maintain an on-disk
1593
        // static backup of the latest channel state.
1594
        chanNotifier := &channelNotifier{
2✔
1595
                chanNotifier: s.channelNotifier,
2✔
1596
                addrs:        dbs.ChanStateDB,
2✔
1597
        }
2✔
1598
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
2✔
1599
        startingChans, err := chanbackup.FetchStaticChanBackups(
2✔
1600
                s.chanStateDB, s.addrSource,
2✔
1601
        )
2✔
1602
        if err != nil {
2✔
1603
                return nil, err
×
1604
        }
×
1605
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
2✔
1606
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
2✔
1607
        )
2✔
1608
        if err != nil {
2✔
1609
                return nil, err
×
1610
        }
×
1611

1612
        // Assemble a peer notifier which will provide clients with subscriptions
1613
        // to peer online and offline events.
1614
        s.peerNotifier = peernotifier.New()
2✔
1615

2✔
1616
        // Create a channel event store which monitors all open channels.
2✔
1617
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
2✔
1618
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
4✔
1619
                        return s.channelNotifier.SubscribeChannelEvents()
2✔
1620
                },
2✔
1621
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
2✔
1622
                        return s.peerNotifier.SubscribePeerEvents()
2✔
1623
                },
2✔
1624
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1625
                Clock:           clock.NewDefaultClock(),
1626
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1627
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1628
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1629
        })
1630

1631
        if cfg.WtClient.Active {
4✔
1632
                policy := wtpolicy.DefaultPolicy()
2✔
1633
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
2✔
1634

2✔
1635
                // We expose the sweep fee rate in sat/vbyte, but the tower
2✔
1636
                // protocol operations on sat/kw.
2✔
1637
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
2✔
1638
                        1000 * cfg.WtClient.SweepFeeRate,
2✔
1639
                )
2✔
1640

2✔
1641
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
2✔
1642

2✔
1643
                if err := policy.Validate(); err != nil {
2✔
1644
                        return nil, err
×
1645
                }
×
1646

1647
                // authDial is the wrapper around the btrontide.Dial for the
1648
                // watchtower.
1649
                authDial := func(localKey keychain.SingleKeyECDH,
2✔
1650
                        netAddr *lnwire.NetAddress,
2✔
1651
                        dialer tor.DialFunc) (wtserver.Peer, error) {
4✔
1652

2✔
1653
                        return brontide.Dial(
2✔
1654
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
2✔
1655
                        )
2✔
1656
                }
2✔
1657

1658
                // buildBreachRetribution is a call-back that can be used to
1659
                // query the BreachRetribution info and channel type given a
1660
                // channel ID and commitment height.
1661
                buildBreachRetribution := func(chanID lnwire.ChannelID,
2✔
1662
                        commitHeight uint64) (*lnwallet.BreachRetribution,
2✔
1663
                        channeldb.ChannelType, error) {
4✔
1664

2✔
1665
                        channel, err := s.chanStateDB.FetchChannelByID(
2✔
1666
                                nil, chanID,
2✔
1667
                        )
2✔
1668
                        if err != nil {
2✔
1669
                                return nil, 0, err
×
1670
                        }
×
1671

1672
                        br, err := lnwallet.NewBreachRetribution(
2✔
1673
                                channel, commitHeight, 0, nil,
2✔
1674
                                implCfg.AuxLeafStore,
2✔
1675
                                implCfg.AuxContractResolver,
2✔
1676
                        )
2✔
1677
                        if err != nil {
2✔
1678
                                return nil, 0, err
×
1679
                        }
×
1680

1681
                        return br, channel.ChanType, nil
2✔
1682
                }
1683

1684
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
2✔
1685

2✔
1686
                // Copy the policy for legacy channels and set the blob flag
2✔
1687
                // signalling support for anchor channels.
2✔
1688
                anchorPolicy := policy
2✔
1689
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
2✔
1690

2✔
1691
                // Copy the policy for legacy channels and set the blob flag
2✔
1692
                // signalling support for taproot channels.
2✔
1693
                taprootPolicy := policy
2✔
1694
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
2✔
1695
                        blob.FlagTaprootChannel,
2✔
1696
                )
2✔
1697

2✔
1698
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
2✔
1699
                        FetchClosedChannel:     fetchClosedChannel,
2✔
1700
                        BuildBreachRetribution: buildBreachRetribution,
2✔
1701
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
2✔
1702
                        ChainNotifier:          s.cc.ChainNotifier,
2✔
1703
                        SubscribeChannelEvents: func() (subscribe.Subscription,
2✔
1704
                                error) {
4✔
1705

2✔
1706
                                return s.channelNotifier.
2✔
1707
                                        SubscribeChannelEvents()
2✔
1708
                        },
2✔
1709
                        Signer: cc.Wallet.Cfg.Signer,
1710
                        NewAddress: func() ([]byte, error) {
2✔
1711
                                addr, err := newSweepPkScriptGen(
2✔
1712
                                        cc.Wallet, netParams,
2✔
1713
                                )().Unpack()
2✔
1714
                                if err != nil {
2✔
1715
                                        return nil, err
×
1716
                                }
×
1717

1718
                                return addr.DeliveryAddress, nil
2✔
1719
                        },
1720
                        SecretKeyRing:      s.cc.KeyRing,
1721
                        Dial:               cfg.net.Dial,
1722
                        AuthDial:           authDial,
1723
                        DB:                 dbs.TowerClientDB,
1724
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1725
                        MinBackoff:         10 * time.Second,
1726
                        MaxBackoff:         5 * time.Minute,
1727
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1728
                }, policy, anchorPolicy, taprootPolicy)
1729
                if err != nil {
2✔
1730
                        return nil, err
×
1731
                }
×
1732
        }
1733

1734
        if len(cfg.ExternalHosts) != 0 {
2✔
1735
                advertisedIPs := make(map[string]struct{})
×
1736
                for _, addr := range s.currentNodeAnn.Addresses {
×
1737
                        advertisedIPs[addr.String()] = struct{}{}
×
1738
                }
×
1739

1740
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1741
                        Hosts:         cfg.ExternalHosts,
×
1742
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1743
                        LookupHost: func(host string) (net.Addr, error) {
×
1744
                                return lncfg.ParseAddressString(
×
1745
                                        host, strconv.Itoa(defaultPeerPort),
×
1746
                                        cfg.net.ResolveTCPAddr,
×
1747
                                )
×
1748
                        },
×
1749
                        AdvertisedIPs: advertisedIPs,
1750
                        AnnounceNewIPs: netann.IPAnnouncer(
1751
                                func(modifier ...netann.NodeAnnModifier) (
1752
                                        lnwire.NodeAnnouncement, error) {
×
1753

×
1754
                                        return s.genNodeAnnouncement(
×
1755
                                                nil, modifier...,
×
1756
                                        )
×
1757
                                }),
×
1758
                })
1759
        }
1760

1761
        // Create liveness monitor.
1762
        s.createLivenessMonitor(cfg, cc, leaderElector)
2✔
1763

2✔
1764
        // Create the connection manager which will be responsible for
2✔
1765
        // maintaining persistent outbound connections and also accepting new
2✔
1766
        // incoming connections
2✔
1767
        cmgr, err := connmgr.New(&connmgr.Config{
2✔
1768
                Listeners:      listeners,
2✔
1769
                OnAccept:       s.InboundPeerConnected,
2✔
1770
                RetryDuration:  time.Second * 5,
2✔
1771
                TargetOutbound: 100,
2✔
1772
                Dial: noiseDial(
2✔
1773
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
2✔
1774
                ),
2✔
1775
                OnConnection: s.OutboundPeerConnected,
2✔
1776
        })
2✔
1777
        if err != nil {
2✔
1778
                return nil, err
×
1779
        }
×
1780
        s.connMgr = cmgr
2✔
1781

2✔
1782
        return s, nil
2✔
1783
}
1784

1785
// UpdateRoutingConfig is a callback function to update the routing config
1786
// values in the main cfg.
1787
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
2✔
1788
        routerCfg := s.cfg.SubRPCServers.RouterRPC
2✔
1789

2✔
1790
        switch c := cfg.Estimator.Config().(type) {
2✔
1791
        case routing.AprioriConfig:
2✔
1792
                routerCfg.ProbabilityEstimatorType =
2✔
1793
                        routing.AprioriEstimatorName
2✔
1794

2✔
1795
                targetCfg := routerCfg.AprioriConfig
2✔
1796
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
2✔
1797
                targetCfg.Weight = c.AprioriWeight
2✔
1798
                targetCfg.CapacityFraction = c.CapacityFraction
2✔
1799
                targetCfg.HopProbability = c.AprioriHopProbability
2✔
1800

1801
        case routing.BimodalConfig:
2✔
1802
                routerCfg.ProbabilityEstimatorType =
2✔
1803
                        routing.BimodalEstimatorName
2✔
1804

2✔
1805
                targetCfg := routerCfg.BimodalConfig
2✔
1806
                targetCfg.Scale = int64(c.BimodalScaleMsat)
2✔
1807
                targetCfg.NodeWeight = c.BimodalNodeWeight
2✔
1808
                targetCfg.DecayTime = c.BimodalDecayTime
2✔
1809
        }
1810

1811
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
2✔
1812
}
1813

1814
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1815
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1816
// may differ from what is on disk.
1817
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1818
        error) {
2✔
1819

2✔
1820
        data, err := u.DataToSign()
2✔
1821
        if err != nil {
2✔
1822
                return nil, err
×
1823
        }
×
1824

1825
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
2✔
1826
}
1827

1828
// createLivenessMonitor creates a set of health checks using our configured
1829
// values and uses these checks to create a liveness monitor. Available
1830
// health checks,
1831
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1832
//   - diskCheck
1833
//   - tlsHealthCheck
1834
//   - torController, only created when tor is enabled.
1835
//
1836
// If a health check has been disabled by setting attempts to 0, our monitor
1837
// will not run it.
1838
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1839
        leaderElector cluster.LeaderElector) {
2✔
1840

2✔
1841
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
2✔
1842
        if cfg.Bitcoin.Node == "nochainbackend" {
2✔
1843
                srvrLog.Info("Disabling chain backend checks for " +
×
1844
                        "nochainbackend mode")
×
1845

×
1846
                chainBackendAttempts = 0
×
1847
        }
×
1848

1849
        chainHealthCheck := healthcheck.NewObservation(
2✔
1850
                "chain backend",
2✔
1851
                cc.HealthCheck,
2✔
1852
                cfg.HealthChecks.ChainCheck.Interval,
2✔
1853
                cfg.HealthChecks.ChainCheck.Timeout,
2✔
1854
                cfg.HealthChecks.ChainCheck.Backoff,
2✔
1855
                chainBackendAttempts,
2✔
1856
        )
2✔
1857

2✔
1858
        diskCheck := healthcheck.NewObservation(
2✔
1859
                "disk space",
2✔
1860
                func() error {
2✔
1861
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1862
                                cfg.LndDir,
×
1863
                        )
×
1864
                        if err != nil {
×
1865
                                return err
×
1866
                        }
×
1867

1868
                        // If we have more free space than we require,
1869
                        // we return a nil error.
1870
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1871
                                return nil
×
1872
                        }
×
1873

1874
                        return fmt.Errorf("require: %v free space, got: %v",
×
1875
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1876
                                free)
×
1877
                },
1878
                cfg.HealthChecks.DiskCheck.Interval,
1879
                cfg.HealthChecks.DiskCheck.Timeout,
1880
                cfg.HealthChecks.DiskCheck.Backoff,
1881
                cfg.HealthChecks.DiskCheck.Attempts,
1882
        )
1883

1884
        tlsHealthCheck := healthcheck.NewObservation(
2✔
1885
                "tls",
2✔
1886
                func() error {
2✔
1887
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1888
                                s.cc.KeyRing,
×
1889
                        )
×
1890
                        if err != nil {
×
1891
                                return err
×
1892
                        }
×
1893
                        if expired {
×
1894
                                return fmt.Errorf("TLS certificate is "+
×
1895
                                        "expired as of %v", expTime)
×
1896
                        }
×
1897

1898
                        // If the certificate is not outdated, no error needs
1899
                        // to be returned
1900
                        return nil
×
1901
                },
1902
                cfg.HealthChecks.TLSCheck.Interval,
1903
                cfg.HealthChecks.TLSCheck.Timeout,
1904
                cfg.HealthChecks.TLSCheck.Backoff,
1905
                cfg.HealthChecks.TLSCheck.Attempts,
1906
        )
1907

1908
        checks := []*healthcheck.Observation{
2✔
1909
                chainHealthCheck, diskCheck, tlsHealthCheck,
2✔
1910
        }
2✔
1911

2✔
1912
        // If Tor is enabled, add the healthcheck for tor connection.
2✔
1913
        if s.torController != nil {
2✔
1914
                torConnectionCheck := healthcheck.NewObservation(
×
1915
                        "tor connection",
×
1916
                        func() error {
×
1917
                                return healthcheck.CheckTorServiceStatus(
×
1918
                                        s.torController,
×
1919
                                        s.createNewHiddenService,
×
1920
                                )
×
1921
                        },
×
1922
                        cfg.HealthChecks.TorConnection.Interval,
1923
                        cfg.HealthChecks.TorConnection.Timeout,
1924
                        cfg.HealthChecks.TorConnection.Backoff,
1925
                        cfg.HealthChecks.TorConnection.Attempts,
1926
                )
1927
                checks = append(checks, torConnectionCheck)
×
1928
        }
1929

1930
        // If remote signing is enabled, add the healthcheck for the remote
1931
        // signing RPC interface.
1932
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
4✔
1933
                // Because we have two cascading timeouts here, we need to add
2✔
1934
                // some slack to the "outer" one of them in case the "inner"
2✔
1935
                // returns exactly on time.
2✔
1936
                overhead := time.Millisecond * 10
2✔
1937

2✔
1938
                remoteSignerConnectionCheck := healthcheck.NewObservation(
2✔
1939
                        "remote signer connection",
2✔
1940
                        rpcwallet.HealthCheck(
2✔
1941
                                s.cfg.RemoteSigner,
2✔
1942

2✔
1943
                                // For the health check we might to be even
2✔
1944
                                // stricter than the initial/normal connect, so
2✔
1945
                                // we use the health check timeout here.
2✔
1946
                                cfg.HealthChecks.RemoteSigner.Timeout,
2✔
1947
                        ),
2✔
1948
                        cfg.HealthChecks.RemoteSigner.Interval,
2✔
1949
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
2✔
1950
                        cfg.HealthChecks.RemoteSigner.Backoff,
2✔
1951
                        cfg.HealthChecks.RemoteSigner.Attempts,
2✔
1952
                )
2✔
1953
                checks = append(checks, remoteSignerConnectionCheck)
2✔
1954
        }
2✔
1955

1956
        // If we have a leader elector, we add a health check to ensure we are
1957
        // still the leader. During normal operation, we should always be the
1958
        // leader, but there are circumstances where this may change, such as
1959
        // when we lose network connectivity for long enough expiring out lease.
1960
        if leaderElector != nil {
2✔
1961
                leaderCheck := healthcheck.NewObservation(
×
1962
                        "leader status",
×
1963
                        func() error {
×
1964
                                // Check if we are still the leader. Note that
×
1965
                                // we don't need to use a timeout context here
×
1966
                                // as the healthcheck observer will handle the
×
1967
                                // timeout case for us.
×
1968
                                timeoutCtx, cancel := context.WithTimeout(
×
1969
                                        context.Background(),
×
1970
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
1971
                                )
×
1972
                                defer cancel()
×
1973

×
1974
                                leader, err := leaderElector.IsLeader(
×
1975
                                        timeoutCtx,
×
1976
                                )
×
1977
                                if err != nil {
×
1978
                                        return fmt.Errorf("unable to check if "+
×
1979
                                                "still leader: %v", err)
×
1980
                                }
×
1981

1982
                                if !leader {
×
1983
                                        srvrLog.Debug("Not the current leader")
×
1984
                                        return fmt.Errorf("not the current " +
×
1985
                                                "leader")
×
1986
                                }
×
1987

1988
                                return nil
×
1989
                        },
1990
                        cfg.HealthChecks.LeaderCheck.Interval,
1991
                        cfg.HealthChecks.LeaderCheck.Timeout,
1992
                        cfg.HealthChecks.LeaderCheck.Backoff,
1993
                        cfg.HealthChecks.LeaderCheck.Attempts,
1994
                )
1995

1996
                checks = append(checks, leaderCheck)
×
1997
        }
1998

1999
        // If we have not disabled all of our health checks, we create a
2000
        // liveness monitor with our configured checks.
2001
        s.livenessMonitor = healthcheck.NewMonitor(
2✔
2002
                &healthcheck.Config{
2✔
2003
                        Checks:   checks,
2✔
2004
                        Shutdown: srvrLog.Criticalf,
2✔
2005
                },
2✔
2006
        )
2✔
2007
}
2008

2009
// Started returns true if the server has been started, and false otherwise.
2010
// NOTE: This function is safe for concurrent access.
2011
func (s *server) Started() bool {
2✔
2012
        return atomic.LoadInt32(&s.active) != 0
2✔
2013
}
2✔
2014

2015
// cleaner is used to aggregate "cleanup" functions during an operation that
2016
// starts several subsystems. In case one of the subsystem fails to start
2017
// and a proper resource cleanup is required, the "run" method achieves this
2018
// by running all these added "cleanup" functions.
2019
type cleaner []func() error
2020

2021
// add is used to add a cleanup function to be called when
2022
// the run function is executed.
2023
func (c cleaner) add(cleanup func() error) cleaner {
2✔
2024
        return append(c, cleanup)
2✔
2025
}
2✔
2026

2027
// run is used to run all the previousely added cleanup functions.
2028
func (c cleaner) run() {
×
2029
        for i := len(c) - 1; i >= 0; i-- {
×
2030
                if err := c[i](); err != nil {
×
2031
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2032
                }
×
2033
        }
2034
}
2035

2036
// Start starts the main daemon server, all requested listeners, and any helper
2037
// goroutines.
2038
// NOTE: This function is safe for concurrent access.
2039
//
2040
//nolint:funlen
2041
func (s *server) Start() error {
2✔
2042
        var startErr error
2✔
2043

2✔
2044
        // If one sub system fails to start, the following code ensures that the
2✔
2045
        // previous started ones are stopped. It also ensures a proper wallet
2✔
2046
        // shutdown which is important for releasing its resources (boltdb, etc...)
2✔
2047
        cleanup := cleaner{}
2✔
2048

2✔
2049
        s.start.Do(func() {
4✔
2050
                cleanup = cleanup.add(s.customMessageServer.Stop)
2✔
2051
                if err := s.customMessageServer.Start(); err != nil {
2✔
2052
                        startErr = err
×
2053
                        return
×
2054
                }
×
2055

2056
                if s.hostAnn != nil {
2✔
2057
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2058
                        if err := s.hostAnn.Start(); err != nil {
×
2059
                                startErr = err
×
2060
                                return
×
2061
                        }
×
2062
                }
2063

2064
                if s.livenessMonitor != nil {
4✔
2065
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
2✔
2066
                        if err := s.livenessMonitor.Start(); err != nil {
2✔
2067
                                startErr = err
×
2068
                                return
×
2069
                        }
×
2070
                }
2071

2072
                // Start the notification server. This is used so channel
2073
                // management goroutines can be notified when a funding
2074
                // transaction reaches a sufficient number of confirmations, or
2075
                // when the input for the funding transaction is spent in an
2076
                // attempt at an uncooperative close by the counterparty.
2077
                cleanup = cleanup.add(s.sigPool.Stop)
2✔
2078
                if err := s.sigPool.Start(); err != nil {
2✔
2079
                        startErr = err
×
2080
                        return
×
2081
                }
×
2082

2083
                cleanup = cleanup.add(s.writePool.Stop)
2✔
2084
                if err := s.writePool.Start(); err != nil {
2✔
2085
                        startErr = err
×
2086
                        return
×
2087
                }
×
2088

2089
                cleanup = cleanup.add(s.readPool.Stop)
2✔
2090
                if err := s.readPool.Start(); err != nil {
2✔
2091
                        startErr = err
×
2092
                        return
×
2093
                }
×
2094

2095
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
2✔
2096
                if err := s.cc.ChainNotifier.Start(); err != nil {
2✔
2097
                        startErr = err
×
2098
                        return
×
2099
                }
×
2100

2101
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
2✔
2102
                if err := s.cc.BestBlockTracker.Start(); err != nil {
2✔
2103
                        startErr = err
×
2104
                        return
×
2105
                }
×
2106

2107
                cleanup = cleanup.add(s.channelNotifier.Stop)
2✔
2108
                if err := s.channelNotifier.Start(); err != nil {
2✔
2109
                        startErr = err
×
2110
                        return
×
2111
                }
×
2112

2113
                cleanup = cleanup.add(func() error {
2✔
2114
                        return s.peerNotifier.Stop()
×
2115
                })
×
2116
                if err := s.peerNotifier.Start(); err != nil {
2✔
2117
                        startErr = err
×
2118
                        return
×
2119
                }
×
2120

2121
                cleanup = cleanup.add(s.htlcNotifier.Stop)
2✔
2122
                if err := s.htlcNotifier.Start(); err != nil {
2✔
2123
                        startErr = err
×
2124
                        return
×
2125
                }
×
2126

2127
                if s.towerClientMgr != nil {
4✔
2128
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
2✔
2129
                        if err := s.towerClientMgr.Start(); err != nil {
2✔
2130
                                startErr = err
×
2131
                                return
×
2132
                        }
×
2133
                }
2134

2135
                cleanup = cleanup.add(s.txPublisher.Stop)
2✔
2136
                if err := s.txPublisher.Start(); err != nil {
2✔
2137
                        startErr = err
×
2138
                        return
×
2139
                }
×
2140

2141
                cleanup = cleanup.add(s.sweeper.Stop)
2✔
2142
                if err := s.sweeper.Start(); err != nil {
2✔
2143
                        startErr = err
×
2144
                        return
×
2145
                }
×
2146

2147
                cleanup = cleanup.add(s.utxoNursery.Stop)
2✔
2148
                if err := s.utxoNursery.Start(); err != nil {
2✔
2149
                        startErr = err
×
2150
                        return
×
2151
                }
×
2152

2153
                cleanup = cleanup.add(s.breachArbitrator.Stop)
2✔
2154
                if err := s.breachArbitrator.Start(); err != nil {
2✔
2155
                        startErr = err
×
2156
                        return
×
2157
                }
×
2158

2159
                cleanup = cleanup.add(s.fundingMgr.Stop)
2✔
2160
                if err := s.fundingMgr.Start(); err != nil {
2✔
2161
                        startErr = err
×
2162
                        return
×
2163
                }
×
2164

2165
                // htlcSwitch must be started before chainArb since the latter
2166
                // relies on htlcSwitch to deliver resolution message upon
2167
                // start.
2168
                cleanup = cleanup.add(s.htlcSwitch.Stop)
2✔
2169
                if err := s.htlcSwitch.Start(); err != nil {
2✔
2170
                        startErr = err
×
2171
                        return
×
2172
                }
×
2173

2174
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
2✔
2175
                if err := s.interceptableSwitch.Start(); err != nil {
2✔
2176
                        startErr = err
×
2177
                        return
×
2178
                }
×
2179

2180
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
2✔
2181
                if err := s.invoiceHtlcModifier.Start(); err != nil {
2✔
2182
                        startErr = err
×
2183
                        return
×
2184
                }
×
2185

2186
                cleanup = cleanup.add(s.chainArb.Stop)
2✔
2187
                if err := s.chainArb.Start(); err != nil {
2✔
2188
                        startErr = err
×
2189
                        return
×
2190
                }
×
2191

2192
                cleanup = cleanup.add(s.graphBuilder.Stop)
2✔
2193
                if err := s.graphBuilder.Start(); err != nil {
2✔
2194
                        startErr = err
×
2195
                        return
×
2196
                }
×
2197

2198
                cleanup = cleanup.add(s.chanRouter.Stop)
2✔
2199
                if err := s.chanRouter.Start(); err != nil {
2✔
2200
                        startErr = err
×
2201
                        return
×
2202
                }
×
2203
                // The authGossiper depends on the chanRouter and therefore
2204
                // should be started after it.
2205
                cleanup = cleanup.add(s.authGossiper.Stop)
2✔
2206
                if err := s.authGossiper.Start(); err != nil {
2✔
2207
                        startErr = err
×
2208
                        return
×
2209
                }
×
2210

2211
                cleanup = cleanup.add(s.invoices.Stop)
2✔
2212
                if err := s.invoices.Start(); err != nil {
2✔
2213
                        startErr = err
×
2214
                        return
×
2215
                }
×
2216

2217
                cleanup = cleanup.add(s.sphinx.Stop)
2✔
2218
                if err := s.sphinx.Start(); err != nil {
2✔
2219
                        startErr = err
×
2220
                        return
×
2221
                }
×
2222

2223
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
2✔
2224
                if err := s.chanStatusMgr.Start(); err != nil {
2✔
2225
                        startErr = err
×
2226
                        return
×
2227
                }
×
2228

2229
                cleanup = cleanup.add(s.chanEventStore.Stop)
2✔
2230
                if err := s.chanEventStore.Start(); err != nil {
2✔
2231
                        startErr = err
×
2232
                        return
×
2233
                }
×
2234

2235
                cleanup.add(func() error {
2✔
2236
                        s.missionController.StopStoreTickers()
×
2237
                        return nil
×
2238
                })
×
2239
                s.missionController.RunStoreTickers()
2✔
2240

2✔
2241
                // Before we start the connMgr, we'll check to see if we have
2✔
2242
                // any backups to recover. We do this now as we want to ensure
2✔
2243
                // that have all the information we need to handle channel
2✔
2244
                // recovery _before_ we even accept connections from any peers.
2✔
2245
                chanRestorer := &chanDBRestorer{
2✔
2246
                        db:         s.chanStateDB,
2✔
2247
                        secretKeys: s.cc.KeyRing,
2✔
2248
                        chainArb:   s.chainArb,
2✔
2249
                }
2✔
2250
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
2✔
2251
                        err := chanbackup.UnpackAndRecoverSingles(
×
2252
                                s.chansToRestore.PackedSingleChanBackups,
×
2253
                                s.cc.KeyRing, chanRestorer, s,
×
2254
                        )
×
2255
                        if err != nil {
×
2256
                                startErr = fmt.Errorf("unable to unpack single "+
×
2257
                                        "backups: %v", err)
×
2258
                                return
×
2259
                        }
×
2260
                }
2261
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
4✔
2262
                        err := chanbackup.UnpackAndRecoverMulti(
2✔
2263
                                s.chansToRestore.PackedMultiChanBackup,
2✔
2264
                                s.cc.KeyRing, chanRestorer, s,
2✔
2265
                        )
2✔
2266
                        if err != nil {
2✔
2267
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2268
                                        "backup: %v", err)
×
2269
                                return
×
2270
                        }
×
2271
                }
2272

2273
                // chanSubSwapper must be started after the `channelNotifier`
2274
                // because it depends on channel events as a synchronization
2275
                // point.
2276
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
2✔
2277
                if err := s.chanSubSwapper.Start(); err != nil {
2✔
2278
                        startErr = err
×
2279
                        return
×
2280
                }
×
2281

2282
                if s.torController != nil {
2✔
2283
                        cleanup = cleanup.add(s.torController.Stop)
×
2284
                        if err := s.createNewHiddenService(); err != nil {
×
2285
                                startErr = err
×
2286
                                return
×
2287
                        }
×
2288
                }
2289

2290
                if s.natTraversal != nil {
2✔
2291
                        s.wg.Add(1)
×
2292
                        go s.watchExternalIP()
×
2293
                }
×
2294

2295
                // Start connmgr last to prevent connections before init.
2296
                cleanup = cleanup.add(func() error {
2✔
2297
                        s.connMgr.Stop()
×
2298
                        return nil
×
2299
                })
×
2300
                s.connMgr.Start()
2✔
2301

2✔
2302
                // If peers are specified as a config option, we'll add those
2✔
2303
                // peers first.
2✔
2304
                for _, peerAddrCfg := range s.cfg.AddPeers {
4✔
2305
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
2✔
2306
                                peerAddrCfg,
2✔
2307
                        )
2✔
2308
                        if err != nil {
2✔
2309
                                startErr = fmt.Errorf("unable to parse peer "+
×
2310
                                        "pubkey from config: %v", err)
×
2311
                                return
×
2312
                        }
×
2313
                        addr, err := parseAddr(parsedHost, s.cfg.net)
2✔
2314
                        if err != nil {
2✔
2315
                                startErr = fmt.Errorf("unable to parse peer "+
×
2316
                                        "address provided as a config option: "+
×
2317
                                        "%v", err)
×
2318
                                return
×
2319
                        }
×
2320

2321
                        peerAddr := &lnwire.NetAddress{
2✔
2322
                                IdentityKey: parsedPubkey,
2✔
2323
                                Address:     addr,
2✔
2324
                                ChainNet:    s.cfg.ActiveNetParams.Net,
2✔
2325
                        }
2✔
2326

2✔
2327
                        err = s.ConnectToPeer(
2✔
2328
                                peerAddr, true,
2✔
2329
                                s.cfg.ConnectionTimeout,
2✔
2330
                        )
2✔
2331
                        if err != nil {
2✔
2332
                                startErr = fmt.Errorf("unable to connect to "+
×
2333
                                        "peer address provided as a config "+
×
2334
                                        "option: %v", err)
×
2335
                                return
×
2336
                        }
×
2337
                }
2338

2339
                // Subscribe to NodeAnnouncements that advertise new addresses
2340
                // our persistent peers.
2341
                if err := s.updatePersistentPeerAddrs(); err != nil {
2✔
2342
                        startErr = err
×
2343
                        return
×
2344
                }
×
2345

2346
                // With all the relevant sub-systems started, we'll now attempt
2347
                // to establish persistent connections to our direct channel
2348
                // collaborators within the network. Before doing so however,
2349
                // we'll prune our set of link nodes found within the database
2350
                // to ensure we don't reconnect to any nodes we no longer have
2351
                // open channels with.
2352
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
2✔
2353
                        startErr = err
×
2354
                        return
×
2355
                }
×
2356
                if err := s.establishPersistentConnections(); err != nil {
2✔
2357
                        startErr = err
×
2358
                        return
×
2359
                }
×
2360

2361
                // setSeedList is a helper function that turns multiple DNS seed
2362
                // server tuples from the command line or config file into the
2363
                // data structure we need and does a basic formal sanity check
2364
                // in the process.
2365
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
2✔
2366
                        if len(tuples) == 0 {
×
2367
                                return
×
2368
                        }
×
2369

2370
                        result := make([][2]string, len(tuples))
×
2371
                        for idx, tuple := range tuples {
×
2372
                                tuple = strings.TrimSpace(tuple)
×
2373
                                if len(tuple) == 0 {
×
2374
                                        return
×
2375
                                }
×
2376

2377
                                servers := strings.Split(tuple, ",")
×
2378
                                if len(servers) > 2 || len(servers) == 0 {
×
2379
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2380
                                                "seed tuple: %v", servers)
×
2381
                                        return
×
2382
                                }
×
2383

2384
                                copy(result[idx][:], servers)
×
2385
                        }
2386

2387
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2388
                }
2389

2390
                // Let users overwrite the DNS seed nodes. We only allow them
2391
                // for bitcoin mainnet/testnet/signet.
2392
                if s.cfg.Bitcoin.MainNet {
2✔
2393
                        setSeedList(
×
2394
                                s.cfg.Bitcoin.DNSSeeds,
×
2395
                                chainreg.BitcoinMainnetGenesis,
×
2396
                        )
×
2397
                }
×
2398
                if s.cfg.Bitcoin.TestNet3 {
2✔
2399
                        setSeedList(
×
2400
                                s.cfg.Bitcoin.DNSSeeds,
×
2401
                                chainreg.BitcoinTestnetGenesis,
×
2402
                        )
×
2403
                }
×
2404
                if s.cfg.Bitcoin.SigNet {
2✔
2405
                        setSeedList(
×
2406
                                s.cfg.Bitcoin.DNSSeeds,
×
2407
                                chainreg.BitcoinSignetGenesis,
×
2408
                        )
×
2409
                }
×
2410

2411
                // If network bootstrapping hasn't been disabled, then we'll
2412
                // configure the set of active bootstrappers, and launch a
2413
                // dedicated goroutine to maintain a set of persistent
2414
                // connections.
2415
                if shouldPeerBootstrap(s.cfg) {
2✔
2416
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2417
                        if err != nil {
×
2418
                                startErr = err
×
2419
                                return
×
2420
                        }
×
2421

2422
                        s.wg.Add(1)
×
2423
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2424
                } else {
2✔
2425
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
2✔
2426
                }
2✔
2427

2428
                // Set the active flag now that we've completed the full
2429
                // startup.
2430
                atomic.StoreInt32(&s.active, 1)
2✔
2431
        })
2432

2433
        if startErr != nil {
2✔
2434
                cleanup.run()
×
2435
        }
×
2436
        return startErr
2✔
2437
}
2438

2439
// Stop gracefully shutsdown the main daemon server. This function will signal
2440
// any active goroutines, or helper objects to exit, then blocks until they've
2441
// all successfully exited. Additionally, any/all listeners are closed.
2442
// NOTE: This function is safe for concurrent access.
2443
func (s *server) Stop() error {
2✔
2444
        s.stop.Do(func() {
4✔
2445
                atomic.StoreInt32(&s.stopping, 1)
2✔
2446

2✔
2447
                close(s.quit)
2✔
2448

2✔
2449
                // Shutdown connMgr first to prevent conns during shutdown.
2✔
2450
                s.connMgr.Stop()
2✔
2451

2✔
2452
                // Shutdown the wallet, funding manager, and the rpc server.
2✔
2453
                if err := s.chanStatusMgr.Stop(); err != nil {
2✔
2454
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2455
                }
×
2456
                if err := s.htlcSwitch.Stop(); err != nil {
2✔
2457
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2458
                }
×
2459
                if err := s.sphinx.Stop(); err != nil {
2✔
2460
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2461
                }
×
2462
                if err := s.invoices.Stop(); err != nil {
2✔
2463
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2464
                }
×
2465
                if err := s.interceptableSwitch.Stop(); err != nil {
2✔
2466
                        srvrLog.Warnf("failed to stop interceptable "+
×
2467
                                "switch: %v", err)
×
2468
                }
×
2469
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
2✔
2470
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2471
                                "modifier: %v", err)
×
2472
                }
×
2473
                if err := s.chanRouter.Stop(); err != nil {
2✔
2474
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2475
                }
×
2476
                if err := s.chainArb.Stop(); err != nil {
2✔
2477
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2478
                }
×
2479
                if err := s.fundingMgr.Stop(); err != nil {
2✔
2480
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2481
                }
×
2482
                if err := s.breachArbitrator.Stop(); err != nil {
2✔
2483
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2484
                                err)
×
2485
                }
×
2486
                if err := s.utxoNursery.Stop(); err != nil {
2✔
2487
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2488
                }
×
2489
                if err := s.authGossiper.Stop(); err != nil {
2✔
2490
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2491
                }
×
2492
                if err := s.sweeper.Stop(); err != nil {
2✔
2493
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2494
                }
×
2495
                if err := s.txPublisher.Stop(); err != nil {
2✔
2496
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2497
                }
×
2498
                if err := s.channelNotifier.Stop(); err != nil {
2✔
2499
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2500
                }
×
2501
                if err := s.peerNotifier.Stop(); err != nil {
2✔
2502
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2503
                }
×
2504
                if err := s.htlcNotifier.Stop(); err != nil {
2✔
2505
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2506
                }
×
2507
                if err := s.chanSubSwapper.Stop(); err != nil {
2✔
2508
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2509
                }
×
2510
                if err := s.cc.ChainNotifier.Stop(); err != nil {
2✔
2511
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2512
                }
×
2513
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
2✔
2514
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2515
                                err)
×
2516
                }
×
2517
                if err := s.chanEventStore.Stop(); err != nil {
2✔
2518
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2519
                                err)
×
2520
                }
×
2521
                s.missionController.StopStoreTickers()
2✔
2522

2✔
2523
                // Disconnect from each active peers to ensure that
2✔
2524
                // peerTerminationWatchers signal completion to each peer.
2✔
2525
                for _, peer := range s.Peers() {
4✔
2526
                        err := s.DisconnectPeer(peer.IdentityKey())
2✔
2527
                        if err != nil {
2✔
2528
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2529
                                        "received error: %v", peer.IdentityKey(),
×
2530
                                        err,
×
2531
                                )
×
2532
                        }
×
2533
                }
2534

2535
                // Now that all connections have been torn down, stop the tower
2536
                // client which will reliably flush all queued states to the
2537
                // tower. If this is halted for any reason, the force quit timer
2538
                // will kick in and abort to allow this method to return.
2539
                if s.towerClientMgr != nil {
4✔
2540
                        if err := s.towerClientMgr.Stop(); err != nil {
2✔
2541
                                srvrLog.Warnf("Unable to shut down tower "+
×
2542
                                        "client manager: %v", err)
×
2543
                        }
×
2544
                }
2545

2546
                if s.hostAnn != nil {
2✔
2547
                        if err := s.hostAnn.Stop(); err != nil {
×
2548
                                srvrLog.Warnf("unable to shut down host "+
×
2549
                                        "annoucner: %v", err)
×
2550
                        }
×
2551
                }
2552

2553
                if s.livenessMonitor != nil {
4✔
2554
                        if err := s.livenessMonitor.Stop(); err != nil {
2✔
2555
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2556
                                        "monitor: %v", err)
×
2557
                        }
×
2558
                }
2559

2560
                // Wait for all lingering goroutines to quit.
2561
                srvrLog.Debug("Waiting for server to shutdown...")
2✔
2562
                s.wg.Wait()
2✔
2563

2✔
2564
                srvrLog.Debug("Stopping buffer pools...")
2✔
2565
                s.sigPool.Stop()
2✔
2566
                s.writePool.Stop()
2✔
2567
                s.readPool.Stop()
2✔
2568
        })
2569

2570
        return nil
2✔
2571
}
2572

2573
// Stopped returns true if the server has been instructed to shutdown.
2574
// NOTE: This function is safe for concurrent access.
2575
func (s *server) Stopped() bool {
2✔
2576
        return atomic.LoadInt32(&s.stopping) != 0
2✔
2577
}
2✔
2578

2579
// configurePortForwarding attempts to set up port forwarding for the different
2580
// ports that the server will be listening on.
2581
//
2582
// NOTE: This should only be used when using some kind of NAT traversal to
2583
// automatically set up forwarding rules.
2584
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2585
        ip, err := s.natTraversal.ExternalIP()
×
2586
        if err != nil {
×
2587
                return nil, err
×
2588
        }
×
2589
        s.lastDetectedIP = ip
×
2590

×
2591
        externalIPs := make([]string, 0, len(ports))
×
2592
        for _, port := range ports {
×
2593
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2594
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2595
                        continue
×
2596
                }
2597

2598
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2599
                externalIPs = append(externalIPs, hostIP)
×
2600
        }
2601

2602
        return externalIPs, nil
×
2603
}
2604

2605
// removePortForwarding attempts to clear the forwarding rules for the different
2606
// ports the server is currently listening on.
2607
//
2608
// NOTE: This should only be used when using some kind of NAT traversal to
2609
// automatically set up forwarding rules.
2610
func (s *server) removePortForwarding() {
×
2611
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2612
        for _, port := range forwardedPorts {
×
2613
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2614
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2615
                                "port %d: %v", port, err)
×
2616
                }
×
2617
        }
2618
}
2619

2620
// watchExternalIP continuously checks for an updated external IP address every
2621
// 15 minutes. Once a new IP address has been detected, it will automatically
2622
// handle port forwarding rules and send updated node announcements to the
2623
// currently connected peers.
2624
//
2625
// NOTE: This MUST be run as a goroutine.
2626
func (s *server) watchExternalIP() {
×
2627
        defer s.wg.Done()
×
2628

×
2629
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2630
        // up by the server.
×
2631
        defer s.removePortForwarding()
×
2632

×
2633
        // Keep track of the external IPs set by the user to avoid replacing
×
2634
        // them when detecting a new IP.
×
2635
        ipsSetByUser := make(map[string]struct{})
×
2636
        for _, ip := range s.cfg.ExternalIPs {
×
2637
                ipsSetByUser[ip.String()] = struct{}{}
×
2638
        }
×
2639

2640
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2641

×
2642
        ticker := time.NewTicker(15 * time.Minute)
×
2643
        defer ticker.Stop()
×
2644
out:
×
2645
        for {
×
2646
                select {
×
2647
                case <-ticker.C:
×
2648
                        // We'll start off by making sure a new IP address has
×
2649
                        // been detected.
×
2650
                        ip, err := s.natTraversal.ExternalIP()
×
2651
                        if err != nil {
×
2652
                                srvrLog.Debugf("Unable to retrieve the "+
×
2653
                                        "external IP address: %v", err)
×
2654
                                continue
×
2655
                        }
2656

2657
                        // Periodically renew the NAT port forwarding.
2658
                        for _, port := range forwardedPorts {
×
2659
                                err := s.natTraversal.AddPortMapping(port)
×
2660
                                if err != nil {
×
2661
                                        srvrLog.Warnf("Unable to automatically "+
×
2662
                                                "re-create port forwarding using %s: %v",
×
2663
                                                s.natTraversal.Name(), err)
×
2664
                                } else {
×
2665
                                        srvrLog.Debugf("Automatically re-created "+
×
2666
                                                "forwarding for port %d using %s to "+
×
2667
                                                "advertise external IP",
×
2668
                                                port, s.natTraversal.Name())
×
2669
                                }
×
2670
                        }
2671

2672
                        if ip.Equal(s.lastDetectedIP) {
×
2673
                                continue
×
2674
                        }
2675

2676
                        srvrLog.Infof("Detected new external IP address %s", ip)
×
2677

×
2678
                        // Next, we'll craft the new addresses that will be
×
2679
                        // included in the new node announcement and advertised
×
2680
                        // to the network. Each address will consist of the new
×
2681
                        // IP detected and one of the currently advertised
×
2682
                        // ports.
×
2683
                        var newAddrs []net.Addr
×
2684
                        for _, port := range forwardedPorts {
×
2685
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2686
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2687
                                if err != nil {
×
2688
                                        srvrLog.Debugf("Unable to resolve "+
×
2689
                                                "host %v: %v", addr, err)
×
2690
                                        continue
×
2691
                                }
2692

2693
                                newAddrs = append(newAddrs, addr)
×
2694
                        }
2695

2696
                        // Skip the update if we weren't able to resolve any of
2697
                        // the new addresses.
2698
                        if len(newAddrs) == 0 {
×
2699
                                srvrLog.Debug("Skipping node announcement " +
×
2700
                                        "update due to not being able to " +
×
2701
                                        "resolve any new addresses")
×
2702
                                continue
×
2703
                        }
2704

2705
                        // Now, we'll need to update the addresses in our node's
2706
                        // announcement in order to propagate the update
2707
                        // throughout the network. We'll only include addresses
2708
                        // that have a different IP from the previous one, as
2709
                        // the previous IP is no longer valid.
2710
                        currentNodeAnn := s.getNodeAnnouncement()
×
2711

×
2712
                        for _, addr := range currentNodeAnn.Addresses {
×
2713
                                host, _, err := net.SplitHostPort(addr.String())
×
2714
                                if err != nil {
×
2715
                                        srvrLog.Debugf("Unable to determine "+
×
2716
                                                "host from address %v: %v",
×
2717
                                                addr, err)
×
2718
                                        continue
×
2719
                                }
2720

2721
                                // We'll also make sure to include external IPs
2722
                                // set manually by the user.
2723
                                _, setByUser := ipsSetByUser[addr.String()]
×
2724
                                if setByUser || host != s.lastDetectedIP.String() {
×
2725
                                        newAddrs = append(newAddrs, addr)
×
2726
                                }
×
2727
                        }
2728

2729
                        // Then, we'll generate a new timestamped node
2730
                        // announcement with the updated addresses and broadcast
2731
                        // it to our peers.
2732
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2733
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2734
                        )
×
2735
                        if err != nil {
×
2736
                                srvrLog.Debugf("Unable to generate new node "+
×
2737
                                        "announcement: %v", err)
×
2738
                                continue
×
2739
                        }
2740

2741
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2742
                        if err != nil {
×
2743
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2744
                                        "announcement to peers: %v", err)
×
2745
                                continue
×
2746
                        }
2747

2748
                        // Finally, update the last IP seen to the current one.
2749
                        s.lastDetectedIP = ip
×
2750
                case <-s.quit:
×
2751
                        break out
×
2752
                }
2753
        }
2754
}
2755

2756
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2757
// based on the server, and currently active bootstrap mechanisms as defined
2758
// within the current configuration.
2759
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2760
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2761

×
2762
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2763

×
2764
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2765
        // this can be used by default if we've already partially seeded the
×
2766
        // network.
×
2767
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2768
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2769
        if err != nil {
×
2770
                return nil, err
×
2771
        }
×
2772
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2773

×
2774
        // If this isn't simnet mode, then one of our additional bootstrapping
×
2775
        // sources will be the set of running DNS seeds.
×
2776
        if !s.cfg.Bitcoin.SimNet {
×
2777
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2778

×
2779
                // If we have a set of DNS seeds for this chain, then we'll add
×
2780
                // it as an additional bootstrapping source.
×
2781
                if ok {
×
2782
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2783
                                "seeds: %v", dnsSeeds)
×
2784

×
2785
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2786
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2787
                        )
×
2788
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2789
                }
×
2790
        }
2791

2792
        return bootStrappers, nil
×
2793
}
2794

2795
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2796
// needs to ignore, which is made of three parts,
2797
//   - the node itself needs to be skipped as it doesn't make sense to connect
2798
//     to itself.
2799
//   - the peers that already have connections with, as in s.peersByPub.
2800
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2801
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2802
        s.mu.RLock()
×
2803
        defer s.mu.RUnlock()
×
2804

×
2805
        ignore := make(map[autopilot.NodeID]struct{})
×
2806

×
2807
        // We should ignore ourselves from bootstrapping.
×
2808
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2809
        ignore[selfKey] = struct{}{}
×
2810

×
2811
        // Ignore all connected peers.
×
2812
        for _, peer := range s.peersByPub {
×
2813
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2814
                ignore[nID] = struct{}{}
×
2815
        }
×
2816

2817
        // Ignore all persistent peers as they have a dedicated reconnecting
2818
        // process.
2819
        for pubKeyStr := range s.persistentPeers {
×
2820
                var nID autopilot.NodeID
×
2821
                copy(nID[:], []byte(pubKeyStr))
×
2822
                ignore[nID] = struct{}{}
×
2823
        }
×
2824

2825
        return ignore
×
2826
}
2827

2828
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2829
// and maintain a target minimum number of outbound connections. With this
2830
// invariant, we ensure that our node is connected to a diverse set of peers
2831
// and that nodes newly joining the network receive an up to date network view
2832
// as soon as possible.
2833
func (s *server) peerBootstrapper(numTargetPeers uint32,
2834
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2835

×
2836
        defer s.wg.Done()
×
2837

×
2838
        // Before we continue, init the ignore peers map.
×
2839
        ignoreList := s.createBootstrapIgnorePeers()
×
2840

×
2841
        // We'll start off by aggressively attempting connections to peers in
×
2842
        // order to be a part of the network as soon as possible.
×
2843
        s.initialPeerBootstrap(ignoreList, numTargetPeers, bootstrappers)
×
2844

×
2845
        // Once done, we'll attempt to maintain our target minimum number of
×
2846
        // peers.
×
2847
        //
×
2848
        // We'll use a 15 second backoff, and double the time every time an
×
2849
        // epoch fails up to a ceiling.
×
2850
        backOff := time.Second * 15
×
2851

×
2852
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2853
        // see if we've reached our minimum number of peers.
×
2854
        sampleTicker := time.NewTicker(backOff)
×
2855
        defer sampleTicker.Stop()
×
2856

×
2857
        // We'll use the number of attempts and errors to determine if we need
×
2858
        // to increase the time between discovery epochs.
×
2859
        var epochErrors uint32 // To be used atomically.
×
2860
        var epochAttempts uint32
×
2861

×
2862
        for {
×
2863
                select {
×
2864
                // The ticker has just woken us up, so we'll need to check if
2865
                // we need to attempt to connect our to any more peers.
2866
                case <-sampleTicker.C:
×
2867
                        // Obtain the current number of peers, so we can gauge
×
2868
                        // if we need to sample more peers or not.
×
2869
                        s.mu.RLock()
×
2870
                        numActivePeers := uint32(len(s.peersByPub))
×
2871
                        s.mu.RUnlock()
×
2872

×
2873
                        // If we have enough peers, then we can loop back
×
2874
                        // around to the next round as we're done here.
×
2875
                        if numActivePeers >= numTargetPeers {
×
2876
                                continue
×
2877
                        }
2878

2879
                        // If all of our attempts failed during this last back
2880
                        // off period, then will increase our backoff to 5
2881
                        // minute ceiling to avoid an excessive number of
2882
                        // queries
2883
                        //
2884
                        // TODO(roasbeef): add reverse policy too?
2885

2886
                        if epochAttempts > 0 &&
×
2887
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2888

×
2889
                                sampleTicker.Stop()
×
2890

×
2891
                                backOff *= 2
×
2892
                                if backOff > bootstrapBackOffCeiling {
×
2893
                                        backOff = bootstrapBackOffCeiling
×
2894
                                }
×
2895

2896
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2897
                                        "%v", backOff)
×
2898
                                sampleTicker = time.NewTicker(backOff)
×
2899
                                continue
×
2900
                        }
2901

2902
                        atomic.StoreUint32(&epochErrors, 0)
×
2903
                        epochAttempts = 0
×
2904

×
2905
                        // Since we know need more peers, we'll compute the
×
2906
                        // exact number we need to reach our threshold.
×
2907
                        numNeeded := numTargetPeers - numActivePeers
×
2908

×
2909
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2910
                                "peers", numNeeded)
×
2911

×
2912
                        // With the number of peers we need calculated, we'll
×
2913
                        // query the network bootstrappers to sample a set of
×
2914
                        // random addrs for us.
×
2915
                        //
×
2916
                        // Before we continue, get a copy of the ignore peers
×
2917
                        // map.
×
2918
                        ignoreList = s.createBootstrapIgnorePeers()
×
2919

×
2920
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2921
                                ignoreList, numNeeded*2, bootstrappers...,
×
2922
                        )
×
2923
                        if err != nil {
×
2924
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2925
                                        "peers: %v", err)
×
2926
                                continue
×
2927
                        }
2928

2929
                        // Finally, we'll launch a new goroutine for each
2930
                        // prospective peer candidates.
2931
                        for _, addr := range peerAddrs {
×
2932
                                epochAttempts++
×
2933

×
2934
                                go func(a *lnwire.NetAddress) {
×
2935
                                        // TODO(roasbeef): can do AS, subnet,
×
2936
                                        // country diversity, etc
×
2937
                                        errChan := make(chan error, 1)
×
2938
                                        s.connectToPeer(
×
2939
                                                a, errChan,
×
2940
                                                s.cfg.ConnectionTimeout,
×
2941
                                        )
×
2942
                                        select {
×
2943
                                        case err := <-errChan:
×
2944
                                                if err == nil {
×
2945
                                                        return
×
2946
                                                }
×
2947

2948
                                                srvrLog.Errorf("Unable to "+
×
2949
                                                        "connect to %v: %v",
×
2950
                                                        a, err)
×
2951
                                                atomic.AddUint32(&epochErrors, 1)
×
2952
                                        case <-s.quit:
×
2953
                                        }
2954
                                }(addr)
2955
                        }
2956
                case <-s.quit:
×
2957
                        return
×
2958
                }
2959
        }
2960
}
2961

2962
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
2963
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
2964
// query back off each time we encounter a failure.
2965
const bootstrapBackOffCeiling = time.Minute * 5
2966

2967
// initialPeerBootstrap attempts to continuously connect to peers on startup
2968
// until the target number of peers has been reached. This ensures that nodes
2969
// receive an up to date network view as soon as possible.
2970
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2971
        numTargetPeers uint32,
2972
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2973

×
2974
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
2975
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
2976

×
2977
        // We'll start off by waiting 2 seconds between failed attempts, then
×
2978
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
2979
        var delaySignal <-chan time.Time
×
2980
        delayTime := time.Second * 2
×
2981

×
2982
        // As want to be more aggressive, we'll use a lower back off celling
×
2983
        // then the main peer bootstrap logic.
×
2984
        backOffCeiling := bootstrapBackOffCeiling / 5
×
2985

×
2986
        for attempts := 0; ; attempts++ {
×
2987
                // Check if the server has been requested to shut down in order
×
2988
                // to prevent blocking.
×
2989
                if s.Stopped() {
×
2990
                        return
×
2991
                }
×
2992

2993
                // We can exit our aggressive initial peer bootstrapping stage
2994
                // if we've reached out target number of peers.
2995
                s.mu.RLock()
×
2996
                numActivePeers := uint32(len(s.peersByPub))
×
2997
                s.mu.RUnlock()
×
2998

×
2999
                if numActivePeers >= numTargetPeers {
×
3000
                        return
×
3001
                }
×
3002

3003
                if attempts > 0 {
×
3004
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3005
                                "bootstrap peers (attempt #%v)", delayTime,
×
3006
                                attempts)
×
3007

×
3008
                        // We've completed at least one iterating and haven't
×
3009
                        // finished, so we'll start to insert a delay period
×
3010
                        // between each attempt.
×
3011
                        delaySignal = time.After(delayTime)
×
3012
                        select {
×
3013
                        case <-delaySignal:
×
3014
                        case <-s.quit:
×
3015
                                return
×
3016
                        }
3017

3018
                        // After our delay, we'll double the time we wait up to
3019
                        // the max back off period.
3020
                        delayTime *= 2
×
3021
                        if delayTime > backOffCeiling {
×
3022
                                delayTime = backOffCeiling
×
3023
                        }
×
3024
                }
3025

3026
                // Otherwise, we'll request for the remaining number of peers
3027
                // in order to reach our target.
3028
                peersNeeded := numTargetPeers - numActivePeers
×
3029
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3030
                        ignore, peersNeeded, bootstrappers...,
×
3031
                )
×
3032
                if err != nil {
×
3033
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3034
                                "peers: %v", err)
×
3035
                        continue
×
3036
                }
3037

3038
                // Then, we'll attempt to establish a connection to the
3039
                // different peer addresses retrieved by our bootstrappers.
3040
                var wg sync.WaitGroup
×
3041
                for _, bootstrapAddr := range bootstrapAddrs {
×
3042
                        wg.Add(1)
×
3043
                        go func(addr *lnwire.NetAddress) {
×
3044
                                defer wg.Done()
×
3045

×
3046
                                errChan := make(chan error, 1)
×
3047
                                go s.connectToPeer(
×
3048
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3049
                                )
×
3050

×
3051
                                // We'll only allow this connection attempt to
×
3052
                                // take up to 3 seconds. This allows us to move
×
3053
                                // quickly by discarding peers that are slowing
×
3054
                                // us down.
×
3055
                                select {
×
3056
                                case err := <-errChan:
×
3057
                                        if err == nil {
×
3058
                                                return
×
3059
                                        }
×
3060
                                        srvrLog.Errorf("Unable to connect to "+
×
3061
                                                "%v: %v", addr, err)
×
3062
                                // TODO: tune timeout? 3 seconds might be *too*
3063
                                // aggressive but works well.
3064
                                case <-time.After(3 * time.Second):
×
3065
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3066
                                                "to not establishing a "+
×
3067
                                                "connection within 3 seconds",
×
3068
                                                addr)
×
3069
                                case <-s.quit:
×
3070
                                }
3071
                        }(bootstrapAddr)
3072
                }
3073

3074
                wg.Wait()
×
3075
        }
3076
}
3077

3078
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3079
// order to listen for inbound connections over Tor.
3080
func (s *server) createNewHiddenService() error {
×
3081
        // Determine the different ports the server is listening on. The onion
×
3082
        // service's virtual port will map to these ports and one will be picked
×
3083
        // at random when the onion service is being accessed.
×
3084
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3085
        for _, listenAddr := range s.listenAddrs {
×
3086
                port := listenAddr.(*net.TCPAddr).Port
×
3087
                listenPorts = append(listenPorts, port)
×
3088
        }
×
3089

3090
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3091
        if err != nil {
×
3092
                return err
×
3093
        }
×
3094

3095
        // Once the port mapping has been set, we can go ahead and automatically
3096
        // create our onion service. The service's private key will be saved to
3097
        // disk in order to regain access to this service when restarting `lnd`.
3098
        onionCfg := tor.AddOnionConfig{
×
3099
                VirtualPort: defaultPeerPort,
×
3100
                TargetPorts: listenPorts,
×
3101
                Store: tor.NewOnionFile(
×
3102
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3103
                        encrypter,
×
3104
                ),
×
3105
        }
×
3106

×
3107
        switch {
×
3108
        case s.cfg.Tor.V2:
×
3109
                onionCfg.Type = tor.V2
×
3110
        case s.cfg.Tor.V3:
×
3111
                onionCfg.Type = tor.V3
×
3112
        }
3113

3114
        addr, err := s.torController.AddOnion(onionCfg)
×
3115
        if err != nil {
×
3116
                return err
×
3117
        }
×
3118

3119
        // Now that the onion service has been created, we'll add the onion
3120
        // address it can be reached at to our list of advertised addresses.
3121
        newNodeAnn, err := s.genNodeAnnouncement(
×
3122
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3123
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3124
                },
×
3125
        )
3126
        if err != nil {
×
3127
                return fmt.Errorf("unable to generate new node "+
×
3128
                        "announcement: %v", err)
×
3129
        }
×
3130

3131
        // Finally, we'll update the on-disk version of our announcement so it
3132
        // will eventually propagate to nodes in the network.
3133
        selfNode := &channeldb.LightningNode{
×
3134
                HaveNodeAnnouncement: true,
×
3135
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3136
                Addresses:            newNodeAnn.Addresses,
×
3137
                Alias:                newNodeAnn.Alias.String(),
×
3138
                Features: lnwire.NewFeatureVector(
×
3139
                        newNodeAnn.Features, lnwire.Features,
×
3140
                ),
×
3141
                Color:        newNodeAnn.RGBColor,
×
3142
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3143
        }
×
3144
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3145
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3146
                return fmt.Errorf("can't set self node: %w", err)
×
3147
        }
×
3148

3149
        return nil
×
3150
}
3151

3152
// findChannel finds a channel given a public key and ChannelID. It is an
3153
// optimization that is quicker than seeking for a channel given only the
3154
// ChannelID.
3155
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3156
        *channeldb.OpenChannel, error) {
2✔
3157

2✔
3158
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
2✔
3159
        if err != nil {
2✔
3160
                return nil, err
×
3161
        }
×
3162

3163
        for _, channel := range nodeChans {
4✔
3164
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
4✔
3165
                        return channel, nil
2✔
3166
                }
2✔
3167
        }
3168

3169
        return nil, fmt.Errorf("unable to find channel")
2✔
3170
}
3171

3172
// getNodeAnnouncement fetches the current, fully signed node announcement.
3173
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
2✔
3174
        s.mu.Lock()
2✔
3175
        defer s.mu.Unlock()
2✔
3176

2✔
3177
        return *s.currentNodeAnn
2✔
3178
}
2✔
3179

3180
// genNodeAnnouncement generates and returns the current fully signed node
3181
// announcement. The time stamp of the announcement will be updated in order
3182
// to ensure it propagates through the network.
3183
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3184
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
2✔
3185

2✔
3186
        s.mu.Lock()
2✔
3187
        defer s.mu.Unlock()
2✔
3188

2✔
3189
        // First, try to update our feature manager with the updated set of
2✔
3190
        // features.
2✔
3191
        if features != nil {
4✔
3192
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
2✔
3193
                        feature.SetNodeAnn: features,
2✔
3194
                }
2✔
3195
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
2✔
3196
                if err != nil {
4✔
3197
                        return lnwire.NodeAnnouncement{}, err
2✔
3198
                }
2✔
3199

3200
                // If we could successfully update our feature manager, add
3201
                // an update modifier to include these new features to our
3202
                // set.
3203
                modifiers = append(
2✔
3204
                        modifiers, netann.NodeAnnSetFeatures(features),
2✔
3205
                )
2✔
3206
        }
3207

3208
        // Always update the timestamp when refreshing to ensure the update
3209
        // propagates.
3210
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
2✔
3211

2✔
3212
        // Apply the requested changes to the node announcement.
2✔
3213
        for _, modifier := range modifiers {
4✔
3214
                modifier(s.currentNodeAnn)
2✔
3215
        }
2✔
3216

3217
        // Sign a new update after applying all of the passed modifiers.
3218
        err := netann.SignNodeAnnouncement(
2✔
3219
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
2✔
3220
        )
2✔
3221
        if err != nil {
2✔
3222
                return lnwire.NodeAnnouncement{}, err
×
3223
        }
×
3224

3225
        return *s.currentNodeAnn, nil
2✔
3226
}
3227

3228
// updateAndBrodcastSelfNode generates a new node announcement
3229
// applying the giving modifiers and updating the time stamp
3230
// to ensure it propagates through the network. Then it brodcasts
3231
// it to the network.
3232
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
3233
        modifiers ...netann.NodeAnnModifier) error {
2✔
3234

2✔
3235
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
2✔
3236
        if err != nil {
4✔
3237
                return fmt.Errorf("unable to generate new node "+
2✔
3238
                        "announcement: %v", err)
2✔
3239
        }
2✔
3240

3241
        // Update the on-disk version of our announcement.
3242
        // Load and modify self node istead of creating anew instance so we
3243
        // don't risk overwriting any existing values.
3244
        selfNode, err := s.graphDB.SourceNode()
2✔
3245
        if err != nil {
2✔
3246
                return fmt.Errorf("unable to get current source node: %w", err)
×
3247
        }
×
3248

3249
        selfNode.HaveNodeAnnouncement = true
2✔
3250
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
2✔
3251
        selfNode.Addresses = newNodeAnn.Addresses
2✔
3252
        selfNode.Alias = newNodeAnn.Alias.String()
2✔
3253
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
2✔
3254
        selfNode.Color = newNodeAnn.RGBColor
2✔
3255
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
2✔
3256

2✔
3257
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
2✔
3258

2✔
3259
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
2✔
3260
                return fmt.Errorf("can't set self node: %w", err)
×
3261
        }
×
3262

3263
        // Finally, propagate it to the nodes in the network.
3264
        err = s.BroadcastMessage(nil, &newNodeAnn)
2✔
3265
        if err != nil {
2✔
3266
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3267
                        "announcement to peers: %v", err)
×
3268
                return err
×
3269
        }
×
3270

3271
        return nil
2✔
3272
}
3273

3274
type nodeAddresses struct {
3275
        pubKey    *btcec.PublicKey
3276
        addresses []net.Addr
3277
}
3278

3279
// establishPersistentConnections attempts to establish persistent connections
3280
// to all our direct channel collaborators. In order to promote liveness of our
3281
// active channels, we instruct the connection manager to attempt to establish
3282
// and maintain persistent connections to all our direct channel counterparties.
3283
func (s *server) establishPersistentConnections() error {
2✔
3284
        // nodeAddrsMap stores the combination of node public keys and addresses
2✔
3285
        // that we'll attempt to reconnect to. PubKey strings are used as keys
2✔
3286
        // since other PubKey forms can't be compared.
2✔
3287
        nodeAddrsMap := map[string]*nodeAddresses{}
2✔
3288

2✔
3289
        // Iterate through the list of LinkNodes to find addresses we should
2✔
3290
        // attempt to connect to based on our set of previous connections. Set
2✔
3291
        // the reconnection port to the default peer port.
2✔
3292
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
2✔
3293
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
2✔
3294
                return err
×
3295
        }
×
3296
        for _, node := range linkNodes {
4✔
3297
                pubStr := string(node.IdentityPub.SerializeCompressed())
2✔
3298
                nodeAddrs := &nodeAddresses{
2✔
3299
                        pubKey:    node.IdentityPub,
2✔
3300
                        addresses: node.Addresses,
2✔
3301
                }
2✔
3302
                nodeAddrsMap[pubStr] = nodeAddrs
2✔
3303
        }
2✔
3304

3305
        // After checking our previous connections for addresses to connect to,
3306
        // iterate through the nodes in our channel graph to find addresses
3307
        // that have been added via NodeAnnouncement messages.
3308
        sourceNode, err := s.graphDB.SourceNode()
2✔
3309
        if err != nil {
2✔
3310
                return err
×
3311
        }
×
3312

3313
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3314
        // each of the nodes.
3315
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
2✔
3316
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
2✔
3317
                tx kvdb.RTx,
2✔
3318
                chanInfo *models.ChannelEdgeInfo,
2✔
3319
                policy, _ *models.ChannelEdgePolicy) error {
4✔
3320

2✔
3321
                // If the remote party has announced the channel to us, but we
2✔
3322
                // haven't yet, then we won't have a policy. However, we don't
2✔
3323
                // need this to connect to the peer, so we'll log it and move on.
2✔
3324
                if policy == nil {
2✔
3325
                        srvrLog.Warnf("No channel policy found for "+
×
3326
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3327
                }
×
3328

3329
                // We'll now fetch the peer opposite from us within this
3330
                // channel so we can queue up a direct connection to them.
3331
                channelPeer, err := s.graphDB.FetchOtherNode(
2✔
3332
                        tx, chanInfo, selfPub,
2✔
3333
                )
2✔
3334
                if err != nil {
2✔
3335
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3336
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3337
                                err)
×
3338
                }
×
3339

3340
                pubStr := string(channelPeer.PubKeyBytes[:])
2✔
3341

2✔
3342
                // Add all unique addresses from channel
2✔
3343
                // graph/NodeAnnouncements to the list of addresses we'll
2✔
3344
                // connect to for this peer.
2✔
3345
                addrSet := make(map[string]net.Addr)
2✔
3346
                for _, addr := range channelPeer.Addresses {
4✔
3347
                        switch addr.(type) {
2✔
3348
                        case *net.TCPAddr:
2✔
3349
                                addrSet[addr.String()] = addr
2✔
3350

3351
                        // We'll only attempt to connect to Tor addresses if Tor
3352
                        // outbound support is enabled.
3353
                        case *tor.OnionAddr:
×
3354
                                if s.cfg.Tor.Active {
×
3355
                                        addrSet[addr.String()] = addr
×
3356
                                }
×
3357
                        }
3358
                }
3359

3360
                // If this peer is also recorded as a link node, we'll add any
3361
                // additional addresses that have not already been selected.
3362
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
2✔
3363
                if ok {
4✔
3364
                        for _, lnAddress := range linkNodeAddrs.addresses {
4✔
3365
                                switch lnAddress.(type) {
2✔
3366
                                case *net.TCPAddr:
2✔
3367
                                        addrSet[lnAddress.String()] = lnAddress
2✔
3368

3369
                                // We'll only attempt to connect to Tor
3370
                                // addresses if Tor outbound support is enabled.
3371
                                case *tor.OnionAddr:
×
3372
                                        if s.cfg.Tor.Active {
×
3373
                                                addrSet[lnAddress.String()] = lnAddress
×
3374
                                        }
×
3375
                                }
3376
                        }
3377
                }
3378

3379
                // Construct a slice of the deduped addresses.
3380
                var addrs []net.Addr
2✔
3381
                for _, addr := range addrSet {
4✔
3382
                        addrs = append(addrs, addr)
2✔
3383
                }
2✔
3384

3385
                n := &nodeAddresses{
2✔
3386
                        addresses: addrs,
2✔
3387
                }
2✔
3388
                n.pubKey, err = channelPeer.PubKey()
2✔
3389
                if err != nil {
2✔
3390
                        return err
×
3391
                }
×
3392

3393
                nodeAddrsMap[pubStr] = n
2✔
3394
                return nil
2✔
3395
        })
3396
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
2✔
3397
                return err
×
3398
        }
×
3399

3400
        srvrLog.Debugf("Establishing %v persistent connections on start",
2✔
3401
                len(nodeAddrsMap))
2✔
3402

2✔
3403
        // Acquire and hold server lock until all persistent connection requests
2✔
3404
        // have been recorded and sent to the connection manager.
2✔
3405
        s.mu.Lock()
2✔
3406
        defer s.mu.Unlock()
2✔
3407

2✔
3408
        // Iterate through the combined list of addresses from prior links and
2✔
3409
        // node announcements and attempt to reconnect to each node.
2✔
3410
        var numOutboundConns int
2✔
3411
        for pubStr, nodeAddr := range nodeAddrsMap {
4✔
3412
                // Add this peer to the set of peers we should maintain a
2✔
3413
                // persistent connection with. We set the value to false to
2✔
3414
                // indicate that we should not continue to reconnect if the
2✔
3415
                // number of channels returns to zero, since this peer has not
2✔
3416
                // been requested as perm by the user.
2✔
3417
                s.persistentPeers[pubStr] = false
2✔
3418
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
4✔
3419
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
2✔
3420
                }
2✔
3421

3422
                for _, address := range nodeAddr.addresses {
4✔
3423
                        // Create a wrapper address which couples the IP and
2✔
3424
                        // the pubkey so the brontide authenticated connection
2✔
3425
                        // can be established.
2✔
3426
                        lnAddr := &lnwire.NetAddress{
2✔
3427
                                IdentityKey: nodeAddr.pubKey,
2✔
3428
                                Address:     address,
2✔
3429
                        }
2✔
3430

2✔
3431
                        s.persistentPeerAddrs[pubStr] = append(
2✔
3432
                                s.persistentPeerAddrs[pubStr], lnAddr)
2✔
3433
                }
2✔
3434

3435
                // We'll connect to the first 10 peers immediately, then
3436
                // randomly stagger any remaining connections if the
3437
                // stagger initial reconnect flag is set. This ensures
3438
                // that mobile nodes or nodes with a small number of
3439
                // channels obtain connectivity quickly, but larger
3440
                // nodes are able to disperse the costs of connecting to
3441
                // all peers at once.
3442
                if numOutboundConns < numInstantInitReconnect ||
2✔
3443
                        !s.cfg.StaggerInitialReconnect {
4✔
3444

2✔
3445
                        go s.connectToPersistentPeer(pubStr)
2✔
3446
                } else {
2✔
3447
                        go s.delayInitialReconnect(pubStr)
×
3448
                }
×
3449

3450
                numOutboundConns++
2✔
3451
        }
3452

3453
        return nil
2✔
3454
}
3455

3456
// delayInitialReconnect will attempt a reconnection to the given peer after
3457
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3458
//
3459
// NOTE: This method MUST be run as a goroutine.
3460
func (s *server) delayInitialReconnect(pubStr string) {
×
3461
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3462
        select {
×
3463
        case <-time.After(delay):
×
3464
                s.connectToPersistentPeer(pubStr)
×
3465
        case <-s.quit:
×
3466
        }
3467
}
3468

3469
// prunePersistentPeerConnection removes all internal state related to
3470
// persistent connections to a peer within the server. This is used to avoid
3471
// persistent connection retries to peers we do not have any open channels with.
3472
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
2✔
3473
        pubKeyStr := string(compressedPubKey[:])
2✔
3474

2✔
3475
        s.mu.Lock()
2✔
3476
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
4✔
3477
                delete(s.persistentPeers, pubKeyStr)
2✔
3478
                delete(s.persistentPeersBackoff, pubKeyStr)
2✔
3479
                delete(s.persistentPeerAddrs, pubKeyStr)
2✔
3480
                s.cancelConnReqs(pubKeyStr, nil)
2✔
3481
                s.mu.Unlock()
2✔
3482

2✔
3483
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
2✔
3484
                        "peer has no open channels", compressedPubKey)
2✔
3485

2✔
3486
                return
2✔
3487
        }
2✔
3488
        s.mu.Unlock()
2✔
3489
}
3490

3491
// BroadcastMessage sends a request to the server to broadcast a set of
3492
// messages to all peers other than the one specified by the `skips` parameter.
3493
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3494
// the target peers.
3495
//
3496
// NOTE: This function is safe for concurrent access.
3497
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3498
        msgs ...lnwire.Message) error {
2✔
3499

2✔
3500
        // Filter out peers found in the skips map. We synchronize access to
2✔
3501
        // peersByPub throughout this process to ensure we deliver messages to
2✔
3502
        // exact set of peers present at the time of invocation.
2✔
3503
        s.mu.RLock()
2✔
3504
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
2✔
3505
        for pubStr, sPeer := range s.peersByPub {
4✔
3506
                if skips != nil {
4✔
3507
                        if _, ok := skips[sPeer.PubKey()]; ok {
4✔
3508
                                srvrLog.Tracef("Skipping %x in broadcast with "+
2✔
3509
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
2✔
3510
                                continue
2✔
3511
                        }
3512
                }
3513

3514
                peers = append(peers, sPeer)
2✔
3515
        }
3516
        s.mu.RUnlock()
2✔
3517

2✔
3518
        // Iterate over all known peers, dispatching a go routine to enqueue
2✔
3519
        // all messages to each of peers.
2✔
3520
        var wg sync.WaitGroup
2✔
3521
        for _, sPeer := range peers {
4✔
3522
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
2✔
3523
                        sPeer.PubKey())
2✔
3524

2✔
3525
                // Dispatch a go routine to enqueue all messages to this peer.
2✔
3526
                wg.Add(1)
2✔
3527
                s.wg.Add(1)
2✔
3528
                go func(p lnpeer.Peer) {
4✔
3529
                        defer s.wg.Done()
2✔
3530
                        defer wg.Done()
2✔
3531

2✔
3532
                        p.SendMessageLazy(false, msgs...)
2✔
3533
                }(sPeer)
2✔
3534
        }
3535

3536
        // Wait for all messages to have been dispatched before returning to
3537
        // caller.
3538
        wg.Wait()
2✔
3539

2✔
3540
        return nil
2✔
3541
}
3542

3543
// NotifyWhenOnline can be called by other subsystems to get notified when a
3544
// particular peer comes online. The peer itself is sent across the peerChan.
3545
//
3546
// NOTE: This function is safe for concurrent access.
3547
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3548
        peerChan chan<- lnpeer.Peer) {
2✔
3549

2✔
3550
        s.mu.Lock()
2✔
3551

2✔
3552
        // Compute the target peer's identifier.
2✔
3553
        pubStr := string(peerKey[:])
2✔
3554

2✔
3555
        // Check if peer is connected.
2✔
3556
        peer, ok := s.peersByPub[pubStr]
2✔
3557
        if ok {
4✔
3558
                // Unlock here so that the mutex isn't held while we are
2✔
3559
                // waiting for the peer to become active.
2✔
3560
                s.mu.Unlock()
2✔
3561

2✔
3562
                // Wait until the peer signals that it is actually active
2✔
3563
                // rather than only in the server's maps.
2✔
3564
                select {
2✔
3565
                case <-peer.ActiveSignal():
2✔
3566
                case <-peer.QuitSignal():
×
3567
                        // The peer quit, so we'll add the channel to the slice
×
3568
                        // and return.
×
3569
                        s.mu.Lock()
×
3570
                        s.peerConnectedListeners[pubStr] = append(
×
3571
                                s.peerConnectedListeners[pubStr], peerChan,
×
3572
                        )
×
3573
                        s.mu.Unlock()
×
3574
                        return
×
3575
                }
3576

3577
                // Connected, can return early.
3578
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
2✔
3579

2✔
3580
                select {
2✔
3581
                case peerChan <- peer:
2✔
3582
                case <-s.quit:
×
3583
                }
3584

3585
                return
2✔
3586
        }
3587

3588
        // Not connected, store this listener such that it can be notified when
3589
        // the peer comes online.
3590
        s.peerConnectedListeners[pubStr] = append(
2✔
3591
                s.peerConnectedListeners[pubStr], peerChan,
2✔
3592
        )
2✔
3593
        s.mu.Unlock()
2✔
3594
}
3595

3596
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3597
// the given public key has been disconnected. The notification is signaled by
3598
// closing the channel returned.
3599
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
2✔
3600
        s.mu.Lock()
2✔
3601
        defer s.mu.Unlock()
2✔
3602

2✔
3603
        c := make(chan struct{})
2✔
3604

2✔
3605
        // If the peer is already offline, we can immediately trigger the
2✔
3606
        // notification.
2✔
3607
        peerPubKeyStr := string(peerPubKey[:])
2✔
3608
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
2✔
3609
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3610
                close(c)
×
3611
                return c
×
3612
        }
×
3613

3614
        // Otherwise, the peer is online, so we'll keep track of the channel to
3615
        // trigger the notification once the server detects the peer
3616
        // disconnects.
3617
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
2✔
3618
                s.peerDisconnectedListeners[peerPubKeyStr], c,
2✔
3619
        )
2✔
3620

2✔
3621
        return c
2✔
3622
}
3623

3624
// FindPeer will return the peer that corresponds to the passed in public key.
3625
// This function is used by the funding manager, allowing it to update the
3626
// daemon's local representation of the remote peer.
3627
//
3628
// NOTE: This function is safe for concurrent access.
3629
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
2✔
3630
        s.mu.RLock()
2✔
3631
        defer s.mu.RUnlock()
2✔
3632

2✔
3633
        pubStr := string(peerKey.SerializeCompressed())
2✔
3634

2✔
3635
        return s.findPeerByPubStr(pubStr)
2✔
3636
}
2✔
3637

3638
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3639
// which should be a string representation of the peer's serialized, compressed
3640
// public key.
3641
//
3642
// NOTE: This function is safe for concurrent access.
3643
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
2✔
3644
        s.mu.RLock()
2✔
3645
        defer s.mu.RUnlock()
2✔
3646

2✔
3647
        return s.findPeerByPubStr(pubStr)
2✔
3648
}
2✔
3649

3650
// findPeerByPubStr is an internal method that retrieves the specified peer from
3651
// the server's internal state using.
3652
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
2✔
3653
        peer, ok := s.peersByPub[pubStr]
2✔
3654
        if !ok {
4✔
3655
                return nil, ErrPeerNotConnected
2✔
3656
        }
2✔
3657

3658
        return peer, nil
2✔
3659
}
3660

3661
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3662
// exponential backoff. If no previous backoff was known, the default is
3663
// returned.
3664
func (s *server) nextPeerBackoff(pubStr string,
3665
        startTime time.Time) time.Duration {
2✔
3666

2✔
3667
        // Now, determine the appropriate backoff to use for the retry.
2✔
3668
        backoff, ok := s.persistentPeersBackoff[pubStr]
2✔
3669
        if !ok {
4✔
3670
                // If an existing backoff was unknown, use the default.
2✔
3671
                return s.cfg.MinBackoff
2✔
3672
        }
2✔
3673

3674
        // If the peer failed to start properly, we'll just use the previous
3675
        // backoff to compute the subsequent randomized exponential backoff
3676
        // duration. This will roughly double on average.
3677
        if startTime.IsZero() {
2✔
3678
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3679
        }
×
3680

3681
        // The peer succeeded in starting. If the connection didn't last long
3682
        // enough to be considered stable, we'll continue to back off retries
3683
        // with this peer.
3684
        connDuration := time.Since(startTime)
2✔
3685
        if connDuration < defaultStableConnDuration {
4✔
3686
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
2✔
3687
        }
2✔
3688

3689
        // The peer succeed in starting and this was stable peer, so we'll
3690
        // reduce the timeout duration by the length of the connection after
3691
        // applying randomized exponential backoff. We'll only apply this in the
3692
        // case that:
3693
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3694
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3695
        if relaxedBackoff > s.cfg.MinBackoff {
×
3696
                return relaxedBackoff
×
3697
        }
×
3698

3699
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3700
        // the stable connection lasted much longer than our previous backoff.
3701
        // To reward such good behavior, we'll reconnect after the default
3702
        // timeout.
3703
        return s.cfg.MinBackoff
×
3704
}
3705

3706
// shouldDropLocalConnection determines if our local connection to a remote peer
3707
// should be dropped in the case of concurrent connection establishment. In
3708
// order to deterministically decide which connection should be dropped, we'll
3709
// utilize the ordering of the local and remote public key. If we didn't use
3710
// such a tie breaker, then we risk _both_ connections erroneously being
3711
// dropped.
3712
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3713
        localPubBytes := local.SerializeCompressed()
×
3714
        remotePubPbytes := remote.SerializeCompressed()
×
3715

×
3716
        // The connection that comes from the node with a "smaller" pubkey
×
3717
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3718
        // should drop our established connection.
×
3719
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3720
}
×
3721

3722
// InboundPeerConnected initializes a new peer in response to a new inbound
3723
// connection.
3724
//
3725
// NOTE: This function is safe for concurrent access.
3726
func (s *server) InboundPeerConnected(conn net.Conn) {
2✔
3727
        // Exit early if we have already been instructed to shutdown, this
2✔
3728
        // prevents any delayed callbacks from accidentally registering peers.
2✔
3729
        if s.Stopped() {
2✔
3730
                return
×
3731
        }
×
3732

3733
        nodePub := conn.(*brontide.Conn).RemotePub()
2✔
3734
        pubSer := nodePub.SerializeCompressed()
2✔
3735
        pubStr := string(pubSer)
2✔
3736

2✔
3737
        var pubBytes [33]byte
2✔
3738
        copy(pubBytes[:], pubSer)
2✔
3739

2✔
3740
        s.mu.Lock()
2✔
3741
        defer s.mu.Unlock()
2✔
3742

2✔
3743
        // If the remote node's public key is banned, drop the connection.
2✔
3744
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
2✔
3745
        if dcErr != nil {
2✔
3746
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3747
                        "peer: %v", dcErr)
×
3748
                conn.Close()
×
3749

×
3750
                return
×
3751
        }
×
3752

3753
        if shouldDc {
2✔
3754
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3755
                        "banned.", pubSer)
×
3756

×
3757
                conn.Close()
×
3758

×
3759
                return
×
3760
        }
×
3761

3762
        // If we already have an outbound connection to this peer, then ignore
3763
        // this new connection.
3764
        if p, ok := s.outboundPeers[pubStr]; ok {
4✔
3765
                srvrLog.Debugf("Already have outbound connection for %v, "+
2✔
3766
                        "ignoring inbound connection from local=%v, remote=%v",
2✔
3767
                        p, conn.LocalAddr(), conn.RemoteAddr())
2✔
3768

2✔
3769
                conn.Close()
2✔
3770
                return
2✔
3771
        }
2✔
3772

3773
        // If we already have a valid connection that is scheduled to take
3774
        // precedence once the prior peer has finished disconnecting, we'll
3775
        // ignore this connection.
3776
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
2✔
3777
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3778
                        "scheduled", conn.RemoteAddr(), p)
×
3779
                conn.Close()
×
3780
                return
×
3781
        }
×
3782

3783
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
2✔
3784

2✔
3785
        // Check to see if we already have a connection with this peer. If so,
2✔
3786
        // we may need to drop our existing connection. This prevents us from
2✔
3787
        // having duplicate connections to the same peer. We forgo adding a
2✔
3788
        // default case as we expect these to be the only error values returned
2✔
3789
        // from findPeerByPubStr.
2✔
3790
        connectedPeer, err := s.findPeerByPubStr(pubStr)
2✔
3791
        switch err {
2✔
3792
        case ErrPeerNotConnected:
2✔
3793
                // We were unable to locate an existing connection with the
2✔
3794
                // target peer, proceed to connect.
2✔
3795
                s.cancelConnReqs(pubStr, nil)
2✔
3796
                s.peerConnected(conn, nil, true)
2✔
3797

3798
        case nil:
×
3799
                // We already have a connection with the incoming peer. If the
×
3800
                // connection we've already established should be kept and is
×
3801
                // not of the same type of the new connection (inbound), then
×
3802
                // we'll close out the new connection s.t there's only a single
×
3803
                // connection between us.
×
3804
                localPub := s.identityECDH.PubKey()
×
3805
                if !connectedPeer.Inbound() &&
×
3806
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3807

×
3808
                        srvrLog.Warnf("Received inbound connection from "+
×
3809
                                "peer %v, but already have outbound "+
×
3810
                                "connection, dropping conn", connectedPeer)
×
3811
                        conn.Close()
×
3812
                        return
×
3813
                }
×
3814

3815
                // Otherwise, if we should drop the connection, then we'll
3816
                // disconnect our already connected peer.
3817
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3818
                        connectedPeer)
×
3819

×
3820
                s.cancelConnReqs(pubStr, nil)
×
3821

×
3822
                // Remove the current peer from the server's internal state and
×
3823
                // signal that the peer termination watcher does not need to
×
3824
                // execute for this peer.
×
3825
                s.removePeer(connectedPeer)
×
3826
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3827
                s.scheduledPeerConnection[pubStr] = func() {
×
3828
                        s.peerConnected(conn, nil, true)
×
3829
                }
×
3830
        }
3831
}
3832

3833
// OutboundPeerConnected initializes a new peer in response to a new outbound
3834
// connection.
3835
// NOTE: This function is safe for concurrent access.
3836
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
2✔
3837
        // Exit early if we have already been instructed to shutdown, this
2✔
3838
        // prevents any delayed callbacks from accidentally registering peers.
2✔
3839
        if s.Stopped() {
2✔
3840
                return
×
3841
        }
×
3842

3843
        nodePub := conn.(*brontide.Conn).RemotePub()
2✔
3844
        pubSer := nodePub.SerializeCompressed()
2✔
3845
        pubStr := string(pubSer)
2✔
3846

2✔
3847
        var pubBytes [33]byte
2✔
3848
        copy(pubBytes[:], pubSer)
2✔
3849

2✔
3850
        s.mu.Lock()
2✔
3851
        defer s.mu.Unlock()
2✔
3852

2✔
3853
        // If the remote node's public key is banned, drop the connection.
2✔
3854
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
2✔
3855
        if dcErr != nil {
2✔
3856
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3857
                        "peer: %v", dcErr)
×
3858
                conn.Close()
×
3859

×
3860
                return
×
3861
        }
×
3862

3863
        if shouldDc {
2✔
3864
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3865
                        "banned.", pubSer)
×
3866

×
3867
                if connReq != nil {
×
3868
                        s.connMgr.Remove(connReq.ID())
×
3869
                }
×
3870

3871
                conn.Close()
×
3872

×
3873
                return
×
3874
        }
3875

3876
        // If we already have an inbound connection to this peer, then ignore
3877
        // this new connection.
3878
        if p, ok := s.inboundPeers[pubStr]; ok {
4✔
3879
                srvrLog.Debugf("Already have inbound connection for %v, "+
2✔
3880
                        "ignoring outbound connection from local=%v, remote=%v",
2✔
3881
                        p, conn.LocalAddr(), conn.RemoteAddr())
2✔
3882

2✔
3883
                if connReq != nil {
4✔
3884
                        s.connMgr.Remove(connReq.ID())
2✔
3885
                }
2✔
3886
                conn.Close()
2✔
3887
                return
2✔
3888
        }
3889
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
2✔
3890
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3891
                s.connMgr.Remove(connReq.ID())
×
3892
                conn.Close()
×
3893
                return
×
3894
        }
×
3895

3896
        // If we already have a valid connection that is scheduled to take
3897
        // precedence once the prior peer has finished disconnecting, we'll
3898
        // ignore this connection.
3899
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
2✔
3900
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
3901

×
3902
                if connReq != nil {
×
3903
                        s.connMgr.Remove(connReq.ID())
×
3904
                }
×
3905

3906
                conn.Close()
×
3907
                return
×
3908
        }
3909

3910
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
2✔
3911
                conn.RemoteAddr())
2✔
3912

2✔
3913
        if connReq != nil {
4✔
3914
                // A successful connection was returned by the connmgr.
2✔
3915
                // Immediately cancel all pending requests, excluding the
2✔
3916
                // outbound connection we just established.
2✔
3917
                ignore := connReq.ID()
2✔
3918
                s.cancelConnReqs(pubStr, &ignore)
2✔
3919
        } else {
4✔
3920
                // This was a successful connection made by some other
2✔
3921
                // subsystem. Remove all requests being managed by the connmgr.
2✔
3922
                s.cancelConnReqs(pubStr, nil)
2✔
3923
        }
2✔
3924

3925
        // If we already have a connection with this peer, decide whether or not
3926
        // we need to drop the stale connection. We forgo adding a default case
3927
        // as we expect these to be the only error values returned from
3928
        // findPeerByPubStr.
3929
        connectedPeer, err := s.findPeerByPubStr(pubStr)
2✔
3930
        switch err {
2✔
3931
        case ErrPeerNotConnected:
2✔
3932
                // We were unable to locate an existing connection with the
2✔
3933
                // target peer, proceed to connect.
2✔
3934
                s.peerConnected(conn, connReq, false)
2✔
3935

3936
        case nil:
×
3937
                // We already have a connection with the incoming peer. If the
×
3938
                // connection we've already established should be kept and is
×
3939
                // not of the same type of the new connection (outbound), then
×
3940
                // we'll close out the new connection s.t there's only a single
×
3941
                // connection between us.
×
3942
                localPub := s.identityECDH.PubKey()
×
3943
                if connectedPeer.Inbound() &&
×
3944
                        shouldDropLocalConnection(localPub, nodePub) {
×
3945

×
3946
                        srvrLog.Warnf("Established outbound connection to "+
×
3947
                                "peer %v, but already have inbound "+
×
3948
                                "connection, dropping conn", connectedPeer)
×
3949
                        if connReq != nil {
×
3950
                                s.connMgr.Remove(connReq.ID())
×
3951
                        }
×
3952
                        conn.Close()
×
3953
                        return
×
3954
                }
3955

3956
                // Otherwise, _their_ connection should be dropped. So we'll
3957
                // disconnect the peer and send the now obsolete peer to the
3958
                // server for garbage collection.
3959
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3960
                        connectedPeer)
×
3961

×
3962
                // Remove the current peer from the server's internal state and
×
3963
                // signal that the peer termination watcher does not need to
×
3964
                // execute for this peer.
×
3965
                s.removePeer(connectedPeer)
×
3966
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3967
                s.scheduledPeerConnection[pubStr] = func() {
×
3968
                        s.peerConnected(conn, connReq, false)
×
3969
                }
×
3970
        }
3971
}
3972

3973
// UnassignedConnID is the default connection ID that a request can have before
3974
// it actually is submitted to the connmgr.
3975
// TODO(conner): move into connmgr package, or better, add connmgr method for
3976
// generating atomic IDs
3977
const UnassignedConnID uint64 = 0
3978

3979
// cancelConnReqs stops all persistent connection requests for a given pubkey.
3980
// Any attempts initiated by the peerTerminationWatcher are canceled first.
3981
// Afterwards, each connection request removed from the connmgr. The caller can
3982
// optionally specify a connection ID to ignore, which prevents us from
3983
// canceling a successful request. All persistent connreqs for the provided
3984
// pubkey are discarded after the operationjw.
3985
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
2✔
3986
        // First, cancel any lingering persistent retry attempts, which will
2✔
3987
        // prevent retries for any with backoffs that are still maturing.
2✔
3988
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
4✔
3989
                close(cancelChan)
2✔
3990
                delete(s.persistentRetryCancels, pubStr)
2✔
3991
        }
2✔
3992

3993
        // Next, check to see if we have any outstanding persistent connection
3994
        // requests to this peer. If so, then we'll remove all of these
3995
        // connection requests, and also delete the entry from the map.
3996
        connReqs, ok := s.persistentConnReqs[pubStr]
2✔
3997
        if !ok {
4✔
3998
                return
2✔
3999
        }
2✔
4000

4001
        for _, connReq := range connReqs {
4✔
4002
                srvrLog.Tracef("Canceling %s:", connReqs)
2✔
4003

2✔
4004
                // Atomically capture the current request identifier.
2✔
4005
                connID := connReq.ID()
2✔
4006

2✔
4007
                // Skip any zero IDs, this indicates the request has not
2✔
4008
                // yet been schedule.
2✔
4009
                if connID == UnassignedConnID {
2✔
4010
                        continue
×
4011
                }
4012

4013
                // Skip a particular connection ID if instructed.
4014
                if skip != nil && connID == *skip {
4✔
4015
                        continue
2✔
4016
                }
4017

4018
                s.connMgr.Remove(connID)
2✔
4019
        }
4020

4021
        delete(s.persistentConnReqs, pubStr)
2✔
4022
}
4023

4024
// handleCustomMessage dispatches an incoming custom peers message to
4025
// subscribers.
4026
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
2✔
4027
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
2✔
4028
                peer, msg.Type)
2✔
4029

2✔
4030
        return s.customMessageServer.SendUpdate(&CustomMessage{
2✔
4031
                Peer: peer,
2✔
4032
                Msg:  msg,
2✔
4033
        })
2✔
4034
}
2✔
4035

4036
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4037
// messages.
4038
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
2✔
4039
        return s.customMessageServer.Subscribe()
2✔
4040
}
2✔
4041

4042
// peerConnected is a function that handles initialization a newly connected
4043
// peer by adding it to the server's global list of all active peers, and
4044
// starting all the goroutines the peer needs to function properly. The inbound
4045
// boolean should be true if the peer initiated the connection to us.
4046
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4047
        inbound bool) {
2✔
4048

2✔
4049
        brontideConn := conn.(*brontide.Conn)
2✔
4050
        addr := conn.RemoteAddr()
2✔
4051
        pubKey := brontideConn.RemotePub()
2✔
4052

2✔
4053
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
2✔
4054
                pubKey.SerializeCompressed(), addr, inbound)
2✔
4055

2✔
4056
        peerAddr := &lnwire.NetAddress{
2✔
4057
                IdentityKey: pubKey,
2✔
4058
                Address:     addr,
2✔
4059
                ChainNet:    s.cfg.ActiveNetParams.Net,
2✔
4060
        }
2✔
4061

2✔
4062
        // With the brontide connection established, we'll now craft the feature
2✔
4063
        // vectors to advertise to the remote node.
2✔
4064
        initFeatures := s.featureMgr.Get(feature.SetInit)
2✔
4065
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
2✔
4066

2✔
4067
        // Lookup past error caches for the peer in the server. If no buffer is
2✔
4068
        // found, create a fresh buffer.
2✔
4069
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
2✔
4070
        errBuffer, ok := s.peerErrors[pkStr]
2✔
4071
        if !ok {
4✔
4072
                var err error
2✔
4073
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
2✔
4074
                if err != nil {
2✔
4075
                        srvrLog.Errorf("unable to create peer %v", err)
×
4076
                        return
×
4077
                }
×
4078
        }
4079

4080
        // If we directly set the peer.Config TowerClient member to the
4081
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4082
        // the peer.Config's TowerClient member will not evaluate to nil even
4083
        // though the underlying value is nil. To avoid this gotcha which can
4084
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4085
        // TowerClient if needed.
4086
        var towerClient wtclient.ClientManager
2✔
4087
        if s.towerClientMgr != nil {
4✔
4088
                towerClient = s.towerClientMgr
2✔
4089
        }
2✔
4090

4091
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
2✔
4092
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
2✔
4093

2✔
4094
        // Now that we've established a connection, create a peer, and it to the
2✔
4095
        // set of currently active peers. Configure the peer with the incoming
2✔
4096
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
2✔
4097
        // offered that would trigger channel closure. In case of outgoing
2✔
4098
        // htlcs, an extra block is added to prevent the channel from being
2✔
4099
        // closed when the htlc is outstanding and a new block comes in.
2✔
4100
        pCfg := peer.Config{
2✔
4101
                Conn:                    brontideConn,
2✔
4102
                ConnReq:                 connReq,
2✔
4103
                Addr:                    peerAddr,
2✔
4104
                Inbound:                 inbound,
2✔
4105
                Features:                initFeatures,
2✔
4106
                LegacyFeatures:          legacyFeatures,
2✔
4107
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
2✔
4108
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
2✔
4109
                ErrorBuffer:             errBuffer,
2✔
4110
                WritePool:               s.writePool,
2✔
4111
                ReadPool:                s.readPool,
2✔
4112
                Switch:                  s.htlcSwitch,
2✔
4113
                InterceptSwitch:         s.interceptableSwitch,
2✔
4114
                ChannelDB:               s.chanStateDB,
2✔
4115
                ChannelGraph:            s.graphDB,
2✔
4116
                ChainArb:                s.chainArb,
2✔
4117
                AuthGossiper:            s.authGossiper,
2✔
4118
                ChanStatusMgr:           s.chanStatusMgr,
2✔
4119
                ChainIO:                 s.cc.ChainIO,
2✔
4120
                FeeEstimator:            s.cc.FeeEstimator,
2✔
4121
                Signer:                  s.cc.Wallet.Cfg.Signer,
2✔
4122
                SigPool:                 s.sigPool,
2✔
4123
                Wallet:                  s.cc.Wallet,
2✔
4124
                ChainNotifier:           s.cc.ChainNotifier,
2✔
4125
                BestBlockView:           s.cc.BestBlockTracker,
2✔
4126
                RoutingPolicy:           s.cc.RoutingPolicy,
2✔
4127
                Sphinx:                  s.sphinx,
2✔
4128
                WitnessBeacon:           s.witnessBeacon,
2✔
4129
                Invoices:                s.invoices,
2✔
4130
                ChannelNotifier:         s.channelNotifier,
2✔
4131
                HtlcNotifier:            s.htlcNotifier,
2✔
4132
                TowerClient:             towerClient,
2✔
4133
                DisconnectPeer:          s.DisconnectPeer,
2✔
4134
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
2✔
4135
                        lnwire.NodeAnnouncement, error) {
4✔
4136

2✔
4137
                        return s.genNodeAnnouncement(nil)
2✔
4138
                },
2✔
4139

4140
                PongBuf: s.pongBuf,
4141

4142
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4143

4144
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4145

4146
                FundingManager: s.fundingMgr,
4147

4148
                Hodl:                    s.cfg.Hodl,
4149
                UnsafeReplay:            s.cfg.UnsafeReplay,
4150
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4151
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4152
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4153
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4154
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4155
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4156
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4157
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4158
                HandleCustomMessage:    s.handleCustomMessage,
4159
                GetAliases:             s.aliasMgr.GetAliases,
4160
                RequestAlias:           s.aliasMgr.RequestAlias,
4161
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4162
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4163
                MaxFeeExposure:         thresholdMSats,
4164
                Quit:                   s.quit,
4165
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4166
                AuxSigner:              s.implCfg.AuxSigner,
4167
                MsgRouter:              s.implCfg.MsgRouter,
4168
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4169
                AuxResolver:            s.implCfg.AuxContractResolver,
4170
        }
4171

4172
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
2✔
4173
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
2✔
4174

2✔
4175
        p := peer.NewBrontide(pCfg)
2✔
4176

2✔
4177
        // TODO(roasbeef): update IP address for link-node
2✔
4178
        //  * also mark last-seen, do it one single transaction?
2✔
4179

2✔
4180
        s.addPeer(p)
2✔
4181

2✔
4182
        // Once we have successfully added the peer to the server, we can
2✔
4183
        // delete the previous error buffer from the server's map of error
2✔
4184
        // buffers.
2✔
4185
        delete(s.peerErrors, pkStr)
2✔
4186

2✔
4187
        // Dispatch a goroutine to asynchronously start the peer. This process
2✔
4188
        // includes sending and receiving Init messages, which would be a DOS
2✔
4189
        // vector if we held the server's mutex throughout the procedure.
2✔
4190
        s.wg.Add(1)
2✔
4191
        go s.peerInitializer(p)
2✔
4192
}
4193

4194
// addPeer adds the passed peer to the server's global state of all active
4195
// peers.
4196
func (s *server) addPeer(p *peer.Brontide) {
2✔
4197
        if p == nil {
2✔
4198
                return
×
4199
        }
×
4200

4201
        // Ignore new peers if we're shutting down.
4202
        if s.Stopped() {
2✔
4203
                p.Disconnect(ErrServerShuttingDown)
×
4204
                return
×
4205
        }
×
4206

4207
        // Track the new peer in our indexes so we can quickly look it up either
4208
        // according to its public key, or its peer ID.
4209
        // TODO(roasbeef): pipe all requests through to the
4210
        // queryHandler/peerManager
4211

4212
        pubSer := p.IdentityKey().SerializeCompressed()
2✔
4213
        pubStr := string(pubSer)
2✔
4214

2✔
4215
        s.peersByPub[pubStr] = p
2✔
4216

2✔
4217
        if p.Inbound() {
4✔
4218
                s.inboundPeers[pubStr] = p
2✔
4219
        } else {
4✔
4220
                s.outboundPeers[pubStr] = p
2✔
4221
        }
2✔
4222

4223
        // Inform the peer notifier of a peer online event so that it can be reported
4224
        // to clients listening for peer events.
4225
        var pubKey [33]byte
2✔
4226
        copy(pubKey[:], pubSer)
2✔
4227

2✔
4228
        s.peerNotifier.NotifyPeerOnline(pubKey)
2✔
4229
}
4230

4231
// peerInitializer asynchronously starts a newly connected peer after it has
4232
// been added to the server's peer map. This method sets up a
4233
// peerTerminationWatcher for the given peer, and ensures that it executes even
4234
// if the peer failed to start. In the event of a successful connection, this
4235
// method reads the negotiated, local feature-bits and spawns the appropriate
4236
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4237
// be signaled of the new peer once the method returns.
4238
//
4239
// NOTE: This MUST be launched as a goroutine.
4240
func (s *server) peerInitializer(p *peer.Brontide) {
2✔
4241
        defer s.wg.Done()
2✔
4242

2✔
4243
        // Avoid initializing peers while the server is exiting.
2✔
4244
        if s.Stopped() {
2✔
4245
                return
×
4246
        }
×
4247

4248
        // Create a channel that will be used to signal a successful start of
4249
        // the link. This prevents the peer termination watcher from beginning
4250
        // its duty too early.
4251
        ready := make(chan struct{})
2✔
4252

2✔
4253
        // Before starting the peer, launch a goroutine to watch for the
2✔
4254
        // unexpected termination of this peer, which will ensure all resources
2✔
4255
        // are properly cleaned up, and re-establish persistent connections when
2✔
4256
        // necessary. The peer termination watcher will be short circuited if
2✔
4257
        // the peer is ever added to the ignorePeerTermination map, indicating
2✔
4258
        // that the server has already handled the removal of this peer.
2✔
4259
        s.wg.Add(1)
2✔
4260
        go s.peerTerminationWatcher(p, ready)
2✔
4261

2✔
4262
        pubBytes := p.IdentityKey().SerializeCompressed()
2✔
4263

2✔
4264
        // Start the peer! If an error occurs, we Disconnect the peer, which
2✔
4265
        // will unblock the peerTerminationWatcher.
2✔
4266
        if err := p.Start(); err != nil {
3✔
4267
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
1✔
4268

1✔
4269
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
1✔
4270
                return
1✔
4271
        }
1✔
4272

4273
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4274
        // was successful, and to begin watching the peer's wait group.
4275
        close(ready)
2✔
4276

2✔
4277
        s.mu.Lock()
2✔
4278
        defer s.mu.Unlock()
2✔
4279

2✔
4280
        // Check if there are listeners waiting for this peer to come online.
2✔
4281
        srvrLog.Debugf("Notifying that peer %v is online", p)
2✔
4282

2✔
4283
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
2✔
4284
        // route.Vertex as the key type of peerConnectedListeners.
2✔
4285
        pubStr := string(pubBytes)
2✔
4286
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
4✔
4287
                select {
2✔
4288
                case peerChan <- p:
2✔
UNCOV
4289
                case <-s.quit:
×
UNCOV
4290
                        return
×
4291
                }
4292
        }
4293
        delete(s.peerConnectedListeners, pubStr)
2✔
4294
}
4295

4296
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4297
// and then cleans up all resources allocated to the peer, notifies relevant
4298
// sub-systems of its demise, and finally handles re-connecting to the peer if
4299
// it's persistent. If the server intentionally disconnects a peer, it should
4300
// have a corresponding entry in the ignorePeerTermination map which will cause
4301
// the cleanup routine to exit early. The passed `ready` chan is used to
4302
// synchronize when WaitForDisconnect should begin watching on the peer's
4303
// waitgroup. The ready chan should only be signaled if the peer starts
4304
// successfully, otherwise the peer should be disconnected instead.
4305
//
4306
// NOTE: This MUST be launched as a goroutine.
4307
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
2✔
4308
        defer s.wg.Done()
2✔
4309

2✔
4310
        p.WaitForDisconnect(ready)
2✔
4311

2✔
4312
        srvrLog.Debugf("Peer %v has been disconnected", p)
2✔
4313

2✔
4314
        // If the server is exiting then we can bail out early ourselves as all
2✔
4315
        // the other sub-systems will already be shutting down.
2✔
4316
        if s.Stopped() {
4✔
4317
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
2✔
4318
                return
2✔
4319
        }
2✔
4320

4321
        // Next, we'll cancel all pending funding reservations with this node.
4322
        // If we tried to initiate any funding flows that haven't yet finished,
4323
        // then we need to unlock those committed outputs so they're still
4324
        // available for use.
4325
        s.fundingMgr.CancelPeerReservations(p.PubKey())
2✔
4326

2✔
4327
        pubKey := p.IdentityKey()
2✔
4328

2✔
4329
        // We'll also inform the gossiper that this peer is no longer active,
2✔
4330
        // so we don't need to maintain sync state for it any longer.
2✔
4331
        s.authGossiper.PruneSyncState(p.PubKey())
2✔
4332

2✔
4333
        // Tell the switch to remove all links associated with this peer.
2✔
4334
        // Passing nil as the target link indicates that all links associated
2✔
4335
        // with this interface should be closed.
2✔
4336
        //
2✔
4337
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
2✔
4338
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
2✔
4339
        if err != nil && err != htlcswitch.ErrNoLinksFound {
2✔
4340
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4341
        }
×
4342

4343
        for _, link := range links {
4✔
4344
                s.htlcSwitch.RemoveLink(link.ChanID())
2✔
4345
        }
2✔
4346

4347
        s.mu.Lock()
2✔
4348
        defer s.mu.Unlock()
2✔
4349

2✔
4350
        // If there were any notification requests for when this peer
2✔
4351
        // disconnected, we can trigger them now.
2✔
4352
        srvrLog.Debugf("Notifying that peer %v is offline", p)
2✔
4353
        pubStr := string(pubKey.SerializeCompressed())
2✔
4354
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
4✔
4355
                close(offlineChan)
2✔
4356
        }
2✔
4357
        delete(s.peerDisconnectedListeners, pubStr)
2✔
4358

2✔
4359
        // If the server has already removed this peer, we can short circuit the
2✔
4360
        // peer termination watcher and skip cleanup.
2✔
4361
        if _, ok := s.ignorePeerTermination[p]; ok {
2✔
4362
                delete(s.ignorePeerTermination, p)
×
4363

×
4364
                pubKey := p.PubKey()
×
4365
                pubStr := string(pubKey[:])
×
4366

×
4367
                // If a connection callback is present, we'll go ahead and
×
4368
                // execute it now that previous peer has fully disconnected. If
×
4369
                // the callback is not present, this likely implies the peer was
×
4370
                // purposefully disconnected via RPC, and that no reconnect
×
4371
                // should be attempted.
×
4372
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4373
                if ok {
×
4374
                        delete(s.scheduledPeerConnection, pubStr)
×
4375
                        connCallback()
×
4376
                }
×
4377
                return
×
4378
        }
4379

4380
        // First, cleanup any remaining state the server has regarding the peer
4381
        // in question.
4382
        s.removePeer(p)
2✔
4383

2✔
4384
        // Next, check to see if this is a persistent peer or not.
2✔
4385
        if _, ok := s.persistentPeers[pubStr]; !ok {
4✔
4386
                return
2✔
4387
        }
2✔
4388

4389
        // Get the last address that we used to connect to the peer.
4390
        addrs := []net.Addr{
2✔
4391
                p.NetAddress().Address,
2✔
4392
        }
2✔
4393

2✔
4394
        // We'll ensure that we locate all the peers advertised addresses for
2✔
4395
        // reconnection purposes.
2✔
4396
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
2✔
4397
        switch {
2✔
4398
        // We found advertised addresses, so use them.
4399
        case err == nil:
2✔
4400
                addrs = advertisedAddrs
2✔
4401

4402
        // The peer doesn't have an advertised address.
4403
        case err == errNoAdvertisedAddr:
2✔
4404
                // If it is an outbound peer then we fall back to the existing
2✔
4405
                // peer address.
2✔
4406
                if !p.Inbound() {
4✔
4407
                        break
2✔
4408
                }
4409

4410
                // Fall back to the existing peer address if
4411
                // we're not accepting connections over Tor.
4412
                if s.torController == nil {
4✔
4413
                        break
2✔
4414
                }
4415

4416
                // If we are, the peer's address won't be known
4417
                // to us (we'll see a private address, which is
4418
                // the address used by our onion service to dial
4419
                // to lnd), so we don't have enough information
4420
                // to attempt a reconnect.
4421
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4422
                        "to inbound peer %v without "+
×
4423
                        "advertised address", p)
×
4424
                return
×
4425

4426
        // We came across an error retrieving an advertised
4427
        // address, log it, and fall back to the existing peer
4428
        // address.
4429
        default:
2✔
4430
                srvrLog.Errorf("Unable to retrieve advertised "+
2✔
4431
                        "address for node %x: %v", p.PubKey(),
2✔
4432
                        err)
2✔
4433
        }
4434

4435
        // Make an easy lookup map so that we can check if an address
4436
        // is already in the address list that we have stored for this peer.
4437
        existingAddrs := make(map[string]bool)
2✔
4438
        for _, addr := range s.persistentPeerAddrs[pubStr] {
4✔
4439
                existingAddrs[addr.String()] = true
2✔
4440
        }
2✔
4441

4442
        // Add any missing addresses for this peer to persistentPeerAddr.
4443
        for _, addr := range addrs {
4✔
4444
                if existingAddrs[addr.String()] {
2✔
4445
                        continue
×
4446
                }
4447

4448
                s.persistentPeerAddrs[pubStr] = append(
2✔
4449
                        s.persistentPeerAddrs[pubStr],
2✔
4450
                        &lnwire.NetAddress{
2✔
4451
                                IdentityKey: p.IdentityKey(),
2✔
4452
                                Address:     addr,
2✔
4453
                                ChainNet:    p.NetAddress().ChainNet,
2✔
4454
                        },
2✔
4455
                )
2✔
4456
        }
4457

4458
        // Record the computed backoff in the backoff map.
4459
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
2✔
4460
        s.persistentPeersBackoff[pubStr] = backoff
2✔
4461

2✔
4462
        // Initialize a retry canceller for this peer if one does not
2✔
4463
        // exist.
2✔
4464
        cancelChan, ok := s.persistentRetryCancels[pubStr]
2✔
4465
        if !ok {
4✔
4466
                cancelChan = make(chan struct{})
2✔
4467
                s.persistentRetryCancels[pubStr] = cancelChan
2✔
4468
        }
2✔
4469

4470
        // We choose not to wait group this go routine since the Connect
4471
        // call can stall for arbitrarily long if we shutdown while an
4472
        // outbound connection attempt is being made.
4473
        go func() {
4✔
4474
                srvrLog.Debugf("Scheduling connection re-establishment to "+
2✔
4475
                        "persistent peer %x in %s",
2✔
4476
                        p.IdentityKey().SerializeCompressed(), backoff)
2✔
4477

2✔
4478
                select {
2✔
4479
                case <-time.After(backoff):
2✔
4480
                case <-cancelChan:
2✔
4481
                        return
2✔
4482
                case <-s.quit:
2✔
4483
                        return
2✔
4484
                }
4485

4486
                srvrLog.Debugf("Attempting to re-establish persistent "+
2✔
4487
                        "connection to peer %x",
2✔
4488
                        p.IdentityKey().SerializeCompressed())
2✔
4489

2✔
4490
                s.connectToPersistentPeer(pubStr)
2✔
4491
        }()
4492
}
4493

4494
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4495
// to connect to the peer. It creates connection requests if there are
4496
// currently none for a given address and it removes old connection requests
4497
// if the associated address is no longer in the latest address list for the
4498
// peer.
4499
func (s *server) connectToPersistentPeer(pubKeyStr string) {
2✔
4500
        s.mu.Lock()
2✔
4501
        defer s.mu.Unlock()
2✔
4502

2✔
4503
        // Create an easy lookup map of the addresses we have stored for the
2✔
4504
        // peer. We will remove entries from this map if we have existing
2✔
4505
        // connection requests for the associated address and then any leftover
2✔
4506
        // entries will indicate which addresses we should create new
2✔
4507
        // connection requests for.
2✔
4508
        addrMap := make(map[string]*lnwire.NetAddress)
2✔
4509
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
4✔
4510
                addrMap[addr.String()] = addr
2✔
4511
        }
2✔
4512

4513
        // Go through each of the existing connection requests and
4514
        // check if they correspond to the latest set of addresses. If
4515
        // there is a connection requests that does not use one of the latest
4516
        // advertised addresses then remove that connection request.
4517
        var updatedConnReqs []*connmgr.ConnReq
2✔
4518
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
4✔
4519
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
2✔
4520

2✔
4521
                switch _, ok := addrMap[lnAddr]; ok {
2✔
4522
                // If the existing connection request is using one of the
4523
                // latest advertised addresses for the peer then we add it to
4524
                // updatedConnReqs and remove the associated address from
4525
                // addrMap so that we don't recreate this connReq later on.
4526
                case true:
×
4527
                        updatedConnReqs = append(
×
4528
                                updatedConnReqs, connReq,
×
4529
                        )
×
4530
                        delete(addrMap, lnAddr)
×
4531

4532
                // If the existing connection request is using an address that
4533
                // is not one of the latest advertised addresses for the peer
4534
                // then we remove the connecting request from the connection
4535
                // manager.
4536
                case false:
2✔
4537
                        srvrLog.Info(
2✔
4538
                                "Removing conn req:", connReq.Addr.String(),
2✔
4539
                        )
2✔
4540
                        s.connMgr.Remove(connReq.ID())
2✔
4541
                }
4542
        }
4543

4544
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
2✔
4545

2✔
4546
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
2✔
4547
        if !ok {
4✔
4548
                cancelChan = make(chan struct{})
2✔
4549
                s.persistentRetryCancels[pubKeyStr] = cancelChan
2✔
4550
        }
2✔
4551

4552
        // Any addresses left in addrMap are new ones that we have not made
4553
        // connection requests for. So create new connection requests for those.
4554
        // If there is more than one address in the address map, stagger the
4555
        // creation of the connection requests for those.
4556
        go func() {
4✔
4557
                ticker := time.NewTicker(multiAddrConnectionStagger)
2✔
4558
                defer ticker.Stop()
2✔
4559

2✔
4560
                for _, addr := range addrMap {
4✔
4561
                        // Send the persistent connection request to the
2✔
4562
                        // connection manager, saving the request itself so we
2✔
4563
                        // can cancel/restart the process as needed.
2✔
4564
                        connReq := &connmgr.ConnReq{
2✔
4565
                                Addr:      addr,
2✔
4566
                                Permanent: true,
2✔
4567
                        }
2✔
4568

2✔
4569
                        s.mu.Lock()
2✔
4570
                        s.persistentConnReqs[pubKeyStr] = append(
2✔
4571
                                s.persistentConnReqs[pubKeyStr], connReq,
2✔
4572
                        )
2✔
4573
                        s.mu.Unlock()
2✔
4574

2✔
4575
                        srvrLog.Debugf("Attempting persistent connection to "+
2✔
4576
                                "channel peer %v", addr)
2✔
4577

2✔
4578
                        go s.connMgr.Connect(connReq)
2✔
4579

2✔
4580
                        select {
2✔
4581
                        case <-s.quit:
2✔
4582
                                return
2✔
4583
                        case <-cancelChan:
2✔
4584
                                return
2✔
4585
                        case <-ticker.C:
2✔
4586
                        }
4587
                }
4588
        }()
4589
}
4590

4591
// removePeer removes the passed peer from the server's state of all active
4592
// peers.
4593
func (s *server) removePeer(p *peer.Brontide) {
2✔
4594
        if p == nil {
2✔
4595
                return
×
4596
        }
×
4597

4598
        srvrLog.Debugf("removing peer %v", p)
2✔
4599

2✔
4600
        // As the peer is now finished, ensure that the TCP connection is
2✔
4601
        // closed and all of its related goroutines have exited.
2✔
4602
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
2✔
4603

2✔
4604
        // If this peer had an active persistent connection request, remove it.
2✔
4605
        if p.ConnReq() != nil {
4✔
4606
                s.connMgr.Remove(p.ConnReq().ID())
2✔
4607
        }
2✔
4608

4609
        // Ignore deleting peers if we're shutting down.
4610
        if s.Stopped() {
2✔
4611
                return
×
4612
        }
×
4613

4614
        pKey := p.PubKey()
2✔
4615
        pubSer := pKey[:]
2✔
4616
        pubStr := string(pubSer)
2✔
4617

2✔
4618
        delete(s.peersByPub, pubStr)
2✔
4619

2✔
4620
        if p.Inbound() {
4✔
4621
                delete(s.inboundPeers, pubStr)
2✔
4622
        } else {
4✔
4623
                delete(s.outboundPeers, pubStr)
2✔
4624
        }
2✔
4625

4626
        // Copy the peer's error buffer across to the server if it has any items
4627
        // in it so that we can restore peer errors across connections.
4628
        if p.ErrorBuffer().Total() > 0 {
4✔
4629
                s.peerErrors[pubStr] = p.ErrorBuffer()
2✔
4630
        }
2✔
4631

4632
        // Inform the peer notifier of a peer offline event so that it can be
4633
        // reported to clients listening for peer events.
4634
        var pubKey [33]byte
2✔
4635
        copy(pubKey[:], pubSer)
2✔
4636

2✔
4637
        s.peerNotifier.NotifyPeerOffline(pubKey)
2✔
4638
}
4639

4640
// ConnectToPeer requests that the server connect to a Lightning Network peer
4641
// at the specified address. This function will *block* until either a
4642
// connection is established, or the initial handshake process fails.
4643
//
4644
// NOTE: This function is safe for concurrent access.
4645
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4646
        perm bool, timeout time.Duration) error {
2✔
4647

2✔
4648
        targetPub := string(addr.IdentityKey.SerializeCompressed())
2✔
4649

2✔
4650
        // Acquire mutex, but use explicit unlocking instead of defer for
2✔
4651
        // better granularity.  In certain conditions, this method requires
2✔
4652
        // making an outbound connection to a remote peer, which requires the
2✔
4653
        // lock to be released, and subsequently reacquired.
2✔
4654
        s.mu.Lock()
2✔
4655

2✔
4656
        // Ensure we're not already connected to this peer.
2✔
4657
        peer, err := s.findPeerByPubStr(targetPub)
2✔
4658
        if err == nil {
4✔
4659
                s.mu.Unlock()
2✔
4660
                return &errPeerAlreadyConnected{peer: peer}
2✔
4661
        }
2✔
4662

4663
        // Peer was not found, continue to pursue connection with peer.
4664

4665
        // If there's already a pending connection request for this pubkey,
4666
        // then we ignore this request to ensure we don't create a redundant
4667
        // connection.
4668
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
4✔
4669
                srvrLog.Warnf("Already have %d persistent connection "+
2✔
4670
                        "requests for %v, connecting anyway.", len(reqs), addr)
2✔
4671
        }
2✔
4672

4673
        // If there's not already a pending or active connection to this node,
4674
        // then instruct the connection manager to attempt to establish a
4675
        // persistent connection to the peer.
4676
        srvrLog.Debugf("Connecting to %v", addr)
2✔
4677
        if perm {
4✔
4678
                connReq := &connmgr.ConnReq{
2✔
4679
                        Addr:      addr,
2✔
4680
                        Permanent: true,
2✔
4681
                }
2✔
4682

2✔
4683
                // Since the user requested a permanent connection, we'll set
2✔
4684
                // the entry to true which will tell the server to continue
2✔
4685
                // reconnecting even if the number of channels with this peer is
2✔
4686
                // zero.
2✔
4687
                s.persistentPeers[targetPub] = true
2✔
4688
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
4✔
4689
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
2✔
4690
                }
2✔
4691
                s.persistentConnReqs[targetPub] = append(
2✔
4692
                        s.persistentConnReqs[targetPub], connReq,
2✔
4693
                )
2✔
4694
                s.mu.Unlock()
2✔
4695

2✔
4696
                go s.connMgr.Connect(connReq)
2✔
4697

2✔
4698
                return nil
2✔
4699
        }
4700
        s.mu.Unlock()
2✔
4701

2✔
4702
        // If we're not making a persistent connection, then we'll attempt to
2✔
4703
        // connect to the target peer. If the we can't make the connection, or
2✔
4704
        // the crypto negotiation breaks down, then return an error to the
2✔
4705
        // caller.
2✔
4706
        errChan := make(chan error, 1)
2✔
4707
        s.connectToPeer(addr, errChan, timeout)
2✔
4708

2✔
4709
        select {
2✔
4710
        case err := <-errChan:
2✔
4711
                return err
2✔
4712
        case <-s.quit:
×
4713
                return ErrServerShuttingDown
×
4714
        }
4715
}
4716

4717
// connectToPeer establishes a connection to a remote peer. errChan is used to
4718
// notify the caller if the connection attempt has failed. Otherwise, it will be
4719
// closed.
4720
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4721
        errChan chan<- error, timeout time.Duration) {
2✔
4722

2✔
4723
        conn, err := brontide.Dial(
2✔
4724
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
2✔
4725
        )
2✔
4726
        if err != nil {
4✔
4727
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
2✔
4728
                select {
2✔
4729
                case errChan <- err:
2✔
4730
                case <-s.quit:
×
4731
                }
4732
                return
2✔
4733
        }
4734

4735
        close(errChan)
2✔
4736

2✔
4737
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
2✔
4738
                conn.LocalAddr(), conn.RemoteAddr())
2✔
4739

2✔
4740
        s.OutboundPeerConnected(nil, conn)
2✔
4741
}
4742

4743
// DisconnectPeer sends the request to server to close the connection with peer
4744
// identified by public key.
4745
//
4746
// NOTE: This function is safe for concurrent access.
4747
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
2✔
4748
        pubBytes := pubKey.SerializeCompressed()
2✔
4749
        pubStr := string(pubBytes)
2✔
4750

2✔
4751
        s.mu.Lock()
2✔
4752
        defer s.mu.Unlock()
2✔
4753

2✔
4754
        // Check that were actually connected to this peer. If not, then we'll
2✔
4755
        // exit in an error as we can't disconnect from a peer that we're not
2✔
4756
        // currently connected to.
2✔
4757
        peer, err := s.findPeerByPubStr(pubStr)
2✔
4758
        if err == ErrPeerNotConnected {
4✔
4759
                return fmt.Errorf("peer %x is not connected", pubBytes)
2✔
4760
        }
2✔
4761

4762
        srvrLog.Infof("Disconnecting from %v", peer)
2✔
4763

2✔
4764
        s.cancelConnReqs(pubStr, nil)
2✔
4765

2✔
4766
        // If this peer was formerly a persistent connection, then we'll remove
2✔
4767
        // them from this map so we don't attempt to re-connect after we
2✔
4768
        // disconnect.
2✔
4769
        delete(s.persistentPeers, pubStr)
2✔
4770
        delete(s.persistentPeersBackoff, pubStr)
2✔
4771

2✔
4772
        // Remove the peer by calling Disconnect. Previously this was done with
2✔
4773
        // removePeer, which bypassed the peerTerminationWatcher.
2✔
4774
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
2✔
4775

2✔
4776
        return nil
2✔
4777
}
4778

4779
// OpenChannel sends a request to the server to open a channel to the specified
4780
// peer identified by nodeKey with the passed channel funding parameters.
4781
//
4782
// NOTE: This function is safe for concurrent access.
4783
func (s *server) OpenChannel(
4784
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
2✔
4785

2✔
4786
        // The updateChan will have a buffer of 2, since we expect a ChanPending
2✔
4787
        // + a ChanOpen update, and we want to make sure the funding process is
2✔
4788
        // not blocked if the caller is not reading the updates.
2✔
4789
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
2✔
4790
        req.Err = make(chan error, 1)
2✔
4791

2✔
4792
        // First attempt to locate the target peer to open a channel with, if
2✔
4793
        // we're unable to locate the peer then this request will fail.
2✔
4794
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
2✔
4795
        s.mu.RLock()
2✔
4796
        peer, ok := s.peersByPub[string(pubKeyBytes)]
2✔
4797
        if !ok {
2✔
4798
                s.mu.RUnlock()
×
4799

×
4800
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4801
                return req.Updates, req.Err
×
4802
        }
×
4803
        req.Peer = peer
2✔
4804
        s.mu.RUnlock()
2✔
4805

2✔
4806
        // We'll wait until the peer is active before beginning the channel
2✔
4807
        // opening process.
2✔
4808
        select {
2✔
4809
        case <-peer.ActiveSignal():
2✔
4810
        case <-peer.QuitSignal():
×
4811
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4812
                return req.Updates, req.Err
×
4813
        case <-s.quit:
×
4814
                req.Err <- ErrServerShuttingDown
×
4815
                return req.Updates, req.Err
×
4816
        }
4817

4818
        // If the fee rate wasn't specified at this point we fail the funding
4819
        // because of the missing fee rate information. The caller of the
4820
        // `OpenChannel` method needs to make sure that default values for the
4821
        // fee rate are set beforehand.
4822
        if req.FundingFeePerKw == 0 {
2✔
4823
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4824
                        "the channel opening transaction")
×
4825

×
4826
                return req.Updates, req.Err
×
4827
        }
×
4828

4829
        // Spawn a goroutine to send the funding workflow request to the funding
4830
        // manager. This allows the server to continue handling queries instead
4831
        // of blocking on this request which is exported as a synchronous
4832
        // request to the outside world.
4833
        go s.fundingMgr.InitFundingWorkflow(req)
2✔
4834

2✔
4835
        return req.Updates, req.Err
2✔
4836
}
4837

4838
// Peers returns a slice of all active peers.
4839
//
4840
// NOTE: This function is safe for concurrent access.
4841
func (s *server) Peers() []*peer.Brontide {
2✔
4842
        s.mu.RLock()
2✔
4843
        defer s.mu.RUnlock()
2✔
4844

2✔
4845
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
2✔
4846
        for _, peer := range s.peersByPub {
4✔
4847
                peers = append(peers, peer)
2✔
4848
        }
2✔
4849

4850
        return peers
2✔
4851
}
4852

4853
// computeNextBackoff uses a truncated exponential backoff to compute the next
4854
// backoff using the value of the exiting backoff. The returned duration is
4855
// randomized in either direction by 1/20 to prevent tight loops from
4856
// stabilizing.
4857
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
2✔
4858
        // Double the current backoff, truncating if it exceeds our maximum.
2✔
4859
        nextBackoff := 2 * currBackoff
2✔
4860
        if nextBackoff > maxBackoff {
4✔
4861
                nextBackoff = maxBackoff
2✔
4862
        }
2✔
4863

4864
        // Using 1/10 of our duration as a margin, compute a random offset to
4865
        // avoid the nodes entering connection cycles.
4866
        margin := nextBackoff / 10
2✔
4867

2✔
4868
        var wiggle big.Int
2✔
4869
        wiggle.SetUint64(uint64(margin))
2✔
4870
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
2✔
4871
                // Randomizing is not mission critical, so we'll just return the
×
4872
                // current backoff.
×
4873
                return nextBackoff
×
4874
        }
×
4875

4876
        // Otherwise add in our wiggle, but subtract out half of the margin so
4877
        // that the backoff can tweaked by 1/20 in either direction.
4878
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
2✔
4879
}
4880

4881
// errNoAdvertisedAddr is an error returned when we attempt to retrieve the
4882
// advertised address of a node, but they don't have one.
4883
var errNoAdvertisedAddr = errors.New("no advertised address found")
4884

4885
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4886
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
2✔
4887
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
2✔
4888
        if err != nil {
2✔
4889
                return nil, err
×
4890
        }
×
4891

4892
        node, err := s.graphDB.FetchLightningNode(vertex)
2✔
4893
        if err != nil {
4✔
4894
                return nil, err
2✔
4895
        }
2✔
4896

4897
        if len(node.Addresses) == 0 {
4✔
4898
                return nil, errNoAdvertisedAddr
2✔
4899
        }
2✔
4900

4901
        return node.Addresses, nil
2✔
4902
}
4903

4904
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4905
// channel update for a target channel.
4906
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4907
        *lnwire.ChannelUpdate1, error) {
2✔
4908

2✔
4909
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
2✔
4910
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
4✔
4911
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
2✔
4912
                if err != nil {
4✔
4913
                        return nil, err
2✔
4914
                }
2✔
4915

4916
                return netann.ExtractChannelUpdate(
2✔
4917
                        ourPubKey[:], info, edge1, edge2,
2✔
4918
                )
2✔
4919
        }
4920
}
4921

4922
// applyChannelUpdate applies the channel update to the different sub-systems of
4923
// the server. The useAlias boolean denotes whether or not to send an alias in
4924
// place of the real SCID.
4925
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
4926
        op *wire.OutPoint, useAlias bool) error {
2✔
4927

2✔
4928
        var (
2✔
4929
                peerAlias    *lnwire.ShortChannelID
2✔
4930
                defaultAlias lnwire.ShortChannelID
2✔
4931
        )
2✔
4932

2✔
4933
        chanID := lnwire.NewChanIDFromOutPoint(*op)
2✔
4934

2✔
4935
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
2✔
4936
        // in the ChannelUpdate if it hasn't been announced yet.
2✔
4937
        if useAlias {
4✔
4938
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
2✔
4939
                if foundAlias != defaultAlias {
4✔
4940
                        peerAlias = &foundAlias
2✔
4941
                }
2✔
4942
        }
4943

4944
        errChan := s.authGossiper.ProcessLocalAnnouncement(
2✔
4945
                update, discovery.RemoteAlias(peerAlias),
2✔
4946
        )
2✔
4947
        select {
2✔
4948
        case err := <-errChan:
2✔
4949
                return err
2✔
4950
        case <-s.quit:
×
4951
                return ErrServerShuttingDown
×
4952
        }
4953
}
4954

4955
// SendCustomMessage sends a custom message to the peer with the specified
4956
// pubkey.
4957
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
4958
        data []byte) error {
2✔
4959

2✔
4960
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
2✔
4961
        if err != nil {
2✔
4962
                return err
×
4963
        }
×
4964

4965
        // We'll wait until the peer is active.
4966
        select {
2✔
4967
        case <-peer.ActiveSignal():
2✔
4968
        case <-peer.QuitSignal():
×
4969
                return fmt.Errorf("peer %x disconnected", peerPub)
×
4970
        case <-s.quit:
×
4971
                return ErrServerShuttingDown
×
4972
        }
4973

4974
        msg, err := lnwire.NewCustom(msgType, data)
2✔
4975
        if err != nil {
4✔
4976
                return err
2✔
4977
        }
2✔
4978

4979
        // Send the message as low-priority. For now we assume that all
4980
        // application-defined message are low priority.
4981
        return peer.SendMessageLazy(true, msg)
2✔
4982
}
4983

4984
// newSweepPkScriptGen creates closure that generates a new public key script
4985
// which should be used to sweep any funds into the on-chain wallet.
4986
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
4987
// (p2wkh) output.
4988
func newSweepPkScriptGen(
4989
        wallet lnwallet.WalletController,
4990
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
2✔
4991

2✔
4992
        return func() fn.Result[lnwallet.AddrWithKey] {
4✔
4993
                sweepAddr, err := wallet.NewAddress(
2✔
4994
                        lnwallet.TaprootPubkey, false,
2✔
4995
                        lnwallet.DefaultAccountName,
2✔
4996
                )
2✔
4997
                if err != nil {
2✔
4998
                        return fn.Err[lnwallet.AddrWithKey](err)
×
4999
                }
×
5000

5001
                addr, err := txscript.PayToAddrScript(sweepAddr)
2✔
5002
                if err != nil {
2✔
5003
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5004
                }
×
5005

5006
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
2✔
5007
                        wallet, netParams, addr,
2✔
5008
                )
2✔
5009
                if err != nil {
2✔
5010
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5011
                }
×
5012

5013
                return fn.Ok(lnwallet.AddrWithKey{
2✔
5014
                        DeliveryAddress: addr,
2✔
5015
                        InternalKey:     internalKeyDesc,
2✔
5016
                })
2✔
5017
        }
5018
}
5019

5020
// shouldPeerBootstrap returns true if we should attempt to perform peer
5021
// bootstrapping to actively seek our peers using the set of active network
5022
// bootstrappers.
5023
func shouldPeerBootstrap(cfg *Config) bool {
2✔
5024
        isSimnet := cfg.Bitcoin.SimNet
2✔
5025
        isSignet := cfg.Bitcoin.SigNet
2✔
5026
        isRegtest := cfg.Bitcoin.RegTest
2✔
5027
        isDevNetwork := isSimnet || isSignet || isRegtest
2✔
5028

2✔
5029
        // TODO(yy): remove the check on simnet/regtest such that the itest is
2✔
5030
        // covering the bootstrapping process.
2✔
5031
        return !cfg.NoNetBootstrap && !isDevNetwork
2✔
5032
}
2✔
5033

5034
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5035
// finished.
5036
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
2✔
5037
        // Get a list of closed channels.
2✔
5038
        channels, err := s.chanStateDB.FetchClosedChannels(false)
2✔
5039
        if err != nil {
2✔
5040
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5041
                return nil
×
5042
        }
×
5043

5044
        // Save the SCIDs in a map.
5045
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
2✔
5046
        for _, c := range channels {
4✔
5047
                // If the channel is not pending, its FC has been finalized.
2✔
5048
                if !c.IsPending {
4✔
5049
                        closedSCIDs[c.ShortChanID] = struct{}{}
2✔
5050
                }
2✔
5051
        }
5052

5053
        // Double check whether the reported closed channel has indeed finished
5054
        // closing.
5055
        //
5056
        // NOTE: There are misalignments regarding when a channel's FC is
5057
        // marked as finalized. We double check the pending channels to make
5058
        // sure the returned SCIDs are indeed terminated.
5059
        //
5060
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5061
        pendings, err := s.chanStateDB.FetchPendingChannels()
2✔
5062
        if err != nil {
2✔
5063
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5064
                return nil
×
5065
        }
×
5066

5067
        for _, c := range pendings {
4✔
5068
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
4✔
5069
                        continue
2✔
5070
                }
5071

5072
                // If the channel is still reported as pending, remove it from
5073
                // the map.
5074
                delete(closedSCIDs, c.ShortChannelID)
×
5075

×
5076
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5077
                        c.ShortChannelID)
×
5078
        }
5079

5080
        return closedSCIDs
2✔
5081
}
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