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

lightningnetwork / lnd / 11909028775

19 Nov 2024 08:27AM UTC coverage: 58.987% (+0.04%) from 58.947%
11909028775

Pull #9258

github

yyforyongyu
chainntnfs: skip duplicate `numConfsLeft` notifications

This commit adds a new state to the `ConfNtfn` struct to start tracking
the number of confs left to be notified to avoid sending duplicate
notifications.
Pull Request #9258: chainntnfs: fix missing notifications

59 of 72 new or added lines in 5 files covered. (81.94%)

176 existing lines in 31 files now uncovered.

132559 of 224725 relevant lines covered (58.99%)

19680.56 hits per line

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

63.58
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

144
// Error returns the human readable version of this error type.
145
//
146
// NOTE: Part of the error interface.
147
func (e *errPeerAlreadyConnected) Error() string {
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
        // featureMgr dispatches feature vectors for various contexts within the
321
        // daemon.
322
        featureMgr *feature.Manager
323

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

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

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

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

342
        hostAnn *netann.HostAnnouncer
343

344
        // livenessMonitor monitors that lnd has access to critical resources.
345
        livenessMonitor *healthcheck.Monitor
346

347
        customMessageServer *subscribe.Server
348

349
        // txPublisher is a publisher with fee-bumping capability.
350
        txPublisher *sweep.TxPublisher
351

352
        quit chan struct{}
353

354
        wg sync.WaitGroup
355
}
356

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

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

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

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

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

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

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

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

412
                                        s.mu.Lock()
4✔
413

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

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

428
                                        s.mu.Unlock()
4✔
429

4✔
430
                                        s.connectToPersistentPeer(pubKeyStr)
4✔
431
                                }
432
                        }
433
                }
434
        }()
435

436
        return nil
4✔
437
}
438

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

444
        // Msg is the custom wire message.
445
        Msg *lnwire.Custom
446
}
447

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

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

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

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

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

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

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

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

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

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

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

4✔
533
        netParams := cfg.ActiveNetParams.Params
4✔
534

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

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

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

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

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

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

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

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

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

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

4✔
615
                channelNotifier: channelnotifier.New(
4✔
616
                        dbs.ChanStateDB.ChannelStateDB(),
4✔
617
                ),
4✔
618

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

4✔
623
                listenAddrs: listenAddrs,
4✔
624

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

4✔
629
                torController: torController,
4✔
630

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

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

4✔
647
                invoiceHtlcModifier: invoiceHtlcModifier,
4✔
648

4✔
649
                customMessageServer: subscribe.NewServer(),
4✔
650

4✔
651
                tlsManager: tlsManager,
4✔
652

4✔
653
                featureMgr: featureMgr,
4✔
654
                quit:       make(chan struct{}),
4✔
655
        }
4✔
656

4✔
657
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
4✔
658
        if err != nil {
4✔
659
                return nil, err
×
660
        }
×
661

662
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
4✔
663
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
4✔
664
                uint32(currentHeight), currentHash, cc.ChainNotifier,
4✔
665
        )
4✔
666
        s.invoices = invoices.NewRegistry(
4✔
667
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
4✔
668
        )
4✔
669

4✔
670
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
4✔
671

4✔
672
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
4✔
673
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
674

4✔
675
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
8✔
676
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
4✔
677
                if err != nil {
4✔
678
                        return err
×
679
                }
×
680

681
                s.htlcSwitch.UpdateLinkAliases(link)
4✔
682

4✔
683
                return nil
4✔
684
        }
685

686
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
4✔
687
        if err != nil {
4✔
688
                return nil, err
×
689
        }
×
690

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

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

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

743
        s.witnessBeacon = newPreimageBeacon(
4✔
744
                dbs.ChanStateDB.NewWitnessCache(),
4✔
745
                s.interceptableSwitch.ForwardPacket,
4✔
746
        )
4✔
747

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

4✔
761
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
4✔
762
        if err != nil {
4✔
763
                return nil, err
×
764
        }
×
765
        s.chanStatusMgr = chanStatusMgr
4✔
766

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

×
772
                discoveryTimeout := time.Duration(10 * time.Second)
×
773

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

×
788
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
789
                                "enabled device")
×
790

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

800
                        s.natTraversal = pmp
×
801
                }
802
        }
803

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

×
819
                        listenPorts = append(listenPorts, uint16(port))
×
820
                }
×
821

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

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

845
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
4✔
846
        selfAddrs = append(selfAddrs, externalIPs...)
4✔
847

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

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

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

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

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

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

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

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

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

4✔
943
                        estimator, err = routing.NewAprioriEstimator(
4✔
944
                                aprioriConfig,
4✔
945
                        )
4✔
946
                        if err != nil {
4✔
947
                                return nil, err
×
948
                        }
×
949

950
                case routing.BimodalEstimatorName:
×
951
                        bCfg := routingConfig.BimodalConfig
×
952
                        bimodalConfig := routing.BimodalConfig{
×
953
                                BimodalNodeWeight: bCfg.NodeWeight,
×
954
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
955
                                        bCfg.Scale,
×
956
                                ),
×
957
                                BimodalDecayTime: bCfg.DecayTime,
×
958
                        }
×
959

×
960
                        estimator, err = routing.NewBimodalEstimator(
×
961
                                bimodalConfig,
×
962
                        )
×
963
                        if err != nil {
×
964
                                return nil, err
×
965
                        }
×
966

967
                default:
×
968
                        return nil, fmt.Errorf("unknown estimator type %v",
×
969
                                routingConfig.ProbabilityEstimatorType)
×
970
                }
971
        }
972

973
        mcCfg := &routing.MissionControlConfig{
4✔
974
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
4✔
975
                Estimator:               estimator,
4✔
976
                MaxMcHistory:            routingConfig.MaxMcHistory,
4✔
977
                McFlushInterval:         routingConfig.McFlushInterval,
4✔
978
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
4✔
979
        }
4✔
980

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

996
        srvrLog.Debugf("Instantiating payment session source with config: "+
4✔
997
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
4✔
998
                int64(routingConfig.AttemptCost),
4✔
999
                float64(routingConfig.AttemptCostPPM)/10000,
4✔
1000
                routingConfig.MinRouteProbability)
4✔
1001

4✔
1002
        pathFindingConfig := routing.PathFindingConfig{
4✔
1003
                AttemptCost: lnwire.NewMSatFromSatoshis(
4✔
1004
                        routingConfig.AttemptCost,
4✔
1005
                ),
4✔
1006
                AttemptCostPPM: routingConfig.AttemptCostPPM,
4✔
1007
                MinProbability: routingConfig.MinRouteProbability,
4✔
1008
        }
4✔
1009

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

4✔
1024
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
4✔
1025

4✔
1026
        s.controlTower = routing.NewControlTower(paymentControl)
4✔
1027

4✔
1028
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
4✔
1029
                cfg.Routing.StrictZombiePruning
4✔
1030

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

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

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

1078
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
4✔
1079

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

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

1121
        //nolint:lll
1122
        s.localChanMgr = &localchans.Manager{
4✔
1123
                ForAllOutgoingChannels:    s.graphBuilder.ForAllOutgoingChannels,
4✔
1124
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
4✔
1125
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
4✔
1126
                FetchChannel:              s.chanStateDB.FetchChannel,
4✔
1127
        }
4✔
1128

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

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

1145
        aggregator := sweep.NewBudgetAggregator(
4✔
1146
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
4✔
1147
                s.implCfg.AuxSweeper,
4✔
1148
        )
4✔
1149

4✔
1150
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
4✔
1151
                Signer:     cc.Wallet.Cfg.Signer,
4✔
1152
                Wallet:     cc.Wallet,
4✔
1153
                Estimator:  cc.FeeEstimator,
4✔
1154
                Notifier:   cc.ChainNotifier,
4✔
1155
                AuxSweeper: s.implCfg.AuxSweeper,
4✔
1156
        })
4✔
1157

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

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

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

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

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

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

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

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

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

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

1282
                                // If the BreachArbitrator successfully handled
1283
                                // the event, we can signal that the handoff
1284
                                // was successful.
1285
                                finalErr <- nil
4✔
1286
                        }
1287

1288
                        event := &contractcourt.ContractBreachEvent{
4✔
1289
                                ChanPoint:         chanPoint,
4✔
1290
                                ProcessACK:        processACK,
4✔
1291
                                BreachRetribution: breachRet,
4✔
1292
                        }
4✔
1293

4✔
1294
                        // Send the contract breach event to the
4✔
1295
                        // BreachArbitrator.
4✔
1296
                        select {
4✔
1297
                        case contractBreaches <- event:
4✔
1298
                        case <-s.quit:
×
1299
                                return ErrServerShuttingDown
×
1300
                        }
1301

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

1327
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1328
                QueryIncomingCircuit: func(
1329
                        circuit models.CircuitKey) *models.CircuitKey {
4✔
1330

4✔
1331
                        // Get the circuit map.
4✔
1332
                        circuits := s.htlcSwitch.CircuitLookup()
4✔
1333

4✔
1334
                        // Lookup the outgoing circuit.
4✔
1335
                        pc := circuits.LookupOpenCircuit(circuit)
4✔
1336
                        if pc == nil {
8✔
1337
                                return nil
4✔
1338
                        }
4✔
1339

1340
                        return &pc.Incoming
4✔
1341
                },
1342
                AuxLeafStore: implCfg.AuxLeafStore,
1343
                AuxSigner:    implCfg.AuxSigner,
1344
                AuxResolver:  implCfg.AuxContractResolver,
1345
        }, dbs.ChanStateDB)
1346

1347
        // Select the configuration and funding parameters for Bitcoin.
1348
        chainCfg := cfg.Bitcoin
4✔
1349
        minRemoteDelay := funding.MinBtcRemoteDelay
4✔
1350
        maxRemoteDelay := funding.MaxBtcRemoteDelay
4✔
1351

4✔
1352
        var chanIDSeed [32]byte
4✔
1353
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
4✔
1354
                return nil, err
×
1355
        }
×
1356

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

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

1375
                // Grab our key to find our policy.
1376
                var ourKey [33]byte
4✔
1377
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
4✔
1378

4✔
1379
                var ourPolicy *models.ChannelEdgePolicy
4✔
1380
                if info != nil && info.NodeKey1Bytes == ourKey {
8✔
1381
                        ourPolicy = e1
4✔
1382
                } else {
8✔
1383
                        ourPolicy = e2
4✔
1384
                }
4✔
1385

1386
                if ourPolicy == nil {
4✔
1387
                        // Something is wrong, so return an error.
×
1388
                        return nil, fmt.Errorf("we don't have an edge")
×
1389
                }
×
1390

1391
                err = s.graphDB.DeleteChannelEdges(
4✔
1392
                        false, false, scid.ToUint64(),
4✔
1393
                )
4✔
1394
                return ourPolicy, err
4✔
1395
        }
1396

1397
        // For the reservationTimeout and the zombieSweeperInterval different
1398
        // values are set in case we are in a dev environment so enhance test
1399
        // capacilities.
1400
        reservationTimeout := chanfunding.DefaultReservationTimeout
4✔
1401
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
4✔
1402

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

4✔
1411
                reservationTimeout = cfg.Dev.GetReservationTimeout()
4✔
1412
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
4✔
1413

4✔
1414
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
4✔
1415
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
4✔
1416
                        devCfg, reservationTimeout, zombieSweeperInterval)
4✔
1417
        }
4✔
1418

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

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

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

1465
                        minConf := uint64(3)
×
1466
                        maxConf := uint64(6)
×
1467

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

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

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

1504
                        // If this is a wumbo channel, then we'll require the
1505
                        // max value.
1506
                        if chanAmt > MaxFundingAmount {
×
1507
                                return maxRemoteDelay
×
1508
                        }
×
1509

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

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

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

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

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

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

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

1620
        // Assemble a peer notifier which will provide clients with subscriptions
1621
        // to peer online and offline events.
1622
        s.peerNotifier = peernotifier.New()
4✔
1623

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

1639
        if cfg.WtClient.Active {
8✔
1640
                policy := wtpolicy.DefaultPolicy()
4✔
1641
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
4✔
1642

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

4✔
1649
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
4✔
1650

4✔
1651
                if err := policy.Validate(); err != nil {
4✔
1652
                        return nil, err
×
1653
                }
×
1654

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

4✔
1661
                        return brontide.Dial(
4✔
1662
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
4✔
1663
                        )
4✔
1664
                }
4✔
1665

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

4✔
1673
                        channel, err := s.chanStateDB.FetchChannelByID(
4✔
1674
                                nil, chanID,
4✔
1675
                        )
4✔
1676
                        if err != nil {
4✔
1677
                                return nil, 0, err
×
1678
                        }
×
1679

1680
                        br, err := lnwallet.NewBreachRetribution(
4✔
1681
                                channel, commitHeight, 0, nil,
4✔
1682
                                implCfg.AuxLeafStore,
4✔
1683
                                implCfg.AuxContractResolver,
4✔
1684
                        )
4✔
1685
                        if err != nil {
4✔
1686
                                return nil, 0, err
×
1687
                        }
×
1688

1689
                        return br, channel.ChanType, nil
4✔
1690
                }
1691

1692
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
4✔
1693

4✔
1694
                // Copy the policy for legacy channels and set the blob flag
4✔
1695
                // signalling support for anchor channels.
4✔
1696
                anchorPolicy := policy
4✔
1697
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
4✔
1698

4✔
1699
                // Copy the policy for legacy channels and set the blob flag
4✔
1700
                // signalling support for taproot channels.
4✔
1701
                taprootPolicy := policy
4✔
1702
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
4✔
1703
                        blob.FlagTaprootChannel,
4✔
1704
                )
4✔
1705

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

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

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

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

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

×
1762
                                        return s.genNodeAnnouncement(
×
1763
                                                nil, modifier...,
×
1764
                                        )
×
1765
                                }),
×
1766
                })
1767
        }
1768

1769
        // Create liveness monitor.
1770
        s.createLivenessMonitor(cfg, cc, leaderElector)
4✔
1771

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

4✔
1790
        return s, nil
4✔
1791
}
1792

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

4✔
1798
        switch c := cfg.Estimator.Config().(type) {
4✔
1799
        case routing.AprioriConfig:
4✔
1800
                routerCfg.ProbabilityEstimatorType =
4✔
1801
                        routing.AprioriEstimatorName
4✔
1802

4✔
1803
                targetCfg := routerCfg.AprioriConfig
4✔
1804
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
4✔
1805
                targetCfg.Weight = c.AprioriWeight
4✔
1806
                targetCfg.CapacityFraction = c.CapacityFraction
4✔
1807
                targetCfg.HopProbability = c.AprioriHopProbability
4✔
1808

1809
        case routing.BimodalConfig:
4✔
1810
                routerCfg.ProbabilityEstimatorType =
4✔
1811
                        routing.BimodalEstimatorName
4✔
1812

4✔
1813
                targetCfg := routerCfg.BimodalConfig
4✔
1814
                targetCfg.Scale = int64(c.BimodalScaleMsat)
4✔
1815
                targetCfg.NodeWeight = c.BimodalNodeWeight
4✔
1816
                targetCfg.DecayTime = c.BimodalDecayTime
4✔
1817
        }
1818

1819
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
4✔
1820
}
1821

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

4✔
1828
        data, err := u.DataToSign()
4✔
1829
        if err != nil {
4✔
1830
                return nil, err
×
1831
        }
×
1832

1833
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
4✔
1834
}
1835

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

4✔
1849
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
4✔
1850
        if cfg.Bitcoin.Node == "nochainbackend" {
4✔
1851
                srvrLog.Info("Disabling chain backend checks for " +
×
1852
                        "nochainbackend mode")
×
1853

×
1854
                chainBackendAttempts = 0
×
1855
        }
×
1856

1857
        chainHealthCheck := healthcheck.NewObservation(
4✔
1858
                "chain backend",
4✔
1859
                cc.HealthCheck,
4✔
1860
                cfg.HealthChecks.ChainCheck.Interval,
4✔
1861
                cfg.HealthChecks.ChainCheck.Timeout,
4✔
1862
                cfg.HealthChecks.ChainCheck.Backoff,
4✔
1863
                chainBackendAttempts,
4✔
1864
        )
4✔
1865

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

1876
                        // If we have more free space than we require,
1877
                        // we return a nil error.
1878
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1879
                                return nil
×
1880
                        }
×
1881

1882
                        return fmt.Errorf("require: %v free space, got: %v",
×
1883
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1884
                                free)
×
1885
                },
1886
                cfg.HealthChecks.DiskCheck.Interval,
1887
                cfg.HealthChecks.DiskCheck.Timeout,
1888
                cfg.HealthChecks.DiskCheck.Backoff,
1889
                cfg.HealthChecks.DiskCheck.Attempts,
1890
        )
1891

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

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

1916
        checks := []*healthcheck.Observation{
4✔
1917
                chainHealthCheck, diskCheck, tlsHealthCheck,
4✔
1918
        }
4✔
1919

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

1938
        // If remote signing is enabled, add the healthcheck for the remote
1939
        // signing RPC interface.
1940
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
8✔
1941
                // Because we have two cascading timeouts here, we need to add
4✔
1942
                // some slack to the "outer" one of them in case the "inner"
4✔
1943
                // returns exactly on time.
4✔
1944
                overhead := time.Millisecond * 10
4✔
1945

4✔
1946
                remoteSignerConnectionCheck := healthcheck.NewObservation(
4✔
1947
                        "remote signer connection",
4✔
1948
                        rpcwallet.HealthCheck(
4✔
1949
                                s.cfg.RemoteSigner,
4✔
1950

4✔
1951
                                // For the health check we might to be even
4✔
1952
                                // stricter than the initial/normal connect, so
4✔
1953
                                // we use the health check timeout here.
4✔
1954
                                cfg.HealthChecks.RemoteSigner.Timeout,
4✔
1955
                        ),
4✔
1956
                        cfg.HealthChecks.RemoteSigner.Interval,
4✔
1957
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
4✔
1958
                        cfg.HealthChecks.RemoteSigner.Backoff,
4✔
1959
                        cfg.HealthChecks.RemoteSigner.Attempts,
4✔
1960
                )
4✔
1961
                checks = append(checks, remoteSignerConnectionCheck)
4✔
1962
        }
4✔
1963

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

×
1982
                                leader, err := leaderElector.IsLeader(
×
1983
                                        timeoutCtx,
×
1984
                                )
×
1985
                                if err != nil {
×
1986
                                        return fmt.Errorf("unable to check if "+
×
1987
                                                "still leader: %v", err)
×
1988
                                }
×
1989

1990
                                if !leader {
×
1991
                                        srvrLog.Debug("Not the current leader")
×
1992
                                        return fmt.Errorf("not the current " +
×
1993
                                                "leader")
×
1994
                                }
×
1995

1996
                                return nil
×
1997
                        },
1998
                        cfg.HealthChecks.LeaderCheck.Interval,
1999
                        cfg.HealthChecks.LeaderCheck.Timeout,
2000
                        cfg.HealthChecks.LeaderCheck.Backoff,
2001
                        cfg.HealthChecks.LeaderCheck.Attempts,
2002
                )
2003

2004
                checks = append(checks, leaderCheck)
×
2005
        }
2006

2007
        // If we have not disabled all of our health checks, we create a
2008
        // liveness monitor with our configured checks.
2009
        s.livenessMonitor = healthcheck.NewMonitor(
4✔
2010
                &healthcheck.Config{
4✔
2011
                        Checks:   checks,
4✔
2012
                        Shutdown: srvrLog.Criticalf,
4✔
2013
                },
4✔
2014
        )
4✔
2015
}
2016

2017
// Started returns true if the server has been started, and false otherwise.
2018
// NOTE: This function is safe for concurrent access.
2019
func (s *server) Started() bool {
4✔
2020
        return atomic.LoadInt32(&s.active) != 0
4✔
2021
}
4✔
2022

2023
// cleaner is used to aggregate "cleanup" functions during an operation that
2024
// starts several subsystems. In case one of the subsystem fails to start
2025
// and a proper resource cleanup is required, the "run" method achieves this
2026
// by running all these added "cleanup" functions.
2027
type cleaner []func() error
2028

2029
// add is used to add a cleanup function to be called when
2030
// the run function is executed.
2031
func (c cleaner) add(cleanup func() error) cleaner {
4✔
2032
        return append(c, cleanup)
4✔
2033
}
4✔
2034

2035
// run is used to run all the previousely added cleanup functions.
2036
func (c cleaner) run() {
×
2037
        for i := len(c) - 1; i >= 0; i-- {
×
2038
                if err := c[i](); err != nil {
×
2039
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2040
                }
×
2041
        }
2042
}
2043

2044
// Start starts the main daemon server, all requested listeners, and any helper
2045
// goroutines.
2046
// NOTE: This function is safe for concurrent access.
2047
//
2048
//nolint:funlen
2049
func (s *server) Start() error {
4✔
2050
        var startErr error
4✔
2051

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

4✔
2057
        s.start.Do(func() {
8✔
2058
                cleanup = cleanup.add(s.customMessageServer.Stop)
4✔
2059
                if err := s.customMessageServer.Start(); err != nil {
4✔
2060
                        startErr = err
×
2061
                        return
×
2062
                }
×
2063

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

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

2080
                // Start the notification server. This is used so channel
2081
                // management goroutines can be notified when a funding
2082
                // transaction reaches a sufficient number of confirmations, or
2083
                // when the input for the funding transaction is spent in an
2084
                // attempt at an uncooperative close by the counterparty.
2085
                cleanup = cleanup.add(s.sigPool.Stop)
4✔
2086
                if err := s.sigPool.Start(); err != nil {
4✔
2087
                        startErr = err
×
2088
                        return
×
2089
                }
×
2090

2091
                cleanup = cleanup.add(s.writePool.Stop)
4✔
2092
                if err := s.writePool.Start(); err != nil {
4✔
2093
                        startErr = err
×
2094
                        return
×
2095
                }
×
2096

2097
                cleanup = cleanup.add(s.readPool.Stop)
4✔
2098
                if err := s.readPool.Start(); err != nil {
4✔
2099
                        startErr = err
×
2100
                        return
×
2101
                }
×
2102

2103
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
4✔
2104
                if err := s.cc.ChainNotifier.Start(); err != nil {
4✔
2105
                        startErr = err
×
2106
                        return
×
2107
                }
×
2108

2109
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
4✔
2110
                if err := s.cc.BestBlockTracker.Start(); err != nil {
4✔
2111
                        startErr = err
×
2112
                        return
×
2113
                }
×
2114

2115
                cleanup = cleanup.add(s.channelNotifier.Stop)
4✔
2116
                if err := s.channelNotifier.Start(); err != nil {
4✔
2117
                        startErr = err
×
2118
                        return
×
2119
                }
×
2120

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

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

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

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

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

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

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

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

2173
                // htlcSwitch must be started before chainArb since the latter
2174
                // relies on htlcSwitch to deliver resolution message upon
2175
                // start.
2176
                cleanup = cleanup.add(s.htlcSwitch.Stop)
4✔
2177
                if err := s.htlcSwitch.Start(); err != nil {
4✔
2178
                        startErr = err
×
2179
                        return
×
2180
                }
×
2181

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

2188
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
4✔
2189
                if err := s.invoiceHtlcModifier.Start(); err != nil {
4✔
2190
                        startErr = err
×
2191
                        return
×
2192
                }
×
2193

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

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

2206
                cleanup = cleanup.add(s.chanRouter.Stop)
4✔
2207
                if err := s.chanRouter.Start(); err != nil {
4✔
2208
                        startErr = err
×
2209
                        return
×
2210
                }
×
2211
                // The authGossiper depends on the chanRouter and therefore
2212
                // should be started after it.
2213
                cleanup = cleanup.add(s.authGossiper.Stop)
4✔
2214
                if err := s.authGossiper.Start(); err != nil {
4✔
2215
                        startErr = err
×
2216
                        return
×
2217
                }
×
2218

2219
                cleanup = cleanup.add(s.invoices.Stop)
4✔
2220
                if err := s.invoices.Start(); err != nil {
4✔
2221
                        startErr = err
×
2222
                        return
×
2223
                }
×
2224

2225
                cleanup = cleanup.add(s.sphinx.Stop)
4✔
2226
                if err := s.sphinx.Start(); err != nil {
4✔
2227
                        startErr = err
×
2228
                        return
×
2229
                }
×
2230

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

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

2243
                cleanup.add(func() error {
4✔
2244
                        s.missionController.StopStoreTickers()
×
2245
                        return nil
×
2246
                })
×
2247
                s.missionController.RunStoreTickers()
4✔
2248

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

2281
                // chanSubSwapper must be started after the `channelNotifier`
2282
                // because it depends on channel events as a synchronization
2283
                // point.
2284
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
4✔
2285
                if err := s.chanSubSwapper.Start(); err != nil {
4✔
2286
                        startErr = err
×
2287
                        return
×
2288
                }
×
2289

2290
                if s.torController != nil {
4✔
2291
                        cleanup = cleanup.add(s.torController.Stop)
×
2292
                        if err := s.createNewHiddenService(); err != nil {
×
2293
                                startErr = err
×
2294
                                return
×
2295
                        }
×
2296
                }
2297

2298
                if s.natTraversal != nil {
4✔
2299
                        s.wg.Add(1)
×
2300
                        go s.watchExternalIP()
×
2301
                }
×
2302

2303
                // Start connmgr last to prevent connections before init.
2304
                cleanup = cleanup.add(func() error {
4✔
2305
                        s.connMgr.Stop()
×
2306
                        return nil
×
2307
                })
×
2308
                s.connMgr.Start()
4✔
2309

4✔
2310
                // If peers are specified as a config option, we'll add those
4✔
2311
                // peers first.
4✔
2312
                for _, peerAddrCfg := range s.cfg.AddPeers {
8✔
2313
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
4✔
2314
                                peerAddrCfg,
4✔
2315
                        )
4✔
2316
                        if err != nil {
4✔
2317
                                startErr = fmt.Errorf("unable to parse peer "+
×
2318
                                        "pubkey from config: %v", err)
×
2319
                                return
×
2320
                        }
×
2321
                        addr, err := parseAddr(parsedHost, s.cfg.net)
4✔
2322
                        if err != nil {
4✔
2323
                                startErr = fmt.Errorf("unable to parse peer "+
×
2324
                                        "address provided as a config option: "+
×
2325
                                        "%v", err)
×
2326
                                return
×
2327
                        }
×
2328

2329
                        peerAddr := &lnwire.NetAddress{
4✔
2330
                                IdentityKey: parsedPubkey,
4✔
2331
                                Address:     addr,
4✔
2332
                                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
2333
                        }
4✔
2334

4✔
2335
                        err = s.ConnectToPeer(
4✔
2336
                                peerAddr, true,
4✔
2337
                                s.cfg.ConnectionTimeout,
4✔
2338
                        )
4✔
2339
                        if err != nil {
4✔
2340
                                startErr = fmt.Errorf("unable to connect to "+
×
2341
                                        "peer address provided as a config "+
×
2342
                                        "option: %v", err)
×
2343
                                return
×
2344
                        }
×
2345
                }
2346

2347
                // Subscribe to NodeAnnouncements that advertise new addresses
2348
                // our persistent peers.
2349
                if err := s.updatePersistentPeerAddrs(); err != nil {
4✔
2350
                        startErr = err
×
2351
                        return
×
2352
                }
×
2353

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

2369
                // setSeedList is a helper function that turns multiple DNS seed
2370
                // server tuples from the command line or config file into the
2371
                // data structure we need and does a basic formal sanity check
2372
                // in the process.
2373
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
4✔
2374
                        if len(tuples) == 0 {
×
2375
                                return
×
2376
                        }
×
2377

2378
                        result := make([][2]string, len(tuples))
×
2379
                        for idx, tuple := range tuples {
×
2380
                                tuple = strings.TrimSpace(tuple)
×
2381
                                if len(tuple) == 0 {
×
2382
                                        return
×
2383
                                }
×
2384

2385
                                servers := strings.Split(tuple, ",")
×
2386
                                if len(servers) > 2 || len(servers) == 0 {
×
2387
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2388
                                                "seed tuple: %v", servers)
×
2389
                                        return
×
2390
                                }
×
2391

2392
                                copy(result[idx][:], servers)
×
2393
                        }
2394

2395
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2396
                }
2397

2398
                // Let users overwrite the DNS seed nodes. We only allow them
2399
                // for bitcoin mainnet/testnet/signet.
2400
                if s.cfg.Bitcoin.MainNet {
4✔
2401
                        setSeedList(
×
2402
                                s.cfg.Bitcoin.DNSSeeds,
×
2403
                                chainreg.BitcoinMainnetGenesis,
×
2404
                        )
×
2405
                }
×
2406
                if s.cfg.Bitcoin.TestNet3 {
4✔
2407
                        setSeedList(
×
2408
                                s.cfg.Bitcoin.DNSSeeds,
×
2409
                                chainreg.BitcoinTestnetGenesis,
×
2410
                        )
×
2411
                }
×
2412
                if s.cfg.Bitcoin.SigNet {
4✔
2413
                        setSeedList(
×
2414
                                s.cfg.Bitcoin.DNSSeeds,
×
2415
                                chainreg.BitcoinSignetGenesis,
×
2416
                        )
×
2417
                }
×
2418

2419
                // If network bootstrapping hasn't been disabled, then we'll
2420
                // configure the set of active bootstrappers, and launch a
2421
                // dedicated goroutine to maintain a set of persistent
2422
                // connections.
2423
                if shouldPeerBootstrap(s.cfg) {
4✔
2424
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2425
                        if err != nil {
×
2426
                                startErr = err
×
2427
                                return
×
2428
                        }
×
2429

2430
                        s.wg.Add(1)
×
2431
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2432
                } else {
4✔
2433
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
4✔
2434
                }
4✔
2435

2436
                // Set the active flag now that we've completed the full
2437
                // startup.
2438
                atomic.StoreInt32(&s.active, 1)
4✔
2439
        })
2440

2441
        if startErr != nil {
4✔
2442
                cleanup.run()
×
2443
        }
×
2444
        return startErr
4✔
2445
}
2446

2447
// Stop gracefully shutsdown the main daemon server. This function will signal
2448
// any active goroutines, or helper objects to exit, then blocks until they've
2449
// all successfully exited. Additionally, any/all listeners are closed.
2450
// NOTE: This function is safe for concurrent access.
2451
func (s *server) Stop() error {
4✔
2452
        s.stop.Do(func() {
8✔
2453
                atomic.StoreInt32(&s.stopping, 1)
4✔
2454

4✔
2455
                close(s.quit)
4✔
2456

4✔
2457
                // Shutdown connMgr first to prevent conns during shutdown.
4✔
2458
                s.connMgr.Stop()
4✔
2459

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

2516
                // Update channel.backup file. Make sure to do it before
2517
                // stopping chanSubSwapper.
2518
                singles, err := chanbackup.FetchStaticChanBackups(
4✔
2519
                        s.chanStateDB, s.addrSource,
4✔
2520
                )
4✔
2521
                if err != nil {
4✔
2522
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2523
                                err)
×
2524
                } else {
4✔
2525
                        err := s.chanSubSwapper.ManualUpdate(singles)
4✔
2526
                        if err != nil {
8✔
2527
                                srvrLog.Warnf("Manual update of channel "+
4✔
2528
                                        "backup failed: %v", err)
4✔
2529
                        }
4✔
2530
                }
2531

2532
                if err := s.chanSubSwapper.Stop(); err != nil {
4✔
2533
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2534
                }
×
2535
                if err := s.cc.ChainNotifier.Stop(); err != nil {
4✔
2536
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2537
                }
×
2538
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
4✔
2539
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2540
                                err)
×
2541
                }
×
2542
                if err := s.chanEventStore.Stop(); err != nil {
4✔
2543
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2544
                                err)
×
2545
                }
×
2546
                s.missionController.StopStoreTickers()
4✔
2547

4✔
2548
                // Disconnect from each active peers to ensure that
4✔
2549
                // peerTerminationWatchers signal completion to each peer.
4✔
2550
                for _, peer := range s.Peers() {
8✔
2551
                        err := s.DisconnectPeer(peer.IdentityKey())
4✔
2552
                        if err != nil {
4✔
2553
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2554
                                        "received error: %v", peer.IdentityKey(),
×
2555
                                        err,
×
2556
                                )
×
2557
                        }
×
2558
                }
2559

2560
                // Now that all connections have been torn down, stop the tower
2561
                // client which will reliably flush all queued states to the
2562
                // tower. If this is halted for any reason, the force quit timer
2563
                // will kick in and abort to allow this method to return.
2564
                if s.towerClientMgr != nil {
8✔
2565
                        if err := s.towerClientMgr.Stop(); err != nil {
4✔
2566
                                srvrLog.Warnf("Unable to shut down tower "+
×
2567
                                        "client manager: %v", err)
×
2568
                        }
×
2569
                }
2570

2571
                if s.hostAnn != nil {
4✔
2572
                        if err := s.hostAnn.Stop(); err != nil {
×
2573
                                srvrLog.Warnf("unable to shut down host "+
×
2574
                                        "annoucner: %v", err)
×
2575
                        }
×
2576
                }
2577

2578
                if s.livenessMonitor != nil {
8✔
2579
                        if err := s.livenessMonitor.Stop(); err != nil {
4✔
2580
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2581
                                        "monitor: %v", err)
×
2582
                        }
×
2583
                }
2584

2585
                // Wait for all lingering goroutines to quit.
2586
                srvrLog.Debug("Waiting for server to shutdown...")
4✔
2587
                s.wg.Wait()
4✔
2588

4✔
2589
                srvrLog.Debug("Stopping buffer pools...")
4✔
2590
                s.sigPool.Stop()
4✔
2591
                s.writePool.Stop()
4✔
2592
                s.readPool.Stop()
4✔
2593
        })
2594

2595
        return nil
4✔
2596
}
2597

2598
// Stopped returns true if the server has been instructed to shutdown.
2599
// NOTE: This function is safe for concurrent access.
2600
func (s *server) Stopped() bool {
4✔
2601
        return atomic.LoadInt32(&s.stopping) != 0
4✔
2602
}
4✔
2603

2604
// configurePortForwarding attempts to set up port forwarding for the different
2605
// ports that the server will be listening on.
2606
//
2607
// NOTE: This should only be used when using some kind of NAT traversal to
2608
// automatically set up forwarding rules.
2609
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2610
        ip, err := s.natTraversal.ExternalIP()
×
2611
        if err != nil {
×
2612
                return nil, err
×
2613
        }
×
2614
        s.lastDetectedIP = ip
×
2615

×
2616
        externalIPs := make([]string, 0, len(ports))
×
2617
        for _, port := range ports {
×
2618
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2619
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2620
                        continue
×
2621
                }
2622

2623
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2624
                externalIPs = append(externalIPs, hostIP)
×
2625
        }
2626

2627
        return externalIPs, nil
×
2628
}
2629

2630
// removePortForwarding attempts to clear the forwarding rules for the different
2631
// ports the server is currently listening on.
2632
//
2633
// NOTE: This should only be used when using some kind of NAT traversal to
2634
// automatically set up forwarding rules.
2635
func (s *server) removePortForwarding() {
×
2636
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2637
        for _, port := range forwardedPorts {
×
2638
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2639
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2640
                                "port %d: %v", port, err)
×
2641
                }
×
2642
        }
2643
}
2644

2645
// watchExternalIP continuously checks for an updated external IP address every
2646
// 15 minutes. Once a new IP address has been detected, it will automatically
2647
// handle port forwarding rules and send updated node announcements to the
2648
// currently connected peers.
2649
//
2650
// NOTE: This MUST be run as a goroutine.
2651
func (s *server) watchExternalIP() {
×
2652
        defer s.wg.Done()
×
2653

×
2654
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2655
        // up by the server.
×
2656
        defer s.removePortForwarding()
×
2657

×
2658
        // Keep track of the external IPs set by the user to avoid replacing
×
2659
        // them when detecting a new IP.
×
2660
        ipsSetByUser := make(map[string]struct{})
×
2661
        for _, ip := range s.cfg.ExternalIPs {
×
2662
                ipsSetByUser[ip.String()] = struct{}{}
×
2663
        }
×
2664

2665
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2666

×
2667
        ticker := time.NewTicker(15 * time.Minute)
×
2668
        defer ticker.Stop()
×
2669
out:
×
2670
        for {
×
2671
                select {
×
2672
                case <-ticker.C:
×
2673
                        // We'll start off by making sure a new IP address has
×
2674
                        // been detected.
×
2675
                        ip, err := s.natTraversal.ExternalIP()
×
2676
                        if err != nil {
×
2677
                                srvrLog.Debugf("Unable to retrieve the "+
×
2678
                                        "external IP address: %v", err)
×
2679
                                continue
×
2680
                        }
2681

2682
                        // Periodically renew the NAT port forwarding.
2683
                        for _, port := range forwardedPorts {
×
2684
                                err := s.natTraversal.AddPortMapping(port)
×
2685
                                if err != nil {
×
2686
                                        srvrLog.Warnf("Unable to automatically "+
×
2687
                                                "re-create port forwarding using %s: %v",
×
2688
                                                s.natTraversal.Name(), err)
×
2689
                                } else {
×
2690
                                        srvrLog.Debugf("Automatically re-created "+
×
2691
                                                "forwarding for port %d using %s to "+
×
2692
                                                "advertise external IP",
×
2693
                                                port, s.natTraversal.Name())
×
2694
                                }
×
2695
                        }
2696

2697
                        if ip.Equal(s.lastDetectedIP) {
×
2698
                                continue
×
2699
                        }
2700

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

×
2703
                        // Next, we'll craft the new addresses that will be
×
2704
                        // included in the new node announcement and advertised
×
2705
                        // to the network. Each address will consist of the new
×
2706
                        // IP detected and one of the currently advertised
×
2707
                        // ports.
×
2708
                        var newAddrs []net.Addr
×
2709
                        for _, port := range forwardedPorts {
×
2710
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2711
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2712
                                if err != nil {
×
2713
                                        srvrLog.Debugf("Unable to resolve "+
×
2714
                                                "host %v: %v", addr, err)
×
2715
                                        continue
×
2716
                                }
2717

2718
                                newAddrs = append(newAddrs, addr)
×
2719
                        }
2720

2721
                        // Skip the update if we weren't able to resolve any of
2722
                        // the new addresses.
2723
                        if len(newAddrs) == 0 {
×
2724
                                srvrLog.Debug("Skipping node announcement " +
×
2725
                                        "update due to not being able to " +
×
2726
                                        "resolve any new addresses")
×
2727
                                continue
×
2728
                        }
2729

2730
                        // Now, we'll need to update the addresses in our node's
2731
                        // announcement in order to propagate the update
2732
                        // throughout the network. We'll only include addresses
2733
                        // that have a different IP from the previous one, as
2734
                        // the previous IP is no longer valid.
2735
                        currentNodeAnn := s.getNodeAnnouncement()
×
2736

×
2737
                        for _, addr := range currentNodeAnn.Addresses {
×
2738
                                host, _, err := net.SplitHostPort(addr.String())
×
2739
                                if err != nil {
×
2740
                                        srvrLog.Debugf("Unable to determine "+
×
2741
                                                "host from address %v: %v",
×
2742
                                                addr, err)
×
2743
                                        continue
×
2744
                                }
2745

2746
                                // We'll also make sure to include external IPs
2747
                                // set manually by the user.
2748
                                _, setByUser := ipsSetByUser[addr.String()]
×
2749
                                if setByUser || host != s.lastDetectedIP.String() {
×
2750
                                        newAddrs = append(newAddrs, addr)
×
2751
                                }
×
2752
                        }
2753

2754
                        // Then, we'll generate a new timestamped node
2755
                        // announcement with the updated addresses and broadcast
2756
                        // it to our peers.
2757
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2758
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2759
                        )
×
2760
                        if err != nil {
×
2761
                                srvrLog.Debugf("Unable to generate new node "+
×
2762
                                        "announcement: %v", err)
×
2763
                                continue
×
2764
                        }
2765

2766
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2767
                        if err != nil {
×
2768
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2769
                                        "announcement to peers: %v", err)
×
2770
                                continue
×
2771
                        }
2772

2773
                        // Finally, update the last IP seen to the current one.
2774
                        s.lastDetectedIP = ip
×
2775
                case <-s.quit:
×
2776
                        break out
×
2777
                }
2778
        }
2779
}
2780

2781
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2782
// based on the server, and currently active bootstrap mechanisms as defined
2783
// within the current configuration.
2784
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2785
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2786

×
2787
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2788

×
2789
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2790
        // this can be used by default if we've already partially seeded the
×
2791
        // network.
×
2792
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2793
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2794
        if err != nil {
×
2795
                return nil, err
×
2796
        }
×
2797
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2798

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

×
2804
                // If we have a set of DNS seeds for this chain, then we'll add
×
2805
                // it as an additional bootstrapping source.
×
2806
                if ok {
×
2807
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2808
                                "seeds: %v", dnsSeeds)
×
2809

×
2810
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2811
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2812
                        )
×
2813
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2814
                }
×
2815
        }
2816

2817
        return bootStrappers, nil
×
2818
}
2819

2820
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2821
// needs to ignore, which is made of three parts,
2822
//   - the node itself needs to be skipped as it doesn't make sense to connect
2823
//     to itself.
2824
//   - the peers that already have connections with, as in s.peersByPub.
2825
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2826
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2827
        s.mu.RLock()
×
2828
        defer s.mu.RUnlock()
×
2829

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

×
2832
        // We should ignore ourselves from bootstrapping.
×
2833
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2834
        ignore[selfKey] = struct{}{}
×
2835

×
2836
        // Ignore all connected peers.
×
2837
        for _, peer := range s.peersByPub {
×
2838
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2839
                ignore[nID] = struct{}{}
×
2840
        }
×
2841

2842
        // Ignore all persistent peers as they have a dedicated reconnecting
2843
        // process.
2844
        for pubKeyStr := range s.persistentPeers {
×
2845
                var nID autopilot.NodeID
×
2846
                copy(nID[:], []byte(pubKeyStr))
×
2847
                ignore[nID] = struct{}{}
×
2848
        }
×
2849

2850
        return ignore
×
2851
}
2852

2853
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2854
// and maintain a target minimum number of outbound connections. With this
2855
// invariant, we ensure that our node is connected to a diverse set of peers
2856
// and that nodes newly joining the network receive an up to date network view
2857
// as soon as possible.
2858
func (s *server) peerBootstrapper(numTargetPeers uint32,
2859
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2860

×
2861
        defer s.wg.Done()
×
2862

×
2863
        // Before we continue, init the ignore peers map.
×
2864
        ignoreList := s.createBootstrapIgnorePeers()
×
2865

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

×
2870
        // Once done, we'll attempt to maintain our target minimum number of
×
2871
        // peers.
×
2872
        //
×
2873
        // We'll use a 15 second backoff, and double the time every time an
×
2874
        // epoch fails up to a ceiling.
×
2875
        backOff := time.Second * 15
×
2876

×
2877
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2878
        // see if we've reached our minimum number of peers.
×
2879
        sampleTicker := time.NewTicker(backOff)
×
2880
        defer sampleTicker.Stop()
×
2881

×
2882
        // We'll use the number of attempts and errors to determine if we need
×
2883
        // to increase the time between discovery epochs.
×
2884
        var epochErrors uint32 // To be used atomically.
×
2885
        var epochAttempts uint32
×
2886

×
2887
        for {
×
2888
                select {
×
2889
                // The ticker has just woken us up, so we'll need to check if
2890
                // we need to attempt to connect our to any more peers.
2891
                case <-sampleTicker.C:
×
2892
                        // Obtain the current number of peers, so we can gauge
×
2893
                        // if we need to sample more peers or not.
×
2894
                        s.mu.RLock()
×
2895
                        numActivePeers := uint32(len(s.peersByPub))
×
2896
                        s.mu.RUnlock()
×
2897

×
2898
                        // If we have enough peers, then we can loop back
×
2899
                        // around to the next round as we're done here.
×
2900
                        if numActivePeers >= numTargetPeers {
×
2901
                                continue
×
2902
                        }
2903

2904
                        // If all of our attempts failed during this last back
2905
                        // off period, then will increase our backoff to 5
2906
                        // minute ceiling to avoid an excessive number of
2907
                        // queries
2908
                        //
2909
                        // TODO(roasbeef): add reverse policy too?
2910

2911
                        if epochAttempts > 0 &&
×
2912
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2913

×
2914
                                sampleTicker.Stop()
×
2915

×
2916
                                backOff *= 2
×
2917
                                if backOff > bootstrapBackOffCeiling {
×
2918
                                        backOff = bootstrapBackOffCeiling
×
2919
                                }
×
2920

2921
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2922
                                        "%v", backOff)
×
2923
                                sampleTicker = time.NewTicker(backOff)
×
2924
                                continue
×
2925
                        }
2926

2927
                        atomic.StoreUint32(&epochErrors, 0)
×
2928
                        epochAttempts = 0
×
2929

×
2930
                        // Since we know need more peers, we'll compute the
×
2931
                        // exact number we need to reach our threshold.
×
2932
                        numNeeded := numTargetPeers - numActivePeers
×
2933

×
2934
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2935
                                "peers", numNeeded)
×
2936

×
2937
                        // With the number of peers we need calculated, we'll
×
2938
                        // query the network bootstrappers to sample a set of
×
2939
                        // random addrs for us.
×
2940
                        //
×
2941
                        // Before we continue, get a copy of the ignore peers
×
2942
                        // map.
×
2943
                        ignoreList = s.createBootstrapIgnorePeers()
×
2944

×
2945
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2946
                                ignoreList, numNeeded*2, bootstrappers...,
×
2947
                        )
×
2948
                        if err != nil {
×
2949
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2950
                                        "peers: %v", err)
×
2951
                                continue
×
2952
                        }
2953

2954
                        // Finally, we'll launch a new goroutine for each
2955
                        // prospective peer candidates.
2956
                        for _, addr := range peerAddrs {
×
2957
                                epochAttempts++
×
2958

×
2959
                                go func(a *lnwire.NetAddress) {
×
2960
                                        // TODO(roasbeef): can do AS, subnet,
×
2961
                                        // country diversity, etc
×
2962
                                        errChan := make(chan error, 1)
×
2963
                                        s.connectToPeer(
×
2964
                                                a, errChan,
×
2965
                                                s.cfg.ConnectionTimeout,
×
2966
                                        )
×
2967
                                        select {
×
2968
                                        case err := <-errChan:
×
2969
                                                if err == nil {
×
2970
                                                        return
×
2971
                                                }
×
2972

2973
                                                srvrLog.Errorf("Unable to "+
×
2974
                                                        "connect to %v: %v",
×
2975
                                                        a, err)
×
2976
                                                atomic.AddUint32(&epochErrors, 1)
×
2977
                                        case <-s.quit:
×
2978
                                        }
2979
                                }(addr)
2980
                        }
2981
                case <-s.quit:
×
2982
                        return
×
2983
                }
2984
        }
2985
}
2986

2987
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
2988
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
2989
// query back off each time we encounter a failure.
2990
const bootstrapBackOffCeiling = time.Minute * 5
2991

2992
// initialPeerBootstrap attempts to continuously connect to peers on startup
2993
// until the target number of peers has been reached. This ensures that nodes
2994
// receive an up to date network view as soon as possible.
2995
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2996
        numTargetPeers uint32,
2997
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2998

×
2999
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3000
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3001

×
3002
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3003
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3004
        var delaySignal <-chan time.Time
×
3005
        delayTime := time.Second * 2
×
3006

×
3007
        // As want to be more aggressive, we'll use a lower back off celling
×
3008
        // then the main peer bootstrap logic.
×
3009
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3010

×
3011
        for attempts := 0; ; attempts++ {
×
3012
                // Check if the server has been requested to shut down in order
×
3013
                // to prevent blocking.
×
3014
                if s.Stopped() {
×
3015
                        return
×
3016
                }
×
3017

3018
                // We can exit our aggressive initial peer bootstrapping stage
3019
                // if we've reached out target number of peers.
3020
                s.mu.RLock()
×
3021
                numActivePeers := uint32(len(s.peersByPub))
×
3022
                s.mu.RUnlock()
×
3023

×
3024
                if numActivePeers >= numTargetPeers {
×
3025
                        return
×
3026
                }
×
3027

3028
                if attempts > 0 {
×
3029
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3030
                                "bootstrap peers (attempt #%v)", delayTime,
×
3031
                                attempts)
×
3032

×
3033
                        // We've completed at least one iterating and haven't
×
3034
                        // finished, so we'll start to insert a delay period
×
3035
                        // between each attempt.
×
3036
                        delaySignal = time.After(delayTime)
×
3037
                        select {
×
3038
                        case <-delaySignal:
×
3039
                        case <-s.quit:
×
3040
                                return
×
3041
                        }
3042

3043
                        // After our delay, we'll double the time we wait up to
3044
                        // the max back off period.
3045
                        delayTime *= 2
×
3046
                        if delayTime > backOffCeiling {
×
3047
                                delayTime = backOffCeiling
×
3048
                        }
×
3049
                }
3050

3051
                // Otherwise, we'll request for the remaining number of peers
3052
                // in order to reach our target.
3053
                peersNeeded := numTargetPeers - numActivePeers
×
3054
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3055
                        ignore, peersNeeded, bootstrappers...,
×
3056
                )
×
3057
                if err != nil {
×
3058
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3059
                                "peers: %v", err)
×
3060
                        continue
×
3061
                }
3062

3063
                // Then, we'll attempt to establish a connection to the
3064
                // different peer addresses retrieved by our bootstrappers.
3065
                var wg sync.WaitGroup
×
3066
                for _, bootstrapAddr := range bootstrapAddrs {
×
3067
                        wg.Add(1)
×
3068
                        go func(addr *lnwire.NetAddress) {
×
3069
                                defer wg.Done()
×
3070

×
3071
                                errChan := make(chan error, 1)
×
3072
                                go s.connectToPeer(
×
3073
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3074
                                )
×
3075

×
3076
                                // We'll only allow this connection attempt to
×
3077
                                // take up to 3 seconds. This allows us to move
×
3078
                                // quickly by discarding peers that are slowing
×
3079
                                // us down.
×
3080
                                select {
×
3081
                                case err := <-errChan:
×
3082
                                        if err == nil {
×
3083
                                                return
×
3084
                                        }
×
3085
                                        srvrLog.Errorf("Unable to connect to "+
×
3086
                                                "%v: %v", addr, err)
×
3087
                                // TODO: tune timeout? 3 seconds might be *too*
3088
                                // aggressive but works well.
3089
                                case <-time.After(3 * time.Second):
×
3090
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3091
                                                "to not establishing a "+
×
3092
                                                "connection within 3 seconds",
×
3093
                                                addr)
×
3094
                                case <-s.quit:
×
3095
                                }
3096
                        }(bootstrapAddr)
3097
                }
3098

3099
                wg.Wait()
×
3100
        }
3101
}
3102

3103
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3104
// order to listen for inbound connections over Tor.
3105
func (s *server) createNewHiddenService() error {
×
3106
        // Determine the different ports the server is listening on. The onion
×
3107
        // service's virtual port will map to these ports and one will be picked
×
3108
        // at random when the onion service is being accessed.
×
3109
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3110
        for _, listenAddr := range s.listenAddrs {
×
3111
                port := listenAddr.(*net.TCPAddr).Port
×
3112
                listenPorts = append(listenPorts, port)
×
3113
        }
×
3114

3115
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3116
        if err != nil {
×
3117
                return err
×
3118
        }
×
3119

3120
        // Once the port mapping has been set, we can go ahead and automatically
3121
        // create our onion service. The service's private key will be saved to
3122
        // disk in order to regain access to this service when restarting `lnd`.
3123
        onionCfg := tor.AddOnionConfig{
×
3124
                VirtualPort: defaultPeerPort,
×
3125
                TargetPorts: listenPorts,
×
3126
                Store: tor.NewOnionFile(
×
3127
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3128
                        encrypter,
×
3129
                ),
×
3130
        }
×
3131

×
3132
        switch {
×
3133
        case s.cfg.Tor.V2:
×
3134
                onionCfg.Type = tor.V2
×
3135
        case s.cfg.Tor.V3:
×
3136
                onionCfg.Type = tor.V3
×
3137
        }
3138

3139
        addr, err := s.torController.AddOnion(onionCfg)
×
3140
        if err != nil {
×
3141
                return err
×
3142
        }
×
3143

3144
        // Now that the onion service has been created, we'll add the onion
3145
        // address it can be reached at to our list of advertised addresses.
3146
        newNodeAnn, err := s.genNodeAnnouncement(
×
3147
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3148
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3149
                },
×
3150
        )
3151
        if err != nil {
×
3152
                return fmt.Errorf("unable to generate new node "+
×
3153
                        "announcement: %v", err)
×
3154
        }
×
3155

3156
        // Finally, we'll update the on-disk version of our announcement so it
3157
        // will eventually propagate to nodes in the network.
3158
        selfNode := &channeldb.LightningNode{
×
3159
                HaveNodeAnnouncement: true,
×
3160
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3161
                Addresses:            newNodeAnn.Addresses,
×
3162
                Alias:                newNodeAnn.Alias.String(),
×
3163
                Features: lnwire.NewFeatureVector(
×
3164
                        newNodeAnn.Features, lnwire.Features,
×
3165
                ),
×
3166
                Color:        newNodeAnn.RGBColor,
×
3167
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3168
        }
×
3169
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3170
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3171
                return fmt.Errorf("can't set self node: %w", err)
×
3172
        }
×
3173

3174
        return nil
×
3175
}
3176

3177
// findChannel finds a channel given a public key and ChannelID. It is an
3178
// optimization that is quicker than seeking for a channel given only the
3179
// ChannelID.
3180
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3181
        *channeldb.OpenChannel, error) {
4✔
3182

4✔
3183
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
4✔
3184
        if err != nil {
4✔
3185
                return nil, err
×
3186
        }
×
3187

3188
        for _, channel := range nodeChans {
8✔
3189
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
8✔
3190
                        return channel, nil
4✔
3191
                }
4✔
3192
        }
3193

3194
        return nil, fmt.Errorf("unable to find channel")
4✔
3195
}
3196

3197
// getNodeAnnouncement fetches the current, fully signed node announcement.
3198
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
4✔
3199
        s.mu.Lock()
4✔
3200
        defer s.mu.Unlock()
4✔
3201

4✔
3202
        return *s.currentNodeAnn
4✔
3203
}
4✔
3204

3205
// genNodeAnnouncement generates and returns the current fully signed node
3206
// announcement. The time stamp of the announcement will be updated in order
3207
// to ensure it propagates through the network.
3208
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3209
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
4✔
3210

4✔
3211
        s.mu.Lock()
4✔
3212
        defer s.mu.Unlock()
4✔
3213

4✔
3214
        // First, try to update our feature manager with the updated set of
4✔
3215
        // features.
4✔
3216
        if features != nil {
8✔
3217
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
4✔
3218
                        feature.SetNodeAnn: features,
4✔
3219
                }
4✔
3220
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
4✔
3221
                if err != nil {
8✔
3222
                        return lnwire.NodeAnnouncement{}, err
4✔
3223
                }
4✔
3224

3225
                // If we could successfully update our feature manager, add
3226
                // an update modifier to include these new features to our
3227
                // set.
3228
                modifiers = append(
4✔
3229
                        modifiers, netann.NodeAnnSetFeatures(features),
4✔
3230
                )
4✔
3231
        }
3232

3233
        // Always update the timestamp when refreshing to ensure the update
3234
        // propagates.
3235
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
4✔
3236

4✔
3237
        // Apply the requested changes to the node announcement.
4✔
3238
        for _, modifier := range modifiers {
8✔
3239
                modifier(s.currentNodeAnn)
4✔
3240
        }
4✔
3241

3242
        // Sign a new update after applying all of the passed modifiers.
3243
        err := netann.SignNodeAnnouncement(
4✔
3244
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
4✔
3245
        )
4✔
3246
        if err != nil {
4✔
3247
                return lnwire.NodeAnnouncement{}, err
×
3248
        }
×
3249

3250
        return *s.currentNodeAnn, nil
4✔
3251
}
3252

3253
// updateAndBrodcastSelfNode generates a new node announcement
3254
// applying the giving modifiers and updating the time stamp
3255
// to ensure it propagates through the network. Then it brodcasts
3256
// it to the network.
3257
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
3258
        modifiers ...netann.NodeAnnModifier) error {
4✔
3259

4✔
3260
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
4✔
3261
        if err != nil {
8✔
3262
                return fmt.Errorf("unable to generate new node "+
4✔
3263
                        "announcement: %v", err)
4✔
3264
        }
4✔
3265

3266
        // Update the on-disk version of our announcement.
3267
        // Load and modify self node istead of creating anew instance so we
3268
        // don't risk overwriting any existing values.
3269
        selfNode, err := s.graphDB.SourceNode()
4✔
3270
        if err != nil {
4✔
3271
                return fmt.Errorf("unable to get current source node: %w", err)
×
3272
        }
×
3273

3274
        selfNode.HaveNodeAnnouncement = true
4✔
3275
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
4✔
3276
        selfNode.Addresses = newNodeAnn.Addresses
4✔
3277
        selfNode.Alias = newNodeAnn.Alias.String()
4✔
3278
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
4✔
3279
        selfNode.Color = newNodeAnn.RGBColor
4✔
3280
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
4✔
3281

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

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

3288
        // Finally, propagate it to the nodes in the network.
3289
        err = s.BroadcastMessage(nil, &newNodeAnn)
4✔
3290
        if err != nil {
4✔
3291
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3292
                        "announcement to peers: %v", err)
×
3293
                return err
×
3294
        }
×
3295

3296
        return nil
4✔
3297
}
3298

3299
type nodeAddresses struct {
3300
        pubKey    *btcec.PublicKey
3301
        addresses []net.Addr
3302
}
3303

3304
// establishPersistentConnections attempts to establish persistent connections
3305
// to all our direct channel collaborators. In order to promote liveness of our
3306
// active channels, we instruct the connection manager to attempt to establish
3307
// and maintain persistent connections to all our direct channel counterparties.
3308
func (s *server) establishPersistentConnections() error {
4✔
3309
        // nodeAddrsMap stores the combination of node public keys and addresses
4✔
3310
        // that we'll attempt to reconnect to. PubKey strings are used as keys
4✔
3311
        // since other PubKey forms can't be compared.
4✔
3312
        nodeAddrsMap := map[string]*nodeAddresses{}
4✔
3313

4✔
3314
        // Iterate through the list of LinkNodes to find addresses we should
4✔
3315
        // attempt to connect to based on our set of previous connections. Set
4✔
3316
        // the reconnection port to the default peer port.
4✔
3317
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
4✔
3318
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
4✔
3319
                return err
×
3320
        }
×
3321
        for _, node := range linkNodes {
8✔
3322
                pubStr := string(node.IdentityPub.SerializeCompressed())
4✔
3323
                nodeAddrs := &nodeAddresses{
4✔
3324
                        pubKey:    node.IdentityPub,
4✔
3325
                        addresses: node.Addresses,
4✔
3326
                }
4✔
3327
                nodeAddrsMap[pubStr] = nodeAddrs
4✔
3328
        }
4✔
3329

3330
        // After checking our previous connections for addresses to connect to,
3331
        // iterate through the nodes in our channel graph to find addresses
3332
        // that have been added via NodeAnnouncement messages.
3333
        sourceNode, err := s.graphDB.SourceNode()
4✔
3334
        if err != nil {
4✔
3335
                return err
×
3336
        }
×
3337

3338
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3339
        // each of the nodes.
3340
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
4✔
3341
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
4✔
3342
                tx kvdb.RTx,
4✔
3343
                chanInfo *models.ChannelEdgeInfo,
4✔
3344
                policy, _ *models.ChannelEdgePolicy) error {
8✔
3345

4✔
3346
                // If the remote party has announced the channel to us, but we
4✔
3347
                // haven't yet, then we won't have a policy. However, we don't
4✔
3348
                // need this to connect to the peer, so we'll log it and move on.
4✔
3349
                if policy == nil {
4✔
3350
                        srvrLog.Warnf("No channel policy found for "+
×
3351
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3352
                }
×
3353

3354
                // We'll now fetch the peer opposite from us within this
3355
                // channel so we can queue up a direct connection to them.
3356
                channelPeer, err := s.graphDB.FetchOtherNode(
4✔
3357
                        tx, chanInfo, selfPub,
4✔
3358
                )
4✔
3359
                if err != nil {
4✔
3360
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3361
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3362
                                err)
×
3363
                }
×
3364

3365
                pubStr := string(channelPeer.PubKeyBytes[:])
4✔
3366

4✔
3367
                // Add all unique addresses from channel
4✔
3368
                // graph/NodeAnnouncements to the list of addresses we'll
4✔
3369
                // connect to for this peer.
4✔
3370
                addrSet := make(map[string]net.Addr)
4✔
3371
                for _, addr := range channelPeer.Addresses {
8✔
3372
                        switch addr.(type) {
4✔
3373
                        case *net.TCPAddr:
4✔
3374
                                addrSet[addr.String()] = addr
4✔
3375

3376
                        // We'll only attempt to connect to Tor addresses if Tor
3377
                        // outbound support is enabled.
3378
                        case *tor.OnionAddr:
×
3379
                                if s.cfg.Tor.Active {
×
3380
                                        addrSet[addr.String()] = addr
×
3381
                                }
×
3382
                        }
3383
                }
3384

3385
                // If this peer is also recorded as a link node, we'll add any
3386
                // additional addresses that have not already been selected.
3387
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
4✔
3388
                if ok {
8✔
3389
                        for _, lnAddress := range linkNodeAddrs.addresses {
8✔
3390
                                switch lnAddress.(type) {
4✔
3391
                                case *net.TCPAddr:
4✔
3392
                                        addrSet[lnAddress.String()] = lnAddress
4✔
3393

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

3404
                // Construct a slice of the deduped addresses.
3405
                var addrs []net.Addr
4✔
3406
                for _, addr := range addrSet {
8✔
3407
                        addrs = append(addrs, addr)
4✔
3408
                }
4✔
3409

3410
                n := &nodeAddresses{
4✔
3411
                        addresses: addrs,
4✔
3412
                }
4✔
3413
                n.pubKey, err = channelPeer.PubKey()
4✔
3414
                if err != nil {
4✔
3415
                        return err
×
3416
                }
×
3417

3418
                nodeAddrsMap[pubStr] = n
4✔
3419
                return nil
4✔
3420
        })
3421
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
4✔
3422
                return err
×
3423
        }
×
3424

3425
        srvrLog.Debugf("Establishing %v persistent connections on start",
4✔
3426
                len(nodeAddrsMap))
4✔
3427

4✔
3428
        // Acquire and hold server lock until all persistent connection requests
4✔
3429
        // have been recorded and sent to the connection manager.
4✔
3430
        s.mu.Lock()
4✔
3431
        defer s.mu.Unlock()
4✔
3432

4✔
3433
        // Iterate through the combined list of addresses from prior links and
4✔
3434
        // node announcements and attempt to reconnect to each node.
4✔
3435
        var numOutboundConns int
4✔
3436
        for pubStr, nodeAddr := range nodeAddrsMap {
8✔
3437
                // Add this peer to the set of peers we should maintain a
4✔
3438
                // persistent connection with. We set the value to false to
4✔
3439
                // indicate that we should not continue to reconnect if the
4✔
3440
                // number of channels returns to zero, since this peer has not
4✔
3441
                // been requested as perm by the user.
4✔
3442
                s.persistentPeers[pubStr] = false
4✔
3443
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
8✔
3444
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
4✔
3445
                }
4✔
3446

3447
                for _, address := range nodeAddr.addresses {
8✔
3448
                        // Create a wrapper address which couples the IP and
4✔
3449
                        // the pubkey so the brontide authenticated connection
4✔
3450
                        // can be established.
4✔
3451
                        lnAddr := &lnwire.NetAddress{
4✔
3452
                                IdentityKey: nodeAddr.pubKey,
4✔
3453
                                Address:     address,
4✔
3454
                        }
4✔
3455

4✔
3456
                        s.persistentPeerAddrs[pubStr] = append(
4✔
3457
                                s.persistentPeerAddrs[pubStr], lnAddr)
4✔
3458
                }
4✔
3459

3460
                // We'll connect to the first 10 peers immediately, then
3461
                // randomly stagger any remaining connections if the
3462
                // stagger initial reconnect flag is set. This ensures
3463
                // that mobile nodes or nodes with a small number of
3464
                // channels obtain connectivity quickly, but larger
3465
                // nodes are able to disperse the costs of connecting to
3466
                // all peers at once.
3467
                if numOutboundConns < numInstantInitReconnect ||
4✔
3468
                        !s.cfg.StaggerInitialReconnect {
8✔
3469

4✔
3470
                        go s.connectToPersistentPeer(pubStr)
4✔
3471
                } else {
4✔
3472
                        go s.delayInitialReconnect(pubStr)
×
3473
                }
×
3474

3475
                numOutboundConns++
4✔
3476
        }
3477

3478
        return nil
4✔
3479
}
3480

3481
// delayInitialReconnect will attempt a reconnection to the given peer after
3482
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3483
//
3484
// NOTE: This method MUST be run as a goroutine.
3485
func (s *server) delayInitialReconnect(pubStr string) {
×
3486
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3487
        select {
×
3488
        case <-time.After(delay):
×
3489
                s.connectToPersistentPeer(pubStr)
×
3490
        case <-s.quit:
×
3491
        }
3492
}
3493

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

4✔
3500
        s.mu.Lock()
4✔
3501
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
8✔
3502
                delete(s.persistentPeers, pubKeyStr)
4✔
3503
                delete(s.persistentPeersBackoff, pubKeyStr)
4✔
3504
                delete(s.persistentPeerAddrs, pubKeyStr)
4✔
3505
                s.cancelConnReqs(pubKeyStr, nil)
4✔
3506
                s.mu.Unlock()
4✔
3507

4✔
3508
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
4✔
3509
                        "peer has no open channels", compressedPubKey)
4✔
3510

4✔
3511
                return
4✔
3512
        }
4✔
3513
        s.mu.Unlock()
4✔
3514
}
3515

3516
// BroadcastMessage sends a request to the server to broadcast a set of
3517
// messages to all peers other than the one specified by the `skips` parameter.
3518
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3519
// the target peers.
3520
//
3521
// NOTE: This function is safe for concurrent access.
3522
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3523
        msgs ...lnwire.Message) error {
4✔
3524

4✔
3525
        // Filter out peers found in the skips map. We synchronize access to
4✔
3526
        // peersByPub throughout this process to ensure we deliver messages to
4✔
3527
        // exact set of peers present at the time of invocation.
4✔
3528
        s.mu.RLock()
4✔
3529
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
3530
        for pubStr, sPeer := range s.peersByPub {
8✔
3531
                if skips != nil {
8✔
3532
                        if _, ok := skips[sPeer.PubKey()]; ok {
8✔
3533
                                srvrLog.Tracef("Skipping %x in broadcast with "+
4✔
3534
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
4✔
3535
                                continue
4✔
3536
                        }
3537
                }
3538

3539
                peers = append(peers, sPeer)
4✔
3540
        }
3541
        s.mu.RUnlock()
4✔
3542

4✔
3543
        // Iterate over all known peers, dispatching a go routine to enqueue
4✔
3544
        // all messages to each of peers.
4✔
3545
        var wg sync.WaitGroup
4✔
3546
        for _, sPeer := range peers {
8✔
3547
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
4✔
3548
                        sPeer.PubKey())
4✔
3549

4✔
3550
                // Dispatch a go routine to enqueue all messages to this peer.
4✔
3551
                wg.Add(1)
4✔
3552
                s.wg.Add(1)
4✔
3553
                go func(p lnpeer.Peer) {
8✔
3554
                        defer s.wg.Done()
4✔
3555
                        defer wg.Done()
4✔
3556

4✔
3557
                        p.SendMessageLazy(false, msgs...)
4✔
3558
                }(sPeer)
4✔
3559
        }
3560

3561
        // Wait for all messages to have been dispatched before returning to
3562
        // caller.
3563
        wg.Wait()
4✔
3564

4✔
3565
        return nil
4✔
3566
}
3567

3568
// NotifyWhenOnline can be called by other subsystems to get notified when a
3569
// particular peer comes online. The peer itself is sent across the peerChan.
3570
//
3571
// NOTE: This function is safe for concurrent access.
3572
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3573
        peerChan chan<- lnpeer.Peer) {
4✔
3574

4✔
3575
        s.mu.Lock()
4✔
3576

4✔
3577
        // Compute the target peer's identifier.
4✔
3578
        pubStr := string(peerKey[:])
4✔
3579

4✔
3580
        // Check if peer is connected.
4✔
3581
        peer, ok := s.peersByPub[pubStr]
4✔
3582
        if ok {
8✔
3583
                // Unlock here so that the mutex isn't held while we are
4✔
3584
                // waiting for the peer to become active.
4✔
3585
                s.mu.Unlock()
4✔
3586

4✔
3587
                // Wait until the peer signals that it is actually active
4✔
3588
                // rather than only in the server's maps.
4✔
3589
                select {
4✔
3590
                case <-peer.ActiveSignal():
4✔
3591
                case <-peer.QuitSignal():
×
3592
                        // The peer quit, so we'll add the channel to the slice
×
3593
                        // and return.
×
3594
                        s.mu.Lock()
×
3595
                        s.peerConnectedListeners[pubStr] = append(
×
3596
                                s.peerConnectedListeners[pubStr], peerChan,
×
3597
                        )
×
3598
                        s.mu.Unlock()
×
3599
                        return
×
3600
                }
3601

3602
                // Connected, can return early.
3603
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
4✔
3604

4✔
3605
                select {
4✔
3606
                case peerChan <- peer:
4✔
3607
                case <-s.quit:
×
3608
                }
3609

3610
                return
4✔
3611
        }
3612

3613
        // Not connected, store this listener such that it can be notified when
3614
        // the peer comes online.
3615
        s.peerConnectedListeners[pubStr] = append(
4✔
3616
                s.peerConnectedListeners[pubStr], peerChan,
4✔
3617
        )
4✔
3618
        s.mu.Unlock()
4✔
3619
}
3620

3621
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3622
// the given public key has been disconnected. The notification is signaled by
3623
// closing the channel returned.
3624
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
4✔
3625
        s.mu.Lock()
4✔
3626
        defer s.mu.Unlock()
4✔
3627

4✔
3628
        c := make(chan struct{})
4✔
3629

4✔
3630
        // If the peer is already offline, we can immediately trigger the
4✔
3631
        // notification.
4✔
3632
        peerPubKeyStr := string(peerPubKey[:])
4✔
3633
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
4✔
3634
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3635
                close(c)
×
3636
                return c
×
3637
        }
×
3638

3639
        // Otherwise, the peer is online, so we'll keep track of the channel to
3640
        // trigger the notification once the server detects the peer
3641
        // disconnects.
3642
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
4✔
3643
                s.peerDisconnectedListeners[peerPubKeyStr], c,
4✔
3644
        )
4✔
3645

4✔
3646
        return c
4✔
3647
}
3648

3649
// FindPeer will return the peer that corresponds to the passed in public key.
3650
// This function is used by the funding manager, allowing it to update the
3651
// daemon's local representation of the remote peer.
3652
//
3653
// NOTE: This function is safe for concurrent access.
3654
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
4✔
3655
        s.mu.RLock()
4✔
3656
        defer s.mu.RUnlock()
4✔
3657

4✔
3658
        pubStr := string(peerKey.SerializeCompressed())
4✔
3659

4✔
3660
        return s.findPeerByPubStr(pubStr)
4✔
3661
}
4✔
3662

3663
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3664
// which should be a string representation of the peer's serialized, compressed
3665
// public key.
3666
//
3667
// NOTE: This function is safe for concurrent access.
3668
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3669
        s.mu.RLock()
4✔
3670
        defer s.mu.RUnlock()
4✔
3671

4✔
3672
        return s.findPeerByPubStr(pubStr)
4✔
3673
}
4✔
3674

3675
// findPeerByPubStr is an internal method that retrieves the specified peer from
3676
// the server's internal state using.
3677
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3678
        peer, ok := s.peersByPub[pubStr]
4✔
3679
        if !ok {
8✔
3680
                return nil, ErrPeerNotConnected
4✔
3681
        }
4✔
3682

3683
        return peer, nil
4✔
3684
}
3685

3686
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3687
// exponential backoff. If no previous backoff was known, the default is
3688
// returned.
3689
func (s *server) nextPeerBackoff(pubStr string,
3690
        startTime time.Time) time.Duration {
4✔
3691

4✔
3692
        // Now, determine the appropriate backoff to use for the retry.
4✔
3693
        backoff, ok := s.persistentPeersBackoff[pubStr]
4✔
3694
        if !ok {
8✔
3695
                // If an existing backoff was unknown, use the default.
4✔
3696
                return s.cfg.MinBackoff
4✔
3697
        }
4✔
3698

3699
        // If the peer failed to start properly, we'll just use the previous
3700
        // backoff to compute the subsequent randomized exponential backoff
3701
        // duration. This will roughly double on average.
3702
        if startTime.IsZero() {
4✔
3703
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3704
        }
×
3705

3706
        // The peer succeeded in starting. If the connection didn't last long
3707
        // enough to be considered stable, we'll continue to back off retries
3708
        // with this peer.
3709
        connDuration := time.Since(startTime)
4✔
3710
        if connDuration < defaultStableConnDuration {
8✔
3711
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
4✔
3712
        }
4✔
3713

3714
        // The peer succeed in starting and this was stable peer, so we'll
3715
        // reduce the timeout duration by the length of the connection after
3716
        // applying randomized exponential backoff. We'll only apply this in the
3717
        // case that:
3718
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3719
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3720
        if relaxedBackoff > s.cfg.MinBackoff {
×
3721
                return relaxedBackoff
×
3722
        }
×
3723

3724
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3725
        // the stable connection lasted much longer than our previous backoff.
3726
        // To reward such good behavior, we'll reconnect after the default
3727
        // timeout.
3728
        return s.cfg.MinBackoff
×
3729
}
3730

3731
// shouldDropLocalConnection determines if our local connection to a remote peer
3732
// should be dropped in the case of concurrent connection establishment. In
3733
// order to deterministically decide which connection should be dropped, we'll
3734
// utilize the ordering of the local and remote public key. If we didn't use
3735
// such a tie breaker, then we risk _both_ connections erroneously being
3736
// dropped.
3737
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3738
        localPubBytes := local.SerializeCompressed()
×
3739
        remotePubPbytes := remote.SerializeCompressed()
×
3740

×
3741
        // The connection that comes from the node with a "smaller" pubkey
×
3742
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3743
        // should drop our established connection.
×
3744
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3745
}
×
3746

3747
// InboundPeerConnected initializes a new peer in response to a new inbound
3748
// connection.
3749
//
3750
// NOTE: This function is safe for concurrent access.
3751
func (s *server) InboundPeerConnected(conn net.Conn) {
4✔
3752
        // Exit early if we have already been instructed to shutdown, this
4✔
3753
        // prevents any delayed callbacks from accidentally registering peers.
4✔
3754
        if s.Stopped() {
4✔
3755
                return
×
3756
        }
×
3757

3758
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3759
        pubSer := nodePub.SerializeCompressed()
4✔
3760
        pubStr := string(pubSer)
4✔
3761

4✔
3762
        var pubBytes [33]byte
4✔
3763
        copy(pubBytes[:], pubSer)
4✔
3764

4✔
3765
        s.mu.Lock()
4✔
3766
        defer s.mu.Unlock()
4✔
3767

4✔
3768
        // If the remote node's public key is banned, drop the connection.
4✔
3769
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
4✔
3770
        if dcErr != nil {
4✔
3771
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3772
                        "peer: %v", dcErr)
×
3773
                conn.Close()
×
3774

×
3775
                return
×
3776
        }
×
3777

3778
        if shouldDc {
4✔
3779
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3780
                        "banned.", pubSer)
×
3781

×
3782
                conn.Close()
×
3783

×
3784
                return
×
3785
        }
×
3786

3787
        // If we already have an outbound connection to this peer, then ignore
3788
        // this new connection.
3789
        if p, ok := s.outboundPeers[pubStr]; ok {
8✔
3790
                srvrLog.Debugf("Already have outbound connection for %v, "+
4✔
3791
                        "ignoring inbound connection from local=%v, remote=%v",
4✔
3792
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
3793

4✔
3794
                conn.Close()
4✔
3795
                return
4✔
3796
        }
4✔
3797

3798
        // If we already have a valid connection that is scheduled to take
3799
        // precedence once the prior peer has finished disconnecting, we'll
3800
        // ignore this connection.
3801
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
4✔
3802
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3803
                        "scheduled", conn.RemoteAddr(), p)
×
3804
                conn.Close()
×
3805
                return
×
3806
        }
×
3807

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

4✔
3810
        // Check to see if we already have a connection with this peer. If so,
4✔
3811
        // we may need to drop our existing connection. This prevents us from
4✔
3812
        // having duplicate connections to the same peer. We forgo adding a
4✔
3813
        // default case as we expect these to be the only error values returned
4✔
3814
        // from findPeerByPubStr.
4✔
3815
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
3816
        switch err {
4✔
3817
        case ErrPeerNotConnected:
4✔
3818
                // We were unable to locate an existing connection with the
4✔
3819
                // target peer, proceed to connect.
4✔
3820
                s.cancelConnReqs(pubStr, nil)
4✔
3821
                s.peerConnected(conn, nil, true)
4✔
3822

3823
        case nil:
×
3824
                // We already have a connection with the incoming peer. If the
×
3825
                // connection we've already established should be kept and is
×
3826
                // not of the same type of the new connection (inbound), then
×
3827
                // we'll close out the new connection s.t there's only a single
×
3828
                // connection between us.
×
3829
                localPub := s.identityECDH.PubKey()
×
3830
                if !connectedPeer.Inbound() &&
×
3831
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3832

×
3833
                        srvrLog.Warnf("Received inbound connection from "+
×
3834
                                "peer %v, but already have outbound "+
×
3835
                                "connection, dropping conn", connectedPeer)
×
3836
                        conn.Close()
×
3837
                        return
×
3838
                }
×
3839

3840
                // Otherwise, if we should drop the connection, then we'll
3841
                // disconnect our already connected peer.
3842
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3843
                        connectedPeer)
×
3844

×
3845
                s.cancelConnReqs(pubStr, nil)
×
3846

×
3847
                // Remove the current peer from the server's internal state and
×
3848
                // signal that the peer termination watcher does not need to
×
3849
                // execute for this peer.
×
3850
                s.removePeer(connectedPeer)
×
3851
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3852
                s.scheduledPeerConnection[pubStr] = func() {
×
3853
                        s.peerConnected(conn, nil, true)
×
3854
                }
×
3855
        }
3856
}
3857

3858
// OutboundPeerConnected initializes a new peer in response to a new outbound
3859
// connection.
3860
// NOTE: This function is safe for concurrent access.
3861
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
4✔
3862
        // Exit early if we have already been instructed to shutdown, this
4✔
3863
        // prevents any delayed callbacks from accidentally registering peers.
4✔
3864
        if s.Stopped() {
4✔
3865
                return
×
3866
        }
×
3867

3868
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3869
        pubSer := nodePub.SerializeCompressed()
4✔
3870
        pubStr := string(pubSer)
4✔
3871

4✔
3872
        var pubBytes [33]byte
4✔
3873
        copy(pubBytes[:], pubSer)
4✔
3874

4✔
3875
        s.mu.Lock()
4✔
3876
        defer s.mu.Unlock()
4✔
3877

4✔
3878
        // If the remote node's public key is banned, drop the connection.
4✔
3879
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
4✔
3880
        if dcErr != nil {
4✔
3881
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3882
                        "peer: %v", dcErr)
×
3883
                conn.Close()
×
3884

×
3885
                return
×
3886
        }
×
3887

3888
        if shouldDc {
4✔
3889
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3890
                        "banned.", pubSer)
×
3891

×
3892
                if connReq != nil {
×
3893
                        s.connMgr.Remove(connReq.ID())
×
3894
                }
×
3895

3896
                conn.Close()
×
3897

×
3898
                return
×
3899
        }
3900

3901
        // If we already have an inbound connection to this peer, then ignore
3902
        // this new connection.
3903
        if p, ok := s.inboundPeers[pubStr]; ok {
8✔
3904
                srvrLog.Debugf("Already have inbound connection for %v, "+
4✔
3905
                        "ignoring outbound connection from local=%v, remote=%v",
4✔
3906
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
3907

4✔
3908
                if connReq != nil {
8✔
3909
                        s.connMgr.Remove(connReq.ID())
4✔
3910
                }
4✔
3911
                conn.Close()
4✔
3912
                return
4✔
3913
        }
3914
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
4✔
3915
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3916
                s.connMgr.Remove(connReq.ID())
×
3917
                conn.Close()
×
3918
                return
×
3919
        }
×
3920

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

×
3927
                if connReq != nil {
×
3928
                        s.connMgr.Remove(connReq.ID())
×
3929
                }
×
3930

3931
                conn.Close()
×
3932
                return
×
3933
        }
3934

3935
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
4✔
3936
                conn.RemoteAddr())
4✔
3937

4✔
3938
        if connReq != nil {
8✔
3939
                // A successful connection was returned by the connmgr.
4✔
3940
                // Immediately cancel all pending requests, excluding the
4✔
3941
                // outbound connection we just established.
4✔
3942
                ignore := connReq.ID()
4✔
3943
                s.cancelConnReqs(pubStr, &ignore)
4✔
3944
        } else {
8✔
3945
                // This was a successful connection made by some other
4✔
3946
                // subsystem. Remove all requests being managed by the connmgr.
4✔
3947
                s.cancelConnReqs(pubStr, nil)
4✔
3948
        }
4✔
3949

3950
        // If we already have a connection with this peer, decide whether or not
3951
        // we need to drop the stale connection. We forgo adding a default case
3952
        // as we expect these to be the only error values returned from
3953
        // findPeerByPubStr.
3954
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
3955
        switch err {
4✔
3956
        case ErrPeerNotConnected:
4✔
3957
                // We were unable to locate an existing connection with the
4✔
3958
                // target peer, proceed to connect.
4✔
3959
                s.peerConnected(conn, connReq, false)
4✔
3960

3961
        case nil:
×
3962
                // We already have a connection with the incoming peer. If the
×
3963
                // connection we've already established should be kept and is
×
3964
                // not of the same type of the new connection (outbound), then
×
3965
                // we'll close out the new connection s.t there's only a single
×
3966
                // connection between us.
×
3967
                localPub := s.identityECDH.PubKey()
×
3968
                if connectedPeer.Inbound() &&
×
3969
                        shouldDropLocalConnection(localPub, nodePub) {
×
3970

×
3971
                        srvrLog.Warnf("Established outbound connection to "+
×
3972
                                "peer %v, but already have inbound "+
×
3973
                                "connection, dropping conn", connectedPeer)
×
3974
                        if connReq != nil {
×
3975
                                s.connMgr.Remove(connReq.ID())
×
3976
                        }
×
3977
                        conn.Close()
×
3978
                        return
×
3979
                }
3980

3981
                // Otherwise, _their_ connection should be dropped. So we'll
3982
                // disconnect the peer and send the now obsolete peer to the
3983
                // server for garbage collection.
3984
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3985
                        connectedPeer)
×
3986

×
3987
                // Remove the current peer from the server's internal state and
×
3988
                // signal that the peer termination watcher does not need to
×
3989
                // execute for this peer.
×
3990
                s.removePeer(connectedPeer)
×
3991
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3992
                s.scheduledPeerConnection[pubStr] = func() {
×
3993
                        s.peerConnected(conn, connReq, false)
×
3994
                }
×
3995
        }
3996
}
3997

3998
// UnassignedConnID is the default connection ID that a request can have before
3999
// it actually is submitted to the connmgr.
4000
// TODO(conner): move into connmgr package, or better, add connmgr method for
4001
// generating atomic IDs
4002
const UnassignedConnID uint64 = 0
4003

4004
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4005
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4006
// Afterwards, each connection request removed from the connmgr. The caller can
4007
// optionally specify a connection ID to ignore, which prevents us from
4008
// canceling a successful request. All persistent connreqs for the provided
4009
// pubkey are discarded after the operationjw.
4010
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
4✔
4011
        // First, cancel any lingering persistent retry attempts, which will
4✔
4012
        // prevent retries for any with backoffs that are still maturing.
4✔
4013
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
8✔
4014
                close(cancelChan)
4✔
4015
                delete(s.persistentRetryCancels, pubStr)
4✔
4016
        }
4✔
4017

4018
        // Next, check to see if we have any outstanding persistent connection
4019
        // requests to this peer. If so, then we'll remove all of these
4020
        // connection requests, and also delete the entry from the map.
4021
        connReqs, ok := s.persistentConnReqs[pubStr]
4✔
4022
        if !ok {
8✔
4023
                return
4✔
4024
        }
4✔
4025

4026
        for _, connReq := range connReqs {
8✔
4027
                srvrLog.Tracef("Canceling %s:", connReqs)
4✔
4028

4✔
4029
                // Atomically capture the current request identifier.
4✔
4030
                connID := connReq.ID()
4✔
4031

4✔
4032
                // Skip any zero IDs, this indicates the request has not
4✔
4033
                // yet been schedule.
4✔
4034
                if connID == UnassignedConnID {
4✔
4035
                        continue
×
4036
                }
4037

4038
                // Skip a particular connection ID if instructed.
4039
                if skip != nil && connID == *skip {
8✔
4040
                        continue
4✔
4041
                }
4042

4043
                s.connMgr.Remove(connID)
4✔
4044
        }
4045

4046
        delete(s.persistentConnReqs, pubStr)
4✔
4047
}
4048

4049
// handleCustomMessage dispatches an incoming custom peers message to
4050
// subscribers.
4051
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
4✔
4052
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
4✔
4053
                peer, msg.Type)
4✔
4054

4✔
4055
        return s.customMessageServer.SendUpdate(&CustomMessage{
4✔
4056
                Peer: peer,
4✔
4057
                Msg:  msg,
4✔
4058
        })
4✔
4059
}
4✔
4060

4061
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4062
// messages.
4063
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
4✔
4064
        return s.customMessageServer.Subscribe()
4✔
4065
}
4✔
4066

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

4✔
4074
        brontideConn := conn.(*brontide.Conn)
4✔
4075
        addr := conn.RemoteAddr()
4✔
4076
        pubKey := brontideConn.RemotePub()
4✔
4077

4✔
4078
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
4✔
4079
                pubKey.SerializeCompressed(), addr, inbound)
4✔
4080

4✔
4081
        peerAddr := &lnwire.NetAddress{
4✔
4082
                IdentityKey: pubKey,
4✔
4083
                Address:     addr,
4✔
4084
                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
4085
        }
4✔
4086

4✔
4087
        // With the brontide connection established, we'll now craft the feature
4✔
4088
        // vectors to advertise to the remote node.
4✔
4089
        initFeatures := s.featureMgr.Get(feature.SetInit)
4✔
4090
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
4✔
4091

4✔
4092
        // Lookup past error caches for the peer in the server. If no buffer is
4✔
4093
        // found, create a fresh buffer.
4✔
4094
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
4✔
4095
        errBuffer, ok := s.peerErrors[pkStr]
4✔
4096
        if !ok {
8✔
4097
                var err error
4✔
4098
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
4✔
4099
                if err != nil {
4✔
4100
                        srvrLog.Errorf("unable to create peer %v", err)
×
4101
                        return
×
4102
                }
×
4103
        }
4104

4105
        // If we directly set the peer.Config TowerClient member to the
4106
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4107
        // the peer.Config's TowerClient member will not evaluate to nil even
4108
        // though the underlying value is nil. To avoid this gotcha which can
4109
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4110
        // TowerClient if needed.
4111
        var towerClient wtclient.ClientManager
4✔
4112
        if s.towerClientMgr != nil {
8✔
4113
                towerClient = s.towerClientMgr
4✔
4114
        }
4✔
4115

4116
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
4✔
4117
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
4118

4✔
4119
        // Now that we've established a connection, create a peer, and it to the
4✔
4120
        // set of currently active peers. Configure the peer with the incoming
4✔
4121
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
4✔
4122
        // offered that would trigger channel closure. In case of outgoing
4✔
4123
        // htlcs, an extra block is added to prevent the channel from being
4✔
4124
        // closed when the htlc is outstanding and a new block comes in.
4✔
4125
        pCfg := peer.Config{
4✔
4126
                Conn:                    brontideConn,
4✔
4127
                ConnReq:                 connReq,
4✔
4128
                Addr:                    peerAddr,
4✔
4129
                Inbound:                 inbound,
4✔
4130
                Features:                initFeatures,
4✔
4131
                LegacyFeatures:          legacyFeatures,
4✔
4132
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
4✔
4133
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
4✔
4134
                ErrorBuffer:             errBuffer,
4✔
4135
                WritePool:               s.writePool,
4✔
4136
                ReadPool:                s.readPool,
4✔
4137
                Switch:                  s.htlcSwitch,
4✔
4138
                InterceptSwitch:         s.interceptableSwitch,
4✔
4139
                ChannelDB:               s.chanStateDB,
4✔
4140
                ChannelGraph:            s.graphDB,
4✔
4141
                ChainArb:                s.chainArb,
4✔
4142
                AuthGossiper:            s.authGossiper,
4✔
4143
                ChanStatusMgr:           s.chanStatusMgr,
4✔
4144
                ChainIO:                 s.cc.ChainIO,
4✔
4145
                FeeEstimator:            s.cc.FeeEstimator,
4✔
4146
                Signer:                  s.cc.Wallet.Cfg.Signer,
4✔
4147
                SigPool:                 s.sigPool,
4✔
4148
                Wallet:                  s.cc.Wallet,
4✔
4149
                ChainNotifier:           s.cc.ChainNotifier,
4✔
4150
                BestBlockView:           s.cc.BestBlockTracker,
4✔
4151
                RoutingPolicy:           s.cc.RoutingPolicy,
4✔
4152
                Sphinx:                  s.sphinx,
4✔
4153
                WitnessBeacon:           s.witnessBeacon,
4✔
4154
                Invoices:                s.invoices,
4✔
4155
                ChannelNotifier:         s.channelNotifier,
4✔
4156
                HtlcNotifier:            s.htlcNotifier,
4✔
4157
                TowerClient:             towerClient,
4✔
4158
                DisconnectPeer:          s.DisconnectPeer,
4✔
4159
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
4✔
4160
                        lnwire.NodeAnnouncement, error) {
8✔
4161

4✔
4162
                        return s.genNodeAnnouncement(nil)
4✔
4163
                },
4✔
4164

4165
                PongBuf: s.pongBuf,
4166

4167
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4168

4169
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4170

4171
                FundingManager: s.fundingMgr,
4172

4173
                Hodl:                    s.cfg.Hodl,
4174
                UnsafeReplay:            s.cfg.UnsafeReplay,
4175
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4176
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4177
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4178
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4179
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4180
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4181
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4182
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4183
                HandleCustomMessage:    s.handleCustomMessage,
4184
                GetAliases:             s.aliasMgr.GetAliases,
4185
                RequestAlias:           s.aliasMgr.RequestAlias,
4186
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4187
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4188
                MaxFeeExposure:         thresholdMSats,
4189
                Quit:                   s.quit,
4190
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4191
                AuxSigner:              s.implCfg.AuxSigner,
4192
                MsgRouter:              s.implCfg.MsgRouter,
4193
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4194
                AuxResolver:            s.implCfg.AuxContractResolver,
4195
        }
4196

4197
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
4✔
4198
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
4✔
4199

4✔
4200
        p := peer.NewBrontide(pCfg)
4✔
4201

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

4✔
4205
        s.addPeer(p)
4✔
4206

4✔
4207
        // Once we have successfully added the peer to the server, we can
4✔
4208
        // delete the previous error buffer from the server's map of error
4✔
4209
        // buffers.
4✔
4210
        delete(s.peerErrors, pkStr)
4✔
4211

4✔
4212
        // Dispatch a goroutine to asynchronously start the peer. This process
4✔
4213
        // includes sending and receiving Init messages, which would be a DOS
4✔
4214
        // vector if we held the server's mutex throughout the procedure.
4✔
4215
        s.wg.Add(1)
4✔
4216
        go s.peerInitializer(p)
4✔
4217
}
4218

4219
// addPeer adds the passed peer to the server's global state of all active
4220
// peers.
4221
func (s *server) addPeer(p *peer.Brontide) {
4✔
4222
        if p == nil {
4✔
4223
                return
×
4224
        }
×
4225

4226
        pubBytes := p.IdentityKey().SerializeCompressed()
4✔
4227

4✔
4228
        // Ignore new peers if we're shutting down.
4✔
4229
        if s.Stopped() {
4✔
4230
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4231
                        pubBytes)
×
4232
                p.Disconnect(ErrServerShuttingDown)
×
4233

×
4234
                return
×
4235
        }
×
4236

4237
        // Track the new peer in our indexes so we can quickly look it up either
4238
        // according to its public key, or its peer ID.
4239
        // TODO(roasbeef): pipe all requests through to the
4240
        // queryHandler/peerManager
4241

4242
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4243
        // be human-readable.
4244
        pubStr := string(pubBytes)
4✔
4245

4✔
4246
        s.peersByPub[pubStr] = p
4✔
4247

4✔
4248
        if p.Inbound() {
8✔
4249
                s.inboundPeers[pubStr] = p
4✔
4250
        } else {
8✔
4251
                s.outboundPeers[pubStr] = p
4✔
4252
        }
4✔
4253

4254
        // Inform the peer notifier of a peer online event so that it can be reported
4255
        // to clients listening for peer events.
4256
        var pubKey [33]byte
4✔
4257
        copy(pubKey[:], pubBytes)
4✔
4258

4✔
4259
        s.peerNotifier.NotifyPeerOnline(pubKey)
4✔
4260
}
4261

4262
// peerInitializer asynchronously starts a newly connected peer after it has
4263
// been added to the server's peer map. This method sets up a
4264
// peerTerminationWatcher for the given peer, and ensures that it executes even
4265
// if the peer failed to start. In the event of a successful connection, this
4266
// method reads the negotiated, local feature-bits and spawns the appropriate
4267
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4268
// be signaled of the new peer once the method returns.
4269
//
4270
// NOTE: This MUST be launched as a goroutine.
4271
func (s *server) peerInitializer(p *peer.Brontide) {
4✔
4272
        defer s.wg.Done()
4✔
4273

4✔
4274
        pubBytes := p.IdentityKey().SerializeCompressed()
4✔
4275

4✔
4276
        // Avoid initializing peers while the server is exiting.
4✔
4277
        if s.Stopped() {
4✔
4278
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4279
                        pubBytes)
×
4280
                return
×
4281
        }
×
4282

4283
        // Create a channel that will be used to signal a successful start of
4284
        // the link. This prevents the peer termination watcher from beginning
4285
        // its duty too early.
4286
        ready := make(chan struct{})
4✔
4287

4✔
4288
        // Before starting the peer, launch a goroutine to watch for the
4✔
4289
        // unexpected termination of this peer, which will ensure all resources
4✔
4290
        // are properly cleaned up, and re-establish persistent connections when
4✔
4291
        // necessary. The peer termination watcher will be short circuited if
4✔
4292
        // the peer is ever added to the ignorePeerTermination map, indicating
4✔
4293
        // that the server has already handled the removal of this peer.
4✔
4294
        s.wg.Add(1)
4✔
4295
        go s.peerTerminationWatcher(p, ready)
4✔
4296

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

2✔
4302
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
2✔
4303
                return
2✔
4304
        }
2✔
4305

4306
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4307
        // was successful, and to begin watching the peer's wait group.
4308
        close(ready)
4✔
4309

4✔
4310
        s.mu.Lock()
4✔
4311
        defer s.mu.Unlock()
4✔
4312

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

4✔
4316
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
4✔
4317
        // route.Vertex as the key type of peerConnectedListeners.
4✔
4318
        pubStr := string(pubBytes)
4✔
4319
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
8✔
4320
                select {
4✔
4321
                case peerChan <- p:
4✔
UNCOV
4322
                case <-s.quit:
×
UNCOV
4323
                        return
×
4324
                }
4325
        }
4326
        delete(s.peerConnectedListeners, pubStr)
4✔
4327
}
4328

4329
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4330
// and then cleans up all resources allocated to the peer, notifies relevant
4331
// sub-systems of its demise, and finally handles re-connecting to the peer if
4332
// it's persistent. If the server intentionally disconnects a peer, it should
4333
// have a corresponding entry in the ignorePeerTermination map which will cause
4334
// the cleanup routine to exit early. The passed `ready` chan is used to
4335
// synchronize when WaitForDisconnect should begin watching on the peer's
4336
// waitgroup. The ready chan should only be signaled if the peer starts
4337
// successfully, otherwise the peer should be disconnected instead.
4338
//
4339
// NOTE: This MUST be launched as a goroutine.
4340
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
4✔
4341
        defer s.wg.Done()
4✔
4342

4✔
4343
        p.WaitForDisconnect(ready)
4✔
4344

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

4✔
4347
        // If the server is exiting then we can bail out early ourselves as all
4✔
4348
        // the other sub-systems will already be shutting down.
4✔
4349
        if s.Stopped() {
8✔
4350
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
4✔
4351
                return
4✔
4352
        }
4✔
4353

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

4✔
4360
        pubKey := p.IdentityKey()
4✔
4361

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

4✔
4366
        // Tell the switch to remove all links associated with this peer.
4✔
4367
        // Passing nil as the target link indicates that all links associated
4✔
4368
        // with this interface should be closed.
4✔
4369
        //
4✔
4370
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
4✔
4371
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
4✔
4372
        if err != nil && err != htlcswitch.ErrNoLinksFound {
4✔
4373
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4374
        }
×
4375

4376
        for _, link := range links {
8✔
4377
                s.htlcSwitch.RemoveLink(link.ChanID())
4✔
4378
        }
4✔
4379

4380
        s.mu.Lock()
4✔
4381
        defer s.mu.Unlock()
4✔
4382

4✔
4383
        // If there were any notification requests for when this peer
4✔
4384
        // disconnected, we can trigger them now.
4✔
4385
        srvrLog.Debugf("Notifying that peer %v is offline", p)
4✔
4386
        pubStr := string(pubKey.SerializeCompressed())
4✔
4387
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
8✔
4388
                close(offlineChan)
4✔
4389
        }
4✔
4390
        delete(s.peerDisconnectedListeners, pubStr)
4✔
4391

4✔
4392
        // If the server has already removed this peer, we can short circuit the
4✔
4393
        // peer termination watcher and skip cleanup.
4✔
4394
        if _, ok := s.ignorePeerTermination[p]; ok {
4✔
4395
                delete(s.ignorePeerTermination, p)
×
4396

×
4397
                pubKey := p.PubKey()
×
4398
                pubStr := string(pubKey[:])
×
4399

×
4400
                // If a connection callback is present, we'll go ahead and
×
4401
                // execute it now that previous peer has fully disconnected. If
×
4402
                // the callback is not present, this likely implies the peer was
×
4403
                // purposefully disconnected via RPC, and that no reconnect
×
4404
                // should be attempted.
×
4405
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4406
                if ok {
×
4407
                        delete(s.scheduledPeerConnection, pubStr)
×
4408
                        connCallback()
×
4409
                }
×
4410
                return
×
4411
        }
4412

4413
        // First, cleanup any remaining state the server has regarding the peer
4414
        // in question.
4415
        s.removePeer(p)
4✔
4416

4✔
4417
        // Next, check to see if this is a persistent peer or not.
4✔
4418
        if _, ok := s.persistentPeers[pubStr]; !ok {
8✔
4419
                return
4✔
4420
        }
4✔
4421

4422
        // Get the last address that we used to connect to the peer.
4423
        addrs := []net.Addr{
4✔
4424
                p.NetAddress().Address,
4✔
4425
        }
4✔
4426

4✔
4427
        // We'll ensure that we locate all the peers advertised addresses for
4✔
4428
        // reconnection purposes.
4✔
4429
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
4✔
4430
        switch {
4✔
4431
        // We found advertised addresses, so use them.
4432
        case err == nil:
4✔
4433
                addrs = advertisedAddrs
4✔
4434

4435
        // The peer doesn't have an advertised address.
4436
        case err == errNoAdvertisedAddr:
4✔
4437
                // If it is an outbound peer then we fall back to the existing
4✔
4438
                // peer address.
4✔
4439
                if !p.Inbound() {
8✔
4440
                        break
4✔
4441
                }
4442

4443
                // Fall back to the existing peer address if
4444
                // we're not accepting connections over Tor.
4445
                if s.torController == nil {
8✔
4446
                        break
4✔
4447
                }
4448

4449
                // If we are, the peer's address won't be known
4450
                // to us (we'll see a private address, which is
4451
                // the address used by our onion service to dial
4452
                // to lnd), so we don't have enough information
4453
                // to attempt a reconnect.
4454
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4455
                        "to inbound peer %v without "+
×
4456
                        "advertised address", p)
×
4457
                return
×
4458

4459
        // We came across an error retrieving an advertised
4460
        // address, log it, and fall back to the existing peer
4461
        // address.
4462
        default:
4✔
4463
                srvrLog.Errorf("Unable to retrieve advertised "+
4✔
4464
                        "address for node %x: %v", p.PubKey(),
4✔
4465
                        err)
4✔
4466
        }
4467

4468
        // Make an easy lookup map so that we can check if an address
4469
        // is already in the address list that we have stored for this peer.
4470
        existingAddrs := make(map[string]bool)
4✔
4471
        for _, addr := range s.persistentPeerAddrs[pubStr] {
8✔
4472
                existingAddrs[addr.String()] = true
4✔
4473
        }
4✔
4474

4475
        // Add any missing addresses for this peer to persistentPeerAddr.
4476
        for _, addr := range addrs {
8✔
4477
                if existingAddrs[addr.String()] {
4✔
4478
                        continue
×
4479
                }
4480

4481
                s.persistentPeerAddrs[pubStr] = append(
4✔
4482
                        s.persistentPeerAddrs[pubStr],
4✔
4483
                        &lnwire.NetAddress{
4✔
4484
                                IdentityKey: p.IdentityKey(),
4✔
4485
                                Address:     addr,
4✔
4486
                                ChainNet:    p.NetAddress().ChainNet,
4✔
4487
                        },
4✔
4488
                )
4✔
4489
        }
4490

4491
        // Record the computed backoff in the backoff map.
4492
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
4✔
4493
        s.persistentPeersBackoff[pubStr] = backoff
4✔
4494

4✔
4495
        // Initialize a retry canceller for this peer if one does not
4✔
4496
        // exist.
4✔
4497
        cancelChan, ok := s.persistentRetryCancels[pubStr]
4✔
4498
        if !ok {
8✔
4499
                cancelChan = make(chan struct{})
4✔
4500
                s.persistentRetryCancels[pubStr] = cancelChan
4✔
4501
        }
4✔
4502

4503
        // We choose not to wait group this go routine since the Connect
4504
        // call can stall for arbitrarily long if we shutdown while an
4505
        // outbound connection attempt is being made.
4506
        go func() {
8✔
4507
                srvrLog.Debugf("Scheduling connection re-establishment to "+
4✔
4508
                        "persistent peer %x in %s",
4✔
4509
                        p.IdentityKey().SerializeCompressed(), backoff)
4✔
4510

4✔
4511
                select {
4✔
4512
                case <-time.After(backoff):
4✔
4513
                case <-cancelChan:
4✔
4514
                        return
4✔
4515
                case <-s.quit:
4✔
4516
                        return
4✔
4517
                }
4518

4519
                srvrLog.Debugf("Attempting to re-establish persistent "+
4✔
4520
                        "connection to peer %x",
4✔
4521
                        p.IdentityKey().SerializeCompressed())
4✔
4522

4✔
4523
                s.connectToPersistentPeer(pubStr)
4✔
4524
        }()
4525
}
4526

4527
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4528
// to connect to the peer. It creates connection requests if there are
4529
// currently none for a given address and it removes old connection requests
4530
// if the associated address is no longer in the latest address list for the
4531
// peer.
4532
func (s *server) connectToPersistentPeer(pubKeyStr string) {
4✔
4533
        s.mu.Lock()
4✔
4534
        defer s.mu.Unlock()
4✔
4535

4✔
4536
        // Create an easy lookup map of the addresses we have stored for the
4✔
4537
        // peer. We will remove entries from this map if we have existing
4✔
4538
        // connection requests for the associated address and then any leftover
4✔
4539
        // entries will indicate which addresses we should create new
4✔
4540
        // connection requests for.
4✔
4541
        addrMap := make(map[string]*lnwire.NetAddress)
4✔
4542
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
8✔
4543
                addrMap[addr.String()] = addr
4✔
4544
        }
4✔
4545

4546
        // Go through each of the existing connection requests and
4547
        // check if they correspond to the latest set of addresses. If
4548
        // there is a connection requests that does not use one of the latest
4549
        // advertised addresses then remove that connection request.
4550
        var updatedConnReqs []*connmgr.ConnReq
4✔
4551
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
8✔
4552
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
4✔
4553

4✔
4554
                switch _, ok := addrMap[lnAddr]; ok {
4✔
4555
                // If the existing connection request is using one of the
4556
                // latest advertised addresses for the peer then we add it to
4557
                // updatedConnReqs and remove the associated address from
4558
                // addrMap so that we don't recreate this connReq later on.
4559
                case true:
×
4560
                        updatedConnReqs = append(
×
4561
                                updatedConnReqs, connReq,
×
4562
                        )
×
4563
                        delete(addrMap, lnAddr)
×
4564

4565
                // If the existing connection request is using an address that
4566
                // is not one of the latest advertised addresses for the peer
4567
                // then we remove the connecting request from the connection
4568
                // manager.
4569
                case false:
4✔
4570
                        srvrLog.Info(
4✔
4571
                                "Removing conn req:", connReq.Addr.String(),
4✔
4572
                        )
4✔
4573
                        s.connMgr.Remove(connReq.ID())
4✔
4574
                }
4575
        }
4576

4577
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
4✔
4578

4✔
4579
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
4✔
4580
        if !ok {
8✔
4581
                cancelChan = make(chan struct{})
4✔
4582
                s.persistentRetryCancels[pubKeyStr] = cancelChan
4✔
4583
        }
4✔
4584

4585
        // Any addresses left in addrMap are new ones that we have not made
4586
        // connection requests for. So create new connection requests for those.
4587
        // If there is more than one address in the address map, stagger the
4588
        // creation of the connection requests for those.
4589
        go func() {
8✔
4590
                ticker := time.NewTicker(multiAddrConnectionStagger)
4✔
4591
                defer ticker.Stop()
4✔
4592

4✔
4593
                for _, addr := range addrMap {
8✔
4594
                        // Send the persistent connection request to the
4✔
4595
                        // connection manager, saving the request itself so we
4✔
4596
                        // can cancel/restart the process as needed.
4✔
4597
                        connReq := &connmgr.ConnReq{
4✔
4598
                                Addr:      addr,
4✔
4599
                                Permanent: true,
4✔
4600
                        }
4✔
4601

4✔
4602
                        s.mu.Lock()
4✔
4603
                        s.persistentConnReqs[pubKeyStr] = append(
4✔
4604
                                s.persistentConnReqs[pubKeyStr], connReq,
4✔
4605
                        )
4✔
4606
                        s.mu.Unlock()
4✔
4607

4✔
4608
                        srvrLog.Debugf("Attempting persistent connection to "+
4✔
4609
                                "channel peer %v", addr)
4✔
4610

4✔
4611
                        go s.connMgr.Connect(connReq)
4✔
4612

4✔
4613
                        select {
4✔
4614
                        case <-s.quit:
4✔
4615
                                return
4✔
4616
                        case <-cancelChan:
4✔
4617
                                return
4✔
4618
                        case <-ticker.C:
4✔
4619
                        }
4620
                }
4621
        }()
4622
}
4623

4624
// removePeer removes the passed peer from the server's state of all active
4625
// peers.
4626
func (s *server) removePeer(p *peer.Brontide) {
4✔
4627
        if p == nil {
4✔
4628
                return
×
4629
        }
×
4630

4631
        srvrLog.Debugf("removing peer %v", p)
4✔
4632

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

4✔
4637
        // If this peer had an active persistent connection request, remove it.
4✔
4638
        if p.ConnReq() != nil {
8✔
4639
                s.connMgr.Remove(p.ConnReq().ID())
4✔
4640
        }
4✔
4641

4642
        // Ignore deleting peers if we're shutting down.
4643
        if s.Stopped() {
4✔
4644
                return
×
4645
        }
×
4646

4647
        pKey := p.PubKey()
4✔
4648
        pubSer := pKey[:]
4✔
4649
        pubStr := string(pubSer)
4✔
4650

4✔
4651
        delete(s.peersByPub, pubStr)
4✔
4652

4✔
4653
        if p.Inbound() {
8✔
4654
                delete(s.inboundPeers, pubStr)
4✔
4655
        } else {
8✔
4656
                delete(s.outboundPeers, pubStr)
4✔
4657
        }
4✔
4658

4659
        // Copy the peer's error buffer across to the server if it has any items
4660
        // in it so that we can restore peer errors across connections.
4661
        if p.ErrorBuffer().Total() > 0 {
8✔
4662
                s.peerErrors[pubStr] = p.ErrorBuffer()
4✔
4663
        }
4✔
4664

4665
        // Inform the peer notifier of a peer offline event so that it can be
4666
        // reported to clients listening for peer events.
4667
        var pubKey [33]byte
4✔
4668
        copy(pubKey[:], pubSer)
4✔
4669

4✔
4670
        s.peerNotifier.NotifyPeerOffline(pubKey)
4✔
4671
}
4672

4673
// ConnectToPeer requests that the server connect to a Lightning Network peer
4674
// at the specified address. This function will *block* until either a
4675
// connection is established, or the initial handshake process fails.
4676
//
4677
// NOTE: This function is safe for concurrent access.
4678
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4679
        perm bool, timeout time.Duration) error {
4✔
4680

4✔
4681
        targetPub := string(addr.IdentityKey.SerializeCompressed())
4✔
4682

4✔
4683
        // Acquire mutex, but use explicit unlocking instead of defer for
4✔
4684
        // better granularity.  In certain conditions, this method requires
4✔
4685
        // making an outbound connection to a remote peer, which requires the
4✔
4686
        // lock to be released, and subsequently reacquired.
4✔
4687
        s.mu.Lock()
4✔
4688

4✔
4689
        // Ensure we're not already connected to this peer.
4✔
4690
        peer, err := s.findPeerByPubStr(targetPub)
4✔
4691
        if err == nil {
8✔
4692
                s.mu.Unlock()
4✔
4693
                return &errPeerAlreadyConnected{peer: peer}
4✔
4694
        }
4✔
4695

4696
        // Peer was not found, continue to pursue connection with peer.
4697

4698
        // If there's already a pending connection request for this pubkey,
4699
        // then we ignore this request to ensure we don't create a redundant
4700
        // connection.
4701
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
8✔
4702
                srvrLog.Warnf("Already have %d persistent connection "+
4✔
4703
                        "requests for %v, connecting anyway.", len(reqs), addr)
4✔
4704
        }
4✔
4705

4706
        // If there's not already a pending or active connection to this node,
4707
        // then instruct the connection manager to attempt to establish a
4708
        // persistent connection to the peer.
4709
        srvrLog.Debugf("Connecting to %v", addr)
4✔
4710
        if perm {
8✔
4711
                connReq := &connmgr.ConnReq{
4✔
4712
                        Addr:      addr,
4✔
4713
                        Permanent: true,
4✔
4714
                }
4✔
4715

4✔
4716
                // Since the user requested a permanent connection, we'll set
4✔
4717
                // the entry to true which will tell the server to continue
4✔
4718
                // reconnecting even if the number of channels with this peer is
4✔
4719
                // zero.
4✔
4720
                s.persistentPeers[targetPub] = true
4✔
4721
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
8✔
4722
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
4✔
4723
                }
4✔
4724
                s.persistentConnReqs[targetPub] = append(
4✔
4725
                        s.persistentConnReqs[targetPub], connReq,
4✔
4726
                )
4✔
4727
                s.mu.Unlock()
4✔
4728

4✔
4729
                go s.connMgr.Connect(connReq)
4✔
4730

4✔
4731
                return nil
4✔
4732
        }
4733
        s.mu.Unlock()
4✔
4734

4✔
4735
        // If we're not making a persistent connection, then we'll attempt to
4✔
4736
        // connect to the target peer. If the we can't make the connection, or
4✔
4737
        // the crypto negotiation breaks down, then return an error to the
4✔
4738
        // caller.
4✔
4739
        errChan := make(chan error, 1)
4✔
4740
        s.connectToPeer(addr, errChan, timeout)
4✔
4741

4✔
4742
        select {
4✔
4743
        case err := <-errChan:
4✔
4744
                return err
4✔
4745
        case <-s.quit:
×
4746
                return ErrServerShuttingDown
×
4747
        }
4748
}
4749

4750
// connectToPeer establishes a connection to a remote peer. errChan is used to
4751
// notify the caller if the connection attempt has failed. Otherwise, it will be
4752
// closed.
4753
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4754
        errChan chan<- error, timeout time.Duration) {
4✔
4755

4✔
4756
        conn, err := brontide.Dial(
4✔
4757
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
4✔
4758
        )
4✔
4759
        if err != nil {
8✔
4760
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
4✔
4761
                select {
4✔
4762
                case errChan <- err:
4✔
4763
                case <-s.quit:
×
4764
                }
4765
                return
4✔
4766
        }
4767

4768
        close(errChan)
4✔
4769

4✔
4770
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
4✔
4771
                conn.LocalAddr(), conn.RemoteAddr())
4✔
4772

4✔
4773
        s.OutboundPeerConnected(nil, conn)
4✔
4774
}
4775

4776
// DisconnectPeer sends the request to server to close the connection with peer
4777
// identified by public key.
4778
//
4779
// NOTE: This function is safe for concurrent access.
4780
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
4✔
4781
        pubBytes := pubKey.SerializeCompressed()
4✔
4782
        pubStr := string(pubBytes)
4✔
4783

4✔
4784
        s.mu.Lock()
4✔
4785
        defer s.mu.Unlock()
4✔
4786

4✔
4787
        // Check that were actually connected to this peer. If not, then we'll
4✔
4788
        // exit in an error as we can't disconnect from a peer that we're not
4✔
4789
        // currently connected to.
4✔
4790
        peer, err := s.findPeerByPubStr(pubStr)
4✔
4791
        if err == ErrPeerNotConnected {
8✔
4792
                return fmt.Errorf("peer %x is not connected", pubBytes)
4✔
4793
        }
4✔
4794

4795
        srvrLog.Infof("Disconnecting from %v", peer)
4✔
4796

4✔
4797
        s.cancelConnReqs(pubStr, nil)
4✔
4798

4✔
4799
        // If this peer was formerly a persistent connection, then we'll remove
4✔
4800
        // them from this map so we don't attempt to re-connect after we
4✔
4801
        // disconnect.
4✔
4802
        delete(s.persistentPeers, pubStr)
4✔
4803
        delete(s.persistentPeersBackoff, pubStr)
4✔
4804

4✔
4805
        // Remove the peer by calling Disconnect. Previously this was done with
4✔
4806
        // removePeer, which bypassed the peerTerminationWatcher.
4✔
4807
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
4✔
4808

4✔
4809
        return nil
4✔
4810
}
4811

4812
// OpenChannel sends a request to the server to open a channel to the specified
4813
// peer identified by nodeKey with the passed channel funding parameters.
4814
//
4815
// NOTE: This function is safe for concurrent access.
4816
func (s *server) OpenChannel(
4817
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
4✔
4818

4✔
4819
        // The updateChan will have a buffer of 2, since we expect a ChanPending
4✔
4820
        // + a ChanOpen update, and we want to make sure the funding process is
4✔
4821
        // not blocked if the caller is not reading the updates.
4✔
4822
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
4✔
4823
        req.Err = make(chan error, 1)
4✔
4824

4✔
4825
        // First attempt to locate the target peer to open a channel with, if
4✔
4826
        // we're unable to locate the peer then this request will fail.
4✔
4827
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
4✔
4828
        s.mu.RLock()
4✔
4829
        peer, ok := s.peersByPub[string(pubKeyBytes)]
4✔
4830
        if !ok {
4✔
4831
                s.mu.RUnlock()
×
4832

×
4833
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4834
                return req.Updates, req.Err
×
4835
        }
×
4836
        req.Peer = peer
4✔
4837
        s.mu.RUnlock()
4✔
4838

4✔
4839
        // We'll wait until the peer is active before beginning the channel
4✔
4840
        // opening process.
4✔
4841
        select {
4✔
4842
        case <-peer.ActiveSignal():
4✔
4843
        case <-peer.QuitSignal():
×
4844
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4845
                return req.Updates, req.Err
×
4846
        case <-s.quit:
×
4847
                req.Err <- ErrServerShuttingDown
×
4848
                return req.Updates, req.Err
×
4849
        }
4850

4851
        // If the fee rate wasn't specified at this point we fail the funding
4852
        // because of the missing fee rate information. The caller of the
4853
        // `OpenChannel` method needs to make sure that default values for the
4854
        // fee rate are set beforehand.
4855
        if req.FundingFeePerKw == 0 {
4✔
4856
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4857
                        "the channel opening transaction")
×
4858

×
4859
                return req.Updates, req.Err
×
4860
        }
×
4861

4862
        // Spawn a goroutine to send the funding workflow request to the funding
4863
        // manager. This allows the server to continue handling queries instead
4864
        // of blocking on this request which is exported as a synchronous
4865
        // request to the outside world.
4866
        go s.fundingMgr.InitFundingWorkflow(req)
4✔
4867

4✔
4868
        return req.Updates, req.Err
4✔
4869
}
4870

4871
// Peers returns a slice of all active peers.
4872
//
4873
// NOTE: This function is safe for concurrent access.
4874
func (s *server) Peers() []*peer.Brontide {
4✔
4875
        s.mu.RLock()
4✔
4876
        defer s.mu.RUnlock()
4✔
4877

4✔
4878
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
4879
        for _, peer := range s.peersByPub {
8✔
4880
                peers = append(peers, peer)
4✔
4881
        }
4✔
4882

4883
        return peers
4✔
4884
}
4885

4886
// computeNextBackoff uses a truncated exponential backoff to compute the next
4887
// backoff using the value of the exiting backoff. The returned duration is
4888
// randomized in either direction by 1/20 to prevent tight loops from
4889
// stabilizing.
4890
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
4✔
4891
        // Double the current backoff, truncating if it exceeds our maximum.
4✔
4892
        nextBackoff := 2 * currBackoff
4✔
4893
        if nextBackoff > maxBackoff {
8✔
4894
                nextBackoff = maxBackoff
4✔
4895
        }
4✔
4896

4897
        // Using 1/10 of our duration as a margin, compute a random offset to
4898
        // avoid the nodes entering connection cycles.
4899
        margin := nextBackoff / 10
4✔
4900

4✔
4901
        var wiggle big.Int
4✔
4902
        wiggle.SetUint64(uint64(margin))
4✔
4903
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
4✔
4904
                // Randomizing is not mission critical, so we'll just return the
×
4905
                // current backoff.
×
4906
                return nextBackoff
×
4907
        }
×
4908

4909
        // Otherwise add in our wiggle, but subtract out half of the margin so
4910
        // that the backoff can tweaked by 1/20 in either direction.
4911
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
4✔
4912
}
4913

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

4918
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4919
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
4✔
4920
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
4✔
4921
        if err != nil {
4✔
4922
                return nil, err
×
4923
        }
×
4924

4925
        node, err := s.graphDB.FetchLightningNode(vertex)
4✔
4926
        if err != nil {
8✔
4927
                return nil, err
4✔
4928
        }
4✔
4929

4930
        if len(node.Addresses) == 0 {
8✔
4931
                return nil, errNoAdvertisedAddr
4✔
4932
        }
4✔
4933

4934
        return node.Addresses, nil
4✔
4935
}
4936

4937
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4938
// channel update for a target channel.
4939
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4940
        *lnwire.ChannelUpdate1, error) {
4✔
4941

4✔
4942
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
4✔
4943
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
8✔
4944
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
4✔
4945
                if err != nil {
8✔
4946
                        return nil, err
4✔
4947
                }
4✔
4948

4949
                return netann.ExtractChannelUpdate(
4✔
4950
                        ourPubKey[:], info, edge1, edge2,
4✔
4951
                )
4✔
4952
        }
4953
}
4954

4955
// applyChannelUpdate applies the channel update to the different sub-systems of
4956
// the server. The useAlias boolean denotes whether or not to send an alias in
4957
// place of the real SCID.
4958
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
4959
        op *wire.OutPoint, useAlias bool) error {
4✔
4960

4✔
4961
        var (
4✔
4962
                peerAlias    *lnwire.ShortChannelID
4✔
4963
                defaultAlias lnwire.ShortChannelID
4✔
4964
        )
4✔
4965

4✔
4966
        chanID := lnwire.NewChanIDFromOutPoint(*op)
4✔
4967

4✔
4968
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
4✔
4969
        // in the ChannelUpdate if it hasn't been announced yet.
4✔
4970
        if useAlias {
8✔
4971
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
4✔
4972
                if foundAlias != defaultAlias {
8✔
4973
                        peerAlias = &foundAlias
4✔
4974
                }
4✔
4975
        }
4976

4977
        errChan := s.authGossiper.ProcessLocalAnnouncement(
4✔
4978
                update, discovery.RemoteAlias(peerAlias),
4✔
4979
        )
4✔
4980
        select {
4✔
4981
        case err := <-errChan:
4✔
4982
                return err
4✔
4983
        case <-s.quit:
×
4984
                return ErrServerShuttingDown
×
4985
        }
4986
}
4987

4988
// SendCustomMessage sends a custom message to the peer with the specified
4989
// pubkey.
4990
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
4991
        data []byte) error {
4✔
4992

4✔
4993
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
4✔
4994
        if err != nil {
4✔
4995
                return err
×
4996
        }
×
4997

4998
        // We'll wait until the peer is active.
4999
        select {
4✔
5000
        case <-peer.ActiveSignal():
4✔
5001
        case <-peer.QuitSignal():
×
5002
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5003
        case <-s.quit:
×
5004
                return ErrServerShuttingDown
×
5005
        }
5006

5007
        msg, err := lnwire.NewCustom(msgType, data)
4✔
5008
        if err != nil {
8✔
5009
                return err
4✔
5010
        }
4✔
5011

5012
        // Send the message as low-priority. For now we assume that all
5013
        // application-defined message are low priority.
5014
        return peer.SendMessageLazy(true, msg)
4✔
5015
}
5016

5017
// newSweepPkScriptGen creates closure that generates a new public key script
5018
// which should be used to sweep any funds into the on-chain wallet.
5019
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5020
// (p2wkh) output.
5021
func newSweepPkScriptGen(
5022
        wallet lnwallet.WalletController,
5023
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
4✔
5024

4✔
5025
        return func() fn.Result[lnwallet.AddrWithKey] {
8✔
5026
                sweepAddr, err := wallet.NewAddress(
4✔
5027
                        lnwallet.TaprootPubkey, false,
4✔
5028
                        lnwallet.DefaultAccountName,
4✔
5029
                )
4✔
5030
                if err != nil {
4✔
5031
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5032
                }
×
5033

5034
                addr, err := txscript.PayToAddrScript(sweepAddr)
4✔
5035
                if err != nil {
4✔
5036
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5037
                }
×
5038

5039
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
4✔
5040
                        wallet, netParams, addr,
4✔
5041
                )
4✔
5042
                if err != nil {
4✔
5043
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5044
                }
×
5045

5046
                return fn.Ok(lnwallet.AddrWithKey{
4✔
5047
                        DeliveryAddress: addr,
4✔
5048
                        InternalKey:     internalKeyDesc,
4✔
5049
                })
4✔
5050
        }
5051
}
5052

5053
// shouldPeerBootstrap returns true if we should attempt to perform peer
5054
// bootstrapping to actively seek our peers using the set of active network
5055
// bootstrappers.
5056
func shouldPeerBootstrap(cfg *Config) bool {
10✔
5057
        isSimnet := cfg.Bitcoin.SimNet
10✔
5058
        isSignet := cfg.Bitcoin.SigNet
10✔
5059
        isRegtest := cfg.Bitcoin.RegTest
10✔
5060
        isDevNetwork := isSimnet || isSignet || isRegtest
10✔
5061

10✔
5062
        // TODO(yy): remove the check on simnet/regtest such that the itest is
10✔
5063
        // covering the bootstrapping process.
10✔
5064
        return !cfg.NoNetBootstrap && !isDevNetwork
10✔
5065
}
10✔
5066

5067
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5068
// finished.
5069
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
4✔
5070
        // Get a list of closed channels.
4✔
5071
        channels, err := s.chanStateDB.FetchClosedChannels(false)
4✔
5072
        if err != nil {
4✔
5073
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5074
                return nil
×
5075
        }
×
5076

5077
        // Save the SCIDs in a map.
5078
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
4✔
5079
        for _, c := range channels {
8✔
5080
                // If the channel is not pending, its FC has been finalized.
4✔
5081
                if !c.IsPending {
8✔
5082
                        closedSCIDs[c.ShortChanID] = struct{}{}
4✔
5083
                }
4✔
5084
        }
5085

5086
        // Double check whether the reported closed channel has indeed finished
5087
        // closing.
5088
        //
5089
        // NOTE: There are misalignments regarding when a channel's FC is
5090
        // marked as finalized. We double check the pending channels to make
5091
        // sure the returned SCIDs are indeed terminated.
5092
        //
5093
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5094
        pendings, err := s.chanStateDB.FetchPendingChannels()
4✔
5095
        if err != nil {
4✔
5096
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5097
                return nil
×
5098
        }
×
5099

5100
        for _, c := range pendings {
8✔
5101
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
8✔
5102
                        continue
4✔
5103
                }
5104

5105
                // If the channel is still reported as pending, remove it from
5106
                // the map.
5107
                delete(closedSCIDs, c.ShortChannelID)
×
5108

×
5109
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5110
                        c.ShortChannelID)
×
5111
        }
5112

5113
        return closedSCIDs
4✔
5114
}
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