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

lightningnetwork / lnd / 11963610117

21 Nov 2024 11:38PM UTC coverage: 59.117% (+0.1%) from 58.98%
11963610117

Pull #8754

github

ViktorTigerstrom
itest: wrap deriveCustomScopeAccounts at 80 chars

This commit fixes that word wrapping for the deriveCustomScopeAccounts
function docs, and ensures that it wraps at 80 characters or less.
Pull Request #8754: Add `Outbound` Remote Signer implementation

1950 of 2984 new or added lines in 44 files covered. (65.35%)

200 existing lines in 39 files now uncovered.

134504 of 227522 relevant lines covered (59.12%)

19449.04 hits per line

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

63.59
/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 {
4✔
148
        return fmt.Sprintf("already connected to peer: %v", e.peer)
4✔
149
}
4✔
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

201
        // peersByPub is a map of the active peers.
202
        //
203
        // NOTE: The key used here is the raw bytes of the peer's public key to
204
        // string conversion, which means it cannot be printed using `%s` as it
205
        // will just print the binary.
206
        //
207
        // TODO(yy): Use the hex string instead.
208
        peersByPub map[string]*peer.Brontide
209

210
        inboundPeers  map[string]*peer.Brontide
211
        outboundPeers map[string]*peer.Brontide
212

213
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
214
        peerDisconnectedListeners map[string][]chan<- struct{}
215

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

226
        // peerErrors keeps a set of peer error buffers for peers that have
227
        // disconnected from us. This allows us to track historic peer errors
228
        // over connections. The string of the peer's compressed pubkey is used
229
        // as a key for this map.
230
        peerErrors map[string]*queue.CircularBuffer
231

232
        // ignorePeerTermination tracks peers for which the server has initiated
233
        // a disconnect. Adding a peer to this map causes the peer termination
234
        // watcher to short circuit in the event that peers are purposefully
235
        // disconnected.
236
        ignorePeerTermination map[*peer.Brontide]struct{}
237

238
        // scheduledPeerConnection maps a pubkey string to a callback that
239
        // should be executed in the peerTerminationWatcher the prior peer with
240
        // the same pubkey exits.  This allows the server to wait until the
241
        // prior peer has cleaned up successfully, before adding the new peer
242
        // intended to replace it.
243
        scheduledPeerConnection map[string]func()
244

245
        // pongBuf is a shared pong reply buffer we'll use across all active
246
        // peer goroutines. We know the max size of a pong message
247
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
248
        // avoid allocations each time we need to send a pong message.
249
        pongBuf []byte
250

251
        cc *chainreg.ChainControl
252

253
        fundingMgr *funding.Manager
254

255
        graphDB *channeldb.ChannelGraph
256

257
        chanStateDB *channeldb.ChannelStateDB
258

259
        addrSource chanbackup.AddressSource
260

261
        // miscDB is the DB that contains all "other" databases within the main
262
        // channel DB that haven't been separated out yet.
263
        miscDB *channeldb.DB
264

265
        invoicesDB invoices.InvoiceDB
266

267
        aliasMgr *aliasmgr.Manager
268

269
        htlcSwitch *htlcswitch.Switch
270

271
        interceptableSwitch *htlcswitch.InterceptableSwitch
272

273
        invoices *invoices.InvoiceRegistry
274

275
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
276

277
        channelNotifier *channelnotifier.ChannelNotifier
278

279
        peerNotifier *peernotifier.PeerNotifier
280

281
        htlcNotifier *htlcswitch.HtlcNotifier
282

283
        witnessBeacon contractcourt.WitnessBeacon
284

285
        breachArbitrator *contractcourt.BreachArbitrator
286

287
        missionController *routing.MissionController
288
        defaultMC         *routing.MissionControl
289

290
        graphBuilder *graph.Builder
291

292
        chanRouter *routing.ChannelRouter
293

294
        controlTower routing.ControlTower
295

296
        authGossiper *discovery.AuthenticatedGossiper
297

298
        localChanMgr *localchans.Manager
299

300
        utxoNursery *contractcourt.UtxoNursery
301

302
        sweeper *sweep.UtxoSweeper
303

304
        chainArb *contractcourt.ChainArbitrator
305

306
        sphinx *hop.OnionProcessor
307

308
        towerClientMgr *wtclient.Manager
309

310
        connMgr *connmgr.ConnManager
311

312
        sigPool *lnwallet.SigPool
313

314
        writePool *pool.Write
315

316
        readPool *pool.Read
317

318
        tlsManager *TLSManager
319

320
        remoteSignerClient rpcwallet.RemoteSignerClient
321

322
        // featureMgr dispatches feature vectors for various contexts within the
323
        // daemon.
324
        featureMgr *feature.Manager
325

326
        // currentNodeAnn is the node announcement that has been broadcast to
327
        // the network upon startup, if the attributes of the node (us) has
328
        // changed since last start.
329
        currentNodeAnn *lnwire.NodeAnnouncement
330

331
        // chansToRestore is the set of channels that upon starting, the server
332
        // should attempt to restore/recover.
333
        chansToRestore walletunlocker.ChannelsToRecover
334

335
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
336
        // backups are consistent at all times. It interacts with the
337
        // channelNotifier to be notified of newly opened and closed channels.
338
        chanSubSwapper *chanbackup.SubSwapper
339

340
        // chanEventStore tracks the behaviour of channels and their remote peers to
341
        // provide insights into their health and performance.
342
        chanEventStore *chanfitness.ChannelEventStore
343

344
        hostAnn *netann.HostAnnouncer
345

346
        // livenessMonitor monitors that lnd has access to critical resources.
347
        livenessMonitor *healthcheck.Monitor
348

349
        customMessageServer *subscribe.Server
350

351
        // txPublisher is a publisher with fee-bumping capability.
352
        txPublisher *sweep.TxPublisher
353

354
        quit chan struct{}
355

356
        wg sync.WaitGroup
357
}
358

359
// updatePersistentPeerAddrs subscribes to topology changes and stores
360
// advertised addresses for any NodeAnnouncements from our persisted peers.
361
func (s *server) updatePersistentPeerAddrs() error {
4✔
362
        graphSub, err := s.graphBuilder.SubscribeTopology()
4✔
363
        if err != nil {
4✔
364
                return err
×
365
        }
×
366

367
        s.wg.Add(1)
4✔
368
        go func() {
8✔
369
                defer func() {
8✔
370
                        graphSub.Cancel()
4✔
371
                        s.wg.Done()
4✔
372
                }()
4✔
373

374
                for {
8✔
375
                        select {
4✔
376
                        case <-s.quit:
4✔
377
                                return
4✔
378

379
                        case topChange, ok := <-graphSub.TopologyChanges:
4✔
380
                                // If the router is shutting down, then we will
4✔
381
                                // as well.
4✔
382
                                if !ok {
4✔
383
                                        return
×
384
                                }
×
385

386
                                for _, update := range topChange.NodeUpdates {
8✔
387
                                        pubKeyStr := string(
4✔
388
                                                update.IdentityKey.
4✔
389
                                                        SerializeCompressed(),
4✔
390
                                        )
4✔
391

4✔
392
                                        // We only care about updates from
4✔
393
                                        // our persistentPeers.
4✔
394
                                        s.mu.RLock()
4✔
395
                                        _, ok := s.persistentPeers[pubKeyStr]
4✔
396
                                        s.mu.RUnlock()
4✔
397
                                        if !ok {
8✔
398
                                                continue
4✔
399
                                        }
400

401
                                        addrs := make([]*lnwire.NetAddress, 0,
4✔
402
                                                len(update.Addresses))
4✔
403

4✔
404
                                        for _, addr := range update.Addresses {
8✔
405
                                                addrs = append(addrs,
4✔
406
                                                        &lnwire.NetAddress{
4✔
407
                                                                IdentityKey: update.IdentityKey,
4✔
408
                                                                Address:     addr,
4✔
409
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
410
                                                        },
4✔
411
                                                )
4✔
412
                                        }
4✔
413

414
                                        s.mu.Lock()
4✔
415

4✔
416
                                        // Update the stored addresses for this
4✔
417
                                        // to peer to reflect the new set.
4✔
418
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
4✔
419

4✔
420
                                        // If there are no outstanding
4✔
421
                                        // connection requests for this peer
4✔
422
                                        // then our work is done since we are
4✔
423
                                        // not currently trying to connect to
4✔
424
                                        // them.
4✔
425
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
8✔
426
                                                s.mu.Unlock()
4✔
427
                                                continue
4✔
428
                                        }
429

430
                                        s.mu.Unlock()
4✔
431

4✔
432
                                        s.connectToPersistentPeer(pubKeyStr)
4✔
433
                                }
434
                        }
435
                }
436
        }()
437

438
        return nil
4✔
439
}
440

441
// CustomMessage is a custom message that is received from a peer.
442
type CustomMessage struct {
443
        // Peer is the peer pubkey
444
        Peer [33]byte
445

446
        // Msg is the custom wire message.
447
        Msg *lnwire.Custom
448
}
449

450
// parseAddr parses an address from its string format to a net.Addr.
451
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
4✔
452
        var (
4✔
453
                host string
4✔
454
                port int
4✔
455
        )
4✔
456

4✔
457
        // Split the address into its host and port components.
4✔
458
        h, p, err := net.SplitHostPort(address)
4✔
459
        if err != nil {
4✔
460
                // If a port wasn't specified, we'll assume the address only
×
461
                // contains the host so we'll use the default port.
×
462
                host = address
×
463
                port = defaultPeerPort
×
464
        } else {
4✔
465
                // Otherwise, we'll note both the host and ports.
4✔
466
                host = h
4✔
467
                portNum, err := strconv.Atoi(p)
4✔
468
                if err != nil {
4✔
469
                        return nil, err
×
470
                }
×
471
                port = portNum
4✔
472
        }
473

474
        if tor.IsOnionHost(host) {
4✔
475
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
476
        }
×
477

478
        // If the host is part of a TCP address, we'll use the network
479
        // specific ResolveTCPAddr function in order to resolve these
480
        // addresses over Tor in order to prevent leaking your real IP
481
        // address.
482
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
4✔
483
        return netCfg.ResolveTCPAddr("tcp", hostPort)
4✔
484
}
485

486
// noiseDial is a factory function which creates a connmgr compliant dialing
487
// function by returning a closure which includes the server's identity key.
488
func noiseDial(idKey keychain.SingleKeyECDH,
489
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
4✔
490

4✔
491
        return func(a net.Addr) (net.Conn, error) {
8✔
492
                lnAddr := a.(*lnwire.NetAddress)
4✔
493
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
4✔
494
        }
4✔
495
}
496

497
// newServer creates a new instance of the server which is to listen using the
498
// passed listener address.
499
func newServer(cfg *Config, listenAddrs []net.Addr,
500
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
501
        nodeKeyDesc *keychain.KeyDescriptor,
502
        chansToRestore walletunlocker.ChannelsToRecover,
503
        chanPredicate chanacceptor.ChannelAcceptor,
504
        torController *tor.Controller, tlsManager *TLSManager,
505
        leaderElector cluster.LeaderElector, implCfg *ImplementationCfg,
506
        remoteSignerClient rpcwallet.RemoteSignerClient) (*server, error) {
4✔
507

4✔
508
        var (
4✔
509
                err         error
4✔
510
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
4✔
511

4✔
512
                // We just derived the full descriptor, so we know the public
4✔
513
                // key is set on it.
4✔
514
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
4✔
515
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
4✔
516
                )
4✔
517
        )
4✔
518

4✔
519
        listeners := make([]net.Listener, len(listenAddrs))
4✔
520
        for i, listenAddr := range listenAddrs {
8✔
521
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
4✔
522
                // doesn't need to call the general lndResolveTCP function
4✔
523
                // since we are resolving a local address.
4✔
524
                listeners[i], err = brontide.NewListener(
4✔
525
                        nodeKeyECDH, listenAddr.String(),
4✔
526
                )
4✔
527
                if err != nil {
4✔
528
                        return nil, err
×
529
                }
×
530
        }
531

532
        var serializedPubKey [33]byte
4✔
533
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
4✔
534

4✔
535
        netParams := cfg.ActiveNetParams.Params
4✔
536

4✔
537
        // Initialize the sphinx router.
4✔
538
        replayLog := htlcswitch.NewDecayedLog(
4✔
539
                dbs.DecayedLogDB, cc.ChainNotifier,
4✔
540
        )
4✔
541
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
4✔
542

4✔
543
        writeBufferPool := pool.NewWriteBuffer(
4✔
544
                pool.DefaultWriteBufferGCInterval,
4✔
545
                pool.DefaultWriteBufferExpiryInterval,
4✔
546
        )
4✔
547

4✔
548
        writePool := pool.NewWrite(
4✔
549
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
4✔
550
        )
4✔
551

4✔
552
        readBufferPool := pool.NewReadBuffer(
4✔
553
                pool.DefaultReadBufferGCInterval,
4✔
554
                pool.DefaultReadBufferExpiryInterval,
4✔
555
        )
4✔
556

4✔
557
        readPool := pool.NewRead(
4✔
558
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
4✔
559
        )
4✔
560

4✔
561
        // If the taproot overlay flag is set, but we don't have an aux funding
4✔
562
        // controller, then we'll exit as this is incompatible.
4✔
563
        if cfg.ProtocolOptions.TaprootOverlayChans &&
4✔
564
                implCfg.AuxFundingController.IsNone() {
4✔
565

×
566
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
567
                        "aux controllers")
×
568
        }
×
569

570
        //nolint:lll
571
        featureMgr, err := feature.NewManager(feature.Config{
4✔
572
                NoTLVOnion:               cfg.ProtocolOptions.LegacyOnion(),
4✔
573
                NoStaticRemoteKey:        cfg.ProtocolOptions.NoStaticRemoteKey(),
4✔
574
                NoAnchors:                cfg.ProtocolOptions.NoAnchorCommitments(),
4✔
575
                NoWumbo:                  !cfg.ProtocolOptions.Wumbo(),
4✔
576
                NoScriptEnforcementLease: cfg.ProtocolOptions.NoScriptEnforcementLease(),
4✔
577
                NoKeysend:                !cfg.AcceptKeySend,
4✔
578
                NoOptionScidAlias:        !cfg.ProtocolOptions.ScidAlias(),
4✔
579
                NoZeroConf:               !cfg.ProtocolOptions.ZeroConf(),
4✔
580
                NoAnySegwit:              cfg.ProtocolOptions.NoAnySegwit(),
4✔
581
                CustomFeatures:           cfg.ProtocolOptions.CustomFeatures(),
4✔
582
                NoTaprootChans:           !cfg.ProtocolOptions.TaprootChans,
4✔
583
                NoTaprootOverlay:         !cfg.ProtocolOptions.TaprootOverlayChans,
4✔
584
                NoRouteBlinding:          cfg.ProtocolOptions.NoRouteBlinding(),
4✔
585
        })
4✔
586
        if err != nil {
4✔
587
                return nil, err
×
588
        }
×
589

590
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
4✔
591
        registryConfig := invoices.RegistryConfig{
4✔
592
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
4✔
593
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
4✔
594
                Clock:                       clock.NewDefaultClock(),
4✔
595
                AcceptKeySend:               cfg.AcceptKeySend,
4✔
596
                AcceptAMP:                   cfg.AcceptAMP,
4✔
597
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
4✔
598
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
4✔
599
                KeysendHoldTime:             cfg.KeysendHoldTime,
4✔
600
                HtlcInterceptor:             invoiceHtlcModifier,
4✔
601
        }
4✔
602

4✔
603
        s := &server{
4✔
604
                cfg:            cfg,
4✔
605
                implCfg:        implCfg,
4✔
606
                graphDB:        dbs.GraphDB.ChannelGraph(),
4✔
607
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
4✔
608
                addrSource:     dbs.ChanStateDB,
4✔
609
                miscDB:         dbs.ChanStateDB,
4✔
610
                invoicesDB:     dbs.InvoiceDB,
4✔
611
                cc:             cc,
4✔
612
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
4✔
613
                writePool:      writePool,
4✔
614
                readPool:       readPool,
4✔
615
                chansToRestore: chansToRestore,
4✔
616

4✔
617
                channelNotifier: channelnotifier.New(
4✔
618
                        dbs.ChanStateDB.ChannelStateDB(),
4✔
619
                ),
4✔
620

4✔
621
                identityECDH:   nodeKeyECDH,
4✔
622
                identityKeyLoc: nodeKeyDesc.KeyLocator,
4✔
623
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
4✔
624

4✔
625
                listenAddrs: listenAddrs,
4✔
626

4✔
627
                // TODO(roasbeef): derive proper onion key based on rotation
4✔
628
                // schedule
4✔
629
                sphinx: hop.NewOnionProcessor(sphinxRouter),
4✔
630

4✔
631
                torController: torController,
4✔
632

4✔
633
                persistentPeers:         make(map[string]bool),
4✔
634
                persistentPeersBackoff:  make(map[string]time.Duration),
4✔
635
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
4✔
636
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
4✔
637
                persistentRetryCancels:  make(map[string]chan struct{}),
4✔
638
                peerErrors:              make(map[string]*queue.CircularBuffer),
4✔
639
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
4✔
640
                scheduledPeerConnection: make(map[string]func()),
4✔
641
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
4✔
642

4✔
643
                peersByPub:                make(map[string]*peer.Brontide),
4✔
644
                inboundPeers:              make(map[string]*peer.Brontide),
4✔
645
                outboundPeers:             make(map[string]*peer.Brontide),
4✔
646
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
4✔
647
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
4✔
648

4✔
649
                invoiceHtlcModifier: invoiceHtlcModifier,
4✔
650

4✔
651
                customMessageServer: subscribe.NewServer(),
4✔
652

4✔
653
                tlsManager: tlsManager,
4✔
654

4✔
655
                remoteSignerClient: remoteSignerClient,
4✔
656

4✔
657
                featureMgr: featureMgr,
4✔
658
                quit:       make(chan struct{}),
4✔
659
        }
4✔
660

4✔
661
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
4✔
662
        if err != nil {
4✔
663
                return nil, err
×
664
        }
×
665

666
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
4✔
667
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
4✔
668
                uint32(currentHeight), currentHash, cc.ChainNotifier,
4✔
669
        )
4✔
670
        s.invoices = invoices.NewRegistry(
4✔
671
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
4✔
672
        )
4✔
673

4✔
674
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
4✔
675

4✔
676
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
4✔
677
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
678

4✔
679
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
8✔
680
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
4✔
681
                if err != nil {
4✔
682
                        return err
×
683
                }
×
684

685
                s.htlcSwitch.UpdateLinkAliases(link)
4✔
686

4✔
687
                return nil
4✔
688
        }
689

690
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
4✔
691
        if err != nil {
4✔
692
                return nil, err
×
693
        }
×
694

695
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
4✔
696
                DB:                   dbs.ChanStateDB,
4✔
697
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
4✔
698
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
4✔
699
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
4✔
700
                LocalChannelClose: func(pubKey []byte,
4✔
701
                        request *htlcswitch.ChanClose) {
8✔
702

4✔
703
                        peer, err := s.FindPeerByPubStr(string(pubKey))
4✔
704
                        if err != nil {
4✔
705
                                srvrLog.Errorf("unable to close channel, peer"+
×
706
                                        " with %v id can't be found: %v",
×
707
                                        pubKey, err,
×
708
                                )
×
709
                                return
×
710
                        }
×
711

712
                        peer.HandleLocalCloseChanReqs(request)
4✔
713
                },
714
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
715
                SwitchPackager:         channeldb.NewSwitchPackager(),
716
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
717
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
718
                Notifier:               s.cc.ChainNotifier,
719
                HtlcNotifier:           s.htlcNotifier,
720
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
721
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
722
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
723
                AllowCircularRoute:     cfg.AllowCircularRoute,
724
                RejectHTLC:             cfg.RejectHTLC,
725
                Clock:                  clock.NewDefaultClock(),
726
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
727
                MaxFeeExposure:         thresholdMSats,
728
                SignAliasUpdate:        s.signAliasUpdate,
729
                IsAlias:                aliasmgr.IsAlias,
730
        }, uint32(currentHeight))
731
        if err != nil {
4✔
732
                return nil, err
×
733
        }
×
734
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
4✔
735
                &htlcswitch.InterceptableSwitchConfig{
4✔
736
                        Switch:             s.htlcSwitch,
4✔
737
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
4✔
738
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
4✔
739
                        RequireInterceptor: s.cfg.RequireInterceptor,
4✔
740
                        Notifier:           s.cc.ChainNotifier,
4✔
741
                },
4✔
742
        )
4✔
743
        if err != nil {
4✔
744
                return nil, err
×
745
        }
×
746

747
        s.witnessBeacon = newPreimageBeacon(
4✔
748
                dbs.ChanStateDB.NewWitnessCache(),
4✔
749
                s.interceptableSwitch.ForwardPacket,
4✔
750
        )
4✔
751

4✔
752
        chanStatusMgrCfg := &netann.ChanStatusConfig{
4✔
753
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
4✔
754
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
4✔
755
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
4✔
756
                OurPubKey:                nodeKeyDesc.PubKey,
4✔
757
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
4✔
758
                MessageSigner:            s.nodeSigner,
4✔
759
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
4✔
760
                ApplyChannelUpdate:       s.applyChannelUpdate,
4✔
761
                DB:                       s.chanStateDB,
4✔
762
                Graph:                    dbs.GraphDB.ChannelGraph(),
4✔
763
        }
4✔
764

4✔
765
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
4✔
766
        if err != nil {
4✔
767
                return nil, err
×
768
        }
×
769
        s.chanStatusMgr = chanStatusMgr
4✔
770

4✔
771
        // If enabled, use either UPnP or NAT-PMP to automatically configure
4✔
772
        // port forwarding for users behind a NAT.
4✔
773
        if cfg.NAT {
4✔
774
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
775

×
776
                discoveryTimeout := time.Duration(10 * time.Second)
×
777

×
778
                ctx, cancel := context.WithTimeout(
×
779
                        context.Background(), discoveryTimeout,
×
780
                )
×
781
                defer cancel()
×
782
                upnp, err := nat.DiscoverUPnP(ctx)
×
783
                if err == nil {
×
784
                        s.natTraversal = upnp
×
785
                } else {
×
786
                        // If we were not able to discover a UPnP enabled device
×
787
                        // on the local network, we'll fall back to attempting
×
788
                        // to discover a NAT-PMP enabled device.
×
789
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
790
                                "device on the local network: %v", err)
×
791

×
792
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
793
                                "enabled device")
×
794

×
795
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
796
                        if err != nil {
×
797
                                err := fmt.Errorf("unable to discover a "+
×
798
                                        "NAT-PMP enabled device on the local "+
×
799
                                        "network: %v", err)
×
800
                                srvrLog.Error(err)
×
801
                                return nil, err
×
802
                        }
×
803

804
                        s.natTraversal = pmp
×
805
                }
806
        }
807

808
        // If we were requested to automatically configure port forwarding,
809
        // we'll use the ports that the server will be listening on.
810
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
4✔
811
        for idx, ip := range cfg.ExternalIPs {
8✔
812
                externalIPStrings[idx] = ip.String()
4✔
813
        }
4✔
814
        if s.natTraversal != nil {
4✔
815
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
816
                for _, listenAddr := range listenAddrs {
×
817
                        // At this point, the listen addresses should have
×
818
                        // already been normalized, so it's safe to ignore the
×
819
                        // errors.
×
820
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
821
                        port, _ := strconv.Atoi(portStr)
×
822

×
823
                        listenPorts = append(listenPorts, uint16(port))
×
824
                }
×
825

826
                ips, err := s.configurePortForwarding(listenPorts...)
×
827
                if err != nil {
×
828
                        srvrLog.Errorf("Unable to automatically set up port "+
×
829
                                "forwarding using %s: %v",
×
830
                                s.natTraversal.Name(), err)
×
831
                } else {
×
832
                        srvrLog.Infof("Automatically set up port forwarding "+
×
833
                                "using %s to advertise external IP",
×
834
                                s.natTraversal.Name())
×
835
                        externalIPStrings = append(externalIPStrings, ips...)
×
836
                }
×
837
        }
838

839
        // If external IP addresses have been specified, add those to the list
840
        // of this server's addresses.
841
        externalIPs, err := lncfg.NormalizeAddresses(
4✔
842
                externalIPStrings, strconv.Itoa(defaultPeerPort),
4✔
843
                cfg.net.ResolveTCPAddr,
4✔
844
        )
4✔
845
        if err != nil {
4✔
846
                return nil, err
×
847
        }
×
848

849
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
4✔
850
        selfAddrs = append(selfAddrs, externalIPs...)
4✔
851

4✔
852
        // As the graph can be obtained at anytime from the network, we won't
4✔
853
        // replicate it, and instead it'll only be stored locally.
4✔
854
        chanGraph := dbs.GraphDB.ChannelGraph()
4✔
855

4✔
856
        // We'll now reconstruct a node announcement based on our current
4✔
857
        // configuration so we can send it out as a sort of heart beat within
4✔
858
        // the network.
4✔
859
        //
4✔
860
        // We'll start by parsing the node color from configuration.
4✔
861
        color, err := lncfg.ParseHexColor(cfg.Color)
4✔
862
        if err != nil {
4✔
863
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
864
                return nil, err
×
865
        }
×
866

867
        // If no alias is provided, default to first 10 characters of public
868
        // key.
869
        alias := cfg.Alias
4✔
870
        if alias == "" {
8✔
871
                alias = hex.EncodeToString(serializedPubKey[:10])
4✔
872
        }
4✔
873
        nodeAlias, err := lnwire.NewNodeAlias(alias)
4✔
874
        if err != nil {
4✔
875
                return nil, err
×
876
        }
×
877
        selfNode := &channeldb.LightningNode{
4✔
878
                HaveNodeAnnouncement: true,
4✔
879
                LastUpdate:           time.Now(),
4✔
880
                Addresses:            selfAddrs,
4✔
881
                Alias:                nodeAlias.String(),
4✔
882
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
4✔
883
                Color:                color,
4✔
884
        }
4✔
885
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
4✔
886

4✔
887
        // Based on the disk representation of the node announcement generated
4✔
888
        // above, we'll generate a node announcement that can go out on the
4✔
889
        // network so we can properly sign it.
4✔
890
        nodeAnn, err := selfNode.NodeAnnouncement(false)
4✔
891
        if err != nil {
4✔
892
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
893
        }
×
894

895
        // With the announcement generated, we'll sign it to properly
896
        // authenticate the message on the network.
897
        authSig, err := netann.SignAnnouncement(
4✔
898
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
4✔
899
        )
4✔
900
        if err != nil {
4✔
901
                return nil, fmt.Errorf("unable to generate signature for "+
×
902
                        "self node announcement: %v", err)
×
903
        }
×
904
        selfNode.AuthSigBytes = authSig.Serialize()
4✔
905
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
4✔
906
                selfNode.AuthSigBytes,
4✔
907
        )
4✔
908
        if err != nil {
4✔
909
                return nil, err
×
910
        }
×
911

912
        // Finally, we'll update the representation on disk, and update our
913
        // cached in-memory version as well.
914
        if err := chanGraph.SetSourceNode(selfNode); err != nil {
4✔
915
                return nil, fmt.Errorf("can't set self node: %w", err)
×
916
        }
×
917
        s.currentNodeAnn = nodeAnn
4✔
918

4✔
919
        // The router will get access to the payment ID sequencer, such that it
4✔
920
        // can generate unique payment IDs.
4✔
921
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
4✔
922
        if err != nil {
4✔
923
                return nil, err
×
924
        }
×
925

926
        // Instantiate mission control with config from the sub server.
927
        //
928
        // TODO(joostjager): When we are further in the process of moving to sub
929
        // servers, the mission control instance itself can be moved there too.
930
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
4✔
931

4✔
932
        // We only initialize a probability estimator if there's no custom one.
4✔
933
        var estimator routing.Estimator
4✔
934
        if cfg.Estimator != nil {
4✔
935
                estimator = cfg.Estimator
×
936
        } else {
4✔
937
                switch routingConfig.ProbabilityEstimatorType {
4✔
938
                case routing.AprioriEstimatorName:
4✔
939
                        aCfg := routingConfig.AprioriConfig
4✔
940
                        aprioriConfig := routing.AprioriConfig{
4✔
941
                                AprioriHopProbability: aCfg.HopProbability,
4✔
942
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
4✔
943
                                AprioriWeight:         aCfg.Weight,
4✔
944
                                CapacityFraction:      aCfg.CapacityFraction,
4✔
945
                        }
4✔
946

4✔
947
                        estimator, err = routing.NewAprioriEstimator(
4✔
948
                                aprioriConfig,
4✔
949
                        )
4✔
950
                        if err != nil {
4✔
951
                                return nil, err
×
952
                        }
×
953

954
                case routing.BimodalEstimatorName:
×
955
                        bCfg := routingConfig.BimodalConfig
×
956
                        bimodalConfig := routing.BimodalConfig{
×
957
                                BimodalNodeWeight: bCfg.NodeWeight,
×
958
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
959
                                        bCfg.Scale,
×
960
                                ),
×
961
                                BimodalDecayTime: bCfg.DecayTime,
×
962
                        }
×
963

×
964
                        estimator, err = routing.NewBimodalEstimator(
×
965
                                bimodalConfig,
×
966
                        )
×
967
                        if err != nil {
×
968
                                return nil, err
×
969
                        }
×
970

971
                default:
×
972
                        return nil, fmt.Errorf("unknown estimator type %v",
×
973
                                routingConfig.ProbabilityEstimatorType)
×
974
                }
975
        }
976

977
        mcCfg := &routing.MissionControlConfig{
4✔
978
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
4✔
979
                Estimator:               estimator,
4✔
980
                MaxMcHistory:            routingConfig.MaxMcHistory,
4✔
981
                McFlushInterval:         routingConfig.McFlushInterval,
4✔
982
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
4✔
983
        }
4✔
984

4✔
985
        s.missionController, err = routing.NewMissionController(
4✔
986
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
4✔
987
        )
4✔
988
        if err != nil {
4✔
989
                return nil, fmt.Errorf("can't create mission control "+
×
990
                        "manager: %w", err)
×
991
        }
×
992
        s.defaultMC, err = s.missionController.GetNamespacedStore(
4✔
993
                routing.DefaultMissionControlNamespace,
4✔
994
        )
4✔
995
        if err != nil {
4✔
996
                return nil, fmt.Errorf("can't create mission control in the "+
×
997
                        "default namespace: %w", err)
×
998
        }
×
999

1000
        srvrLog.Debugf("Instantiating payment session source with config: "+
4✔
1001
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
4✔
1002
                int64(routingConfig.AttemptCost),
4✔
1003
                float64(routingConfig.AttemptCostPPM)/10000,
4✔
1004
                routingConfig.MinRouteProbability)
4✔
1005

4✔
1006
        pathFindingConfig := routing.PathFindingConfig{
4✔
1007
                AttemptCost: lnwire.NewMSatFromSatoshis(
4✔
1008
                        routingConfig.AttemptCost,
4✔
1009
                ),
4✔
1010
                AttemptCostPPM: routingConfig.AttemptCostPPM,
4✔
1011
                MinProbability: routingConfig.MinRouteProbability,
4✔
1012
        }
4✔
1013

4✔
1014
        sourceNode, err := chanGraph.SourceNode()
4✔
1015
        if err != nil {
4✔
1016
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1017
        }
×
1018
        paymentSessionSource := &routing.SessionSource{
4✔
1019
                GraphSessionFactory: graphsession.NewGraphSessionFactory(
4✔
1020
                        chanGraph,
4✔
1021
                ),
4✔
1022
                SourceNode:        sourceNode,
4✔
1023
                MissionControl:    s.defaultMC,
4✔
1024
                GetLink:           s.htlcSwitch.GetLinkByShortID,
4✔
1025
                PathFindingConfig: pathFindingConfig,
4✔
1026
        }
4✔
1027

4✔
1028
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
4✔
1029

4✔
1030
        s.controlTower = routing.NewControlTower(paymentControl)
4✔
1031

4✔
1032
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
4✔
1033
                cfg.Routing.StrictZombiePruning
4✔
1034

4✔
1035
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
4✔
1036
                SelfNode:            selfNode.PubKeyBytes,
4✔
1037
                Graph:               chanGraph,
4✔
1038
                Chain:               cc.ChainIO,
4✔
1039
                ChainView:           cc.ChainView,
4✔
1040
                Notifier:            cc.ChainNotifier,
4✔
1041
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
4✔
1042
                GraphPruneInterval:  time.Hour,
4✔
1043
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
4✔
1044
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
4✔
1045
                StrictZombiePruning: strictPruning,
4✔
1046
                IsAlias:             aliasmgr.IsAlias,
4✔
1047
        })
4✔
1048
        if err != nil {
4✔
1049
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1050
        }
×
1051

1052
        s.chanRouter, err = routing.New(routing.Config{
4✔
1053
                SelfNode:           selfNode.PubKeyBytes,
4✔
1054
                RoutingGraph:       graphsession.NewRoutingGraph(chanGraph),
4✔
1055
                Chain:              cc.ChainIO,
4✔
1056
                Payer:              s.htlcSwitch,
4✔
1057
                Control:            s.controlTower,
4✔
1058
                MissionControl:     s.defaultMC,
4✔
1059
                SessionSource:      paymentSessionSource,
4✔
1060
                GetLink:            s.htlcSwitch.GetLinkByShortID,
4✔
1061
                NextPaymentID:      sequencer.NextID,
4✔
1062
                PathFindingConfig:  pathFindingConfig,
4✔
1063
                Clock:              clock.NewDefaultClock(),
4✔
1064
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
4✔
1065
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
4✔
1066
                TrafficShaper:      implCfg.TrafficShaper,
4✔
1067
        })
4✔
1068
        if err != nil {
4✔
1069
                return nil, fmt.Errorf("can't create router: %w", err)
×
1070
        }
×
1071

1072
        chanSeries := discovery.NewChanSeries(s.graphDB)
4✔
1073
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
4✔
1074
        if err != nil {
4✔
1075
                return nil, err
×
1076
        }
×
1077
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
4✔
1078
        if err != nil {
4✔
1079
                return nil, err
×
1080
        }
×
1081

1082
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
4✔
1083

4✔
1084
        s.authGossiper = discovery.New(discovery.Config{
4✔
1085
                Graph:                 s.graphBuilder,
4✔
1086
                ChainIO:               s.cc.ChainIO,
4✔
1087
                Notifier:              s.cc.ChainNotifier,
4✔
1088
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
4✔
1089
                Broadcast:             s.BroadcastMessage,
4✔
1090
                ChanSeries:            chanSeries,
4✔
1091
                NotifyWhenOnline:      s.NotifyWhenOnline,
4✔
1092
                NotifyWhenOffline:     s.NotifyWhenOffline,
4✔
1093
                FetchSelfAnnouncement: s.getNodeAnnouncement,
4✔
1094
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
4✔
1095
                        error) {
4✔
1096

×
1097
                        return s.genNodeAnnouncement(nil)
×
1098
                },
×
1099
                ProofMatureDelta:        0,
1100
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1101
                RetransmitTicker:        ticker.New(time.Minute * 30),
1102
                RebroadcastInterval:     time.Hour * 24,
1103
                WaitingProofStore:       waitingProofStore,
1104
                MessageStore:            gossipMessageStore,
1105
                AnnSigner:               s.nodeSigner,
1106
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1107
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1108
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1109
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:lll
1110
                MinimumBatchSize:        10,
1111
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1112
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1113
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1114
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1115
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1116
                IsAlias:                 aliasmgr.IsAlias,
1117
                SignAliasUpdate:         s.signAliasUpdate,
1118
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1119
                GetAlias:                s.aliasMgr.GetPeerAlias,
1120
                FindChannel:             s.findChannel,
1121
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1122
                ScidCloser:              scidCloserMan,
1123
        }, nodeKeyDesc)
1124

1125
        //nolint:lll
1126
        s.localChanMgr = &localchans.Manager{
4✔
1127
                ForAllOutgoingChannels:    s.graphBuilder.ForAllOutgoingChannels,
4✔
1128
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
4✔
1129
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
4✔
1130
                FetchChannel:              s.chanStateDB.FetchChannel,
4✔
1131
        }
4✔
1132

4✔
1133
        utxnStore, err := contractcourt.NewNurseryStore(
4✔
1134
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
4✔
1135
        )
4✔
1136
        if err != nil {
4✔
1137
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1138
                return nil, err
×
1139
        }
×
1140

1141
        sweeperStore, err := sweep.NewSweeperStore(
4✔
1142
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
4✔
1143
        )
4✔
1144
        if err != nil {
4✔
1145
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1146
                return nil, err
×
1147
        }
×
1148

1149
        aggregator := sweep.NewBudgetAggregator(
4✔
1150
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
4✔
1151
                s.implCfg.AuxSweeper,
4✔
1152
        )
4✔
1153

4✔
1154
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
4✔
1155
                Signer:     cc.Wallet.Cfg.Signer,
4✔
1156
                Wallet:     cc.Wallet,
4✔
1157
                Estimator:  cc.FeeEstimator,
4✔
1158
                Notifier:   cc.ChainNotifier,
4✔
1159
                AuxSweeper: s.implCfg.AuxSweeper,
4✔
1160
        })
4✔
1161

4✔
1162
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
4✔
1163
                FeeEstimator: cc.FeeEstimator,
4✔
1164
                GenSweepScript: newSweepPkScriptGen(
4✔
1165
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
4✔
1166
                ),
4✔
1167
                Signer:               cc.Wallet.Cfg.Signer,
4✔
1168
                Wallet:               newSweeperWallet(cc.Wallet),
4✔
1169
                Mempool:              cc.MempoolNotifier,
4✔
1170
                Notifier:             cc.ChainNotifier,
4✔
1171
                Store:                sweeperStore,
4✔
1172
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
4✔
1173
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
4✔
1174
                Aggregator:           aggregator,
4✔
1175
                Publisher:            s.txPublisher,
4✔
1176
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
4✔
1177
        })
4✔
1178

4✔
1179
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
4✔
1180
                ChainIO:             cc.ChainIO,
4✔
1181
                ConfDepth:           1,
4✔
1182
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
4✔
1183
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
4✔
1184
                Notifier:            cc.ChainNotifier,
4✔
1185
                PublishTransaction:  cc.Wallet.PublishTransaction,
4✔
1186
                Store:               utxnStore,
4✔
1187
                SweepInput:          s.sweeper.SweepInput,
4✔
1188
                Budget:              s.cfg.Sweeper.Budget,
4✔
1189
        })
4✔
1190

4✔
1191
        // Construct a closure that wraps the htlcswitch's CloseLink method.
4✔
1192
        closeLink := func(chanPoint *wire.OutPoint,
4✔
1193
                closureType contractcourt.ChannelCloseType) {
8✔
1194
                // TODO(conner): Properly respect the update and error channels
4✔
1195
                // returned by CloseLink.
4✔
1196

4✔
1197
                // Instruct the switch to close the channel.  Provide no close out
4✔
1198
                // delivery script or target fee per kw because user input is not
4✔
1199
                // available when the remote peer closes the channel.
4✔
1200
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
4✔
1201
        }
4✔
1202

1203
        // We will use the following channel to reliably hand off contract
1204
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1205
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
4✔
1206

4✔
1207
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
4✔
1208
                &contractcourt.BreachConfig{
4✔
1209
                        CloseLink: closeLink,
4✔
1210
                        DB:        s.chanStateDB,
4✔
1211
                        Estimator: s.cc.FeeEstimator,
4✔
1212
                        GenSweepScript: newSweepPkScriptGen(
4✔
1213
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
4✔
1214
                        ),
4✔
1215
                        Notifier:           cc.ChainNotifier,
4✔
1216
                        PublishTransaction: cc.Wallet.PublishTransaction,
4✔
1217
                        ContractBreaches:   contractBreaches,
4✔
1218
                        Signer:             cc.Wallet.Cfg.Signer,
4✔
1219
                        Store: contractcourt.NewRetributionStore(
4✔
1220
                                dbs.ChanStateDB,
4✔
1221
                        ),
4✔
1222
                        AuxSweeper: s.implCfg.AuxSweeper,
4✔
1223
                },
4✔
1224
        )
4✔
1225

4✔
1226
        //nolint:lll
4✔
1227
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
4✔
1228
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
4✔
1229
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
4✔
1230
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
4✔
1231
                NewSweepAddr: func() ([]byte, error) {
4✔
1232
                        addr, err := newSweepPkScriptGen(
×
1233
                                cc.Wallet, netParams,
×
1234
                        )().Unpack()
×
1235
                        if err != nil {
×
1236
                                return nil, err
×
1237
                        }
×
1238

1239
                        return addr.DeliveryAddress, nil
×
1240
                },
1241
                PublishTx: cc.Wallet.PublishTransaction,
1242
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
4✔
1243
                        for _, msg := range msgs {
8✔
1244
                                err := s.htlcSwitch.ProcessContractResolution(msg)
4✔
1245
                                if err != nil {
4✔
UNCOV
1246
                                        return err
×
UNCOV
1247
                                }
×
1248
                        }
1249
                        return nil
4✔
1250
                },
1251
                IncubateOutputs: func(chanPoint wire.OutPoint,
1252
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1253
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1254
                        broadcastHeight uint32,
1255
                        deadlineHeight fn.Option[int32]) error {
4✔
1256

4✔
1257
                        return s.utxoNursery.IncubateOutputs(
4✔
1258
                                chanPoint, outHtlcRes, inHtlcRes,
4✔
1259
                                broadcastHeight, deadlineHeight,
4✔
1260
                        )
4✔
1261
                },
4✔
1262
                PreimageDB:   s.witnessBeacon,
1263
                Notifier:     cc.ChainNotifier,
1264
                Mempool:      cc.MempoolNotifier,
1265
                Signer:       cc.Wallet.Cfg.Signer,
1266
                FeeEstimator: cc.FeeEstimator,
1267
                ChainIO:      cc.ChainIO,
1268
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
4✔
1269
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1270
                        s.htlcSwitch.RemoveLink(chanID)
4✔
1271
                        return nil
4✔
1272
                },
4✔
1273
                IsOurAddress: cc.Wallet.IsOurAddress,
1274
                ContractBreach: func(chanPoint wire.OutPoint,
1275
                        breachRet *lnwallet.BreachRetribution) error {
4✔
1276

4✔
1277
                        // processACK will handle the BreachArbitrator ACKing
4✔
1278
                        // the event.
4✔
1279
                        finalErr := make(chan error, 1)
4✔
1280
                        processACK := func(brarErr error) {
8✔
1281
                                if brarErr != nil {
4✔
1282
                                        finalErr <- brarErr
×
1283
                                        return
×
1284
                                }
×
1285

1286
                                // If the BreachArbitrator successfully handled
1287
                                // the event, we can signal that the handoff
1288
                                // was successful.
1289
                                finalErr <- nil
4✔
1290
                        }
1291

1292
                        event := &contractcourt.ContractBreachEvent{
4✔
1293
                                ChanPoint:         chanPoint,
4✔
1294
                                ProcessACK:        processACK,
4✔
1295
                                BreachRetribution: breachRet,
4✔
1296
                        }
4✔
1297

4✔
1298
                        // Send the contract breach event to the
4✔
1299
                        // BreachArbitrator.
4✔
1300
                        select {
4✔
1301
                        case contractBreaches <- event:
4✔
1302
                        case <-s.quit:
×
1303
                                return ErrServerShuttingDown
×
1304
                        }
1305

1306
                        // We'll wait for a final error to be available from
1307
                        // the BreachArbitrator.
1308
                        select {
4✔
1309
                        case err := <-finalErr:
4✔
1310
                                return err
4✔
1311
                        case <-s.quit:
×
1312
                                return ErrServerShuttingDown
×
1313
                        }
1314
                },
1315
                DisableChannel: func(chanPoint wire.OutPoint) error {
4✔
1316
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
4✔
1317
                },
4✔
1318
                Sweeper:                       s.sweeper,
1319
                Registry:                      s.invoices,
1320
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1321
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1322
                OnionProcessor:                s.sphinx,
1323
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1324
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1325
                Clock:                         clock.NewDefaultClock(),
1326
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1327
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1328
                HtlcNotifier:                  s.htlcNotifier,
1329
                Budget:                        *s.cfg.Sweeper.Budget,
1330

1331
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1332
                QueryIncomingCircuit: func(
1333
                        circuit models.CircuitKey) *models.CircuitKey {
4✔
1334

4✔
1335
                        // Get the circuit map.
4✔
1336
                        circuits := s.htlcSwitch.CircuitLookup()
4✔
1337

4✔
1338
                        // Lookup the outgoing circuit.
4✔
1339
                        pc := circuits.LookupOpenCircuit(circuit)
4✔
1340
                        if pc == nil {
8✔
1341
                                return nil
4✔
1342
                        }
4✔
1343

1344
                        return &pc.Incoming
4✔
1345
                },
1346
                AuxLeafStore: implCfg.AuxLeafStore,
1347
                AuxSigner:    implCfg.AuxSigner,
1348
                AuxResolver:  implCfg.AuxContractResolver,
1349
        }, dbs.ChanStateDB)
1350

1351
        // Select the configuration and funding parameters for Bitcoin.
1352
        chainCfg := cfg.Bitcoin
4✔
1353
        minRemoteDelay := funding.MinBtcRemoteDelay
4✔
1354
        maxRemoteDelay := funding.MaxBtcRemoteDelay
4✔
1355

4✔
1356
        var chanIDSeed [32]byte
4✔
1357
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
4✔
1358
                return nil, err
×
1359
        }
×
1360

1361
        // Wrap the DeleteChannelEdges method so that the funding manager can
1362
        // use it without depending on several layers of indirection.
1363
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
4✔
1364
                *models.ChannelEdgePolicy, error) {
8✔
1365

4✔
1366
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
4✔
1367
                        scid.ToUint64(),
4✔
1368
                )
4✔
1369
                if errors.Is(err, channeldb.ErrEdgeNotFound) {
4✔
1370
                        // This is unlikely but there is a slim chance of this
×
1371
                        // being hit if lnd was killed via SIGKILL and the
×
1372
                        // funding manager was stepping through the delete
×
1373
                        // alias edge logic.
×
1374
                        return nil, nil
×
1375
                } else if err != nil {
4✔
1376
                        return nil, err
×
1377
                }
×
1378

1379
                // Grab our key to find our policy.
1380
                var ourKey [33]byte
4✔
1381
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
4✔
1382

4✔
1383
                var ourPolicy *models.ChannelEdgePolicy
4✔
1384
                if info != nil && info.NodeKey1Bytes == ourKey {
8✔
1385
                        ourPolicy = e1
4✔
1386
                } else {
8✔
1387
                        ourPolicy = e2
4✔
1388
                }
4✔
1389

1390
                if ourPolicy == nil {
4✔
1391
                        // Something is wrong, so return an error.
×
1392
                        return nil, fmt.Errorf("we don't have an edge")
×
1393
                }
×
1394

1395
                err = s.graphDB.DeleteChannelEdges(
4✔
1396
                        false, false, scid.ToUint64(),
4✔
1397
                )
4✔
1398
                return ourPolicy, err
4✔
1399
        }
1400

1401
        // For the reservationTimeout and the zombieSweeperInterval different
1402
        // values are set in case we are in a dev environment so enhance test
1403
        // capacilities.
1404
        reservationTimeout := chanfunding.DefaultReservationTimeout
4✔
1405
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
4✔
1406

4✔
1407
        // Get the development config for funding manager. If we are not in
4✔
1408
        // development mode, this would be nil.
4✔
1409
        var devCfg *funding.DevConfig
4✔
1410
        if lncfg.IsDevBuild() {
8✔
1411
                devCfg = &funding.DevConfig{
4✔
1412
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
4✔
1413
                }
4✔
1414

4✔
1415
                reservationTimeout = cfg.Dev.GetReservationTimeout()
4✔
1416
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
4✔
1417

4✔
1418
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
4✔
1419
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
4✔
1420
                        devCfg, reservationTimeout, zombieSweeperInterval)
4✔
1421
        }
4✔
1422

1423
        //nolint:lll
1424
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
4✔
1425
                Dev:                devCfg,
4✔
1426
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
4✔
1427
                IDKey:              nodeKeyDesc.PubKey,
4✔
1428
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
4✔
1429
                Wallet:             cc.Wallet,
4✔
1430
                PublishTransaction: cc.Wallet.PublishTransaction,
4✔
1431
                UpdateLabel: func(hash chainhash.Hash, label string) error {
8✔
1432
                        return cc.Wallet.LabelTransaction(hash, label, true)
4✔
1433
                },
4✔
1434
                Notifier:     cc.ChainNotifier,
1435
                ChannelDB:    s.chanStateDB,
1436
                FeeEstimator: cc.FeeEstimator,
1437
                SignMessage:  cc.MsgSigner.SignMessage,
1438
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1439
                        error) {
4✔
1440

4✔
1441
                        return s.genNodeAnnouncement(nil)
4✔
1442
                },
4✔
1443
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1444
                NotifyWhenOnline:     s.NotifyWhenOnline,
1445
                TempChanIDSeed:       chanIDSeed,
1446
                FindChannel:          s.findChannel,
1447
                DefaultRoutingPolicy: cc.RoutingPolicy,
1448
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1449
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1450
                        pushAmt lnwire.MilliSatoshi) uint16 {
4✔
1451
                        // For large channels we increase the number
4✔
1452
                        // of confirmations we require for the
4✔
1453
                        // channel to be considered open. As it is
4✔
1454
                        // always the responder that gets to choose
4✔
1455
                        // value, the pushAmt is value being pushed
4✔
1456
                        // to us. This means we have more to lose
4✔
1457
                        // in the case this gets re-orged out, and
4✔
1458
                        // we will require more confirmations before
4✔
1459
                        // we consider it open.
4✔
1460

4✔
1461
                        // In case the user has explicitly specified
4✔
1462
                        // a default value for the number of
4✔
1463
                        // confirmations, we use it.
4✔
1464
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
4✔
1465
                        if defaultConf != 0 {
8✔
1466
                                return defaultConf
4✔
1467
                        }
4✔
1468

1469
                        minConf := uint64(3)
×
1470
                        maxConf := uint64(6)
×
1471

×
1472
                        // If this is a wumbo channel, then we'll require the
×
1473
                        // max amount of confirmations.
×
1474
                        if chanAmt > MaxFundingAmount {
×
1475
                                return uint16(maxConf)
×
1476
                        }
×
1477

1478
                        // If not we return a value scaled linearly
1479
                        // between 3 and 6, depending on channel size.
1480
                        // TODO(halseth): Use 1 as minimum?
1481
                        maxChannelSize := uint64(
×
1482
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1483
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1484
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1485
                        if conf < minConf {
×
1486
                                conf = minConf
×
1487
                        }
×
1488
                        if conf > maxConf {
×
1489
                                conf = maxConf
×
1490
                        }
×
1491
                        return uint16(conf)
×
1492
                },
1493
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
4✔
1494
                        // We scale the remote CSV delay (the time the
4✔
1495
                        // remote have to claim funds in case of a unilateral
4✔
1496
                        // close) linearly from minRemoteDelay blocks
4✔
1497
                        // for small channels, to maxRemoteDelay blocks
4✔
1498
                        // for channels of size MaxFundingAmount.
4✔
1499

4✔
1500
                        // In case the user has explicitly specified
4✔
1501
                        // a default value for the remote delay, we
4✔
1502
                        // use it.
4✔
1503
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
4✔
1504
                        if defaultDelay > 0 {
8✔
1505
                                return defaultDelay
4✔
1506
                        }
4✔
1507

1508
                        // If this is a wumbo channel, then we'll require the
1509
                        // max value.
1510
                        if chanAmt > MaxFundingAmount {
×
1511
                                return maxRemoteDelay
×
1512
                        }
×
1513

1514
                        // If not we scale according to channel size.
1515
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1516
                                chanAmt / MaxFundingAmount)
×
1517
                        if delay < minRemoteDelay {
×
1518
                                delay = minRemoteDelay
×
1519
                        }
×
1520
                        if delay > maxRemoteDelay {
×
1521
                                delay = maxRemoteDelay
×
1522
                        }
×
1523
                        return delay
×
1524
                },
1525
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1526
                        peerKey *btcec.PublicKey) error {
4✔
1527

4✔
1528
                        // First, we'll mark this new peer as a persistent peer
4✔
1529
                        // for re-connection purposes. If the peer is not yet
4✔
1530
                        // tracked or the user hasn't requested it to be perm,
4✔
1531
                        // we'll set false to prevent the server from continuing
4✔
1532
                        // to connect to this peer even if the number of
4✔
1533
                        // channels with this peer is zero.
4✔
1534
                        s.mu.Lock()
4✔
1535
                        pubStr := string(peerKey.SerializeCompressed())
4✔
1536
                        if _, ok := s.persistentPeers[pubStr]; !ok {
8✔
1537
                                s.persistentPeers[pubStr] = false
4✔
1538
                        }
4✔
1539
                        s.mu.Unlock()
4✔
1540

4✔
1541
                        // With that taken care of, we'll send this channel to
4✔
1542
                        // the chain arb so it can react to on-chain events.
4✔
1543
                        return s.chainArb.WatchNewChannel(channel)
4✔
1544
                },
1545
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
4✔
1546
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1547
                        return s.htlcSwitch.UpdateShortChanID(cid)
4✔
1548
                },
4✔
1549
                RequiredRemoteChanReserve: func(chanAmt,
1550
                        dustLimit btcutil.Amount) btcutil.Amount {
4✔
1551

4✔
1552
                        // By default, we'll require the remote peer to maintain
4✔
1553
                        // at least 1% of the total channel capacity at all
4✔
1554
                        // times. If this value ends up dipping below the dust
4✔
1555
                        // limit, then we'll use the dust limit itself as the
4✔
1556
                        // reserve as required by BOLT #2.
4✔
1557
                        reserve := chanAmt / 100
4✔
1558
                        if reserve < dustLimit {
8✔
1559
                                reserve = dustLimit
4✔
1560
                        }
4✔
1561

1562
                        return reserve
4✔
1563
                },
1564
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
4✔
1565
                        // By default, we'll allow the remote peer to fully
4✔
1566
                        // utilize the full bandwidth of the channel, minus our
4✔
1567
                        // required reserve.
4✔
1568
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
4✔
1569
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
4✔
1570
                },
4✔
1571
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
4✔
1572
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
8✔
1573
                                return cfg.DefaultRemoteMaxHtlcs
4✔
1574
                        }
4✔
1575

1576
                        // By default, we'll permit them to utilize the full
1577
                        // channel bandwidth.
1578
                        return uint16(input.MaxHTLCNumber / 2)
×
1579
                },
1580
                ZombieSweeperInterval:         zombieSweeperInterval,
1581
                ReservationTimeout:            reservationTimeout,
1582
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1583
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1584
                MaxPendingChannels:            cfg.MaxPendingChannels,
1585
                RejectPush:                    cfg.RejectPush,
1586
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1587
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1588
                OpenChannelPredicate:          chanPredicate,
1589
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1590
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1591
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1592
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1593
                DeleteAliasEdge:      deleteAliasEdge,
1594
                AliasManager:         s.aliasMgr,
1595
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1596
                AuxFundingController: implCfg.AuxFundingController,
1597
                AuxSigner:            implCfg.AuxSigner,
1598
                AuxResolver:          implCfg.AuxContractResolver,
1599
        })
1600
        if err != nil {
4✔
1601
                return nil, err
×
1602
        }
×
1603

1604
        // Next, we'll assemble the sub-system that will maintain an on-disk
1605
        // static backup of the latest channel state.
1606
        chanNotifier := &channelNotifier{
4✔
1607
                chanNotifier: s.channelNotifier,
4✔
1608
                addrs:        dbs.ChanStateDB,
4✔
1609
        }
4✔
1610
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
4✔
1611
        startingChans, err := chanbackup.FetchStaticChanBackups(
4✔
1612
                s.chanStateDB, s.addrSource,
4✔
1613
        )
4✔
1614
        if err != nil {
4✔
1615
                return nil, err
×
1616
        }
×
1617
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
4✔
1618
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
4✔
1619
        )
4✔
1620
        if err != nil {
4✔
1621
                return nil, err
×
1622
        }
×
1623

1624
        // Assemble a peer notifier which will provide clients with subscriptions
1625
        // to peer online and offline events.
1626
        s.peerNotifier = peernotifier.New()
4✔
1627

4✔
1628
        // Create a channel event store which monitors all open channels.
4✔
1629
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
4✔
1630
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
8✔
1631
                        return s.channelNotifier.SubscribeChannelEvents()
4✔
1632
                },
4✔
1633
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
4✔
1634
                        return s.peerNotifier.SubscribePeerEvents()
4✔
1635
                },
4✔
1636
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1637
                Clock:           clock.NewDefaultClock(),
1638
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1639
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1640
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1641
        })
1642

1643
        if cfg.WtClient.Active {
8✔
1644
                policy := wtpolicy.DefaultPolicy()
4✔
1645
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
4✔
1646

4✔
1647
                // We expose the sweep fee rate in sat/vbyte, but the tower
4✔
1648
                // protocol operations on sat/kw.
4✔
1649
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
4✔
1650
                        1000 * cfg.WtClient.SweepFeeRate,
4✔
1651
                )
4✔
1652

4✔
1653
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
4✔
1654

4✔
1655
                if err := policy.Validate(); err != nil {
4✔
1656
                        return nil, err
×
1657
                }
×
1658

1659
                // authDial is the wrapper around the btrontide.Dial for the
1660
                // watchtower.
1661
                authDial := func(localKey keychain.SingleKeyECDH,
4✔
1662
                        netAddr *lnwire.NetAddress,
4✔
1663
                        dialer tor.DialFunc) (wtserver.Peer, error) {
8✔
1664

4✔
1665
                        return brontide.Dial(
4✔
1666
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
4✔
1667
                        )
4✔
1668
                }
4✔
1669

1670
                // buildBreachRetribution is a call-back that can be used to
1671
                // query the BreachRetribution info and channel type given a
1672
                // channel ID and commitment height.
1673
                buildBreachRetribution := func(chanID lnwire.ChannelID,
4✔
1674
                        commitHeight uint64) (*lnwallet.BreachRetribution,
4✔
1675
                        channeldb.ChannelType, error) {
8✔
1676

4✔
1677
                        channel, err := s.chanStateDB.FetchChannelByID(
4✔
1678
                                nil, chanID,
4✔
1679
                        )
4✔
1680
                        if err != nil {
4✔
1681
                                return nil, 0, err
×
1682
                        }
×
1683

1684
                        br, err := lnwallet.NewBreachRetribution(
4✔
1685
                                channel, commitHeight, 0, nil,
4✔
1686
                                implCfg.AuxLeafStore,
4✔
1687
                                implCfg.AuxContractResolver,
4✔
1688
                        )
4✔
1689
                        if err != nil {
4✔
1690
                                return nil, 0, err
×
1691
                        }
×
1692

1693
                        return br, channel.ChanType, nil
4✔
1694
                }
1695

1696
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
4✔
1697

4✔
1698
                // Copy the policy for legacy channels and set the blob flag
4✔
1699
                // signalling support for anchor channels.
4✔
1700
                anchorPolicy := policy
4✔
1701
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
4✔
1702

4✔
1703
                // Copy the policy for legacy channels and set the blob flag
4✔
1704
                // signalling support for taproot channels.
4✔
1705
                taprootPolicy := policy
4✔
1706
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
4✔
1707
                        blob.FlagTaprootChannel,
4✔
1708
                )
4✔
1709

4✔
1710
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
4✔
1711
                        FetchClosedChannel:     fetchClosedChannel,
4✔
1712
                        BuildBreachRetribution: buildBreachRetribution,
4✔
1713
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
4✔
1714
                        ChainNotifier:          s.cc.ChainNotifier,
4✔
1715
                        SubscribeChannelEvents: func() (subscribe.Subscription,
4✔
1716
                                error) {
8✔
1717

4✔
1718
                                return s.channelNotifier.
4✔
1719
                                        SubscribeChannelEvents()
4✔
1720
                        },
4✔
1721
                        Signer: cc.Wallet.Cfg.Signer,
1722
                        NewAddress: func() ([]byte, error) {
4✔
1723
                                addr, err := newSweepPkScriptGen(
4✔
1724
                                        cc.Wallet, netParams,
4✔
1725
                                )().Unpack()
4✔
1726
                                if err != nil {
4✔
1727
                                        return nil, err
×
1728
                                }
×
1729

1730
                                return addr.DeliveryAddress, nil
4✔
1731
                        },
1732
                        SecretKeyRing:      s.cc.KeyRing,
1733
                        Dial:               cfg.net.Dial,
1734
                        AuthDial:           authDial,
1735
                        DB:                 dbs.TowerClientDB,
1736
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1737
                        MinBackoff:         10 * time.Second,
1738
                        MaxBackoff:         5 * time.Minute,
1739
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1740
                }, policy, anchorPolicy, taprootPolicy)
1741
                if err != nil {
4✔
1742
                        return nil, err
×
1743
                }
×
1744
        }
1745

1746
        if len(cfg.ExternalHosts) != 0 {
4✔
1747
                advertisedIPs := make(map[string]struct{})
×
1748
                for _, addr := range s.currentNodeAnn.Addresses {
×
1749
                        advertisedIPs[addr.String()] = struct{}{}
×
1750
                }
×
1751

1752
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1753
                        Hosts:         cfg.ExternalHosts,
×
1754
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1755
                        LookupHost: func(host string) (net.Addr, error) {
×
1756
                                return lncfg.ParseAddressString(
×
1757
                                        host, strconv.Itoa(defaultPeerPort),
×
1758
                                        cfg.net.ResolveTCPAddr,
×
1759
                                )
×
1760
                        },
×
1761
                        AdvertisedIPs: advertisedIPs,
1762
                        AnnounceNewIPs: netann.IPAnnouncer(
1763
                                func(modifier ...netann.NodeAnnModifier) (
1764
                                        lnwire.NodeAnnouncement, error) {
×
1765

×
1766
                                        return s.genNodeAnnouncement(
×
1767
                                                nil, modifier...,
×
1768
                                        )
×
1769
                                }),
×
1770
                })
1771
        }
1772

1773
        // Create liveness monitor.
1774
        s.createLivenessMonitor(cfg, cc, leaderElector)
4✔
1775

4✔
1776
        // Create the connection manager which will be responsible for
4✔
1777
        // maintaining persistent outbound connections and also accepting new
4✔
1778
        // incoming connections
4✔
1779
        cmgr, err := connmgr.New(&connmgr.Config{
4✔
1780
                Listeners:      listeners,
4✔
1781
                OnAccept:       s.InboundPeerConnected,
4✔
1782
                RetryDuration:  time.Second * 5,
4✔
1783
                TargetOutbound: 100,
4✔
1784
                Dial: noiseDial(
4✔
1785
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
4✔
1786
                ),
4✔
1787
                OnConnection: s.OutboundPeerConnected,
4✔
1788
        })
4✔
1789
        if err != nil {
4✔
1790
                return nil, err
×
1791
        }
×
1792
        s.connMgr = cmgr
4✔
1793

4✔
1794
        return s, nil
4✔
1795
}
1796

1797
// UpdateRoutingConfig is a callback function to update the routing config
1798
// values in the main cfg.
1799
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
4✔
1800
        routerCfg := s.cfg.SubRPCServers.RouterRPC
4✔
1801

4✔
1802
        switch c := cfg.Estimator.Config().(type) {
4✔
1803
        case routing.AprioriConfig:
4✔
1804
                routerCfg.ProbabilityEstimatorType =
4✔
1805
                        routing.AprioriEstimatorName
4✔
1806

4✔
1807
                targetCfg := routerCfg.AprioriConfig
4✔
1808
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
4✔
1809
                targetCfg.Weight = c.AprioriWeight
4✔
1810
                targetCfg.CapacityFraction = c.CapacityFraction
4✔
1811
                targetCfg.HopProbability = c.AprioriHopProbability
4✔
1812

1813
        case routing.BimodalConfig:
4✔
1814
                routerCfg.ProbabilityEstimatorType =
4✔
1815
                        routing.BimodalEstimatorName
4✔
1816

4✔
1817
                targetCfg := routerCfg.BimodalConfig
4✔
1818
                targetCfg.Scale = int64(c.BimodalScaleMsat)
4✔
1819
                targetCfg.NodeWeight = c.BimodalNodeWeight
4✔
1820
                targetCfg.DecayTime = c.BimodalDecayTime
4✔
1821
        }
1822

1823
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
4✔
1824
}
1825

1826
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1827
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1828
// may differ from what is on disk.
1829
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1830
        error) {
4✔
1831

4✔
1832
        data, err := u.DataToSign()
4✔
1833
        if err != nil {
4✔
1834
                return nil, err
×
1835
        }
×
1836

1837
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
4✔
1838
}
1839

1840
// createLivenessMonitor creates a set of health checks using our configured
1841
// values and uses these checks to create a liveness monitor. Available
1842
// health checks,
1843
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1844
//   - diskCheck
1845
//   - tlsHealthCheck
1846
//   - torController, only created when tor is enabled.
1847
//
1848
// If a health check has been disabled by setting attempts to 0, our monitor
1849
// will not run it.
1850
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1851
        leaderElector cluster.LeaderElector) {
4✔
1852

4✔
1853
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
4✔
1854
        if cfg.Bitcoin.Node == "nochainbackend" {
4✔
1855
                srvrLog.Info("Disabling chain backend checks for " +
×
1856
                        "nochainbackend mode")
×
1857

×
1858
                chainBackendAttempts = 0
×
1859
        }
×
1860

1861
        chainHealthCheck := healthcheck.NewObservation(
4✔
1862
                "chain backend",
4✔
1863
                cc.HealthCheck,
4✔
1864
                cfg.HealthChecks.ChainCheck.Interval,
4✔
1865
                cfg.HealthChecks.ChainCheck.Timeout,
4✔
1866
                cfg.HealthChecks.ChainCheck.Backoff,
4✔
1867
                chainBackendAttempts,
4✔
1868
        )
4✔
1869

4✔
1870
        diskCheck := healthcheck.NewObservation(
4✔
1871
                "disk space",
4✔
1872
                func() error {
4✔
1873
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1874
                                cfg.LndDir,
×
1875
                        )
×
1876
                        if err != nil {
×
1877
                                return err
×
1878
                        }
×
1879

1880
                        // If we have more free space than we require,
1881
                        // we return a nil error.
1882
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1883
                                return nil
×
1884
                        }
×
1885

1886
                        return fmt.Errorf("require: %v free space, got: %v",
×
1887
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1888
                                free)
×
1889
                },
1890
                cfg.HealthChecks.DiskCheck.Interval,
1891
                cfg.HealthChecks.DiskCheck.Timeout,
1892
                cfg.HealthChecks.DiskCheck.Backoff,
1893
                cfg.HealthChecks.DiskCheck.Attempts,
1894
        )
1895

1896
        tlsHealthCheck := healthcheck.NewObservation(
4✔
1897
                "tls",
4✔
1898
                func() error {
4✔
1899
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1900
                                s.cc.KeyRing,
×
1901
                        )
×
1902
                        if err != nil {
×
1903
                                return err
×
1904
                        }
×
1905
                        if expired {
×
1906
                                return fmt.Errorf("TLS certificate is "+
×
1907
                                        "expired as of %v", expTime)
×
1908
                        }
×
1909

1910
                        // If the certificate is not outdated, no error needs
1911
                        // to be returned
1912
                        return nil
×
1913
                },
1914
                cfg.HealthChecks.TLSCheck.Interval,
1915
                cfg.HealthChecks.TLSCheck.Timeout,
1916
                cfg.HealthChecks.TLSCheck.Backoff,
1917
                cfg.HealthChecks.TLSCheck.Attempts,
1918
        )
1919

1920
        checks := []*healthcheck.Observation{
4✔
1921
                chainHealthCheck, diskCheck, tlsHealthCheck,
4✔
1922
        }
4✔
1923

4✔
1924
        // If Tor is enabled, add the healthcheck for tor connection.
4✔
1925
        if s.torController != nil {
4✔
1926
                torConnectionCheck := healthcheck.NewObservation(
×
1927
                        "tor connection",
×
1928
                        func() error {
×
1929
                                return healthcheck.CheckTorServiceStatus(
×
1930
                                        s.torController,
×
1931
                                        s.createNewHiddenService,
×
1932
                                )
×
1933
                        },
×
1934
                        cfg.HealthChecks.TorConnection.Interval,
1935
                        cfg.HealthChecks.TorConnection.Timeout,
1936
                        cfg.HealthChecks.TorConnection.Backoff,
1937
                        cfg.HealthChecks.TorConnection.Attempts,
1938
                )
1939
                checks = append(checks, torConnectionCheck)
×
1940
        }
1941

1942
        // If remote signing is enabled, add the healthcheck for the remote
1943
        // signing RPC interface.
1944
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
8✔
1945
                if rpckKeyRing, ok := cc.Wc.(*rpcwallet.RPCKeyRing); ok {
8✔
1946
                        timeout := cfg.HealthChecks.RemoteSigner.Timeout
4✔
1947

4✔
1948
                        // Because we have two cascading timeouts here, we need
4✔
1949
                        // to add some slack to the "outer" one of them in case
4✔
1950
                        // the "inner" returns exactly on time.
4✔
1951
                        outerTimeout := timeout + time.Millisecond*10
4✔
1952

4✔
1953
                        rsConnectionCheck := healthcheck.NewObservation(
4✔
1954
                                "remote signer connection",
4✔
1955
                                rpcwallet.HealthCheck(
4✔
1956
                                        rpckKeyRing.RemoteSigner(),
4✔
1957
                                        // For the health check we might to be
4✔
1958
                                        // even stricter than the initial/normal
4✔
1959
                                        // connect, so we use the health check
4✔
1960
                                        // timeout.
4✔
1961
                                        timeout,
4✔
1962
                                ),
4✔
1963
                                cfg.HealthChecks.RemoteSigner.Interval,
4✔
1964
                                outerTimeout,
4✔
1965
                                cfg.HealthChecks.RemoteSigner.Backoff,
4✔
1966
                                cfg.HealthChecks.RemoteSigner.Attempts,
4✔
1967
                        )
4✔
1968
                        checks = append(checks, rsConnectionCheck)
4✔
1969
                }
4✔
1970
        }
1971

1972
        // If we have a leader elector, we add a health check to ensure we are
1973
        // still the leader. During normal operation, we should always be the
1974
        // leader, but there are circumstances where this may change, such as
1975
        // when we lose network connectivity for long enough expiring out lease.
1976
        if leaderElector != nil {
4✔
1977
                leaderCheck := healthcheck.NewObservation(
×
1978
                        "leader status",
×
1979
                        func() error {
×
1980
                                // Check if we are still the leader. Note that
×
1981
                                // we don't need to use a timeout context here
×
1982
                                // as the healthcheck observer will handle the
×
1983
                                // timeout case for us.
×
1984
                                timeoutCtx, cancel := context.WithTimeout(
×
1985
                                        context.Background(),
×
1986
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
1987
                                )
×
1988
                                defer cancel()
×
1989

×
1990
                                leader, err := leaderElector.IsLeader(
×
1991
                                        timeoutCtx,
×
1992
                                )
×
1993
                                if err != nil {
×
1994
                                        return fmt.Errorf("unable to check if "+
×
1995
                                                "still leader: %v", err)
×
1996
                                }
×
1997

1998
                                if !leader {
×
1999
                                        srvrLog.Debug("Not the current leader")
×
2000
                                        return fmt.Errorf("not the current " +
×
2001
                                                "leader")
×
2002
                                }
×
2003

2004
                                return nil
×
2005
                        },
2006
                        cfg.HealthChecks.LeaderCheck.Interval,
2007
                        cfg.HealthChecks.LeaderCheck.Timeout,
2008
                        cfg.HealthChecks.LeaderCheck.Backoff,
2009
                        cfg.HealthChecks.LeaderCheck.Attempts,
2010
                )
2011

2012
                checks = append(checks, leaderCheck)
×
2013
        }
2014

2015
        // If we have not disabled all of our health checks, we create a
2016
        // liveness monitor with our configured checks.
2017
        s.livenessMonitor = healthcheck.NewMonitor(
4✔
2018
                &healthcheck.Config{
4✔
2019
                        Checks:   checks,
4✔
2020
                        Shutdown: srvrLog.Criticalf,
4✔
2021
                },
4✔
2022
        )
4✔
2023
}
2024

2025
// Started returns true if the server has been started, and false otherwise.
2026
// NOTE: This function is safe for concurrent access.
2027
func (s *server) Started() bool {
4✔
2028
        return atomic.LoadInt32(&s.active) != 0
4✔
2029
}
4✔
2030

2031
// cleaner is used to aggregate "cleanup" functions during an operation that
2032
// starts several subsystems. In case one of the subsystem fails to start
2033
// and a proper resource cleanup is required, the "run" method achieves this
2034
// by running all these added "cleanup" functions.
2035
type cleaner []func() error
2036

2037
// add is used to add a cleanup function to be called when
2038
// the run function is executed.
2039
func (c cleaner) add(cleanup func() error) cleaner {
4✔
2040
        return append(c, cleanup)
4✔
2041
}
4✔
2042

2043
// run is used to run all the previousely added cleanup functions.
2044
func (c cleaner) run() {
×
2045
        for i := len(c) - 1; i >= 0; i-- {
×
2046
                if err := c[i](); err != nil {
×
2047
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2048
                }
×
2049
        }
2050
}
2051

2052
// Start starts the main daemon server, all requested listeners, and any helper
2053
// goroutines.
2054
// NOTE: This function is safe for concurrent access.
2055
//
2056
//nolint:funlen
2057
func (s *server) Start() error {
4✔
2058
        var startErr error
4✔
2059

4✔
2060
        // If one sub system fails to start, the following code ensures that the
4✔
2061
        // previous started ones are stopped. It also ensures a proper wallet
4✔
2062
        // shutdown which is important for releasing its resources (boltdb, etc...)
4✔
2063
        cleanup := cleaner{}
4✔
2064

4✔
2065
        s.start.Do(func() {
8✔
2066
                cleanup = cleanup.add(s.customMessageServer.Stop)
4✔
2067
                if err := s.customMessageServer.Start(); err != nil {
4✔
2068
                        startErr = err
×
2069
                        return
×
2070
                }
×
2071

2072
                if s.hostAnn != nil {
4✔
2073
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2074
                        if err := s.hostAnn.Start(); err != nil {
×
2075
                                startErr = err
×
2076
                                return
×
2077
                        }
×
2078
                }
2079

2080
                if s.livenessMonitor != nil {
8✔
2081
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
4✔
2082
                        if err := s.livenessMonitor.Start(); err != nil {
4✔
2083
                                startErr = err
×
2084
                                return
×
2085
                        }
×
2086
                }
2087

2088
                cleanup = cleanup.add(s.remoteSignerClient.Stop)
4✔
2089
                if err := s.remoteSignerClient.Start(); err != nil {
4✔
NEW
2090
                        startErr = err
×
NEW
2091
                        return
×
NEW
2092
                }
×
2093

2094
                // Start the notification server. This is used so channel
2095
                // management goroutines can be notified when a funding
2096
                // transaction reaches a sufficient number of confirmations, or
2097
                // when the input for the funding transaction is spent in an
2098
                // attempt at an uncooperative close by the counterparty.
2099
                cleanup = cleanup.add(s.sigPool.Stop)
4✔
2100
                if err := s.sigPool.Start(); err != nil {
4✔
2101
                        startErr = err
×
2102
                        return
×
2103
                }
×
2104

2105
                cleanup = cleanup.add(s.writePool.Stop)
4✔
2106
                if err := s.writePool.Start(); err != nil {
4✔
2107
                        startErr = err
×
2108
                        return
×
2109
                }
×
2110

2111
                cleanup = cleanup.add(s.readPool.Stop)
4✔
2112
                if err := s.readPool.Start(); err != nil {
4✔
2113
                        startErr = err
×
2114
                        return
×
2115
                }
×
2116

2117
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
4✔
2118
                if err := s.cc.ChainNotifier.Start(); err != nil {
4✔
2119
                        startErr = err
×
2120
                        return
×
2121
                }
×
2122

2123
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
4✔
2124
                if err := s.cc.BestBlockTracker.Start(); err != nil {
4✔
2125
                        startErr = err
×
2126
                        return
×
2127
                }
×
2128

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

2135
                cleanup = cleanup.add(func() error {
4✔
2136
                        return s.peerNotifier.Stop()
×
2137
                })
×
2138
                if err := s.peerNotifier.Start(); err != nil {
4✔
2139
                        startErr = err
×
2140
                        return
×
2141
                }
×
2142

2143
                cleanup = cleanup.add(s.htlcNotifier.Stop)
4✔
2144
                if err := s.htlcNotifier.Start(); err != nil {
4✔
2145
                        startErr = err
×
2146
                        return
×
2147
                }
×
2148

2149
                if s.towerClientMgr != nil {
8✔
2150
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
4✔
2151
                        if err := s.towerClientMgr.Start(); err != nil {
4✔
2152
                                startErr = err
×
2153
                                return
×
2154
                        }
×
2155
                }
2156

2157
                cleanup = cleanup.add(s.txPublisher.Stop)
4✔
2158
                if err := s.txPublisher.Start(); err != nil {
4✔
2159
                        startErr = err
×
2160
                        return
×
2161
                }
×
2162

2163
                cleanup = cleanup.add(s.sweeper.Stop)
4✔
2164
                if err := s.sweeper.Start(); err != nil {
4✔
2165
                        startErr = err
×
2166
                        return
×
2167
                }
×
2168

2169
                cleanup = cleanup.add(s.utxoNursery.Stop)
4✔
2170
                if err := s.utxoNursery.Start(); err != nil {
4✔
2171
                        startErr = err
×
2172
                        return
×
2173
                }
×
2174

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

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

2187
                // htlcSwitch must be started before chainArb since the latter
2188
                // relies on htlcSwitch to deliver resolution message upon
2189
                // start.
2190
                cleanup = cleanup.add(s.htlcSwitch.Stop)
4✔
2191
                if err := s.htlcSwitch.Start(); err != nil {
4✔
2192
                        startErr = err
×
2193
                        return
×
2194
                }
×
2195

2196
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
4✔
2197
                if err := s.interceptableSwitch.Start(); err != nil {
4✔
2198
                        startErr = err
×
2199
                        return
×
2200
                }
×
2201

2202
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
4✔
2203
                if err := s.invoiceHtlcModifier.Start(); err != nil {
4✔
2204
                        startErr = err
×
2205
                        return
×
2206
                }
×
2207

2208
                cleanup = cleanup.add(s.chainArb.Stop)
4✔
2209
                if err := s.chainArb.Start(); err != nil {
4✔
2210
                        startErr = err
×
2211
                        return
×
2212
                }
×
2213

2214
                cleanup = cleanup.add(s.graphBuilder.Stop)
4✔
2215
                if err := s.graphBuilder.Start(); err != nil {
4✔
2216
                        startErr = err
×
2217
                        return
×
2218
                }
×
2219

2220
                cleanup = cleanup.add(s.chanRouter.Stop)
4✔
2221
                if err := s.chanRouter.Start(); err != nil {
4✔
2222
                        startErr = err
×
2223
                        return
×
2224
                }
×
2225
                // The authGossiper depends on the chanRouter and therefore
2226
                // should be started after it.
2227
                cleanup = cleanup.add(s.authGossiper.Stop)
4✔
2228
                if err := s.authGossiper.Start(); err != nil {
4✔
2229
                        startErr = err
×
2230
                        return
×
2231
                }
×
2232

2233
                cleanup = cleanup.add(s.invoices.Stop)
4✔
2234
                if err := s.invoices.Start(); err != nil {
4✔
2235
                        startErr = err
×
2236
                        return
×
2237
                }
×
2238

2239
                cleanup = cleanup.add(s.sphinx.Stop)
4✔
2240
                if err := s.sphinx.Start(); err != nil {
4✔
2241
                        startErr = err
×
2242
                        return
×
2243
                }
×
2244

2245
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
4✔
2246
                if err := s.chanStatusMgr.Start(); err != nil {
4✔
2247
                        startErr = err
×
2248
                        return
×
2249
                }
×
2250

2251
                cleanup = cleanup.add(s.chanEventStore.Stop)
4✔
2252
                if err := s.chanEventStore.Start(); err != nil {
4✔
2253
                        startErr = err
×
2254
                        return
×
2255
                }
×
2256

2257
                cleanup.add(func() error {
4✔
2258
                        s.missionController.StopStoreTickers()
×
2259
                        return nil
×
2260
                })
×
2261
                s.missionController.RunStoreTickers()
4✔
2262

4✔
2263
                // Before we start the connMgr, we'll check to see if we have
4✔
2264
                // any backups to recover. We do this now as we want to ensure
4✔
2265
                // that have all the information we need to handle channel
4✔
2266
                // recovery _before_ we even accept connections from any peers.
4✔
2267
                chanRestorer := &chanDBRestorer{
4✔
2268
                        db:         s.chanStateDB,
4✔
2269
                        secretKeys: s.cc.KeyRing,
4✔
2270
                        chainArb:   s.chainArb,
4✔
2271
                }
4✔
2272
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
4✔
2273
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2274
                                s.chansToRestore.PackedSingleChanBackups,
×
2275
                                s.cc.KeyRing, chanRestorer, s,
×
2276
                        )
×
2277
                        if err != nil {
×
2278
                                startErr = fmt.Errorf("unable to unpack single "+
×
2279
                                        "backups: %v", err)
×
2280
                                return
×
2281
                        }
×
2282
                }
2283
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
8✔
2284
                        _, err := chanbackup.UnpackAndRecoverMulti(
4✔
2285
                                s.chansToRestore.PackedMultiChanBackup,
4✔
2286
                                s.cc.KeyRing, chanRestorer, s,
4✔
2287
                        )
4✔
2288
                        if err != nil {
4✔
2289
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2290
                                        "backup: %v", err)
×
2291
                                return
×
2292
                        }
×
2293
                }
2294

2295
                // chanSubSwapper must be started after the `channelNotifier`
2296
                // because it depends on channel events as a synchronization
2297
                // point.
2298
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
4✔
2299
                if err := s.chanSubSwapper.Start(); err != nil {
4✔
2300
                        startErr = err
×
2301
                        return
×
2302
                }
×
2303

2304
                if s.torController != nil {
4✔
2305
                        cleanup = cleanup.add(s.torController.Stop)
×
2306
                        if err := s.createNewHiddenService(); err != nil {
×
2307
                                startErr = err
×
2308
                                return
×
2309
                        }
×
2310
                }
2311

2312
                if s.natTraversal != nil {
4✔
2313
                        s.wg.Add(1)
×
2314
                        go s.watchExternalIP()
×
2315
                }
×
2316

2317
                // Start connmgr last to prevent connections before init.
2318
                cleanup = cleanup.add(func() error {
4✔
2319
                        s.connMgr.Stop()
×
2320
                        return nil
×
2321
                })
×
2322
                s.connMgr.Start()
4✔
2323

4✔
2324
                // If peers are specified as a config option, we'll add those
4✔
2325
                // peers first.
4✔
2326
                for _, peerAddrCfg := range s.cfg.AddPeers {
8✔
2327
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
4✔
2328
                                peerAddrCfg,
4✔
2329
                        )
4✔
2330
                        if err != nil {
4✔
2331
                                startErr = fmt.Errorf("unable to parse peer "+
×
2332
                                        "pubkey from config: %v", err)
×
2333
                                return
×
2334
                        }
×
2335
                        addr, err := parseAddr(parsedHost, s.cfg.net)
4✔
2336
                        if err != nil {
4✔
2337
                                startErr = fmt.Errorf("unable to parse peer "+
×
2338
                                        "address provided as a config option: "+
×
2339
                                        "%v", err)
×
2340
                                return
×
2341
                        }
×
2342

2343
                        peerAddr := &lnwire.NetAddress{
4✔
2344
                                IdentityKey: parsedPubkey,
4✔
2345
                                Address:     addr,
4✔
2346
                                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
2347
                        }
4✔
2348

4✔
2349
                        err = s.ConnectToPeer(
4✔
2350
                                peerAddr, true,
4✔
2351
                                s.cfg.ConnectionTimeout,
4✔
2352
                        )
4✔
2353
                        if err != nil {
4✔
2354
                                startErr = fmt.Errorf("unable to connect to "+
×
2355
                                        "peer address provided as a config "+
×
2356
                                        "option: %v", err)
×
2357
                                return
×
2358
                        }
×
2359
                }
2360

2361
                // Subscribe to NodeAnnouncements that advertise new addresses
2362
                // our persistent peers.
2363
                if err := s.updatePersistentPeerAddrs(); err != nil {
4✔
2364
                        startErr = err
×
2365
                        return
×
2366
                }
×
2367

2368
                // With all the relevant sub-systems started, we'll now attempt
2369
                // to establish persistent connections to our direct channel
2370
                // collaborators within the network. Before doing so however,
2371
                // we'll prune our set of link nodes found within the database
2372
                // to ensure we don't reconnect to any nodes we no longer have
2373
                // open channels with.
2374
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
4✔
2375
                        startErr = err
×
2376
                        return
×
2377
                }
×
2378
                if err := s.establishPersistentConnections(); err != nil {
4✔
2379
                        startErr = err
×
2380
                        return
×
2381
                }
×
2382

2383
                // setSeedList is a helper function that turns multiple DNS seed
2384
                // server tuples from the command line or config file into the
2385
                // data structure we need and does a basic formal sanity check
2386
                // in the process.
2387
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
4✔
2388
                        if len(tuples) == 0 {
×
2389
                                return
×
2390
                        }
×
2391

2392
                        result := make([][2]string, len(tuples))
×
2393
                        for idx, tuple := range tuples {
×
2394
                                tuple = strings.TrimSpace(tuple)
×
2395
                                if len(tuple) == 0 {
×
2396
                                        return
×
2397
                                }
×
2398

2399
                                servers := strings.Split(tuple, ",")
×
2400
                                if len(servers) > 2 || len(servers) == 0 {
×
2401
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2402
                                                "seed tuple: %v", servers)
×
2403
                                        return
×
2404
                                }
×
2405

2406
                                copy(result[idx][:], servers)
×
2407
                        }
2408

2409
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2410
                }
2411

2412
                // Let users overwrite the DNS seed nodes. We only allow them
2413
                // for bitcoin mainnet/testnet/signet.
2414
                if s.cfg.Bitcoin.MainNet {
4✔
2415
                        setSeedList(
×
2416
                                s.cfg.Bitcoin.DNSSeeds,
×
2417
                                chainreg.BitcoinMainnetGenesis,
×
2418
                        )
×
2419
                }
×
2420
                if s.cfg.Bitcoin.TestNet3 {
4✔
2421
                        setSeedList(
×
2422
                                s.cfg.Bitcoin.DNSSeeds,
×
2423
                                chainreg.BitcoinTestnetGenesis,
×
2424
                        )
×
2425
                }
×
2426
                if s.cfg.Bitcoin.SigNet {
4✔
2427
                        setSeedList(
×
2428
                                s.cfg.Bitcoin.DNSSeeds,
×
2429
                                chainreg.BitcoinSignetGenesis,
×
2430
                        )
×
2431
                }
×
2432

2433
                // If network bootstrapping hasn't been disabled, then we'll
2434
                // configure the set of active bootstrappers, and launch a
2435
                // dedicated goroutine to maintain a set of persistent
2436
                // connections.
2437
                if shouldPeerBootstrap(s.cfg) {
4✔
2438
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2439
                        if err != nil {
×
2440
                                startErr = err
×
2441
                                return
×
2442
                        }
×
2443

2444
                        s.wg.Add(1)
×
2445
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2446
                } else {
4✔
2447
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
4✔
2448
                }
4✔
2449

2450
                // Set the active flag now that we've completed the full
2451
                // startup.
2452
                atomic.StoreInt32(&s.active, 1)
4✔
2453
        })
2454

2455
        if startErr != nil {
4✔
2456
                cleanup.run()
×
2457
        }
×
2458
        return startErr
4✔
2459
}
2460

2461
// Stop gracefully shutsdown the main daemon server. This function will signal
2462
// any active goroutines, or helper objects to exit, then blocks until they've
2463
// all successfully exited. Additionally, any/all listeners are closed.
2464
// NOTE: This function is safe for concurrent access.
2465
func (s *server) Stop() error {
4✔
2466
        s.stop.Do(func() {
8✔
2467
                atomic.StoreInt32(&s.stopping, 1)
4✔
2468

4✔
2469
                close(s.quit)
4✔
2470

4✔
2471
                // Shutdown connMgr first to prevent conns during shutdown.
4✔
2472
                s.connMgr.Stop()
4✔
2473

4✔
2474
                // Shutdown the wallet, funding manager, and the rpc server.
4✔
2475
                if err := s.chanStatusMgr.Stop(); err != nil {
4✔
2476
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2477
                }
×
2478
                if err := s.htlcSwitch.Stop(); err != nil {
4✔
2479
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2480
                }
×
2481
                if err := s.sphinx.Stop(); err != nil {
4✔
2482
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2483
                }
×
2484
                if err := s.invoices.Stop(); err != nil {
4✔
2485
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2486
                }
×
2487
                if err := s.interceptableSwitch.Stop(); err != nil {
4✔
2488
                        srvrLog.Warnf("failed to stop interceptable "+
×
2489
                                "switch: %v", err)
×
2490
                }
×
2491
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
4✔
2492
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2493
                                "modifier: %v", err)
×
2494
                }
×
2495
                if err := s.chanRouter.Stop(); err != nil {
4✔
2496
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2497
                }
×
2498
                if err := s.graphBuilder.Stop(); err != nil {
4✔
2499
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2500
                }
×
2501
                if err := s.chainArb.Stop(); err != nil {
4✔
2502
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2503
                }
×
2504
                if err := s.fundingMgr.Stop(); err != nil {
4✔
2505
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2506
                }
×
2507
                if err := s.breachArbitrator.Stop(); err != nil {
4✔
2508
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2509
                                err)
×
2510
                }
×
2511
                if err := s.utxoNursery.Stop(); err != nil {
4✔
2512
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2513
                }
×
2514
                if err := s.authGossiper.Stop(); err != nil {
4✔
2515
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2516
                }
×
2517
                if err := s.sweeper.Stop(); err != nil {
4✔
2518
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2519
                }
×
2520
                if err := s.txPublisher.Stop(); err != nil {
4✔
2521
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2522
                }
×
2523
                if err := s.channelNotifier.Stop(); err != nil {
4✔
2524
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2525
                }
×
2526
                if err := s.peerNotifier.Stop(); err != nil {
4✔
2527
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2528
                }
×
2529
                if err := s.htlcNotifier.Stop(); err != nil {
4✔
2530
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2531
                }
×
2532

2533
                // Update channel.backup file. Make sure to do it before
2534
                // stopping chanSubSwapper.
2535
                singles, err := chanbackup.FetchStaticChanBackups(
4✔
2536
                        s.chanStateDB, s.addrSource,
4✔
2537
                )
4✔
2538
                if err != nil {
4✔
2539
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2540
                                err)
×
2541
                } else {
4✔
2542
                        err := s.chanSubSwapper.ManualUpdate(singles)
4✔
2543
                        if err != nil {
8✔
2544
                                srvrLog.Warnf("Manual update of channel "+
4✔
2545
                                        "backup failed: %v", err)
4✔
2546
                        }
4✔
2547
                }
2548

2549
                if err := s.chanSubSwapper.Stop(); err != nil {
4✔
2550
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2551
                }
×
2552
                if err := s.cc.ChainNotifier.Stop(); err != nil {
4✔
2553
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2554
                }
×
2555
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
4✔
2556
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2557
                                err)
×
2558
                }
×
2559
                if err := s.remoteSignerClient.Stop(); err != nil {
4✔
NEW
2560
                        srvrLog.Warnf("Unable to stop remote signer "+
×
NEW
2561
                                "client: %v", err)
×
NEW
2562
                }
×
2563
                if err := s.chanEventStore.Stop(); err != nil {
4✔
2564
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2565
                                err)
×
2566
                }
×
2567
                s.missionController.StopStoreTickers()
4✔
2568

4✔
2569
                // Disconnect from each active peers to ensure that
4✔
2570
                // peerTerminationWatchers signal completion to each peer.
4✔
2571
                for _, peer := range s.Peers() {
8✔
2572
                        err := s.DisconnectPeer(peer.IdentityKey())
4✔
2573
                        if err != nil {
4✔
2574
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2575
                                        "received error: %v", peer.IdentityKey(),
×
2576
                                        err,
×
2577
                                )
×
2578
                        }
×
2579
                }
2580

2581
                // Now that all connections have been torn down, stop the tower
2582
                // client which will reliably flush all queued states to the
2583
                // tower. If this is halted for any reason, the force quit timer
2584
                // will kick in and abort to allow this method to return.
2585
                if s.towerClientMgr != nil {
8✔
2586
                        if err := s.towerClientMgr.Stop(); err != nil {
4✔
2587
                                srvrLog.Warnf("Unable to shut down tower "+
×
2588
                                        "client manager: %v", err)
×
2589
                        }
×
2590
                }
2591

2592
                if s.hostAnn != nil {
4✔
2593
                        if err := s.hostAnn.Stop(); err != nil {
×
2594
                                srvrLog.Warnf("unable to shut down host "+
×
2595
                                        "annoucner: %v", err)
×
2596
                        }
×
2597
                }
2598

2599
                if s.livenessMonitor != nil {
8✔
2600
                        if err := s.livenessMonitor.Stop(); err != nil {
4✔
2601
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2602
                                        "monitor: %v", err)
×
2603
                        }
×
2604
                }
2605

2606
                // Wait for all lingering goroutines to quit.
2607
                srvrLog.Debug("Waiting for server to shutdown...")
4✔
2608
                s.wg.Wait()
4✔
2609

4✔
2610
                srvrLog.Debug("Stopping buffer pools...")
4✔
2611
                s.sigPool.Stop()
4✔
2612
                s.writePool.Stop()
4✔
2613
                s.readPool.Stop()
4✔
2614
        })
2615

2616
        return nil
4✔
2617
}
2618

2619
// Stopped returns true if the server has been instructed to shutdown.
2620
// NOTE: This function is safe for concurrent access.
2621
func (s *server) Stopped() bool {
4✔
2622
        return atomic.LoadInt32(&s.stopping) != 0
4✔
2623
}
4✔
2624

2625
// configurePortForwarding attempts to set up port forwarding for the different
2626
// ports that the server will be listening on.
2627
//
2628
// NOTE: This should only be used when using some kind of NAT traversal to
2629
// automatically set up forwarding rules.
2630
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2631
        ip, err := s.natTraversal.ExternalIP()
×
2632
        if err != nil {
×
2633
                return nil, err
×
2634
        }
×
2635
        s.lastDetectedIP = ip
×
2636

×
2637
        externalIPs := make([]string, 0, len(ports))
×
2638
        for _, port := range ports {
×
2639
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2640
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2641
                        continue
×
2642
                }
2643

2644
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2645
                externalIPs = append(externalIPs, hostIP)
×
2646
        }
2647

2648
        return externalIPs, nil
×
2649
}
2650

2651
// removePortForwarding attempts to clear the forwarding rules for the different
2652
// ports the server is currently listening on.
2653
//
2654
// NOTE: This should only be used when using some kind of NAT traversal to
2655
// automatically set up forwarding rules.
2656
func (s *server) removePortForwarding() {
×
2657
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2658
        for _, port := range forwardedPorts {
×
2659
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2660
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2661
                                "port %d: %v", port, err)
×
2662
                }
×
2663
        }
2664
}
2665

2666
// watchExternalIP continuously checks for an updated external IP address every
2667
// 15 minutes. Once a new IP address has been detected, it will automatically
2668
// handle port forwarding rules and send updated node announcements to the
2669
// currently connected peers.
2670
//
2671
// NOTE: This MUST be run as a goroutine.
2672
func (s *server) watchExternalIP() {
×
2673
        defer s.wg.Done()
×
2674

×
2675
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2676
        // up by the server.
×
2677
        defer s.removePortForwarding()
×
2678

×
2679
        // Keep track of the external IPs set by the user to avoid replacing
×
2680
        // them when detecting a new IP.
×
2681
        ipsSetByUser := make(map[string]struct{})
×
2682
        for _, ip := range s.cfg.ExternalIPs {
×
2683
                ipsSetByUser[ip.String()] = struct{}{}
×
2684
        }
×
2685

2686
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2687

×
2688
        ticker := time.NewTicker(15 * time.Minute)
×
2689
        defer ticker.Stop()
×
2690
out:
×
2691
        for {
×
2692
                select {
×
2693
                case <-ticker.C:
×
2694
                        // We'll start off by making sure a new IP address has
×
2695
                        // been detected.
×
2696
                        ip, err := s.natTraversal.ExternalIP()
×
2697
                        if err != nil {
×
2698
                                srvrLog.Debugf("Unable to retrieve the "+
×
2699
                                        "external IP address: %v", err)
×
2700
                                continue
×
2701
                        }
2702

2703
                        // Periodically renew the NAT port forwarding.
2704
                        for _, port := range forwardedPorts {
×
2705
                                err := s.natTraversal.AddPortMapping(port)
×
2706
                                if err != nil {
×
2707
                                        srvrLog.Warnf("Unable to automatically "+
×
2708
                                                "re-create port forwarding using %s: %v",
×
2709
                                                s.natTraversal.Name(), err)
×
2710
                                } else {
×
2711
                                        srvrLog.Debugf("Automatically re-created "+
×
2712
                                                "forwarding for port %d using %s to "+
×
2713
                                                "advertise external IP",
×
2714
                                                port, s.natTraversal.Name())
×
2715
                                }
×
2716
                        }
2717

2718
                        if ip.Equal(s.lastDetectedIP) {
×
2719
                                continue
×
2720
                        }
2721

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

×
2724
                        // Next, we'll craft the new addresses that will be
×
2725
                        // included in the new node announcement and advertised
×
2726
                        // to the network. Each address will consist of the new
×
2727
                        // IP detected and one of the currently advertised
×
2728
                        // ports.
×
2729
                        var newAddrs []net.Addr
×
2730
                        for _, port := range forwardedPorts {
×
2731
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2732
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2733
                                if err != nil {
×
2734
                                        srvrLog.Debugf("Unable to resolve "+
×
2735
                                                "host %v: %v", addr, err)
×
2736
                                        continue
×
2737
                                }
2738

2739
                                newAddrs = append(newAddrs, addr)
×
2740
                        }
2741

2742
                        // Skip the update if we weren't able to resolve any of
2743
                        // the new addresses.
2744
                        if len(newAddrs) == 0 {
×
2745
                                srvrLog.Debug("Skipping node announcement " +
×
2746
                                        "update due to not being able to " +
×
2747
                                        "resolve any new addresses")
×
2748
                                continue
×
2749
                        }
2750

2751
                        // Now, we'll need to update the addresses in our node's
2752
                        // announcement in order to propagate the update
2753
                        // throughout the network. We'll only include addresses
2754
                        // that have a different IP from the previous one, as
2755
                        // the previous IP is no longer valid.
2756
                        currentNodeAnn := s.getNodeAnnouncement()
×
2757

×
2758
                        for _, addr := range currentNodeAnn.Addresses {
×
2759
                                host, _, err := net.SplitHostPort(addr.String())
×
2760
                                if err != nil {
×
2761
                                        srvrLog.Debugf("Unable to determine "+
×
2762
                                                "host from address %v: %v",
×
2763
                                                addr, err)
×
2764
                                        continue
×
2765
                                }
2766

2767
                                // We'll also make sure to include external IPs
2768
                                // set manually by the user.
2769
                                _, setByUser := ipsSetByUser[addr.String()]
×
2770
                                if setByUser || host != s.lastDetectedIP.String() {
×
2771
                                        newAddrs = append(newAddrs, addr)
×
2772
                                }
×
2773
                        }
2774

2775
                        // Then, we'll generate a new timestamped node
2776
                        // announcement with the updated addresses and broadcast
2777
                        // it to our peers.
2778
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2779
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2780
                        )
×
2781
                        if err != nil {
×
2782
                                srvrLog.Debugf("Unable to generate new node "+
×
2783
                                        "announcement: %v", err)
×
2784
                                continue
×
2785
                        }
2786

2787
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2788
                        if err != nil {
×
2789
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2790
                                        "announcement to peers: %v", err)
×
2791
                                continue
×
2792
                        }
2793

2794
                        // Finally, update the last IP seen to the current one.
2795
                        s.lastDetectedIP = ip
×
2796
                case <-s.quit:
×
2797
                        break out
×
2798
                }
2799
        }
2800
}
2801

2802
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2803
// based on the server, and currently active bootstrap mechanisms as defined
2804
// within the current configuration.
2805
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2806
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2807

×
2808
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2809

×
2810
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2811
        // this can be used by default if we've already partially seeded the
×
2812
        // network.
×
2813
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2814
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2815
        if err != nil {
×
2816
                return nil, err
×
2817
        }
×
2818
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2819

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

×
2825
                // If we have a set of DNS seeds for this chain, then we'll add
×
2826
                // it as an additional bootstrapping source.
×
2827
                if ok {
×
2828
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2829
                                "seeds: %v", dnsSeeds)
×
2830

×
2831
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2832
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2833
                        )
×
2834
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2835
                }
×
2836
        }
2837

2838
        return bootStrappers, nil
×
2839
}
2840

2841
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2842
// needs to ignore, which is made of three parts,
2843
//   - the node itself needs to be skipped as it doesn't make sense to connect
2844
//     to itself.
2845
//   - the peers that already have connections with, as in s.peersByPub.
2846
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2847
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2848
        s.mu.RLock()
×
2849
        defer s.mu.RUnlock()
×
2850

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

×
2853
        // We should ignore ourselves from bootstrapping.
×
2854
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2855
        ignore[selfKey] = struct{}{}
×
2856

×
2857
        // Ignore all connected peers.
×
2858
        for _, peer := range s.peersByPub {
×
2859
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2860
                ignore[nID] = struct{}{}
×
2861
        }
×
2862

2863
        // Ignore all persistent peers as they have a dedicated reconnecting
2864
        // process.
2865
        for pubKeyStr := range s.persistentPeers {
×
2866
                var nID autopilot.NodeID
×
2867
                copy(nID[:], []byte(pubKeyStr))
×
2868
                ignore[nID] = struct{}{}
×
2869
        }
×
2870

2871
        return ignore
×
2872
}
2873

2874
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2875
// and maintain a target minimum number of outbound connections. With this
2876
// invariant, we ensure that our node is connected to a diverse set of peers
2877
// and that nodes newly joining the network receive an up to date network view
2878
// as soon as possible.
2879
func (s *server) peerBootstrapper(numTargetPeers uint32,
2880
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2881

×
2882
        defer s.wg.Done()
×
2883

×
2884
        // Before we continue, init the ignore peers map.
×
2885
        ignoreList := s.createBootstrapIgnorePeers()
×
2886

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

×
2891
        // Once done, we'll attempt to maintain our target minimum number of
×
2892
        // peers.
×
2893
        //
×
2894
        // We'll use a 15 second backoff, and double the time every time an
×
2895
        // epoch fails up to a ceiling.
×
2896
        backOff := time.Second * 15
×
2897

×
2898
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2899
        // see if we've reached our minimum number of peers.
×
2900
        sampleTicker := time.NewTicker(backOff)
×
2901
        defer sampleTicker.Stop()
×
2902

×
2903
        // We'll use the number of attempts and errors to determine if we need
×
2904
        // to increase the time between discovery epochs.
×
2905
        var epochErrors uint32 // To be used atomically.
×
2906
        var epochAttempts uint32
×
2907

×
2908
        for {
×
2909
                select {
×
2910
                // The ticker has just woken us up, so we'll need to check if
2911
                // we need to attempt to connect our to any more peers.
2912
                case <-sampleTicker.C:
×
2913
                        // Obtain the current number of peers, so we can gauge
×
2914
                        // if we need to sample more peers or not.
×
2915
                        s.mu.RLock()
×
2916
                        numActivePeers := uint32(len(s.peersByPub))
×
2917
                        s.mu.RUnlock()
×
2918

×
2919
                        // If we have enough peers, then we can loop back
×
2920
                        // around to the next round as we're done here.
×
2921
                        if numActivePeers >= numTargetPeers {
×
2922
                                continue
×
2923
                        }
2924

2925
                        // If all of our attempts failed during this last back
2926
                        // off period, then will increase our backoff to 5
2927
                        // minute ceiling to avoid an excessive number of
2928
                        // queries
2929
                        //
2930
                        // TODO(roasbeef): add reverse policy too?
2931

2932
                        if epochAttempts > 0 &&
×
2933
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2934

×
2935
                                sampleTicker.Stop()
×
2936

×
2937
                                backOff *= 2
×
2938
                                if backOff > bootstrapBackOffCeiling {
×
2939
                                        backOff = bootstrapBackOffCeiling
×
2940
                                }
×
2941

2942
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2943
                                        "%v", backOff)
×
2944
                                sampleTicker = time.NewTicker(backOff)
×
2945
                                continue
×
2946
                        }
2947

2948
                        atomic.StoreUint32(&epochErrors, 0)
×
2949
                        epochAttempts = 0
×
2950

×
2951
                        // Since we know need more peers, we'll compute the
×
2952
                        // exact number we need to reach our threshold.
×
2953
                        numNeeded := numTargetPeers - numActivePeers
×
2954

×
2955
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2956
                                "peers", numNeeded)
×
2957

×
2958
                        // With the number of peers we need calculated, we'll
×
2959
                        // query the network bootstrappers to sample a set of
×
2960
                        // random addrs for us.
×
2961
                        //
×
2962
                        // Before we continue, get a copy of the ignore peers
×
2963
                        // map.
×
2964
                        ignoreList = s.createBootstrapIgnorePeers()
×
2965

×
2966
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2967
                                ignoreList, numNeeded*2, bootstrappers...,
×
2968
                        )
×
2969
                        if err != nil {
×
2970
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2971
                                        "peers: %v", err)
×
2972
                                continue
×
2973
                        }
2974

2975
                        // Finally, we'll launch a new goroutine for each
2976
                        // prospective peer candidates.
2977
                        for _, addr := range peerAddrs {
×
2978
                                epochAttempts++
×
2979

×
2980
                                go func(a *lnwire.NetAddress) {
×
2981
                                        // TODO(roasbeef): can do AS, subnet,
×
2982
                                        // country diversity, etc
×
2983
                                        errChan := make(chan error, 1)
×
2984
                                        s.connectToPeer(
×
2985
                                                a, errChan,
×
2986
                                                s.cfg.ConnectionTimeout,
×
2987
                                        )
×
2988
                                        select {
×
2989
                                        case err := <-errChan:
×
2990
                                                if err == nil {
×
2991
                                                        return
×
2992
                                                }
×
2993

2994
                                                srvrLog.Errorf("Unable to "+
×
2995
                                                        "connect to %v: %v",
×
2996
                                                        a, err)
×
2997
                                                atomic.AddUint32(&epochErrors, 1)
×
2998
                                        case <-s.quit:
×
2999
                                        }
3000
                                }(addr)
3001
                        }
3002
                case <-s.quit:
×
3003
                        return
×
3004
                }
3005
        }
3006
}
3007

3008
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3009
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3010
// query back off each time we encounter a failure.
3011
const bootstrapBackOffCeiling = time.Minute * 5
3012

3013
// initialPeerBootstrap attempts to continuously connect to peers on startup
3014
// until the target number of peers has been reached. This ensures that nodes
3015
// receive an up to date network view as soon as possible.
3016
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3017
        numTargetPeers uint32,
3018
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3019

×
3020
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3021
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3022

×
3023
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3024
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3025
        var delaySignal <-chan time.Time
×
3026
        delayTime := time.Second * 2
×
3027

×
3028
        // As want to be more aggressive, we'll use a lower back off celling
×
3029
        // then the main peer bootstrap logic.
×
3030
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3031

×
3032
        for attempts := 0; ; attempts++ {
×
3033
                // Check if the server has been requested to shut down in order
×
3034
                // to prevent blocking.
×
3035
                if s.Stopped() {
×
3036
                        return
×
3037
                }
×
3038

3039
                // We can exit our aggressive initial peer bootstrapping stage
3040
                // if we've reached out target number of peers.
3041
                s.mu.RLock()
×
3042
                numActivePeers := uint32(len(s.peersByPub))
×
3043
                s.mu.RUnlock()
×
3044

×
3045
                if numActivePeers >= numTargetPeers {
×
3046
                        return
×
3047
                }
×
3048

3049
                if attempts > 0 {
×
3050
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3051
                                "bootstrap peers (attempt #%v)", delayTime,
×
3052
                                attempts)
×
3053

×
3054
                        // We've completed at least one iterating and haven't
×
3055
                        // finished, so we'll start to insert a delay period
×
3056
                        // between each attempt.
×
3057
                        delaySignal = time.After(delayTime)
×
3058
                        select {
×
3059
                        case <-delaySignal:
×
3060
                        case <-s.quit:
×
3061
                                return
×
3062
                        }
3063

3064
                        // After our delay, we'll double the time we wait up to
3065
                        // the max back off period.
3066
                        delayTime *= 2
×
3067
                        if delayTime > backOffCeiling {
×
3068
                                delayTime = backOffCeiling
×
3069
                        }
×
3070
                }
3071

3072
                // Otherwise, we'll request for the remaining number of peers
3073
                // in order to reach our target.
3074
                peersNeeded := numTargetPeers - numActivePeers
×
3075
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3076
                        ignore, peersNeeded, bootstrappers...,
×
3077
                )
×
3078
                if err != nil {
×
3079
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3080
                                "peers: %v", err)
×
3081
                        continue
×
3082
                }
3083

3084
                // Then, we'll attempt to establish a connection to the
3085
                // different peer addresses retrieved by our bootstrappers.
3086
                var wg sync.WaitGroup
×
3087
                for _, bootstrapAddr := range bootstrapAddrs {
×
3088
                        wg.Add(1)
×
3089
                        go func(addr *lnwire.NetAddress) {
×
3090
                                defer wg.Done()
×
3091

×
3092
                                errChan := make(chan error, 1)
×
3093
                                go s.connectToPeer(
×
3094
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3095
                                )
×
3096

×
3097
                                // We'll only allow this connection attempt to
×
3098
                                // take up to 3 seconds. This allows us to move
×
3099
                                // quickly by discarding peers that are slowing
×
3100
                                // us down.
×
3101
                                select {
×
3102
                                case err := <-errChan:
×
3103
                                        if err == nil {
×
3104
                                                return
×
3105
                                        }
×
3106
                                        srvrLog.Errorf("Unable to connect to "+
×
3107
                                                "%v: %v", addr, err)
×
3108
                                // TODO: tune timeout? 3 seconds might be *too*
3109
                                // aggressive but works well.
3110
                                case <-time.After(3 * time.Second):
×
3111
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3112
                                                "to not establishing a "+
×
3113
                                                "connection within 3 seconds",
×
3114
                                                addr)
×
3115
                                case <-s.quit:
×
3116
                                }
3117
                        }(bootstrapAddr)
3118
                }
3119

3120
                wg.Wait()
×
3121
        }
3122
}
3123

3124
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3125
// order to listen for inbound connections over Tor.
3126
func (s *server) createNewHiddenService() error {
×
3127
        // Determine the different ports the server is listening on. The onion
×
3128
        // service's virtual port will map to these ports and one will be picked
×
3129
        // at random when the onion service is being accessed.
×
3130
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3131
        for _, listenAddr := range s.listenAddrs {
×
3132
                port := listenAddr.(*net.TCPAddr).Port
×
3133
                listenPorts = append(listenPorts, port)
×
3134
        }
×
3135

3136
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3137
        if err != nil {
×
3138
                return err
×
3139
        }
×
3140

3141
        // Once the port mapping has been set, we can go ahead and automatically
3142
        // create our onion service. The service's private key will be saved to
3143
        // disk in order to regain access to this service when restarting `lnd`.
3144
        onionCfg := tor.AddOnionConfig{
×
3145
                VirtualPort: defaultPeerPort,
×
3146
                TargetPorts: listenPorts,
×
3147
                Store: tor.NewOnionFile(
×
3148
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3149
                        encrypter,
×
3150
                ),
×
3151
        }
×
3152

×
3153
        switch {
×
3154
        case s.cfg.Tor.V2:
×
3155
                onionCfg.Type = tor.V2
×
3156
        case s.cfg.Tor.V3:
×
3157
                onionCfg.Type = tor.V3
×
3158
        }
3159

3160
        addr, err := s.torController.AddOnion(onionCfg)
×
3161
        if err != nil {
×
3162
                return err
×
3163
        }
×
3164

3165
        // Now that the onion service has been created, we'll add the onion
3166
        // address it can be reached at to our list of advertised addresses.
3167
        newNodeAnn, err := s.genNodeAnnouncement(
×
3168
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3169
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3170
                },
×
3171
        )
3172
        if err != nil {
×
3173
                return fmt.Errorf("unable to generate new node "+
×
3174
                        "announcement: %v", err)
×
3175
        }
×
3176

3177
        // Finally, we'll update the on-disk version of our announcement so it
3178
        // will eventually propagate to nodes in the network.
3179
        selfNode := &channeldb.LightningNode{
×
3180
                HaveNodeAnnouncement: true,
×
3181
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3182
                Addresses:            newNodeAnn.Addresses,
×
3183
                Alias:                newNodeAnn.Alias.String(),
×
3184
                Features: lnwire.NewFeatureVector(
×
3185
                        newNodeAnn.Features, lnwire.Features,
×
3186
                ),
×
3187
                Color:        newNodeAnn.RGBColor,
×
3188
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3189
        }
×
3190
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3191
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3192
                return fmt.Errorf("can't set self node: %w", err)
×
3193
        }
×
3194

3195
        return nil
×
3196
}
3197

3198
// findChannel finds a channel given a public key and ChannelID. It is an
3199
// optimization that is quicker than seeking for a channel given only the
3200
// ChannelID.
3201
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3202
        *channeldb.OpenChannel, error) {
4✔
3203

4✔
3204
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
4✔
3205
        if err != nil {
4✔
3206
                return nil, err
×
3207
        }
×
3208

3209
        for _, channel := range nodeChans {
8✔
3210
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
8✔
3211
                        return channel, nil
4✔
3212
                }
4✔
3213
        }
3214

3215
        return nil, fmt.Errorf("unable to find channel")
4✔
3216
}
3217

3218
// getNodeAnnouncement fetches the current, fully signed node announcement.
3219
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
4✔
3220
        s.mu.Lock()
4✔
3221
        defer s.mu.Unlock()
4✔
3222

4✔
3223
        return *s.currentNodeAnn
4✔
3224
}
4✔
3225

3226
// genNodeAnnouncement generates and returns the current fully signed node
3227
// announcement. The time stamp of the announcement will be updated in order
3228
// to ensure it propagates through the network.
3229
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3230
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
4✔
3231

4✔
3232
        s.mu.Lock()
4✔
3233
        defer s.mu.Unlock()
4✔
3234

4✔
3235
        // First, try to update our feature manager with the updated set of
4✔
3236
        // features.
4✔
3237
        if features != nil {
8✔
3238
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
4✔
3239
                        feature.SetNodeAnn: features,
4✔
3240
                }
4✔
3241
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
4✔
3242
                if err != nil {
8✔
3243
                        return lnwire.NodeAnnouncement{}, err
4✔
3244
                }
4✔
3245

3246
                // If we could successfully update our feature manager, add
3247
                // an update modifier to include these new features to our
3248
                // set.
3249
                modifiers = append(
4✔
3250
                        modifiers, netann.NodeAnnSetFeatures(features),
4✔
3251
                )
4✔
3252
        }
3253

3254
        // Always update the timestamp when refreshing to ensure the update
3255
        // propagates.
3256
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
4✔
3257

4✔
3258
        // Apply the requested changes to the node announcement.
4✔
3259
        for _, modifier := range modifiers {
8✔
3260
                modifier(s.currentNodeAnn)
4✔
3261
        }
4✔
3262

3263
        // Sign a new update after applying all of the passed modifiers.
3264
        err := netann.SignNodeAnnouncement(
4✔
3265
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
4✔
3266
        )
4✔
3267
        if err != nil {
4✔
3268
                return lnwire.NodeAnnouncement{}, err
×
3269
        }
×
3270

3271
        return *s.currentNodeAnn, nil
4✔
3272
}
3273

3274
// updateAndBrodcastSelfNode generates a new node announcement
3275
// applying the giving modifiers and updating the time stamp
3276
// to ensure it propagates through the network. Then it brodcasts
3277
// it to the network.
3278
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
3279
        modifiers ...netann.NodeAnnModifier) error {
4✔
3280

4✔
3281
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
4✔
3282
        if err != nil {
8✔
3283
                return fmt.Errorf("unable to generate new node "+
4✔
3284
                        "announcement: %v", err)
4✔
3285
        }
4✔
3286

3287
        // Update the on-disk version of our announcement.
3288
        // Load and modify self node istead of creating anew instance so we
3289
        // don't risk overwriting any existing values.
3290
        selfNode, err := s.graphDB.SourceNode()
4✔
3291
        if err != nil {
4✔
3292
                return fmt.Errorf("unable to get current source node: %w", err)
×
3293
        }
×
3294

3295
        selfNode.HaveNodeAnnouncement = true
4✔
3296
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
4✔
3297
        selfNode.Addresses = newNodeAnn.Addresses
4✔
3298
        selfNode.Alias = newNodeAnn.Alias.String()
4✔
3299
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
4✔
3300
        selfNode.Color = newNodeAnn.RGBColor
4✔
3301
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
4✔
3302

4✔
3303
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
4✔
3304

4✔
3305
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
4✔
3306
                return fmt.Errorf("can't set self node: %w", err)
×
3307
        }
×
3308

3309
        // Finally, propagate it to the nodes in the network.
3310
        err = s.BroadcastMessage(nil, &newNodeAnn)
4✔
3311
        if err != nil {
4✔
3312
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3313
                        "announcement to peers: %v", err)
×
3314
                return err
×
3315
        }
×
3316

3317
        return nil
4✔
3318
}
3319

3320
type nodeAddresses struct {
3321
        pubKey    *btcec.PublicKey
3322
        addresses []net.Addr
3323
}
3324

3325
// establishPersistentConnections attempts to establish persistent connections
3326
// to all our direct channel collaborators. In order to promote liveness of our
3327
// active channels, we instruct the connection manager to attempt to establish
3328
// and maintain persistent connections to all our direct channel counterparties.
3329
func (s *server) establishPersistentConnections() error {
4✔
3330
        // nodeAddrsMap stores the combination of node public keys and addresses
4✔
3331
        // that we'll attempt to reconnect to. PubKey strings are used as keys
4✔
3332
        // since other PubKey forms can't be compared.
4✔
3333
        nodeAddrsMap := map[string]*nodeAddresses{}
4✔
3334

4✔
3335
        // Iterate through the list of LinkNodes to find addresses we should
4✔
3336
        // attempt to connect to based on our set of previous connections. Set
4✔
3337
        // the reconnection port to the default peer port.
4✔
3338
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
4✔
3339
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
4✔
3340
                return err
×
3341
        }
×
3342
        for _, node := range linkNodes {
8✔
3343
                pubStr := string(node.IdentityPub.SerializeCompressed())
4✔
3344
                nodeAddrs := &nodeAddresses{
4✔
3345
                        pubKey:    node.IdentityPub,
4✔
3346
                        addresses: node.Addresses,
4✔
3347
                }
4✔
3348
                nodeAddrsMap[pubStr] = nodeAddrs
4✔
3349
        }
4✔
3350

3351
        // After checking our previous connections for addresses to connect to,
3352
        // iterate through the nodes in our channel graph to find addresses
3353
        // that have been added via NodeAnnouncement messages.
3354
        sourceNode, err := s.graphDB.SourceNode()
4✔
3355
        if err != nil {
4✔
3356
                return err
×
3357
        }
×
3358

3359
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3360
        // each of the nodes.
3361
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
4✔
3362
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
4✔
3363
                tx kvdb.RTx,
4✔
3364
                chanInfo *models.ChannelEdgeInfo,
4✔
3365
                policy, _ *models.ChannelEdgePolicy) error {
8✔
3366

4✔
3367
                // If the remote party has announced the channel to us, but we
4✔
3368
                // haven't yet, then we won't have a policy. However, we don't
4✔
3369
                // need this to connect to the peer, so we'll log it and move on.
4✔
3370
                if policy == nil {
4✔
3371
                        srvrLog.Warnf("No channel policy found for "+
×
3372
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3373
                }
×
3374

3375
                // We'll now fetch the peer opposite from us within this
3376
                // channel so we can queue up a direct connection to them.
3377
                channelPeer, err := s.graphDB.FetchOtherNode(
4✔
3378
                        tx, chanInfo, selfPub,
4✔
3379
                )
4✔
3380
                if err != nil {
4✔
3381
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3382
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3383
                                err)
×
3384
                }
×
3385

3386
                pubStr := string(channelPeer.PubKeyBytes[:])
4✔
3387

4✔
3388
                // Add all unique addresses from channel
4✔
3389
                // graph/NodeAnnouncements to the list of addresses we'll
4✔
3390
                // connect to for this peer.
4✔
3391
                addrSet := make(map[string]net.Addr)
4✔
3392
                for _, addr := range channelPeer.Addresses {
8✔
3393
                        switch addr.(type) {
4✔
3394
                        case *net.TCPAddr:
4✔
3395
                                addrSet[addr.String()] = addr
4✔
3396

3397
                        // We'll only attempt to connect to Tor addresses if Tor
3398
                        // outbound support is enabled.
3399
                        case *tor.OnionAddr:
×
3400
                                if s.cfg.Tor.Active {
×
3401
                                        addrSet[addr.String()] = addr
×
3402
                                }
×
3403
                        }
3404
                }
3405

3406
                // If this peer is also recorded as a link node, we'll add any
3407
                // additional addresses that have not already been selected.
3408
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
4✔
3409
                if ok {
8✔
3410
                        for _, lnAddress := range linkNodeAddrs.addresses {
8✔
3411
                                switch lnAddress.(type) {
4✔
3412
                                case *net.TCPAddr:
4✔
3413
                                        addrSet[lnAddress.String()] = lnAddress
4✔
3414

3415
                                // We'll only attempt to connect to Tor
3416
                                // addresses if Tor outbound support is enabled.
3417
                                case *tor.OnionAddr:
×
3418
                                        if s.cfg.Tor.Active {
×
3419
                                                addrSet[lnAddress.String()] = lnAddress
×
3420
                                        }
×
3421
                                }
3422
                        }
3423
                }
3424

3425
                // Construct a slice of the deduped addresses.
3426
                var addrs []net.Addr
4✔
3427
                for _, addr := range addrSet {
8✔
3428
                        addrs = append(addrs, addr)
4✔
3429
                }
4✔
3430

3431
                n := &nodeAddresses{
4✔
3432
                        addresses: addrs,
4✔
3433
                }
4✔
3434
                n.pubKey, err = channelPeer.PubKey()
4✔
3435
                if err != nil {
4✔
3436
                        return err
×
3437
                }
×
3438

3439
                nodeAddrsMap[pubStr] = n
4✔
3440
                return nil
4✔
3441
        })
3442
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
4✔
3443
                return err
×
3444
        }
×
3445

3446
        srvrLog.Debugf("Establishing %v persistent connections on start",
4✔
3447
                len(nodeAddrsMap))
4✔
3448

4✔
3449
        // Acquire and hold server lock until all persistent connection requests
4✔
3450
        // have been recorded and sent to the connection manager.
4✔
3451
        s.mu.Lock()
4✔
3452
        defer s.mu.Unlock()
4✔
3453

4✔
3454
        // Iterate through the combined list of addresses from prior links and
4✔
3455
        // node announcements and attempt to reconnect to each node.
4✔
3456
        var numOutboundConns int
4✔
3457
        for pubStr, nodeAddr := range nodeAddrsMap {
8✔
3458
                // Add this peer to the set of peers we should maintain a
4✔
3459
                // persistent connection with. We set the value to false to
4✔
3460
                // indicate that we should not continue to reconnect if the
4✔
3461
                // number of channels returns to zero, since this peer has not
4✔
3462
                // been requested as perm by the user.
4✔
3463
                s.persistentPeers[pubStr] = false
4✔
3464
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
8✔
3465
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
4✔
3466
                }
4✔
3467

3468
                for _, address := range nodeAddr.addresses {
8✔
3469
                        // Create a wrapper address which couples the IP and
4✔
3470
                        // the pubkey so the brontide authenticated connection
4✔
3471
                        // can be established.
4✔
3472
                        lnAddr := &lnwire.NetAddress{
4✔
3473
                                IdentityKey: nodeAddr.pubKey,
4✔
3474
                                Address:     address,
4✔
3475
                        }
4✔
3476

4✔
3477
                        s.persistentPeerAddrs[pubStr] = append(
4✔
3478
                                s.persistentPeerAddrs[pubStr], lnAddr)
4✔
3479
                }
4✔
3480

3481
                // We'll connect to the first 10 peers immediately, then
3482
                // randomly stagger any remaining connections if the
3483
                // stagger initial reconnect flag is set. This ensures
3484
                // that mobile nodes or nodes with a small number of
3485
                // channels obtain connectivity quickly, but larger
3486
                // nodes are able to disperse the costs of connecting to
3487
                // all peers at once.
3488
                if numOutboundConns < numInstantInitReconnect ||
4✔
3489
                        !s.cfg.StaggerInitialReconnect {
8✔
3490

4✔
3491
                        go s.connectToPersistentPeer(pubStr)
4✔
3492
                } else {
4✔
3493
                        go s.delayInitialReconnect(pubStr)
×
3494
                }
×
3495

3496
                numOutboundConns++
4✔
3497
        }
3498

3499
        return nil
4✔
3500
}
3501

3502
// delayInitialReconnect will attempt a reconnection to the given peer after
3503
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3504
//
3505
// NOTE: This method MUST be run as a goroutine.
3506
func (s *server) delayInitialReconnect(pubStr string) {
×
3507
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3508
        select {
×
3509
        case <-time.After(delay):
×
3510
                s.connectToPersistentPeer(pubStr)
×
3511
        case <-s.quit:
×
3512
        }
3513
}
3514

3515
// prunePersistentPeerConnection removes all internal state related to
3516
// persistent connections to a peer within the server. This is used to avoid
3517
// persistent connection retries to peers we do not have any open channels with.
3518
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
4✔
3519
        pubKeyStr := string(compressedPubKey[:])
4✔
3520

4✔
3521
        s.mu.Lock()
4✔
3522
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
8✔
3523
                delete(s.persistentPeers, pubKeyStr)
4✔
3524
                delete(s.persistentPeersBackoff, pubKeyStr)
4✔
3525
                delete(s.persistentPeerAddrs, pubKeyStr)
4✔
3526
                s.cancelConnReqs(pubKeyStr, nil)
4✔
3527
                s.mu.Unlock()
4✔
3528

4✔
3529
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
4✔
3530
                        "peer has no open channels", compressedPubKey)
4✔
3531

4✔
3532
                return
4✔
3533
        }
4✔
3534
        s.mu.Unlock()
4✔
3535
}
3536

3537
// BroadcastMessage sends a request to the server to broadcast a set of
3538
// messages to all peers other than the one specified by the `skips` parameter.
3539
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3540
// the target peers.
3541
//
3542
// NOTE: This function is safe for concurrent access.
3543
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3544
        msgs ...lnwire.Message) error {
4✔
3545

4✔
3546
        // Filter out peers found in the skips map. We synchronize access to
4✔
3547
        // peersByPub throughout this process to ensure we deliver messages to
4✔
3548
        // exact set of peers present at the time of invocation.
4✔
3549
        s.mu.RLock()
4✔
3550
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
3551
        for pubStr, sPeer := range s.peersByPub {
8✔
3552
                if skips != nil {
8✔
3553
                        if _, ok := skips[sPeer.PubKey()]; ok {
8✔
3554
                                srvrLog.Tracef("Skipping %x in broadcast with "+
4✔
3555
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
4✔
3556
                                continue
4✔
3557
                        }
3558
                }
3559

3560
                peers = append(peers, sPeer)
4✔
3561
        }
3562
        s.mu.RUnlock()
4✔
3563

4✔
3564
        // Iterate over all known peers, dispatching a go routine to enqueue
4✔
3565
        // all messages to each of peers.
4✔
3566
        var wg sync.WaitGroup
4✔
3567
        for _, sPeer := range peers {
8✔
3568
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
4✔
3569
                        sPeer.PubKey())
4✔
3570

4✔
3571
                // Dispatch a go routine to enqueue all messages to this peer.
4✔
3572
                wg.Add(1)
4✔
3573
                s.wg.Add(1)
4✔
3574
                go func(p lnpeer.Peer) {
8✔
3575
                        defer s.wg.Done()
4✔
3576
                        defer wg.Done()
4✔
3577

4✔
3578
                        p.SendMessageLazy(false, msgs...)
4✔
3579
                }(sPeer)
4✔
3580
        }
3581

3582
        // Wait for all messages to have been dispatched before returning to
3583
        // caller.
3584
        wg.Wait()
4✔
3585

4✔
3586
        return nil
4✔
3587
}
3588

3589
// NotifyWhenOnline can be called by other subsystems to get notified when a
3590
// particular peer comes online. The peer itself is sent across the peerChan.
3591
//
3592
// NOTE: This function is safe for concurrent access.
3593
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3594
        peerChan chan<- lnpeer.Peer) {
4✔
3595

4✔
3596
        s.mu.Lock()
4✔
3597

4✔
3598
        // Compute the target peer's identifier.
4✔
3599
        pubStr := string(peerKey[:])
4✔
3600

4✔
3601
        // Check if peer is connected.
4✔
3602
        peer, ok := s.peersByPub[pubStr]
4✔
3603
        if ok {
8✔
3604
                // Unlock here so that the mutex isn't held while we are
4✔
3605
                // waiting for the peer to become active.
4✔
3606
                s.mu.Unlock()
4✔
3607

4✔
3608
                // Wait until the peer signals that it is actually active
4✔
3609
                // rather than only in the server's maps.
4✔
3610
                select {
4✔
3611
                case <-peer.ActiveSignal():
4✔
3612
                case <-peer.QuitSignal():
×
3613
                        // The peer quit, so we'll add the channel to the slice
×
3614
                        // and return.
×
3615
                        s.mu.Lock()
×
3616
                        s.peerConnectedListeners[pubStr] = append(
×
3617
                                s.peerConnectedListeners[pubStr], peerChan,
×
3618
                        )
×
3619
                        s.mu.Unlock()
×
3620
                        return
×
3621
                }
3622

3623
                // Connected, can return early.
3624
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
4✔
3625

4✔
3626
                select {
4✔
3627
                case peerChan <- peer:
4✔
3628
                case <-s.quit:
×
3629
                }
3630

3631
                return
4✔
3632
        }
3633

3634
        // Not connected, store this listener such that it can be notified when
3635
        // the peer comes online.
3636
        s.peerConnectedListeners[pubStr] = append(
4✔
3637
                s.peerConnectedListeners[pubStr], peerChan,
4✔
3638
        )
4✔
3639
        s.mu.Unlock()
4✔
3640
}
3641

3642
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3643
// the given public key has been disconnected. The notification is signaled by
3644
// closing the channel returned.
3645
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
4✔
3646
        s.mu.Lock()
4✔
3647
        defer s.mu.Unlock()
4✔
3648

4✔
3649
        c := make(chan struct{})
4✔
3650

4✔
3651
        // If the peer is already offline, we can immediately trigger the
4✔
3652
        // notification.
4✔
3653
        peerPubKeyStr := string(peerPubKey[:])
4✔
3654
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
4✔
3655
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3656
                close(c)
×
3657
                return c
×
3658
        }
×
3659

3660
        // Otherwise, the peer is online, so we'll keep track of the channel to
3661
        // trigger the notification once the server detects the peer
3662
        // disconnects.
3663
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
4✔
3664
                s.peerDisconnectedListeners[peerPubKeyStr], c,
4✔
3665
        )
4✔
3666

4✔
3667
        return c
4✔
3668
}
3669

3670
// FindPeer will return the peer that corresponds to the passed in public key.
3671
// This function is used by the funding manager, allowing it to update the
3672
// daemon's local representation of the remote peer.
3673
//
3674
// NOTE: This function is safe for concurrent access.
3675
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
4✔
3676
        s.mu.RLock()
4✔
3677
        defer s.mu.RUnlock()
4✔
3678

4✔
3679
        pubStr := string(peerKey.SerializeCompressed())
4✔
3680

4✔
3681
        return s.findPeerByPubStr(pubStr)
4✔
3682
}
4✔
3683

3684
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3685
// which should be a string representation of the peer's serialized, compressed
3686
// public key.
3687
//
3688
// NOTE: This function is safe for concurrent access.
3689
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3690
        s.mu.RLock()
4✔
3691
        defer s.mu.RUnlock()
4✔
3692

4✔
3693
        return s.findPeerByPubStr(pubStr)
4✔
3694
}
4✔
3695

3696
// findPeerByPubStr is an internal method that retrieves the specified peer from
3697
// the server's internal state using.
3698
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3699
        peer, ok := s.peersByPub[pubStr]
4✔
3700
        if !ok {
8✔
3701
                return nil, ErrPeerNotConnected
4✔
3702
        }
4✔
3703

3704
        return peer, nil
4✔
3705
}
3706

3707
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3708
// exponential backoff. If no previous backoff was known, the default is
3709
// returned.
3710
func (s *server) nextPeerBackoff(pubStr string,
3711
        startTime time.Time) time.Duration {
4✔
3712

4✔
3713
        // Now, determine the appropriate backoff to use for the retry.
4✔
3714
        backoff, ok := s.persistentPeersBackoff[pubStr]
4✔
3715
        if !ok {
8✔
3716
                // If an existing backoff was unknown, use the default.
4✔
3717
                return s.cfg.MinBackoff
4✔
3718
        }
4✔
3719

3720
        // If the peer failed to start properly, we'll just use the previous
3721
        // backoff to compute the subsequent randomized exponential backoff
3722
        // duration. This will roughly double on average.
3723
        if startTime.IsZero() {
5✔
3724
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
1✔
3725
        }
1✔
3726

3727
        // The peer succeeded in starting. If the connection didn't last long
3728
        // enough to be considered stable, we'll continue to back off retries
3729
        // with this peer.
3730
        connDuration := time.Since(startTime)
4✔
3731
        if connDuration < defaultStableConnDuration {
8✔
3732
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
4✔
3733
        }
4✔
3734

3735
        // The peer succeed in starting and this was stable peer, so we'll
3736
        // reduce the timeout duration by the length of the connection after
3737
        // applying randomized exponential backoff. We'll only apply this in the
3738
        // case that:
3739
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3740
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3741
        if relaxedBackoff > s.cfg.MinBackoff {
×
3742
                return relaxedBackoff
×
3743
        }
×
3744

3745
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3746
        // the stable connection lasted much longer than our previous backoff.
3747
        // To reward such good behavior, we'll reconnect after the default
3748
        // timeout.
3749
        return s.cfg.MinBackoff
×
3750
}
3751

3752
// shouldDropLocalConnection determines if our local connection to a remote peer
3753
// should be dropped in the case of concurrent connection establishment. In
3754
// order to deterministically decide which connection should be dropped, we'll
3755
// utilize the ordering of the local and remote public key. If we didn't use
3756
// such a tie breaker, then we risk _both_ connections erroneously being
3757
// dropped.
3758
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3759
        localPubBytes := local.SerializeCompressed()
×
3760
        remotePubPbytes := remote.SerializeCompressed()
×
3761

×
3762
        // The connection that comes from the node with a "smaller" pubkey
×
3763
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3764
        // should drop our established connection.
×
3765
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3766
}
×
3767

3768
// InboundPeerConnected initializes a new peer in response to a new inbound
3769
// connection.
3770
//
3771
// NOTE: This function is safe for concurrent access.
3772
func (s *server) InboundPeerConnected(conn net.Conn) {
4✔
3773
        // Exit early if we have already been instructed to shutdown, this
4✔
3774
        // prevents any delayed callbacks from accidentally registering peers.
4✔
3775
        if s.Stopped() {
4✔
3776
                return
×
3777
        }
×
3778

3779
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3780
        pubSer := nodePub.SerializeCompressed()
4✔
3781
        pubStr := string(pubSer)
4✔
3782

4✔
3783
        var pubBytes [33]byte
4✔
3784
        copy(pubBytes[:], pubSer)
4✔
3785

4✔
3786
        s.mu.Lock()
4✔
3787
        defer s.mu.Unlock()
4✔
3788

4✔
3789
        // If the remote node's public key is banned, drop the connection.
4✔
3790
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
4✔
3791
        if dcErr != nil {
4✔
3792
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3793
                        "peer: %v", dcErr)
×
3794
                conn.Close()
×
3795

×
3796
                return
×
3797
        }
×
3798

3799
        if shouldDc {
4✔
3800
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3801
                        "banned.", pubSer)
×
3802

×
3803
                conn.Close()
×
3804

×
3805
                return
×
3806
        }
×
3807

3808
        // If we already have an outbound connection to this peer, then ignore
3809
        // this new connection.
3810
        if p, ok := s.outboundPeers[pubStr]; ok {
8✔
3811
                srvrLog.Debugf("Already have outbound connection for %v, "+
4✔
3812
                        "ignoring inbound connection from local=%v, remote=%v",
4✔
3813
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
3814

4✔
3815
                conn.Close()
4✔
3816
                return
4✔
3817
        }
4✔
3818

3819
        // If we already have a valid connection that is scheduled to take
3820
        // precedence once the prior peer has finished disconnecting, we'll
3821
        // ignore this connection.
3822
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
4✔
3823
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3824
                        "scheduled", conn.RemoteAddr(), p)
×
3825
                conn.Close()
×
3826
                return
×
3827
        }
×
3828

3829
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
4✔
3830

4✔
3831
        // Check to see if we already have a connection with this peer. If so,
4✔
3832
        // we may need to drop our existing connection. This prevents us from
4✔
3833
        // having duplicate connections to the same peer. We forgo adding a
4✔
3834
        // default case as we expect these to be the only error values returned
4✔
3835
        // from findPeerByPubStr.
4✔
3836
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
3837
        switch err {
4✔
3838
        case ErrPeerNotConnected:
4✔
3839
                // We were unable to locate an existing connection with the
4✔
3840
                // target peer, proceed to connect.
4✔
3841
                s.cancelConnReqs(pubStr, nil)
4✔
3842
                s.peerConnected(conn, nil, true)
4✔
3843

3844
        case nil:
×
3845
                // We already have a connection with the incoming peer. If the
×
3846
                // connection we've already established should be kept and is
×
3847
                // not of the same type of the new connection (inbound), then
×
3848
                // we'll close out the new connection s.t there's only a single
×
3849
                // connection between us.
×
3850
                localPub := s.identityECDH.PubKey()
×
3851
                if !connectedPeer.Inbound() &&
×
3852
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3853

×
3854
                        srvrLog.Warnf("Received inbound connection from "+
×
3855
                                "peer %v, but already have outbound "+
×
3856
                                "connection, dropping conn", connectedPeer)
×
3857
                        conn.Close()
×
3858
                        return
×
3859
                }
×
3860

3861
                // Otherwise, if we should drop the connection, then we'll
3862
                // disconnect our already connected peer.
3863
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3864
                        connectedPeer)
×
3865

×
3866
                s.cancelConnReqs(pubStr, nil)
×
3867

×
3868
                // Remove the current peer from the server's internal state and
×
3869
                // signal that the peer termination watcher does not need to
×
3870
                // execute for this peer.
×
3871
                s.removePeer(connectedPeer)
×
3872
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3873
                s.scheduledPeerConnection[pubStr] = func() {
×
3874
                        s.peerConnected(conn, nil, true)
×
3875
                }
×
3876
        }
3877
}
3878

3879
// OutboundPeerConnected initializes a new peer in response to a new outbound
3880
// connection.
3881
// NOTE: This function is safe for concurrent access.
3882
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
4✔
3883
        // Exit early if we have already been instructed to shutdown, this
4✔
3884
        // prevents any delayed callbacks from accidentally registering peers.
4✔
3885
        if s.Stopped() {
4✔
3886
                return
×
3887
        }
×
3888

3889
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3890
        pubSer := nodePub.SerializeCompressed()
4✔
3891
        pubStr := string(pubSer)
4✔
3892

4✔
3893
        var pubBytes [33]byte
4✔
3894
        copy(pubBytes[:], pubSer)
4✔
3895

4✔
3896
        s.mu.Lock()
4✔
3897
        defer s.mu.Unlock()
4✔
3898

4✔
3899
        // If the remote node's public key is banned, drop the connection.
4✔
3900
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
4✔
3901
        if dcErr != nil {
4✔
3902
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3903
                        "peer: %v", dcErr)
×
3904
                conn.Close()
×
3905

×
3906
                return
×
3907
        }
×
3908

3909
        if shouldDc {
4✔
3910
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3911
                        "banned.", pubSer)
×
3912

×
3913
                if connReq != nil {
×
3914
                        s.connMgr.Remove(connReq.ID())
×
3915
                }
×
3916

3917
                conn.Close()
×
3918

×
3919
                return
×
3920
        }
3921

3922
        // If we already have an inbound connection to this peer, then ignore
3923
        // this new connection.
3924
        if p, ok := s.inboundPeers[pubStr]; ok {
8✔
3925
                srvrLog.Debugf("Already have inbound connection for %v, "+
4✔
3926
                        "ignoring outbound connection from local=%v, remote=%v",
4✔
3927
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
3928

4✔
3929
                if connReq != nil {
8✔
3930
                        s.connMgr.Remove(connReq.ID())
4✔
3931
                }
4✔
3932
                conn.Close()
4✔
3933
                return
4✔
3934
        }
3935
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
4✔
3936
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3937
                s.connMgr.Remove(connReq.ID())
×
3938
                conn.Close()
×
3939
                return
×
3940
        }
×
3941

3942
        // If we already have a valid connection that is scheduled to take
3943
        // precedence once the prior peer has finished disconnecting, we'll
3944
        // ignore this connection.
3945
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
4✔
3946
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
3947

×
3948
                if connReq != nil {
×
3949
                        s.connMgr.Remove(connReq.ID())
×
3950
                }
×
3951

3952
                conn.Close()
×
3953
                return
×
3954
        }
3955

3956
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
4✔
3957
                conn.RemoteAddr())
4✔
3958

4✔
3959
        if connReq != nil {
8✔
3960
                // A successful connection was returned by the connmgr.
4✔
3961
                // Immediately cancel all pending requests, excluding the
4✔
3962
                // outbound connection we just established.
4✔
3963
                ignore := connReq.ID()
4✔
3964
                s.cancelConnReqs(pubStr, &ignore)
4✔
3965
        } else {
8✔
3966
                // This was a successful connection made by some other
4✔
3967
                // subsystem. Remove all requests being managed by the connmgr.
4✔
3968
                s.cancelConnReqs(pubStr, nil)
4✔
3969
        }
4✔
3970

3971
        // If we already have a connection with this peer, decide whether or not
3972
        // we need to drop the stale connection. We forgo adding a default case
3973
        // as we expect these to be the only error values returned from
3974
        // findPeerByPubStr.
3975
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
3976
        switch err {
4✔
3977
        case ErrPeerNotConnected:
4✔
3978
                // We were unable to locate an existing connection with the
4✔
3979
                // target peer, proceed to connect.
4✔
3980
                s.peerConnected(conn, connReq, false)
4✔
3981

3982
        case nil:
×
3983
                // We already have a connection with the incoming peer. If the
×
3984
                // connection we've already established should be kept and is
×
3985
                // not of the same type of the new connection (outbound), then
×
3986
                // we'll close out the new connection s.t there's only a single
×
3987
                // connection between us.
×
3988
                localPub := s.identityECDH.PubKey()
×
3989
                if connectedPeer.Inbound() &&
×
3990
                        shouldDropLocalConnection(localPub, nodePub) {
×
3991

×
3992
                        srvrLog.Warnf("Established outbound connection to "+
×
3993
                                "peer %v, but already have inbound "+
×
3994
                                "connection, dropping conn", connectedPeer)
×
3995
                        if connReq != nil {
×
3996
                                s.connMgr.Remove(connReq.ID())
×
3997
                        }
×
3998
                        conn.Close()
×
3999
                        return
×
4000
                }
4001

4002
                // Otherwise, _their_ connection should be dropped. So we'll
4003
                // disconnect the peer and send the now obsolete peer to the
4004
                // server for garbage collection.
4005
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4006
                        connectedPeer)
×
4007

×
4008
                // Remove the current peer from the server's internal state and
×
4009
                // signal that the peer termination watcher does not need to
×
4010
                // execute for this peer.
×
4011
                s.removePeer(connectedPeer)
×
4012
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4013
                s.scheduledPeerConnection[pubStr] = func() {
×
4014
                        s.peerConnected(conn, connReq, false)
×
4015
                }
×
4016
        }
4017
}
4018

4019
// UnassignedConnID is the default connection ID that a request can have before
4020
// it actually is submitted to the connmgr.
4021
// TODO(conner): move into connmgr package, or better, add connmgr method for
4022
// generating atomic IDs
4023
const UnassignedConnID uint64 = 0
4024

4025
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4026
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4027
// Afterwards, each connection request removed from the connmgr. The caller can
4028
// optionally specify a connection ID to ignore, which prevents us from
4029
// canceling a successful request. All persistent connreqs for the provided
4030
// pubkey are discarded after the operationjw.
4031
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
4✔
4032
        // First, cancel any lingering persistent retry attempts, which will
4✔
4033
        // prevent retries for any with backoffs that are still maturing.
4✔
4034
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
8✔
4035
                close(cancelChan)
4✔
4036
                delete(s.persistentRetryCancels, pubStr)
4✔
4037
        }
4✔
4038

4039
        // Next, check to see if we have any outstanding persistent connection
4040
        // requests to this peer. If so, then we'll remove all of these
4041
        // connection requests, and also delete the entry from the map.
4042
        connReqs, ok := s.persistentConnReqs[pubStr]
4✔
4043
        if !ok {
8✔
4044
                return
4✔
4045
        }
4✔
4046

4047
        for _, connReq := range connReqs {
8✔
4048
                srvrLog.Tracef("Canceling %s:", connReqs)
4✔
4049

4✔
4050
                // Atomically capture the current request identifier.
4✔
4051
                connID := connReq.ID()
4✔
4052

4✔
4053
                // Skip any zero IDs, this indicates the request has not
4✔
4054
                // yet been schedule.
4✔
4055
                if connID == UnassignedConnID {
4✔
4056
                        continue
×
4057
                }
4058

4059
                // Skip a particular connection ID if instructed.
4060
                if skip != nil && connID == *skip {
8✔
4061
                        continue
4✔
4062
                }
4063

4064
                s.connMgr.Remove(connID)
4✔
4065
        }
4066

4067
        delete(s.persistentConnReqs, pubStr)
4✔
4068
}
4069

4070
// handleCustomMessage dispatches an incoming custom peers message to
4071
// subscribers.
4072
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
4✔
4073
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
4✔
4074
                peer, msg.Type)
4✔
4075

4✔
4076
        return s.customMessageServer.SendUpdate(&CustomMessage{
4✔
4077
                Peer: peer,
4✔
4078
                Msg:  msg,
4✔
4079
        })
4✔
4080
}
4✔
4081

4082
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4083
// messages.
4084
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
4✔
4085
        return s.customMessageServer.Subscribe()
4✔
4086
}
4✔
4087

4088
// peerConnected is a function that handles initialization a newly connected
4089
// peer by adding it to the server's global list of all active peers, and
4090
// starting all the goroutines the peer needs to function properly. The inbound
4091
// boolean should be true if the peer initiated the connection to us.
4092
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4093
        inbound bool) {
4✔
4094

4✔
4095
        brontideConn := conn.(*brontide.Conn)
4✔
4096
        addr := conn.RemoteAddr()
4✔
4097
        pubKey := brontideConn.RemotePub()
4✔
4098

4✔
4099
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
4✔
4100
                pubKey.SerializeCompressed(), addr, inbound)
4✔
4101

4✔
4102
        peerAddr := &lnwire.NetAddress{
4✔
4103
                IdentityKey: pubKey,
4✔
4104
                Address:     addr,
4✔
4105
                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
4106
        }
4✔
4107

4✔
4108
        // With the brontide connection established, we'll now craft the feature
4✔
4109
        // vectors to advertise to the remote node.
4✔
4110
        initFeatures := s.featureMgr.Get(feature.SetInit)
4✔
4111
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
4✔
4112

4✔
4113
        // Lookup past error caches for the peer in the server. If no buffer is
4✔
4114
        // found, create a fresh buffer.
4✔
4115
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
4✔
4116
        errBuffer, ok := s.peerErrors[pkStr]
4✔
4117
        if !ok {
8✔
4118
                var err error
4✔
4119
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
4✔
4120
                if err != nil {
4✔
4121
                        srvrLog.Errorf("unable to create peer %v", err)
×
4122
                        return
×
4123
                }
×
4124
        }
4125

4126
        // If we directly set the peer.Config TowerClient member to the
4127
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4128
        // the peer.Config's TowerClient member will not evaluate to nil even
4129
        // though the underlying value is nil. To avoid this gotcha which can
4130
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4131
        // TowerClient if needed.
4132
        var towerClient wtclient.ClientManager
4✔
4133
        if s.towerClientMgr != nil {
8✔
4134
                towerClient = s.towerClientMgr
4✔
4135
        }
4✔
4136

4137
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
4✔
4138
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
4139

4✔
4140
        // Now that we've established a connection, create a peer, and it to the
4✔
4141
        // set of currently active peers. Configure the peer with the incoming
4✔
4142
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
4✔
4143
        // offered that would trigger channel closure. In case of outgoing
4✔
4144
        // htlcs, an extra block is added to prevent the channel from being
4✔
4145
        // closed when the htlc is outstanding and a new block comes in.
4✔
4146
        pCfg := peer.Config{
4✔
4147
                Conn:                    brontideConn,
4✔
4148
                ConnReq:                 connReq,
4✔
4149
                Addr:                    peerAddr,
4✔
4150
                Inbound:                 inbound,
4✔
4151
                Features:                initFeatures,
4✔
4152
                LegacyFeatures:          legacyFeatures,
4✔
4153
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
4✔
4154
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
4✔
4155
                ErrorBuffer:             errBuffer,
4✔
4156
                WritePool:               s.writePool,
4✔
4157
                ReadPool:                s.readPool,
4✔
4158
                Switch:                  s.htlcSwitch,
4✔
4159
                InterceptSwitch:         s.interceptableSwitch,
4✔
4160
                ChannelDB:               s.chanStateDB,
4✔
4161
                ChannelGraph:            s.graphDB,
4✔
4162
                ChainArb:                s.chainArb,
4✔
4163
                AuthGossiper:            s.authGossiper,
4✔
4164
                ChanStatusMgr:           s.chanStatusMgr,
4✔
4165
                ChainIO:                 s.cc.ChainIO,
4✔
4166
                FeeEstimator:            s.cc.FeeEstimator,
4✔
4167
                Signer:                  s.cc.Wallet.Cfg.Signer,
4✔
4168
                SigPool:                 s.sigPool,
4✔
4169
                Wallet:                  s.cc.Wallet,
4✔
4170
                ChainNotifier:           s.cc.ChainNotifier,
4✔
4171
                BestBlockView:           s.cc.BestBlockTracker,
4✔
4172
                RoutingPolicy:           s.cc.RoutingPolicy,
4✔
4173
                Sphinx:                  s.sphinx,
4✔
4174
                WitnessBeacon:           s.witnessBeacon,
4✔
4175
                Invoices:                s.invoices,
4✔
4176
                ChannelNotifier:         s.channelNotifier,
4✔
4177
                HtlcNotifier:            s.htlcNotifier,
4✔
4178
                TowerClient:             towerClient,
4✔
4179
                DisconnectPeer:          s.DisconnectPeer,
4✔
4180
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
4✔
4181
                        lnwire.NodeAnnouncement, error) {
8✔
4182

4✔
4183
                        return s.genNodeAnnouncement(nil)
4✔
4184
                },
4✔
4185

4186
                PongBuf: s.pongBuf,
4187

4188
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4189

4190
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4191

4192
                FundingManager: s.fundingMgr,
4193

4194
                Hodl:                    s.cfg.Hodl,
4195
                UnsafeReplay:            s.cfg.UnsafeReplay,
4196
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4197
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4198
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4199
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4200
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4201
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4202
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4203
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4204
                HandleCustomMessage:    s.handleCustomMessage,
4205
                GetAliases:             s.aliasMgr.GetAliases,
4206
                RequestAlias:           s.aliasMgr.RequestAlias,
4207
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4208
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4209
                MaxFeeExposure:         thresholdMSats,
4210
                Quit:                   s.quit,
4211
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4212
                AuxSigner:              s.implCfg.AuxSigner,
4213
                MsgRouter:              s.implCfg.MsgRouter,
4214
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4215
                AuxResolver:            s.implCfg.AuxContractResolver,
4216
        }
4217

4218
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
4✔
4219
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
4✔
4220

4✔
4221
        p := peer.NewBrontide(pCfg)
4✔
4222

4✔
4223
        // TODO(roasbeef): update IP address for link-node
4✔
4224
        //  * also mark last-seen, do it one single transaction?
4✔
4225

4✔
4226
        s.addPeer(p)
4✔
4227

4✔
4228
        // Once we have successfully added the peer to the server, we can
4✔
4229
        // delete the previous error buffer from the server's map of error
4✔
4230
        // buffers.
4✔
4231
        delete(s.peerErrors, pkStr)
4✔
4232

4✔
4233
        // Dispatch a goroutine to asynchronously start the peer. This process
4✔
4234
        // includes sending and receiving Init messages, which would be a DOS
4✔
4235
        // vector if we held the server's mutex throughout the procedure.
4✔
4236
        s.wg.Add(1)
4✔
4237
        go s.peerInitializer(p)
4✔
4238
}
4239

4240
// addPeer adds the passed peer to the server's global state of all active
4241
// peers.
4242
func (s *server) addPeer(p *peer.Brontide) {
4✔
4243
        if p == nil {
4✔
4244
                return
×
4245
        }
×
4246

4247
        pubBytes := p.IdentityKey().SerializeCompressed()
4✔
4248

4✔
4249
        // Ignore new peers if we're shutting down.
4✔
4250
        if s.Stopped() {
4✔
4251
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4252
                        pubBytes)
×
4253
                p.Disconnect(ErrServerShuttingDown)
×
4254

×
4255
                return
×
4256
        }
×
4257

4258
        // Track the new peer in our indexes so we can quickly look it up either
4259
        // according to its public key, or its peer ID.
4260
        // TODO(roasbeef): pipe all requests through to the
4261
        // queryHandler/peerManager
4262

4263
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4264
        // be human-readable.
4265
        pubStr := string(pubBytes)
4✔
4266

4✔
4267
        s.peersByPub[pubStr] = p
4✔
4268

4✔
4269
        if p.Inbound() {
8✔
4270
                s.inboundPeers[pubStr] = p
4✔
4271
        } else {
8✔
4272
                s.outboundPeers[pubStr] = p
4✔
4273
        }
4✔
4274

4275
        // Inform the peer notifier of a peer online event so that it can be reported
4276
        // to clients listening for peer events.
4277
        var pubKey [33]byte
4✔
4278
        copy(pubKey[:], pubBytes)
4✔
4279

4✔
4280
        s.peerNotifier.NotifyPeerOnline(pubKey)
4✔
4281
}
4282

4283
// peerInitializer asynchronously starts a newly connected peer after it has
4284
// been added to the server's peer map. This method sets up a
4285
// peerTerminationWatcher for the given peer, and ensures that it executes even
4286
// if the peer failed to start. In the event of a successful connection, this
4287
// method reads the negotiated, local feature-bits and spawns the appropriate
4288
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4289
// be signaled of the new peer once the method returns.
4290
//
4291
// NOTE: This MUST be launched as a goroutine.
4292
func (s *server) peerInitializer(p *peer.Brontide) {
4✔
4293
        defer s.wg.Done()
4✔
4294

4✔
4295
        pubBytes := p.IdentityKey().SerializeCompressed()
4✔
4296

4✔
4297
        // Avoid initializing peers while the server is exiting.
4✔
4298
        if s.Stopped() {
4✔
4299
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4300
                        pubBytes)
×
4301
                return
×
4302
        }
×
4303

4304
        // Create a channel that will be used to signal a successful start of
4305
        // the link. This prevents the peer termination watcher from beginning
4306
        // its duty too early.
4307
        ready := make(chan struct{})
4✔
4308

4✔
4309
        // Before starting the peer, launch a goroutine to watch for the
4✔
4310
        // unexpected termination of this peer, which will ensure all resources
4✔
4311
        // are properly cleaned up, and re-establish persistent connections when
4✔
4312
        // necessary. The peer termination watcher will be short circuited if
4✔
4313
        // the peer is ever added to the ignorePeerTermination map, indicating
4✔
4314
        // that the server has already handled the removal of this peer.
4✔
4315
        s.wg.Add(1)
4✔
4316
        go s.peerTerminationWatcher(p, ready)
4✔
4317

4✔
4318
        // Start the peer! If an error occurs, we Disconnect the peer, which
4✔
4319
        // will unblock the peerTerminationWatcher.
4✔
4320
        if err := p.Start(); err != nil {
6✔
4321
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
2✔
4322

2✔
4323
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
2✔
4324
                return
2✔
4325
        }
2✔
4326

4327
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4328
        // was successful, and to begin watching the peer's wait group.
4329
        close(ready)
4✔
4330

4✔
4331
        s.mu.Lock()
4✔
4332
        defer s.mu.Unlock()
4✔
4333

4✔
4334
        // Check if there are listeners waiting for this peer to come online.
4✔
4335
        srvrLog.Debugf("Notifying that peer %v is online", p)
4✔
4336

4✔
4337
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
4✔
4338
        // route.Vertex as the key type of peerConnectedListeners.
4✔
4339
        pubStr := string(pubBytes)
4✔
4340
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
8✔
4341
                select {
4✔
4342
                case peerChan <- p:
4✔
4343
                case <-s.quit:
×
4344
                        return
×
4345
                }
4346
        }
4347
        delete(s.peerConnectedListeners, pubStr)
4✔
4348
}
4349

4350
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4351
// and then cleans up all resources allocated to the peer, notifies relevant
4352
// sub-systems of its demise, and finally handles re-connecting to the peer if
4353
// it's persistent. If the server intentionally disconnects a peer, it should
4354
// have a corresponding entry in the ignorePeerTermination map which will cause
4355
// the cleanup routine to exit early. The passed `ready` chan is used to
4356
// synchronize when WaitForDisconnect should begin watching on the peer's
4357
// waitgroup. The ready chan should only be signaled if the peer starts
4358
// successfully, otherwise the peer should be disconnected instead.
4359
//
4360
// NOTE: This MUST be launched as a goroutine.
4361
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
4✔
4362
        defer s.wg.Done()
4✔
4363

4✔
4364
        p.WaitForDisconnect(ready)
4✔
4365

4✔
4366
        srvrLog.Debugf("Peer %v has been disconnected", p)
4✔
4367

4✔
4368
        // If the server is exiting then we can bail out early ourselves as all
4✔
4369
        // the other sub-systems will already be shutting down.
4✔
4370
        if s.Stopped() {
8✔
4371
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
4✔
4372
                return
4✔
4373
        }
4✔
4374

4375
        // Next, we'll cancel all pending funding reservations with this node.
4376
        // If we tried to initiate any funding flows that haven't yet finished,
4377
        // then we need to unlock those committed outputs so they're still
4378
        // available for use.
4379
        s.fundingMgr.CancelPeerReservations(p.PubKey())
4✔
4380

4✔
4381
        pubKey := p.IdentityKey()
4✔
4382

4✔
4383
        // We'll also inform the gossiper that this peer is no longer active,
4✔
4384
        // so we don't need to maintain sync state for it any longer.
4✔
4385
        s.authGossiper.PruneSyncState(p.PubKey())
4✔
4386

4✔
4387
        // Tell the switch to remove all links associated with this peer.
4✔
4388
        // Passing nil as the target link indicates that all links associated
4✔
4389
        // with this interface should be closed.
4✔
4390
        //
4✔
4391
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
4✔
4392
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
4✔
4393
        if err != nil && err != htlcswitch.ErrNoLinksFound {
4✔
4394
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4395
        }
×
4396

4397
        for _, link := range links {
8✔
4398
                s.htlcSwitch.RemoveLink(link.ChanID())
4✔
4399
        }
4✔
4400

4401
        s.mu.Lock()
4✔
4402
        defer s.mu.Unlock()
4✔
4403

4✔
4404
        // If there were any notification requests for when this peer
4✔
4405
        // disconnected, we can trigger them now.
4✔
4406
        srvrLog.Debugf("Notifying that peer %v is offline", p)
4✔
4407
        pubStr := string(pubKey.SerializeCompressed())
4✔
4408
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
8✔
4409
                close(offlineChan)
4✔
4410
        }
4✔
4411
        delete(s.peerDisconnectedListeners, pubStr)
4✔
4412

4✔
4413
        // If the server has already removed this peer, we can short circuit the
4✔
4414
        // peer termination watcher and skip cleanup.
4✔
4415
        if _, ok := s.ignorePeerTermination[p]; ok {
4✔
4416
                delete(s.ignorePeerTermination, p)
×
4417

×
4418
                pubKey := p.PubKey()
×
4419
                pubStr := string(pubKey[:])
×
4420

×
4421
                // If a connection callback is present, we'll go ahead and
×
4422
                // execute it now that previous peer has fully disconnected. If
×
4423
                // the callback is not present, this likely implies the peer was
×
4424
                // purposefully disconnected via RPC, and that no reconnect
×
4425
                // should be attempted.
×
4426
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4427
                if ok {
×
4428
                        delete(s.scheduledPeerConnection, pubStr)
×
4429
                        connCallback()
×
4430
                }
×
4431
                return
×
4432
        }
4433

4434
        // First, cleanup any remaining state the server has regarding the peer
4435
        // in question.
4436
        s.removePeer(p)
4✔
4437

4✔
4438
        // Next, check to see if this is a persistent peer or not.
4✔
4439
        if _, ok := s.persistentPeers[pubStr]; !ok {
8✔
4440
                return
4✔
4441
        }
4✔
4442

4443
        // Get the last address that we used to connect to the peer.
4444
        addrs := []net.Addr{
4✔
4445
                p.NetAddress().Address,
4✔
4446
        }
4✔
4447

4✔
4448
        // We'll ensure that we locate all the peers advertised addresses for
4✔
4449
        // reconnection purposes.
4✔
4450
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
4✔
4451
        switch {
4✔
4452
        // We found advertised addresses, so use them.
4453
        case err == nil:
4✔
4454
                addrs = advertisedAddrs
4✔
4455

4456
        // The peer doesn't have an advertised address.
4457
        case err == errNoAdvertisedAddr:
4✔
4458
                // If it is an outbound peer then we fall back to the existing
4✔
4459
                // peer address.
4✔
4460
                if !p.Inbound() {
8✔
4461
                        break
4✔
4462
                }
4463

4464
                // Fall back to the existing peer address if
4465
                // we're not accepting connections over Tor.
4466
                if s.torController == nil {
8✔
4467
                        break
4✔
4468
                }
4469

4470
                // If we are, the peer's address won't be known
4471
                // to us (we'll see a private address, which is
4472
                // the address used by our onion service to dial
4473
                // to lnd), so we don't have enough information
4474
                // to attempt a reconnect.
4475
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4476
                        "to inbound peer %v without "+
×
4477
                        "advertised address", p)
×
4478
                return
×
4479

4480
        // We came across an error retrieving an advertised
4481
        // address, log it, and fall back to the existing peer
4482
        // address.
4483
        default:
4✔
4484
                srvrLog.Errorf("Unable to retrieve advertised "+
4✔
4485
                        "address for node %x: %v", p.PubKey(),
4✔
4486
                        err)
4✔
4487
        }
4488

4489
        // Make an easy lookup map so that we can check if an address
4490
        // is already in the address list that we have stored for this peer.
4491
        existingAddrs := make(map[string]bool)
4✔
4492
        for _, addr := range s.persistentPeerAddrs[pubStr] {
8✔
4493
                existingAddrs[addr.String()] = true
4✔
4494
        }
4✔
4495

4496
        // Add any missing addresses for this peer to persistentPeerAddr.
4497
        for _, addr := range addrs {
8✔
4498
                if existingAddrs[addr.String()] {
4✔
4499
                        continue
×
4500
                }
4501

4502
                s.persistentPeerAddrs[pubStr] = append(
4✔
4503
                        s.persistentPeerAddrs[pubStr],
4✔
4504
                        &lnwire.NetAddress{
4✔
4505
                                IdentityKey: p.IdentityKey(),
4✔
4506
                                Address:     addr,
4✔
4507
                                ChainNet:    p.NetAddress().ChainNet,
4✔
4508
                        },
4✔
4509
                )
4✔
4510
        }
4511

4512
        // Record the computed backoff in the backoff map.
4513
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
4✔
4514
        s.persistentPeersBackoff[pubStr] = backoff
4✔
4515

4✔
4516
        // Initialize a retry canceller for this peer if one does not
4✔
4517
        // exist.
4✔
4518
        cancelChan, ok := s.persistentRetryCancels[pubStr]
4✔
4519
        if !ok {
8✔
4520
                cancelChan = make(chan struct{})
4✔
4521
                s.persistentRetryCancels[pubStr] = cancelChan
4✔
4522
        }
4✔
4523

4524
        // We choose not to wait group this go routine since the Connect
4525
        // call can stall for arbitrarily long if we shutdown while an
4526
        // outbound connection attempt is being made.
4527
        go func() {
8✔
4528
                srvrLog.Debugf("Scheduling connection re-establishment to "+
4✔
4529
                        "persistent peer %x in %s",
4✔
4530
                        p.IdentityKey().SerializeCompressed(), backoff)
4✔
4531

4✔
4532
                select {
4✔
4533
                case <-time.After(backoff):
4✔
4534
                case <-cancelChan:
4✔
4535
                        return
4✔
4536
                case <-s.quit:
4✔
4537
                        return
4✔
4538
                }
4539

4540
                srvrLog.Debugf("Attempting to re-establish persistent "+
4✔
4541
                        "connection to peer %x",
4✔
4542
                        p.IdentityKey().SerializeCompressed())
4✔
4543

4✔
4544
                s.connectToPersistentPeer(pubStr)
4✔
4545
        }()
4546
}
4547

4548
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4549
// to connect to the peer. It creates connection requests if there are
4550
// currently none for a given address and it removes old connection requests
4551
// if the associated address is no longer in the latest address list for the
4552
// peer.
4553
func (s *server) connectToPersistentPeer(pubKeyStr string) {
4✔
4554
        s.mu.Lock()
4✔
4555
        defer s.mu.Unlock()
4✔
4556

4✔
4557
        // Create an easy lookup map of the addresses we have stored for the
4✔
4558
        // peer. We will remove entries from this map if we have existing
4✔
4559
        // connection requests for the associated address and then any leftover
4✔
4560
        // entries will indicate which addresses we should create new
4✔
4561
        // connection requests for.
4✔
4562
        addrMap := make(map[string]*lnwire.NetAddress)
4✔
4563
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
8✔
4564
                addrMap[addr.String()] = addr
4✔
4565
        }
4✔
4566

4567
        // Go through each of the existing connection requests and
4568
        // check if they correspond to the latest set of addresses. If
4569
        // there is a connection requests that does not use one of the latest
4570
        // advertised addresses then remove that connection request.
4571
        var updatedConnReqs []*connmgr.ConnReq
4✔
4572
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
8✔
4573
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
4✔
4574

4✔
4575
                switch _, ok := addrMap[lnAddr]; ok {
4✔
4576
                // If the existing connection request is using one of the
4577
                // latest advertised addresses for the peer then we add it to
4578
                // updatedConnReqs and remove the associated address from
4579
                // addrMap so that we don't recreate this connReq later on.
4580
                case true:
×
4581
                        updatedConnReqs = append(
×
4582
                                updatedConnReqs, connReq,
×
4583
                        )
×
4584
                        delete(addrMap, lnAddr)
×
4585

4586
                // If the existing connection request is using an address that
4587
                // is not one of the latest advertised addresses for the peer
4588
                // then we remove the connecting request from the connection
4589
                // manager.
4590
                case false:
4✔
4591
                        srvrLog.Info(
4✔
4592
                                "Removing conn req:", connReq.Addr.String(),
4✔
4593
                        )
4✔
4594
                        s.connMgr.Remove(connReq.ID())
4✔
4595
                }
4596
        }
4597

4598
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
4✔
4599

4✔
4600
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
4✔
4601
        if !ok {
8✔
4602
                cancelChan = make(chan struct{})
4✔
4603
                s.persistentRetryCancels[pubKeyStr] = cancelChan
4✔
4604
        }
4✔
4605

4606
        // Any addresses left in addrMap are new ones that we have not made
4607
        // connection requests for. So create new connection requests for those.
4608
        // If there is more than one address in the address map, stagger the
4609
        // creation of the connection requests for those.
4610
        go func() {
8✔
4611
                ticker := time.NewTicker(multiAddrConnectionStagger)
4✔
4612
                defer ticker.Stop()
4✔
4613

4✔
4614
                for _, addr := range addrMap {
8✔
4615
                        // Send the persistent connection request to the
4✔
4616
                        // connection manager, saving the request itself so we
4✔
4617
                        // can cancel/restart the process as needed.
4✔
4618
                        connReq := &connmgr.ConnReq{
4✔
4619
                                Addr:      addr,
4✔
4620
                                Permanent: true,
4✔
4621
                        }
4✔
4622

4✔
4623
                        s.mu.Lock()
4✔
4624
                        s.persistentConnReqs[pubKeyStr] = append(
4✔
4625
                                s.persistentConnReqs[pubKeyStr], connReq,
4✔
4626
                        )
4✔
4627
                        s.mu.Unlock()
4✔
4628

4✔
4629
                        srvrLog.Debugf("Attempting persistent connection to "+
4✔
4630
                                "channel peer %v", addr)
4✔
4631

4✔
4632
                        go s.connMgr.Connect(connReq)
4✔
4633

4✔
4634
                        select {
4✔
4635
                        case <-s.quit:
4✔
4636
                                return
4✔
4637
                        case <-cancelChan:
4✔
4638
                                return
4✔
4639
                        case <-ticker.C:
4✔
4640
                        }
4641
                }
4642
        }()
4643
}
4644

4645
// removePeer removes the passed peer from the server's state of all active
4646
// peers.
4647
func (s *server) removePeer(p *peer.Brontide) {
4✔
4648
        if p == nil {
4✔
4649
                return
×
4650
        }
×
4651

4652
        srvrLog.Debugf("removing peer %v", p)
4✔
4653

4✔
4654
        // As the peer is now finished, ensure that the TCP connection is
4✔
4655
        // closed and all of its related goroutines have exited.
4✔
4656
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
4✔
4657

4✔
4658
        // If this peer had an active persistent connection request, remove it.
4✔
4659
        if p.ConnReq() != nil {
8✔
4660
                s.connMgr.Remove(p.ConnReq().ID())
4✔
4661
        }
4✔
4662

4663
        // Ignore deleting peers if we're shutting down.
4664
        if s.Stopped() {
4✔
4665
                return
×
4666
        }
×
4667

4668
        pKey := p.PubKey()
4✔
4669
        pubSer := pKey[:]
4✔
4670
        pubStr := string(pubSer)
4✔
4671

4✔
4672
        delete(s.peersByPub, pubStr)
4✔
4673

4✔
4674
        if p.Inbound() {
8✔
4675
                delete(s.inboundPeers, pubStr)
4✔
4676
        } else {
8✔
4677
                delete(s.outboundPeers, pubStr)
4✔
4678
        }
4✔
4679

4680
        // Copy the peer's error buffer across to the server if it has any items
4681
        // in it so that we can restore peer errors across connections.
4682
        if p.ErrorBuffer().Total() > 0 {
8✔
4683
                s.peerErrors[pubStr] = p.ErrorBuffer()
4✔
4684
        }
4✔
4685

4686
        // Inform the peer notifier of a peer offline event so that it can be
4687
        // reported to clients listening for peer events.
4688
        var pubKey [33]byte
4✔
4689
        copy(pubKey[:], pubSer)
4✔
4690

4✔
4691
        s.peerNotifier.NotifyPeerOffline(pubKey)
4✔
4692
}
4693

4694
// ConnectToPeer requests that the server connect to a Lightning Network peer
4695
// at the specified address. This function will *block* until either a
4696
// connection is established, or the initial handshake process fails.
4697
//
4698
// NOTE: This function is safe for concurrent access.
4699
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4700
        perm bool, timeout time.Duration) error {
4✔
4701

4✔
4702
        targetPub := string(addr.IdentityKey.SerializeCompressed())
4✔
4703

4✔
4704
        // Acquire mutex, but use explicit unlocking instead of defer for
4✔
4705
        // better granularity.  In certain conditions, this method requires
4✔
4706
        // making an outbound connection to a remote peer, which requires the
4✔
4707
        // lock to be released, and subsequently reacquired.
4✔
4708
        s.mu.Lock()
4✔
4709

4✔
4710
        // Ensure we're not already connected to this peer.
4✔
4711
        peer, err := s.findPeerByPubStr(targetPub)
4✔
4712
        if err == nil {
8✔
4713
                s.mu.Unlock()
4✔
4714
                return &errPeerAlreadyConnected{peer: peer}
4✔
4715
        }
4✔
4716

4717
        // Peer was not found, continue to pursue connection with peer.
4718

4719
        // If there's already a pending connection request for this pubkey,
4720
        // then we ignore this request to ensure we don't create a redundant
4721
        // connection.
4722
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
8✔
4723
                srvrLog.Warnf("Already have %d persistent connection "+
4✔
4724
                        "requests for %v, connecting anyway.", len(reqs), addr)
4✔
4725
        }
4✔
4726

4727
        // If there's not already a pending or active connection to this node,
4728
        // then instruct the connection manager to attempt to establish a
4729
        // persistent connection to the peer.
4730
        srvrLog.Debugf("Connecting to %v", addr)
4✔
4731
        if perm {
8✔
4732
                connReq := &connmgr.ConnReq{
4✔
4733
                        Addr:      addr,
4✔
4734
                        Permanent: true,
4✔
4735
                }
4✔
4736

4✔
4737
                // Since the user requested a permanent connection, we'll set
4✔
4738
                // the entry to true which will tell the server to continue
4✔
4739
                // reconnecting even if the number of channels with this peer is
4✔
4740
                // zero.
4✔
4741
                s.persistentPeers[targetPub] = true
4✔
4742
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
8✔
4743
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
4✔
4744
                }
4✔
4745
                s.persistentConnReqs[targetPub] = append(
4✔
4746
                        s.persistentConnReqs[targetPub], connReq,
4✔
4747
                )
4✔
4748
                s.mu.Unlock()
4✔
4749

4✔
4750
                go s.connMgr.Connect(connReq)
4✔
4751

4✔
4752
                return nil
4✔
4753
        }
4754
        s.mu.Unlock()
4✔
4755

4✔
4756
        // If we're not making a persistent connection, then we'll attempt to
4✔
4757
        // connect to the target peer. If the we can't make the connection, or
4✔
4758
        // the crypto negotiation breaks down, then return an error to the
4✔
4759
        // caller.
4✔
4760
        errChan := make(chan error, 1)
4✔
4761
        s.connectToPeer(addr, errChan, timeout)
4✔
4762

4✔
4763
        select {
4✔
4764
        case err := <-errChan:
4✔
4765
                return err
4✔
4766
        case <-s.quit:
×
4767
                return ErrServerShuttingDown
×
4768
        }
4769
}
4770

4771
// connectToPeer establishes a connection to a remote peer. errChan is used to
4772
// notify the caller if the connection attempt has failed. Otherwise, it will be
4773
// closed.
4774
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4775
        errChan chan<- error, timeout time.Duration) {
4✔
4776

4✔
4777
        conn, err := brontide.Dial(
4✔
4778
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
4✔
4779
        )
4✔
4780
        if err != nil {
8✔
4781
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
4✔
4782
                select {
4✔
4783
                case errChan <- err:
4✔
4784
                case <-s.quit:
×
4785
                }
4786
                return
4✔
4787
        }
4788

4789
        close(errChan)
4✔
4790

4✔
4791
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
4✔
4792
                conn.LocalAddr(), conn.RemoteAddr())
4✔
4793

4✔
4794
        s.OutboundPeerConnected(nil, conn)
4✔
4795
}
4796

4797
// DisconnectPeer sends the request to server to close the connection with peer
4798
// identified by public key.
4799
//
4800
// NOTE: This function is safe for concurrent access.
4801
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
4✔
4802
        pubBytes := pubKey.SerializeCompressed()
4✔
4803
        pubStr := string(pubBytes)
4✔
4804

4✔
4805
        s.mu.Lock()
4✔
4806
        defer s.mu.Unlock()
4✔
4807

4✔
4808
        // Check that were actually connected to this peer. If not, then we'll
4✔
4809
        // exit in an error as we can't disconnect from a peer that we're not
4✔
4810
        // currently connected to.
4✔
4811
        peer, err := s.findPeerByPubStr(pubStr)
4✔
4812
        if err == ErrPeerNotConnected {
8✔
4813
                return fmt.Errorf("peer %x is not connected", pubBytes)
4✔
4814
        }
4✔
4815

4816
        srvrLog.Infof("Disconnecting from %v", peer)
4✔
4817

4✔
4818
        s.cancelConnReqs(pubStr, nil)
4✔
4819

4✔
4820
        // If this peer was formerly a persistent connection, then we'll remove
4✔
4821
        // them from this map so we don't attempt to re-connect after we
4✔
4822
        // disconnect.
4✔
4823
        delete(s.persistentPeers, pubStr)
4✔
4824
        delete(s.persistentPeersBackoff, pubStr)
4✔
4825

4✔
4826
        // Remove the peer by calling Disconnect. Previously this was done with
4✔
4827
        // removePeer, which bypassed the peerTerminationWatcher.
4✔
4828
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
4✔
4829

4✔
4830
        return nil
4✔
4831
}
4832

4833
// OpenChannel sends a request to the server to open a channel to the specified
4834
// peer identified by nodeKey with the passed channel funding parameters.
4835
//
4836
// NOTE: This function is safe for concurrent access.
4837
func (s *server) OpenChannel(
4838
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
4✔
4839

4✔
4840
        // The updateChan will have a buffer of 2, since we expect a ChanPending
4✔
4841
        // + a ChanOpen update, and we want to make sure the funding process is
4✔
4842
        // not blocked if the caller is not reading the updates.
4✔
4843
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
4✔
4844
        req.Err = make(chan error, 1)
4✔
4845

4✔
4846
        // First attempt to locate the target peer to open a channel with, if
4✔
4847
        // we're unable to locate the peer then this request will fail.
4✔
4848
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
4✔
4849
        s.mu.RLock()
4✔
4850
        peer, ok := s.peersByPub[string(pubKeyBytes)]
4✔
4851
        if !ok {
4✔
4852
                s.mu.RUnlock()
×
4853

×
4854
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4855
                return req.Updates, req.Err
×
4856
        }
×
4857
        req.Peer = peer
4✔
4858
        s.mu.RUnlock()
4✔
4859

4✔
4860
        // We'll wait until the peer is active before beginning the channel
4✔
4861
        // opening process.
4✔
4862
        select {
4✔
4863
        case <-peer.ActiveSignal():
4✔
4864
        case <-peer.QuitSignal():
×
4865
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4866
                return req.Updates, req.Err
×
4867
        case <-s.quit:
×
4868
                req.Err <- ErrServerShuttingDown
×
4869
                return req.Updates, req.Err
×
4870
        }
4871

4872
        // If the fee rate wasn't specified at this point we fail the funding
4873
        // because of the missing fee rate information. The caller of the
4874
        // `OpenChannel` method needs to make sure that default values for the
4875
        // fee rate are set beforehand.
4876
        if req.FundingFeePerKw == 0 {
4✔
4877
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4878
                        "the channel opening transaction")
×
4879

×
4880
                return req.Updates, req.Err
×
4881
        }
×
4882

4883
        // Spawn a goroutine to send the funding workflow request to the funding
4884
        // manager. This allows the server to continue handling queries instead
4885
        // of blocking on this request which is exported as a synchronous
4886
        // request to the outside world.
4887
        go s.fundingMgr.InitFundingWorkflow(req)
4✔
4888

4✔
4889
        return req.Updates, req.Err
4✔
4890
}
4891

4892
// Peers returns a slice of all active peers.
4893
//
4894
// NOTE: This function is safe for concurrent access.
4895
func (s *server) Peers() []*peer.Brontide {
4✔
4896
        s.mu.RLock()
4✔
4897
        defer s.mu.RUnlock()
4✔
4898

4✔
4899
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
4900
        for _, peer := range s.peersByPub {
8✔
4901
                peers = append(peers, peer)
4✔
4902
        }
4✔
4903

4904
        return peers
4✔
4905
}
4906

4907
// computeNextBackoff uses a truncated exponential backoff to compute the next
4908
// backoff using the value of the exiting backoff. The returned duration is
4909
// randomized in either direction by 1/20 to prevent tight loops from
4910
// stabilizing.
4911
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
4✔
4912
        // Double the current backoff, truncating if it exceeds our maximum.
4✔
4913
        nextBackoff := 2 * currBackoff
4✔
4914
        if nextBackoff > maxBackoff {
8✔
4915
                nextBackoff = maxBackoff
4✔
4916
        }
4✔
4917

4918
        // Using 1/10 of our duration as a margin, compute a random offset to
4919
        // avoid the nodes entering connection cycles.
4920
        margin := nextBackoff / 10
4✔
4921

4✔
4922
        var wiggle big.Int
4✔
4923
        wiggle.SetUint64(uint64(margin))
4✔
4924
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
4✔
4925
                // Randomizing is not mission critical, so we'll just return the
×
4926
                // current backoff.
×
4927
                return nextBackoff
×
4928
        }
×
4929

4930
        // Otherwise add in our wiggle, but subtract out half of the margin so
4931
        // that the backoff can tweaked by 1/20 in either direction.
4932
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
4✔
4933
}
4934

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

4939
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4940
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
4✔
4941
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
4✔
4942
        if err != nil {
4✔
4943
                return nil, err
×
4944
        }
×
4945

4946
        node, err := s.graphDB.FetchLightningNode(vertex)
4✔
4947
        if err != nil {
8✔
4948
                return nil, err
4✔
4949
        }
4✔
4950

4951
        if len(node.Addresses) == 0 {
8✔
4952
                return nil, errNoAdvertisedAddr
4✔
4953
        }
4✔
4954

4955
        return node.Addresses, nil
4✔
4956
}
4957

4958
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4959
// channel update for a target channel.
4960
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4961
        *lnwire.ChannelUpdate1, error) {
4✔
4962

4✔
4963
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
4✔
4964
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
8✔
4965
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
4✔
4966
                if err != nil {
8✔
4967
                        return nil, err
4✔
4968
                }
4✔
4969

4970
                return netann.ExtractChannelUpdate(
4✔
4971
                        ourPubKey[:], info, edge1, edge2,
4✔
4972
                )
4✔
4973
        }
4974
}
4975

4976
// applyChannelUpdate applies the channel update to the different sub-systems of
4977
// the server. The useAlias boolean denotes whether or not to send an alias in
4978
// place of the real SCID.
4979
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
4980
        op *wire.OutPoint, useAlias bool) error {
4✔
4981

4✔
4982
        var (
4✔
4983
                peerAlias    *lnwire.ShortChannelID
4✔
4984
                defaultAlias lnwire.ShortChannelID
4✔
4985
        )
4✔
4986

4✔
4987
        chanID := lnwire.NewChanIDFromOutPoint(*op)
4✔
4988

4✔
4989
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
4✔
4990
        // in the ChannelUpdate if it hasn't been announced yet.
4✔
4991
        if useAlias {
8✔
4992
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
4✔
4993
                if foundAlias != defaultAlias {
8✔
4994
                        peerAlias = &foundAlias
4✔
4995
                }
4✔
4996
        }
4997

4998
        errChan := s.authGossiper.ProcessLocalAnnouncement(
4✔
4999
                update, discovery.RemoteAlias(peerAlias),
4✔
5000
        )
4✔
5001
        select {
4✔
5002
        case err := <-errChan:
4✔
5003
                return err
4✔
5004
        case <-s.quit:
×
5005
                return ErrServerShuttingDown
×
5006
        }
5007
}
5008

5009
// SendCustomMessage sends a custom message to the peer with the specified
5010
// pubkey.
5011
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5012
        data []byte) error {
4✔
5013

4✔
5014
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
4✔
5015
        if err != nil {
4✔
5016
                return err
×
5017
        }
×
5018

5019
        // We'll wait until the peer is active.
5020
        select {
4✔
5021
        case <-peer.ActiveSignal():
4✔
5022
        case <-peer.QuitSignal():
×
5023
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5024
        case <-s.quit:
×
5025
                return ErrServerShuttingDown
×
5026
        }
5027

5028
        msg, err := lnwire.NewCustom(msgType, data)
4✔
5029
        if err != nil {
8✔
5030
                return err
4✔
5031
        }
4✔
5032

5033
        // Send the message as low-priority. For now we assume that all
5034
        // application-defined message are low priority.
5035
        return peer.SendMessageLazy(true, msg)
4✔
5036
}
5037

5038
// newSweepPkScriptGen creates closure that generates a new public key script
5039
// which should be used to sweep any funds into the on-chain wallet.
5040
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5041
// (p2wkh) output.
5042
func newSweepPkScriptGen(
5043
        wallet lnwallet.WalletController,
5044
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
4✔
5045

4✔
5046
        return func() fn.Result[lnwallet.AddrWithKey] {
8✔
5047
                sweepAddr, err := wallet.NewAddress(
4✔
5048
                        lnwallet.TaprootPubkey, false,
4✔
5049
                        lnwallet.DefaultAccountName,
4✔
5050
                )
4✔
5051
                if err != nil {
4✔
5052
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5053
                }
×
5054

5055
                addr, err := txscript.PayToAddrScript(sweepAddr)
4✔
5056
                if err != nil {
4✔
5057
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5058
                }
×
5059

5060
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
4✔
5061
                        wallet, netParams, addr,
4✔
5062
                )
4✔
5063
                if err != nil {
4✔
5064
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5065
                }
×
5066

5067
                return fn.Ok(lnwallet.AddrWithKey{
4✔
5068
                        DeliveryAddress: addr,
4✔
5069
                        InternalKey:     internalKeyDesc,
4✔
5070
                })
4✔
5071
        }
5072
}
5073

5074
// shouldPeerBootstrap returns true if we should attempt to perform peer
5075
// bootstrapping to actively seek our peers using the set of active network
5076
// bootstrappers.
5077
func shouldPeerBootstrap(cfg *Config) bool {
10✔
5078
        isSimnet := cfg.Bitcoin.SimNet
10✔
5079
        isSignet := cfg.Bitcoin.SigNet
10✔
5080
        isRegtest := cfg.Bitcoin.RegTest
10✔
5081
        isDevNetwork := isSimnet || isSignet || isRegtest
10✔
5082

10✔
5083
        // TODO(yy): remove the check on simnet/regtest such that the itest is
10✔
5084
        // covering the bootstrapping process.
10✔
5085
        return !cfg.NoNetBootstrap && !isDevNetwork
10✔
5086
}
10✔
5087

5088
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5089
// finished.
5090
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
4✔
5091
        // Get a list of closed channels.
4✔
5092
        channels, err := s.chanStateDB.FetchClosedChannels(false)
4✔
5093
        if err != nil {
4✔
5094
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5095
                return nil
×
5096
        }
×
5097

5098
        // Save the SCIDs in a map.
5099
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
4✔
5100
        for _, c := range channels {
8✔
5101
                // If the channel is not pending, its FC has been finalized.
4✔
5102
                if !c.IsPending {
8✔
5103
                        closedSCIDs[c.ShortChanID] = struct{}{}
4✔
5104
                }
4✔
5105
        }
5106

5107
        // Double check whether the reported closed channel has indeed finished
5108
        // closing.
5109
        //
5110
        // NOTE: There are misalignments regarding when a channel's FC is
5111
        // marked as finalized. We double check the pending channels to make
5112
        // sure the returned SCIDs are indeed terminated.
5113
        //
5114
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5115
        pendings, err := s.chanStateDB.FetchPendingChannels()
4✔
5116
        if err != nil {
4✔
5117
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5118
                return nil
×
5119
        }
×
5120

5121
        for _, c := range pendings {
8✔
5122
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
8✔
5123
                        continue
4✔
5124
                }
5125

5126
                // If the channel is still reported as pending, remove it from
5127
                // the map.
5128
                delete(closedSCIDs, c.ShortChannelID)
×
5129

×
5130
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5131
                        c.ShortChannelID)
×
5132
        }
5133

5134
        return closedSCIDs
4✔
5135
}
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