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

lightningnetwork / lnd / 11954540049

21 Nov 2024 01:46PM UTC coverage: 58.98% (+0.2%) from 58.776%
11954540049

push

github

web-flow
Merge pull request #9291 from yyforyongyu/fix-log-unit

lnwallet: log the amounts in the same unit

23 of 25 new or added lines in 1 file covered. (92.0%)

73 existing lines in 14 files now uncovered.

132825 of 225202 relevant lines covered (58.98%)

19603.57 hits per line

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

63.61
/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 {
5✔
1242
                                        return err
1✔
1243
                                }
1✔
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.graphBuilder.Stop(); err != nil {
4✔
2485
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2486
                }
×
2487
                if err := s.chainArb.Stop(); err != nil {
4✔
2488
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2489
                }
×
2490
                if err := s.fundingMgr.Stop(); err != nil {
4✔
2491
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2492
                }
×
2493
                if err := s.breachArbitrator.Stop(); err != nil {
4✔
2494
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2495
                                err)
×
2496
                }
×
2497
                if err := s.utxoNursery.Stop(); err != nil {
4✔
2498
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2499
                }
×
2500
                if err := s.authGossiper.Stop(); err != nil {
4✔
2501
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2502
                }
×
2503
                if err := s.sweeper.Stop(); err != nil {
4✔
2504
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2505
                }
×
2506
                if err := s.txPublisher.Stop(); err != nil {
4✔
2507
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2508
                }
×
2509
                if err := s.channelNotifier.Stop(); err != nil {
4✔
2510
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2511
                }
×
2512
                if err := s.peerNotifier.Stop(); err != nil {
4✔
2513
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2514
                }
×
2515
                if err := s.htlcNotifier.Stop(); err != nil {
4✔
2516
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2517
                }
×
2518

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

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

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

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

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

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

2588
                // Wait for all lingering goroutines to quit.
2589
                srvrLog.Debug("Waiting for server to shutdown...")
4✔
2590
                s.wg.Wait()
4✔
2591

4✔
2592
                srvrLog.Debug("Stopping buffer pools...")
4✔
2593
                s.sigPool.Stop()
4✔
2594
                s.writePool.Stop()
4✔
2595
                s.readPool.Stop()
4✔
2596
        })
2597

2598
        return nil
4✔
2599
}
2600

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

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

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

2626
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2627
                externalIPs = append(externalIPs, hostIP)
×
2628
        }
2629

2630
        return externalIPs, nil
×
2631
}
2632

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

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

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

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

2668
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2669

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

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

2700
                        if ip.Equal(s.lastDetectedIP) {
×
2701
                                continue
×
2702
                        }
2703

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

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

2721
                                newAddrs = append(newAddrs, addr)
×
2722
                        }
2723

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

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

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

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

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

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

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

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

×
2790
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2791

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

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

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

×
2813
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2814
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2815
                        )
×
2816
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2817
                }
×
2818
        }
2819

2820
        return bootStrappers, nil
×
2821
}
2822

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

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

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

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

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

2853
        return ignore
×
2854
}
2855

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

×
2864
        defer s.wg.Done()
×
2865

×
2866
        // Before we continue, init the ignore peers map.
×
2867
        ignoreList := s.createBootstrapIgnorePeers()
×
2868

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

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

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

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

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

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

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

2914
                        if epochAttempts > 0 &&
×
2915
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2916

×
2917
                                sampleTicker.Stop()
×
2918

×
2919
                                backOff *= 2
×
2920
                                if backOff > bootstrapBackOffCeiling {
×
2921
                                        backOff = bootstrapBackOffCeiling
×
2922
                                }
×
2923

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

2930
                        atomic.StoreUint32(&epochErrors, 0)
×
2931
                        epochAttempts = 0
×
2932

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

×
2937
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2938
                                "peers", numNeeded)
×
2939

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

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

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

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

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

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

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

×
3002
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3003
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3004

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

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

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

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

×
3027
                if numActivePeers >= numTargetPeers {
×
3028
                        return
×
3029
                }
×
3030

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

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

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

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

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

×
3074
                                errChan := make(chan error, 1)
×
3075
                                go s.connectToPeer(
×
3076
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3077
                                )
×
3078

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

3102
                wg.Wait()
×
3103
        }
3104
}
3105

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

3118
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3119
        if err != nil {
×
3120
                return err
×
3121
        }
×
3122

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

×
3135
        switch {
×
3136
        case s.cfg.Tor.V2:
×
3137
                onionCfg.Type = tor.V2
×
3138
        case s.cfg.Tor.V3:
×
3139
                onionCfg.Type = tor.V3
×
3140
        }
3141

3142
        addr, err := s.torController.AddOnion(onionCfg)
×
3143
        if err != nil {
×
3144
                return err
×
3145
        }
×
3146

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

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

3177
        return nil
×
3178
}
3179

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

4✔
3186
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
4✔
3187
        if err != nil {
4✔
3188
                return nil, err
×
3189
        }
×
3190

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

3197
        return nil, fmt.Errorf("unable to find channel")
4✔
3198
}
3199

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

4✔
3205
        return *s.currentNodeAnn
4✔
3206
}
4✔
3207

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

4✔
3214
        s.mu.Lock()
4✔
3215
        defer s.mu.Unlock()
4✔
3216

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

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

3236
        // Always update the timestamp when refreshing to ensure the update
3237
        // propagates.
3238
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
4✔
3239

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

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

3253
        return *s.currentNodeAnn, nil
4✔
3254
}
3255

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

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

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

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

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

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

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

3299
        return nil
4✔
3300
}
3301

3302
type nodeAddresses struct {
3303
        pubKey    *btcec.PublicKey
3304
        addresses []net.Addr
3305
}
3306

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

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

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

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

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

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

3368
                pubStr := string(channelPeer.PubKeyBytes[:])
4✔
3369

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

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

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

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

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

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

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

3428
        srvrLog.Debugf("Establishing %v persistent connections on start",
4✔
3429
                len(nodeAddrsMap))
4✔
3430

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

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

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

4✔
3459
                        s.persistentPeerAddrs[pubStr] = append(
4✔
3460
                                s.persistentPeerAddrs[pubStr], lnAddr)
4✔
3461
                }
4✔
3462

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

4✔
3473
                        go s.connectToPersistentPeer(pubStr)
4✔
3474
                } else {
4✔
3475
                        go s.delayInitialReconnect(pubStr)
×
3476
                }
×
3477

3478
                numOutboundConns++
4✔
3479
        }
3480

3481
        return nil
4✔
3482
}
3483

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

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

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

4✔
3511
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
4✔
3512
                        "peer has no open channels", compressedPubKey)
4✔
3513

4✔
3514
                return
4✔
3515
        }
4✔
3516
        s.mu.Unlock()
4✔
3517
}
3518

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

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

3542
                peers = append(peers, sPeer)
4✔
3543
        }
3544
        s.mu.RUnlock()
4✔
3545

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

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

4✔
3560
                        p.SendMessageLazy(false, msgs...)
4✔
3561
                }(sPeer)
4✔
3562
        }
3563

3564
        // Wait for all messages to have been dispatched before returning to
3565
        // caller.
3566
        wg.Wait()
4✔
3567

4✔
3568
        return nil
4✔
3569
}
3570

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

4✔
3578
        s.mu.Lock()
4✔
3579

4✔
3580
        // Compute the target peer's identifier.
4✔
3581
        pubStr := string(peerKey[:])
4✔
3582

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

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

3605
                // Connected, can return early.
3606
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
4✔
3607

4✔
3608
                select {
4✔
3609
                case peerChan <- peer:
4✔
3610
                case <-s.quit:
×
3611
                }
3612

3613
                return
4✔
3614
        }
3615

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

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

4✔
3631
        c := make(chan struct{})
4✔
3632

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

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

4✔
3649
        return c
4✔
3650
}
3651

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

4✔
3661
        pubStr := string(peerKey.SerializeCompressed())
4✔
3662

4✔
3663
        return s.findPeerByPubStr(pubStr)
4✔
3664
}
4✔
3665

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

4✔
3675
        return s.findPeerByPubStr(pubStr)
4✔
3676
}
4✔
3677

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

3686
        return peer, nil
4✔
3687
}
3688

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

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

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

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

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

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

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

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

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

3761
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3762
        pubSer := nodePub.SerializeCompressed()
4✔
3763
        pubStr := string(pubSer)
4✔
3764

4✔
3765
        var pubBytes [33]byte
4✔
3766
        copy(pubBytes[:], pubSer)
4✔
3767

4✔
3768
        s.mu.Lock()
4✔
3769
        defer s.mu.Unlock()
4✔
3770

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

×
3778
                return
×
3779
        }
×
3780

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

×
3785
                conn.Close()
×
3786

×
3787
                return
×
3788
        }
×
3789

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

4✔
3797
                conn.Close()
4✔
3798
                return
4✔
3799
        }
4✔
3800

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

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

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

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

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

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

×
3848
                s.cancelConnReqs(pubStr, nil)
×
3849

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

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

3871
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3872
        pubSer := nodePub.SerializeCompressed()
4✔
3873
        pubStr := string(pubSer)
4✔
3874

4✔
3875
        var pubBytes [33]byte
4✔
3876
        copy(pubBytes[:], pubSer)
4✔
3877

4✔
3878
        s.mu.Lock()
4✔
3879
        defer s.mu.Unlock()
4✔
3880

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

×
3888
                return
×
3889
        }
×
3890

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

×
3895
                if connReq != nil {
×
3896
                        s.connMgr.Remove(connReq.ID())
×
3897
                }
×
3898

3899
                conn.Close()
×
3900

×
3901
                return
×
3902
        }
3903

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

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

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

×
3930
                if connReq != nil {
×
3931
                        s.connMgr.Remove(connReq.ID())
×
3932
                }
×
3933

3934
                conn.Close()
×
3935
                return
×
3936
        }
3937

3938
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
4✔
3939
                conn.RemoteAddr())
4✔
3940

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

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

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

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

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

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

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

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

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

4029
        for _, connReq := range connReqs {
8✔
4030
                srvrLog.Tracef("Canceling %s:", connReqs)
4✔
4031

4✔
4032
                // Atomically capture the current request identifier.
4✔
4033
                connID := connReq.ID()
4✔
4034

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

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

4046
                s.connMgr.Remove(connID)
4✔
4047
        }
4048

4049
        delete(s.persistentConnReqs, pubStr)
4✔
4050
}
4051

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

4✔
4058
        return s.customMessageServer.SendUpdate(&CustomMessage{
4✔
4059
                Peer: peer,
4✔
4060
                Msg:  msg,
4✔
4061
        })
4✔
4062
}
4✔
4063

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

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

4✔
4077
        brontideConn := conn.(*brontide.Conn)
4✔
4078
        addr := conn.RemoteAddr()
4✔
4079
        pubKey := brontideConn.RemotePub()
4✔
4080

4✔
4081
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
4✔
4082
                pubKey.SerializeCompressed(), addr, inbound)
4✔
4083

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

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

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

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

4119
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
4✔
4120
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
4121

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

4✔
4165
                        return s.genNodeAnnouncement(nil)
4✔
4166
                },
4✔
4167

4168
                PongBuf: s.pongBuf,
4169

4170
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4171

4172
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4173

4174
                FundingManager: s.fundingMgr,
4175

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

4200
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
4✔
4201
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
4✔
4202

4✔
4203
        p := peer.NewBrontide(pCfg)
4✔
4204

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

4✔
4208
        s.addPeer(p)
4✔
4209

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

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

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

4229
        pubBytes := p.IdentityKey().SerializeCompressed()
4✔
4230

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

×
4237
                return
×
4238
        }
×
4239

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

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

4✔
4249
        s.peersByPub[pubStr] = p
4✔
4250

4✔
4251
        if p.Inbound() {
8✔
4252
                s.inboundPeers[pubStr] = p
4✔
4253
        } else {
8✔
4254
                s.outboundPeers[pubStr] = p
4✔
4255
        }
4✔
4256

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

4✔
4262
        s.peerNotifier.NotifyPeerOnline(pubKey)
4✔
4263
}
4264

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

4✔
4277
        pubBytes := p.IdentityKey().SerializeCompressed()
4✔
4278

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

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

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

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

2✔
4305
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
2✔
4306
                return
2✔
4307
        }
2✔
4308

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

4✔
4313
        s.mu.Lock()
4✔
4314
        defer s.mu.Unlock()
4✔
4315

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

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

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

4✔
4346
        p.WaitForDisconnect(ready)
4✔
4347

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

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

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

4✔
4363
        pubKey := p.IdentityKey()
4✔
4364

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

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

4379
        for _, link := range links {
8✔
4380
                s.htlcSwitch.RemoveLink(link.ChanID())
4✔
4381
        }
4✔
4382

4383
        s.mu.Lock()
4✔
4384
        defer s.mu.Unlock()
4✔
4385

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

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

×
4400
                pubKey := p.PubKey()
×
4401
                pubStr := string(pubKey[:])
×
4402

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

4416
        // First, cleanup any remaining state the server has regarding the peer
4417
        // in question.
4418
        s.removePeer(p)
4✔
4419

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
4526
                s.connectToPersistentPeer(pubStr)
4✔
4527
        }()
4528
}
4529

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

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

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

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

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

4580
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
4✔
4581

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

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

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

4✔
4605
                        s.mu.Lock()
4✔
4606
                        s.persistentConnReqs[pubKeyStr] = append(
4✔
4607
                                s.persistentConnReqs[pubKeyStr], connReq,
4✔
4608
                        )
4✔
4609
                        s.mu.Unlock()
4✔
4610

4✔
4611
                        srvrLog.Debugf("Attempting persistent connection to "+
4✔
4612
                                "channel peer %v", addr)
4✔
4613

4✔
4614
                        go s.connMgr.Connect(connReq)
4✔
4615

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

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

4634
        srvrLog.Debugf("removing peer %v", p)
4✔
4635

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

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

4645
        // Ignore deleting peers if we're shutting down.
4646
        if s.Stopped() {
4✔
4647
                return
×
4648
        }
×
4649

4650
        pKey := p.PubKey()
4✔
4651
        pubSer := pKey[:]
4✔
4652
        pubStr := string(pubSer)
4✔
4653

4✔
4654
        delete(s.peersByPub, pubStr)
4✔
4655

4✔
4656
        if p.Inbound() {
8✔
4657
                delete(s.inboundPeers, pubStr)
4✔
4658
        } else {
8✔
4659
                delete(s.outboundPeers, pubStr)
4✔
4660
        }
4✔
4661

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

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

4✔
4673
        s.peerNotifier.NotifyPeerOffline(pubKey)
4✔
4674
}
4675

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

4✔
4684
        targetPub := string(addr.IdentityKey.SerializeCompressed())
4✔
4685

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

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

4699
        // Peer was not found, continue to pursue connection with peer.
4700

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

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

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

4✔
4732
                go s.connMgr.Connect(connReq)
4✔
4733

4✔
4734
                return nil
4✔
4735
        }
4736
        s.mu.Unlock()
4✔
4737

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

4✔
4745
        select {
4✔
4746
        case err := <-errChan:
4✔
4747
                return err
4✔
4748
        case <-s.quit:
×
4749
                return ErrServerShuttingDown
×
4750
        }
4751
}
4752

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

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

4771
        close(errChan)
4✔
4772

4✔
4773
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
4✔
4774
                conn.LocalAddr(), conn.RemoteAddr())
4✔
4775

4✔
4776
        s.OutboundPeerConnected(nil, conn)
4✔
4777
}
4778

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

4✔
4787
        s.mu.Lock()
4✔
4788
        defer s.mu.Unlock()
4✔
4789

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

4798
        srvrLog.Infof("Disconnecting from %v", peer)
4✔
4799

4✔
4800
        s.cancelConnReqs(pubStr, nil)
4✔
4801

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

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

4✔
4812
        return nil
4✔
4813
}
4814

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

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

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

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

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

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

×
4862
                return req.Updates, req.Err
×
4863
        }
×
4864

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

4✔
4871
        return req.Updates, req.Err
4✔
4872
}
4873

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

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

4886
        return peers
4✔
4887
}
4888

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

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

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

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

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

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

4928
        node, err := s.graphDB.FetchLightningNode(vertex)
4✔
4929
        if err != nil {
8✔
4930
                return nil, err
4✔
4931
        }
4✔
4932

4933
        if len(node.Addresses) == 0 {
8✔
4934
                return nil, errNoAdvertisedAddr
4✔
4935
        }
4✔
4936

4937
        return node.Addresses, nil
4✔
4938
}
4939

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

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

4952
                return netann.ExtractChannelUpdate(
4✔
4953
                        ourPubKey[:], info, edge1, edge2,
4✔
4954
                )
4✔
4955
        }
4956
}
4957

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

4✔
4964
        var (
4✔
4965
                peerAlias    *lnwire.ShortChannelID
4✔
4966
                defaultAlias lnwire.ShortChannelID
4✔
4967
        )
4✔
4968

4✔
4969
        chanID := lnwire.NewChanIDFromOutPoint(*op)
4✔
4970

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

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

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

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

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

5010
        msg, err := lnwire.NewCustom(msgType, data)
4✔
5011
        if err != nil {
8✔
5012
                return err
4✔
5013
        }
4✔
5014

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

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

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

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

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

5049
                return fn.Ok(lnwallet.AddrWithKey{
4✔
5050
                        DeliveryAddress: addr,
4✔
5051
                        InternalKey:     internalKeyDesc,
4✔
5052
                })
4✔
5053
        }
5054
}
5055

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

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

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

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

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

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

5108
                // If the channel is still reported as pending, remove it from
5109
                // the map.
5110
                delete(closedSCIDs, c.ShortChannelID)
×
5111

×
5112
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5113
                        c.ShortChannelID)
×
5114
        }
5115

5116
        return closedSCIDs
4✔
5117
}
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