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

lightningnetwork / lnd / 12456011944

22 Dec 2024 04:45PM UTC coverage: 58.556% (-0.04%) from 58.598%
12456011944

Pull #9232

github

Abdulkbk
chanbackup: test archiving chan backups
Pull Request #9232: chanbackup: archive old channel backups

46 of 58 new or added lines in 2 files covered. (79.31%)

324 existing lines in 30 files now uncovered.

134919 of 230410 relevant lines covered (58.56%)

19202.13 hits per line

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

63.9
/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 {
148
        return fmt.Sprintf("already connected to peer: %v", e.peer)
149
}
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 {
2✔
156
        active   int32 // atomic
2✔
157
        stopping int32 // atomic
2✔
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 {
360
        graphSub, err := s.graphBuilder.SubscribeTopology()
361
        if err != nil {
362
                return err
363
        }
364

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

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

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

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

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

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

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

2✔
412
                                        s.mu.Lock()
2✔
413

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

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

2✔
428
                                        s.mu.Unlock()
2✔
429

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

4✔
436
        return nil
2✔
437
}
2✔
438

439
// CustomMessage is a custom message that is received from a peer.
440
type CustomMessage struct {
2✔
441
        // Peer is the peer pubkey
2✔
442
        Peer [33]byte
2✔
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.
2✔
449
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
450
        var (
451
                host string
452
                port int
453
        )
454

455
        // Split the address into its host and port components.
456
        h, p, err := net.SplitHostPort(address)
457
        if err != nil {
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
2✔
462
        } else {
2✔
463
                // Otherwise, we'll note both the host and ports.
2✔
464
                host = h
2✔
465
                portNum, err := strconv.Atoi(p)
2✔
466
                if err != nil {
2✔
467
                        return nil, err
2✔
468
                }
2✔
469
                port = portNum
2✔
470
        }
×
471

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

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

484
// noiseDial is a factory function which creates a connmgr compliant dialing
2✔
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) {
488

489
        return func(a net.Addr) (net.Conn, error) {
490
                lnAddr := a.(*lnwire.NetAddress)
491
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
492
        }
2✔
493
}
2✔
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,
2✔
500
        chansToRestore walletunlocker.ChannelsToRecover,
2✔
501
        chanPredicate chanacceptor.ChannelAcceptor,
4✔
502
        torController *tor.Controller, tlsManager *TLSManager,
2✔
503
        leaderElector cluster.LeaderElector,
2✔
504
        implCfg *ImplementationCfg) (*server, error) {
2✔
505

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
623
                listenAddrs: listenAddrs,
2✔
624

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

2✔
629
                torController: torController,
2✔
630

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

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

2✔
647
                invoiceHtlcModifier: invoiceHtlcModifier,
2✔
648

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

2✔
651
                tlsManager: tlsManager,
2✔
652

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

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

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

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

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

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

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

2✔
683
                return nil
2✔
684
        }
×
685

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

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

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

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

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

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

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

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

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

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

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

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

2✔
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))
×
807
        for idx, ip := range cfg.ExternalIPs {
×
808
                externalIPStrings[idx] = ip.String()
×
809
        }
×
810
        if s.natTraversal != nil {
×
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.
2✔
837
        externalIPs, err := lncfg.NormalizeAddresses(
4✔
838
                externalIPStrings, strconv.Itoa(defaultPeerPort),
2✔
839
                cfg.net.ResolveTCPAddr,
2✔
840
        )
2✔
841
        if err != nil {
×
842
                return nil, err
×
843
        }
×
844

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

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

852
        // We'll now reconstruct a node announcement based on our current
×
853
        // configuration so we can send it out as a sort of heart beat within
×
854
        // the network.
×
855
        //
×
856
        // We'll start by parsing the node color from configuration.
×
857
        color, err := lncfg.ParseHexColor(cfg.Color)
×
858
        if err != nil {
×
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
866
        if alias == "" {
867
                alias = hex.EncodeToString(serializedPubKey[:10])
2✔
868
        }
2✔
869
        nodeAlias, err := lnwire.NewNodeAlias(alias)
2✔
870
        if err != nil {
2✔
871
                return nil, err
2✔
872
        }
×
873
        selfNode := &channeldb.LightningNode{
×
874
                HaveNodeAnnouncement: true,
875
                LastUpdate:           time.Now(),
2✔
876
                Addresses:            selfAddrs,
2✔
877
                Alias:                nodeAlias.String(),
2✔
878
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
2✔
879
                Color:                color,
2✔
880
        }
2✔
881
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
2✔
882

2✔
883
        // Based on the disk representation of the node announcement generated
2✔
884
        // above, we'll generate a node announcement that can go out on the
2✔
885
        // network so we can properly sign it.
×
886
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
887
        if err != nil {
×
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
2✔
892
        // authenticate the message on the network.
4✔
893
        authSig, err := netann.SignAnnouncement(
2✔
894
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
2✔
895
        )
2✔
896
        if err != nil {
2✔
897
                return nil, fmt.Errorf("unable to generate signature for "+
×
898
                        "self node announcement: %v", err)
×
899
        }
2✔
900
        selfNode.AuthSigBytes = authSig.Serialize()
2✔
901
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
2✔
902
                selfNode.AuthSigBytes,
2✔
903
        )
2✔
904
        if err != nil {
2✔
905
                return nil, err
2✔
906
        }
2✔
907

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

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

2✔
922
        // Instantiate mission control with config from the sub server.
2✔
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)
2✔
927

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

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

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

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

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

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

×
981
        s.missionController, err = routing.NewMissionController(
×
982
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
×
983
        )
×
984
        if err != nil {
×
985
                return nil, fmt.Errorf("can't create mission control "+
×
986
                        "manager: %w", err)
×
987
        }
×
988
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
989
                routing.DefaultMissionControlNamespace,
×
990
        )
×
991
        if err != nil {
×
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: "+
997
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
998
                int64(routingConfig.AttemptCost),
999
                float64(routingConfig.AttemptCostPPM)/10000,
2✔
1000
                routingConfig.MinRouteProbability)
2✔
1001

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

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

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

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

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

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

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

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

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

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

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

×
1121
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
1122
        //nolint:lll
1123
        s.localChanMgr = &localchans.Manager{
1124
                SelfPub:              nodeKeyDesc.PubKey,
1125
                DefaultRoutingPolicy: cc.RoutingPolicy,
1126
                ForAllOutgoingChannels: func(cb func(kvdb.RTx,
1127
                        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy) error) error {
1128

1129
                        return s.graphDB.ForEachNodeChannel(selfVertex,
1130
                                func(tx kvdb.RTx, c *models.ChannelEdgeInfo,
1131
                                        e *models.ChannelEdgePolicy,
1132
                                        _ *models.ChannelEdgePolicy) error {
1133

1134
                                        // NOTE: The invoked callback here may
1135
                                        // receive a nil channel policy.
1136
                                        return cb(tx, c, e)
1137
                                },
1138
                        )
1139
                },
1140
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1141
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1142
                FetchChannel:              s.chanStateDB.FetchChannel,
1143
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
1144
                        return s.graphBuilder.AddEdge(edge)
1145
                },
1146
        }
1147

2✔
1148
        utxnStore, err := contractcourt.NewNurseryStore(
2✔
1149
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
2✔
1150
        )
2✔
1151
        if err != nil {
2✔
1152
                srvrLog.Errorf("unable to create nursery store: %v", err)
2✔
1153
                return nil, err
4✔
1154
        }
2✔
1155

2✔
1156
        sweeperStore, err := sweep.NewSweeperStore(
2✔
1157
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
2✔
1158
        )
4✔
1159
        if err != nil {
2✔
1160
                srvrLog.Errorf("unable to create sweeper store: %v", err)
2✔
1161
                return nil, err
2✔
1162
        }
2✔
1163

2✔
1164
        aggregator := sweep.NewBudgetAggregator(
1165
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
1166
                s.implCfg.AuxSweeper,
1167
        )
1168

1169
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
1170
                Signer:     cc.Wallet.Cfg.Signer,
×
1171
                Wallet:     cc.Wallet,
×
1172
                Estimator:  cc.FeeEstimator,
1173
                Notifier:   cc.ChainNotifier,
1174
                AuxSweeper: s.implCfg.AuxSweeper,
2✔
1175
        })
2✔
1176

2✔
1177
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
2✔
1178
                FeeEstimator: cc.FeeEstimator,
×
1179
                GenSweepScript: newSweepPkScriptGen(
×
1180
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
×
1181
                ),
1182
                Signer:               cc.Wallet.Cfg.Signer,
2✔
1183
                Wallet:               newSweeperWallet(cc.Wallet),
2✔
1184
                Mempool:              cc.MempoolNotifier,
2✔
1185
                Notifier:             cc.ChainNotifier,
2✔
1186
                Store:                sweeperStore,
×
1187
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
1188
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
1189
                Aggregator:           aggregator,
1190
                Publisher:            s.txPublisher,
2✔
1191
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
2✔
1192
        })
2✔
1193

2✔
1194
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
2✔
1195
                ChainIO:             cc.ChainIO,
2✔
1196
                ConfDepth:           1,
2✔
1197
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
2✔
1198
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
2✔
1199
                Notifier:            cc.ChainNotifier,
2✔
1200
                PublishTransaction:  cc.Wallet.PublishTransaction,
2✔
1201
                Store:               utxnStore,
2✔
1202
                SweepInput:          s.sweeper.SweepInput,
2✔
1203
                Budget:              s.cfg.Sweeper.Budget,
2✔
1204
        })
2✔
1205

2✔
1206
        // Construct a closure that wraps the htlcswitch's CloseLink method.
2✔
1207
        closeLink := func(chanPoint *wire.OutPoint,
2✔
1208
                closureType contractcourt.ChannelCloseType) {
2✔
1209
                // TODO(conner): Properly respect the update and error channels
2✔
1210
                // returned by CloseLink.
2✔
1211

2✔
1212
                // Instruct the switch to close the channel.  Provide no close out
2✔
1213
                // delivery script or target fee per kw because user input is not
2✔
1214
                // available when the remote peer closes the channel.
2✔
1215
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
2✔
1216
        }
2✔
1217

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

2✔
1222
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
2✔
1223
                &contractcourt.BreachConfig{
2✔
1224
                        CloseLink: closeLink,
2✔
1225
                        DB:        s.chanStateDB,
2✔
1226
                        Estimator: s.cc.FeeEstimator,
2✔
1227
                        GenSweepScript: newSweepPkScriptGen(
2✔
1228
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
2✔
1229
                        ),
2✔
1230
                        Notifier:           cc.ChainNotifier,
2✔
1231
                        PublishTransaction: cc.Wallet.PublishTransaction,
2✔
1232
                        ContractBreaches:   contractBreaches,
2✔
1233
                        Signer:             cc.Wallet.Cfg.Signer,
2✔
1234
                        Store: contractcourt.NewRetributionStore(
4✔
1235
                                dbs.ChanStateDB,
2✔
1236
                        ),
2✔
1237
                        AuxSweeper: s.implCfg.AuxSweeper,
2✔
1238
                },
2✔
1239
        )
2✔
1240

2✔
1241
        //nolint:lll
2✔
1242
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
2✔
1243
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
1244
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
1245
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
1246
                NewSweepAddr: func() ([]byte, error) {
2✔
1247
                        addr, err := newSweepPkScriptGen(
2✔
1248
                                cc.Wallet, netParams,
2✔
1249
                        )().Unpack()
2✔
1250
                        if err != nil {
2✔
1251
                                return nil, err
2✔
1252
                        }
2✔
1253

2✔
1254
                        return addr.DeliveryAddress, nil
2✔
1255
                },
2✔
1256
                PublishTx: cc.Wallet.PublishTransaction,
2✔
1257
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
2✔
1258
                        for _, msg := range msgs {
2✔
1259
                                err := s.htlcSwitch.ProcessContractResolution(msg)
2✔
1260
                                if err != nil {
2✔
1261
                                        return err
2✔
1262
                                }
2✔
1263
                        }
2✔
1264
                        return nil
2✔
1265
                },
2✔
1266
                IncubateOutputs: func(chanPoint wire.OutPoint,
2✔
1267
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
2✔
1268
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
2✔
1269
                        broadcastHeight uint32,
2✔
1270
                        deadlineHeight fn.Option[int32]) error {
2✔
1271

2✔
1272
                        return s.utxoNursery.IncubateOutputs(
2✔
1273
                                chanPoint, outHtlcRes, inHtlcRes,
×
1274
                                broadcastHeight, deadlineHeight,
×
1275
                        )
×
1276
                },
×
1277
                PreimageDB:   s.witnessBeacon,
×
1278
                Notifier:     cc.ChainNotifier,
×
1279
                Mempool:      cc.MempoolNotifier,
1280
                Signer:       cc.Wallet.Cfg.Signer,
×
1281
                FeeEstimator: cc.FeeEstimator,
1282
                ChainIO:      cc.ChainIO,
1283
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
2✔
1284
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1285
                        s.htlcSwitch.RemoveLink(chanID)
2✔
1286
                        return nil
2✔
1287
                },
×
1288
                IsOurAddress: cc.Wallet.IsOurAddress,
×
1289
                ContractBreach: func(chanPoint wire.OutPoint,
1290
                        breachRet *lnwallet.BreachRetribution) error {
2✔
1291

1292
                        // processACK will handle the BreachArbitrator ACKing
1293
                        // the event.
1294
                        finalErr := make(chan error, 1)
1295
                        processACK := func(brarErr error) {
1296
                                if brarErr != nil {
2✔
1297
                                        finalErr <- brarErr
2✔
1298
                                        return
2✔
1299
                                }
2✔
1300

2✔
1301
                                // If the BreachArbitrator successfully handled
2✔
1302
                                // the event, we can signal that the handoff
2✔
1303
                                // was successful.
1304
                                finalErr <- nil
1305
                        }
1306

1307
                        event := &contractcourt.ContractBreachEvent{
1308
                                ChanPoint:         chanPoint,
1309
                                ProcessACK:        processACK,
2✔
1310
                                BreachRetribution: breachRet,
2✔
1311
                        }
2✔
1312

2✔
1313
                        // Send the contract breach event to the
2✔
1314
                        // BreachArbitrator.
1315
                        select {
1316
                        case contractBreaches <- event:
2✔
1317
                        case <-s.quit:
2✔
1318
                                return ErrServerShuttingDown
2✔
1319
                        }
2✔
1320

2✔
1321
                        // We'll wait for a final error to be available from
4✔
1322
                        // the BreachArbitrator.
2✔
1323
                        select {
×
1324
                        case err := <-finalErr:
×
1325
                                return err
×
1326
                        case <-s.quit:
1327
                                return ErrServerShuttingDown
1328
                        }
1329
                },
1330
                DisableChannel: func(chanPoint wire.OutPoint) error {
2✔
1331
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
1332
                },
1333
                Sweeper:                       s.sweeper,
2✔
1334
                Registry:                      s.invoices,
2✔
1335
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
2✔
1336
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
2✔
1337
                OnionProcessor:                s.sphinx,
2✔
1338
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
2✔
1339
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
2✔
1340
                Clock:                         clock.NewDefaultClock(),
2✔
1341
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
2✔
1342
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
2✔
1343
                HtlcNotifier:                  s.htlcNotifier,
×
1344
                Budget:                        *s.cfg.Sweeper.Budget,
×
1345

1346
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1347
                QueryIncomingCircuit: func(
1348
                        circuit models.CircuitKey) *models.CircuitKey {
1349

2✔
1350
                        // Get the circuit map.
2✔
1351
                        circuits := s.htlcSwitch.CircuitLookup()
2✔
1352

×
1353
                        // Lookup the outgoing circuit.
×
1354
                        pc := circuits.LookupOpenCircuit(circuit)
1355
                        if pc == nil {
1356
                                return nil
2✔
1357
                        }
2✔
1358

2✔
1359
                        return &pc.Incoming
1360
                },
1361
                AuxLeafStore: implCfg.AuxLeafStore,
1362
                AuxSigner:    implCfg.AuxSigner,
1363
                AuxResolver:  implCfg.AuxContractResolver,
1364
        }, dbs.ChanStateDB)
1365

1366
        // Select the configuration and funding parameters for Bitcoin.
1367
        chainCfg := cfg.Bitcoin
1368
        minRemoteDelay := funding.MinBtcRemoteDelay
1369
        maxRemoteDelay := funding.MaxBtcRemoteDelay
1370

1371
        var chanIDSeed [32]byte
1372
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
1373
                return nil, err
1374
        }
2✔
1375

2✔
1376
        // Wrap the DeleteChannelEdges method so that the funding manager can
2✔
1377
        // use it without depending on several layers of indirection.
2✔
1378
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
2✔
1379
                *models.ChannelEdgePolicy, error) {
2✔
1380

2✔
1381
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
4✔
1382
                        scid.ToUint64(),
2✔
1383
                )
2✔
1384
                if errors.Is(err, channeldb.ErrEdgeNotFound) {
1385
                        // This is unlikely but there is a slim chance of this
2✔
1386
                        // being hit if lnd was killed via SIGKILL and the
1387
                        // funding manager was stepping through the delete
1388
                        // alias edge logic.
1389
                        return nil, nil
1390
                } else if err != nil {
1391
                        return nil, err
1392
                }
1393

2✔
1394
                // Grab our key to find our policy.
2✔
1395
                var ourKey [33]byte
2✔
1396
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
2✔
1397

2✔
1398
                var ourPolicy *models.ChannelEdgePolicy
2✔
1399
                if info != nil && info.NodeKey1Bytes == ourKey {
×
1400
                        ourPolicy = e1
×
1401
                } else {
1402
                        ourPolicy = e2
1403
                }
1404

2✔
1405
                if ourPolicy == nil {
4✔
1406
                        // Something is wrong, so return an error.
2✔
1407
                        return nil, fmt.Errorf("we don't have an edge")
2✔
1408
                }
2✔
1409

2✔
1410
                err = s.graphDB.DeleteChannelEdges(
2✔
1411
                        false, false, scid.ToUint64(),
×
1412
                )
×
1413
                return ourPolicy, err
×
1414
        }
×
1415

×
1416
        // For the reservationTimeout and the zombieSweeperInterval different
2✔
1417
        // values are set in case we are in a dev environment so enhance test
×
1418
        // capacilities.
×
1419
        reservationTimeout := chanfunding.DefaultReservationTimeout
1420
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
1421

2✔
1422
        // Get the development config for funding manager. If we are not in
2✔
1423
        // development mode, this would be nil.
2✔
1424
        var devCfg *funding.DevConfig
2✔
1425
        if lncfg.IsDevBuild() {
4✔
1426
                devCfg = &funding.DevConfig{
2✔
1427
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
4✔
1428
                }
2✔
1429

2✔
1430
                reservationTimeout = cfg.Dev.GetReservationTimeout()
1431
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
2✔
1432

×
1433
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
1434
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
1435
                        devCfg, reservationTimeout, zombieSweeperInterval)
1436
        }
2✔
1437

2✔
1438
        //nolint:lll
2✔
1439
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
2✔
1440
                Dev:                devCfg,
1441
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
1442
                IDKey:              nodeKeyDesc.PubKey,
1443
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
1444
                Wallet:             cc.Wallet,
1445
                PublishTransaction: cc.Wallet.PublishTransaction,
2✔
1446
                UpdateLabel: func(hash chainhash.Hash, label string) error {
2✔
1447
                        return cc.Wallet.LabelTransaction(hash, label, true)
2✔
1448
                },
2✔
1449
                Notifier:     cc.ChainNotifier,
2✔
1450
                ChannelDB:    s.chanStateDB,
2✔
1451
                FeeEstimator: cc.FeeEstimator,
4✔
1452
                SignMessage:  cc.MsgSigner.SignMessage,
2✔
1453
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
2✔
1454
                        error) {
2✔
1455

2✔
1456
                        return s.genNodeAnnouncement(nil)
2✔
1457
                },
2✔
1458
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
2✔
1459
                NotifyWhenOnline:     s.NotifyWhenOnline,
2✔
1460
                TempChanIDSeed:       chanIDSeed,
2✔
1461
                FindChannel:          s.findChannel,
2✔
1462
                DefaultRoutingPolicy: cc.RoutingPolicy,
2✔
1463
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1464
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1465
                        pushAmt lnwire.MilliSatoshi) uint16 {
2✔
1466
                        // For large channels we increase the number
2✔
1467
                        // of confirmations we require for the
2✔
1468
                        // channel to be considered open. As it is
2✔
1469
                        // always the responder that gets to choose
2✔
1470
                        // value, the pushAmt is value being pushed
2✔
1471
                        // to us. This means we have more to lose
2✔
1472
                        // in the case this gets re-orged out, and
4✔
1473
                        // we will require more confirmations before
2✔
1474
                        // we consider it open.
2✔
1475

1476
                        // In case the user has explicitly specified
1477
                        // a default value for the number of
1478
                        // confirmations, we use it.
1479
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
1480
                        if defaultConf != 0 {
2✔
1481
                                return defaultConf
2✔
1482
                        }
2✔
1483

2✔
1484
                        minConf := uint64(3)
1485
                        maxConf := uint64(6)
1486

1487
                        // If this is a wumbo channel, then we'll require the
1488
                        // max amount of confirmations.
1489
                        if chanAmt > MaxFundingAmount {
1490
                                return uint16(maxConf)
1491
                        }
2✔
1492

2✔
1493
                        // If not we return a value scaled linearly
2✔
1494
                        // between 3 and 6, depending on channel size.
2✔
1495
                        // TODO(halseth): Use 1 as minimum?
2✔
1496
                        maxChannelSize := uint64(
2✔
1497
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
2✔
1498
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
2✔
1499
                        conf := maxConf * uint64(stake) / maxChannelSize
2✔
1500
                        if conf < minConf {
2✔
1501
                                conf = minConf
2✔
1502
                        }
2✔
1503
                        if conf > maxConf {
2✔
1504
                                conf = maxConf
2✔
1505
                        }
2✔
1506
                        return uint16(conf)
4✔
1507
                },
2✔
1508
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
2✔
1509
                        // We scale the remote CSV delay (the time the
1510
                        // remote have to claim funds in case of a unilateral
×
1511
                        // close) linearly from minRemoteDelay blocks
×
1512
                        // for small channels, to maxRemoteDelay blocks
×
1513
                        // for channels of size MaxFundingAmount.
×
1514

×
1515
                        // In case the user has explicitly specified
×
1516
                        // a default value for the remote delay, we
×
1517
                        // use it.
×
1518
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
1519
                        if defaultDelay > 0 {
1520
                                return defaultDelay
1521
                        }
1522

×
1523
                        // If this is a wumbo channel, then we'll require the
×
1524
                        // max value.
×
1525
                        if chanAmt > MaxFundingAmount {
×
1526
                                return maxRemoteDelay
×
1527
                        }
×
1528

×
1529
                        // If not we scale according to channel size.
×
1530
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1531
                                chanAmt / MaxFundingAmount)
×
1532
                        if delay < minRemoteDelay {
×
1533
                                delay = minRemoteDelay
1534
                        }
2✔
1535
                        if delay > maxRemoteDelay {
2✔
1536
                                delay = maxRemoteDelay
2✔
1537
                        }
2✔
1538
                        return delay
2✔
1539
                },
2✔
1540
                WatchNewChannel: func(channel *channeldb.OpenChannel,
2✔
1541
                        peerKey *btcec.PublicKey) error {
2✔
1542

2✔
1543
                        // First, we'll mark this new peer as a persistent peer
2✔
1544
                        // for re-connection purposes. If the peer is not yet
2✔
1545
                        // tracked or the user hasn't requested it to be perm,
4✔
1546
                        // we'll set false to prevent the server from continuing
2✔
1547
                        // to connect to this peer even if the number of
2✔
1548
                        // channels with this peer is zero.
1549
                        s.mu.Lock()
1550
                        pubStr := string(peerKey.SerializeCompressed())
1551
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
1552
                                s.persistentPeers[pubStr] = false
×
1553
                        }
×
1554
                        s.mu.Unlock()
1555

1556
                        // With that taken care of, we'll send this channel to
×
1557
                        // the chain arb so it can react to on-chain events.
×
1558
                        return s.chainArb.WatchNewChannel(channel)
×
1559
                },
×
1560
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
1561
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
1562
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
1563
                },
×
1564
                RequiredRemoteChanReserve: func(chanAmt,
×
1565
                        dustLimit btcutil.Amount) btcutil.Amount {
1566

1567
                        // By default, we'll require the remote peer to maintain
2✔
1568
                        // at least 1% of the total channel capacity at all
2✔
1569
                        // times. If this value ends up dipping below the dust
2✔
1570
                        // limit, then we'll use the dust limit itself as the
2✔
1571
                        // reserve as required by BOLT #2.
2✔
1572
                        reserve := chanAmt / 100
2✔
1573
                        if reserve < dustLimit {
2✔
1574
                                reserve = dustLimit
2✔
1575
                        }
2✔
1576

2✔
1577
                        return reserve
4✔
1578
                },
2✔
1579
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
2✔
1580
                        // By default, we'll allow the remote peer to fully
2✔
1581
                        // utilize the full bandwidth of the channel, minus our
2✔
1582
                        // required reserve.
2✔
1583
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
2✔
1584
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
2✔
1585
                },
1586
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
2✔
1587
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
2✔
1588
                                return cfg.DefaultRemoteMaxHtlcs
2✔
1589
                        }
2✔
1590

1591
                        // By default, we'll permit them to utilize the full
2✔
1592
                        // channel bandwidth.
2✔
1593
                        return uint16(input.MaxHTLCNumber / 2)
2✔
1594
                },
2✔
1595
                ZombieSweeperInterval:         zombieSweeperInterval,
2✔
1596
                ReservationTimeout:            reservationTimeout,
2✔
1597
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
2✔
1598
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
2✔
1599
                MaxPendingChannels:            cfg.MaxPendingChannels,
4✔
1600
                RejectPush:                    cfg.RejectPush,
2✔
1601
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
2✔
1602
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1603
                OpenChannelPredicate:          chanPredicate,
2✔
1604
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1605
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
2✔
1606
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
2✔
1607
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
2✔
1608
                DeleteAliasEdge:      deleteAliasEdge,
2✔
1609
                AliasManager:         s.aliasMgr,
2✔
1610
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
2✔
1611
                AuxFundingController: implCfg.AuxFundingController,
2✔
1612
                AuxSigner:            implCfg.AuxSigner,
2✔
1613
                AuxResolver:          implCfg.AuxContractResolver,
4✔
1614
        })
2✔
1615
        if err != nil {
2✔
1616
                return nil, err
1617
        }
1618

1619
        // Next, we'll assemble the sub-system that will maintain an on-disk
×
1620
        // static backup of the latest channel state.
1621
        chanNotifier := &channelNotifier{
1622
                chanNotifier: s.channelNotifier,
1623
                addrs:        dbs.ChanStateDB,
1624
        }
1625
        backupFile := chanbackup.NewMultiFile(
1626
                cfg.BackupFilePath, cfg.DisableBackupArchive,
1627
        )
1628
        startingChans, err := chanbackup.FetchStaticChanBackups(
1629
                s.chanStateDB, s.addrSource,
1630
        )
1631
        if err != nil {
1632
                return nil, err
1633
        }
1634
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
1635
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
1636
        )
1637
        if err != nil {
1638
                return nil, err
1639
        }
1640

1641
        // Assemble a peer notifier which will provide clients with subscriptions
2✔
UNCOV
1642
        // to peer online and offline events.
×
UNCOV
1643
        s.peerNotifier = peernotifier.New()
×
1644

1645
        // Create a channel event store which monitors all open channels.
1646
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
1647
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
2✔
1648
                        return s.channelNotifier.SubscribeChannelEvents()
2✔
1649
                },
2✔
1650
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
2✔
1651
                        return s.peerNotifier.SubscribePeerEvents()
2✔
1652
                },
2✔
1653
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
2✔
1654
                Clock:           clock.NewDefaultClock(),
2✔
1655
                ReadFlapCount:   s.miscDB.ReadFlapCount,
2✔
1656
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
2✔
1657
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
2✔
1658
        })
×
1659

×
1660
        if cfg.WtClient.Active {
2✔
1661
                policy := wtpolicy.DefaultPolicy()
2✔
1662
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
2✔
1663

2✔
1664
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
1665
                // protocol operations on sat/kw.
×
1666
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
1667
                        1000 * cfg.WtClient.SweepFeeRate,
1668
                )
1669

2✔
1670
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
2✔
1671

2✔
1672
                if err := policy.Validate(); err != nil {
2✔
1673
                        return nil, err
4✔
1674
                }
2✔
1675

2✔
1676
                // authDial is the wrapper around the btrontide.Dial for the
2✔
1677
                // watchtower.
2✔
1678
                authDial := func(localKey keychain.SingleKeyECDH,
2✔
1679
                        netAddr *lnwire.NetAddress,
1680
                        dialer tor.DialFunc) (wtserver.Peer, error) {
1681

1682
                        return brontide.Dial(
1683
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
1684
                        )
1685
                }
1686

4✔
1687
                // buildBreachRetribution is a call-back that can be used to
2✔
1688
                // query the BreachRetribution info and channel type given a
2✔
1689
                // channel ID and commitment height.
2✔
1690
                buildBreachRetribution := func(chanID lnwire.ChannelID,
2✔
1691
                        commitHeight uint64) (*lnwallet.BreachRetribution,
2✔
1692
                        channeldb.ChannelType, error) {
2✔
1693

2✔
1694
                        channel, err := s.chanStateDB.FetchChannelByID(
2✔
1695
                                nil, chanID,
2✔
1696
                        )
2✔
1697
                        if err != nil {
2✔
1698
                                return nil, 0, err
2✔
1699
                        }
×
1700

×
1701
                        br, err := lnwallet.NewBreachRetribution(
1702
                                channel, commitHeight, 0, nil,
1703
                                implCfg.AuxLeafStore,
1704
                                implCfg.AuxContractResolver,
2✔
1705
                        )
2✔
1706
                        if err != nil {
4✔
1707
                                return nil, 0, err
2✔
1708
                        }
2✔
1709

2✔
1710
                        return br, channel.ChanType, nil
2✔
1711
                }
2✔
1712

1713
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
1714

1715
                // Copy the policy for legacy channels and set the blob flag
1716
                // signalling support for anchor channels.
2✔
1717
                anchorPolicy := policy
2✔
1718
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
4✔
1719

2✔
1720
                // Copy the policy for legacy channels and set the blob flag
2✔
1721
                // signalling support for taproot channels.
2✔
1722
                taprootPolicy := policy
2✔
1723
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
2✔
1724
                        blob.FlagTaprootChannel,
×
1725
                )
×
1726

1727
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
2✔
1728
                        FetchClosedChannel:     fetchClosedChannel,
2✔
1729
                        BuildBreachRetribution: buildBreachRetribution,
2✔
1730
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
2✔
1731
                        ChainNotifier:          s.cc.ChainNotifier,
2✔
1732
                        SubscribeChannelEvents: func() (subscribe.Subscription,
2✔
1733
                                error) {
×
1734

×
1735
                                return s.channelNotifier.
1736
                                        SubscribeChannelEvents()
2✔
1737
                        },
1738
                        Signer: cc.Wallet.Cfg.Signer,
1739
                        NewAddress: func() ([]byte, error) {
2✔
1740
                                addr, err := newSweepPkScriptGen(
2✔
1741
                                        cc.Wallet, netParams,
2✔
1742
                                )().Unpack()
2✔
1743
                                if err != nil {
2✔
1744
                                        return nil, err
2✔
1745
                                }
2✔
1746

2✔
1747
                                return addr.DeliveryAddress, nil
2✔
1748
                        },
2✔
1749
                        SecretKeyRing:      s.cc.KeyRing,
2✔
1750
                        Dial:               cfg.net.Dial,
2✔
1751
                        AuthDial:           authDial,
2✔
1752
                        DB:                 dbs.TowerClientDB,
2✔
1753
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
2✔
1754
                        MinBackoff:         10 * time.Second,
2✔
1755
                        MaxBackoff:         5 * time.Minute,
2✔
1756
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
2✔
1757
                }, policy, anchorPolicy, taprootPolicy)
2✔
1758
                if err != nil {
2✔
1759
                        return nil, err
4✔
1760
                }
2✔
1761
        }
2✔
1762

2✔
1763
        if len(cfg.ExternalHosts) != 0 {
2✔
1764
                advertisedIPs := make(map[string]struct{})
1765
                for _, addr := range s.currentNodeAnn.Addresses {
2✔
1766
                        advertisedIPs[addr.String()] = struct{}{}
2✔
1767
                }
2✔
1768

2✔
1769
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
2✔
1770
                        Hosts:         cfg.ExternalHosts,
×
1771
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1772
                        LookupHost: func(host string) (net.Addr, error) {
1773
                                return lncfg.ParseAddressString(
2✔
1774
                                        host, strconv.Itoa(defaultPeerPort),
1775
                                        cfg.net.ResolveTCPAddr,
1776
                                )
1777
                        },
1778
                        AdvertisedIPs: advertisedIPs,
1779
                        AnnounceNewIPs: netann.IPAnnouncer(
1780
                                func(modifier ...netann.NodeAnnModifier) (
1781
                                        lnwire.NodeAnnouncement, error) {
1782

1783
                                        return s.genNodeAnnouncement(
1784
                                                nil, modifier...,
2✔
1785
                                        )
×
1786
                                }),
×
1787
                })
1788
        }
1789

2✔
1790
        // Create liveness monitor.
×
1791
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
1792

×
1793
        // Create the connection manager which will be responsible for
×
1794
        // maintaining persistent outbound connections and also accepting new
1795
        // incoming connections
×
1796
        cmgr, err := connmgr.New(&connmgr.Config{
×
1797
                Listeners:      listeners,
×
1798
                OnAccept:       s.InboundPeerConnected,
×
1799
                RetryDuration:  time.Second * 5,
×
1800
                TargetOutbound: 100,
×
1801
                Dial: noiseDial(
×
1802
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
1803
                ),
×
1804
                OnConnection: s.OutboundPeerConnected,
1805
        })
1806
        if err != nil {
1807
                return nil, err
×
1808
        }
×
1809
        s.connMgr = cmgr
×
1810

×
1811
        return s, nil
×
1812
}
×
1813

1814
// UpdateRoutingConfig is a callback function to update the routing config
1815
// values in the main cfg.
1816
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
1817
        routerCfg := s.cfg.SubRPCServers.RouterRPC
2✔
1818

2✔
1819
        switch c := cfg.Estimator.Config().(type) {
2✔
1820
        case routing.AprioriConfig:
2✔
1821
                routerCfg.ProbabilityEstimatorType =
2✔
1822
                        routing.AprioriEstimatorName
2✔
1823

2✔
1824
                targetCfg := routerCfg.AprioriConfig
2✔
1825
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
2✔
1826
                targetCfg.Weight = c.AprioriWeight
2✔
1827
                targetCfg.CapacityFraction = c.CapacityFraction
2✔
1828
                targetCfg.HopProbability = c.AprioriHopProbability
2✔
1829

2✔
1830
        case routing.BimodalConfig:
2✔
1831
                routerCfg.ProbabilityEstimatorType =
2✔
1832
                        routing.BimodalEstimatorName
2✔
1833

×
1834
                targetCfg := routerCfg.BimodalConfig
×
1835
                targetCfg.Scale = int64(c.BimodalScaleMsat)
2✔
1836
                targetCfg.NodeWeight = c.BimodalNodeWeight
2✔
1837
                targetCfg.DecayTime = c.BimodalDecayTime
2✔
1838
        }
2✔
1839

2✔
1840
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
2✔
1841
}
1842

1843
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1844
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1845
// may differ from what is on disk.
2✔
1846
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
2✔
1847
        error) {
2✔
1848

2✔
1849
        data, err := u.DataToSign()
2✔
1850
        if err != nil {
2✔
1851
                return nil, err
2✔
1852
        }
2✔
1853

2✔
1854
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
2✔
1855
}
2✔
1856

2✔
1857
// createLivenessMonitor creates a set of health checks using our configured
2✔
1858
// values and uses these checks to create a liveness monitor. Available
1859
// health checks,
2✔
1860
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2✔
1861
//   - diskCheck
2✔
1862
//   - tlsHealthCheck
2✔
1863
//   - torController, only created when tor is enabled.
2✔
1864
//
2✔
1865
// If a health check has been disabled by setting attempts to 0, our monitor
2✔
1866
// will not run it.
2✔
1867
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1868
        leaderElector cluster.LeaderElector) {
1869

2✔
1870
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
1871
        if cfg.Bitcoin.Node == "nochainbackend" {
1872
                srvrLog.Info("Disabling chain backend checks for " +
1873
                        "nochainbackend mode")
1874

1875
                chainBackendAttempts = 0
1876
        }
1877

1878
        chainHealthCheck := healthcheck.NewObservation(
1879
                "chain backend",
1880
                cc.HealthCheck,
2✔
1881
                cfg.HealthChecks.ChainCheck.Interval,
2✔
1882
                cfg.HealthChecks.ChainCheck.Timeout,
2✔
1883
                cfg.HealthChecks.ChainCheck.Backoff,
2✔
1884
                chainBackendAttempts,
2✔
1885
        )
2✔
1886

2✔
1887
        diskCheck := healthcheck.NewObservation(
2✔
1888
                "disk space",
2✔
1889
                func() error {
2✔
1890
                        free, err := healthcheck.AvailableDiskSpaceRatio(
1891
                                cfg.LndDir,
1892
                        )
1893
                        if err != nil {
1894
                                return err
1895
                        }
2✔
1896

2✔
1897
                        // If we have more free space than we require,
2✔
1898
                        // we return a nil error.
2✔
1899
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1900
                                return nil
×
1901
                        }
1902

2✔
1903
                        return fmt.Errorf("require: %v free space, got: %v",
1904
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
1905
                                free)
1906
                },
1907
                cfg.HealthChecks.DiskCheck.Interval,
1908
                cfg.HealthChecks.DiskCheck.Timeout,
1909
                cfg.HealthChecks.DiskCheck.Backoff,
1910
                cfg.HealthChecks.DiskCheck.Attempts,
1911
        )
1912

1913
        tlsHealthCheck := healthcheck.NewObservation(
1914
                "tls",
1915
                func() error {
1916
                        expired, expTime, err := s.tlsManager.IsCertExpired(
2✔
1917
                                s.cc.KeyRing,
2✔
1918
                        )
2✔
1919
                        if err != nil {
2✔
1920
                                return err
×
1921
                        }
×
1922
                        if expired {
×
1923
                                return fmt.Errorf("TLS certificate is "+
×
1924
                                        "expired as of %v", expTime)
×
1925
                        }
1926

2✔
1927
                        // If the certificate is not outdated, no error needs
2✔
1928
                        // to be returned
2✔
1929
                        return nil
2✔
1930
                },
2✔
1931
                cfg.HealthChecks.TLSCheck.Interval,
2✔
1932
                cfg.HealthChecks.TLSCheck.Timeout,
2✔
1933
                cfg.HealthChecks.TLSCheck.Backoff,
2✔
1934
                cfg.HealthChecks.TLSCheck.Attempts,
2✔
1935
        )
2✔
1936

2✔
1937
        checks := []*healthcheck.Observation{
2✔
1938
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
1939
        }
×
1940

×
1941
        // If Tor is enabled, add the healthcheck for tor connection.
×
1942
        if s.torController != nil {
×
1943
                torConnectionCheck := healthcheck.NewObservation(
×
1944
                        "tor connection",
1945
                        func() error {
1946
                                return healthcheck.CheckTorServiceStatus(
1947
                                        s.torController,
×
1948
                                        s.createNewHiddenService,
×
1949
                                )
×
1950
                        },
1951
                        cfg.HealthChecks.TorConnection.Interval,
×
1952
                        cfg.HealthChecks.TorConnection.Timeout,
×
1953
                        cfg.HealthChecks.TorConnection.Backoff,
×
1954
                        cfg.HealthChecks.TorConnection.Attempts,
1955
                )
1956
                checks = append(checks, torConnectionCheck)
1957
        }
1958

1959
        // If remote signing is enabled, add the healthcheck for the remote
1960
        // signing RPC interface.
1961
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
2✔
1962
                // Because we have two cascading timeouts here, we need to add
2✔
1963
                // some slack to the "outer" one of them in case the "inner"
2✔
1964
                // returns exactly on time.
×
1965
                overhead := time.Millisecond * 10
×
1966

×
1967
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
1968
                        "remote signer connection",
×
1969
                        rpcwallet.HealthCheck(
×
1970
                                s.cfg.RemoteSigner,
×
1971

×
1972
                                // For the health check we might to be even
×
1973
                                // stricter than the initial/normal connect, so
×
1974
                                // we use the health check timeout here.
1975
                                cfg.HealthChecks.RemoteSigner.Timeout,
1976
                        ),
1977
                        cfg.HealthChecks.RemoteSigner.Interval,
×
1978
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
1979
                        cfg.HealthChecks.RemoteSigner.Backoff,
1980
                        cfg.HealthChecks.RemoteSigner.Attempts,
1981
                )
1982
                checks = append(checks, remoteSignerConnectionCheck)
1983
        }
1984

1985
        // If we have a leader elector, we add a health check to ensure we are
2✔
1986
        // still the leader. During normal operation, we should always be the
2✔
1987
        // leader, but there are circumstances where this may change, such as
2✔
1988
        // when we lose network connectivity for long enough expiring out lease.
2✔
1989
        if leaderElector != nil {
2✔
1990
                leaderCheck := healthcheck.NewObservation(
2✔
1991
                        "leader status",
×
1992
                        func() error {
×
1993
                                // Check if we are still the leader. Note that
×
1994
                                // we don't need to use a timeout context here
×
1995
                                // as the healthcheck observer will handle the
×
1996
                                // timeout case for us.
×
1997
                                timeoutCtx, cancel := context.WithTimeout(
×
1998
                                        context.Background(),
×
1999
                                        cfg.HealthChecks.LeaderCheck.Timeout,
2000
                                )
2001
                                defer cancel()
2002

2003
                                leader, err := leaderElector.IsLeader(
2004
                                        timeoutCtx,
×
2005
                                )
2006
                                if err != nil {
2007
                                        return fmt.Errorf("unable to check if "+
2008
                                                "still leader: %v", err)
2009
                                }
4✔
2010

2✔
2011
                                if !leader {
2✔
2012
                                        srvrLog.Debug("Not the current leader")
2✔
2013
                                        return fmt.Errorf("not the current " +
2✔
2014
                                                "leader")
2✔
2015
                                }
2✔
2016

2✔
2017
                                return nil
2✔
2018
                        },
2✔
2019
                        cfg.HealthChecks.LeaderCheck.Interval,
2✔
2020
                        cfg.HealthChecks.LeaderCheck.Timeout,
2✔
2021
                        cfg.HealthChecks.LeaderCheck.Backoff,
2✔
2022
                        cfg.HealthChecks.LeaderCheck.Attempts,
2✔
2023
                )
2✔
2024

2✔
2025
                checks = append(checks, leaderCheck)
2✔
2026
        }
2✔
2027

2✔
2028
        // If we have not disabled all of our health checks, we create a
2✔
2029
        // liveness monitor with our configured checks.
2✔
2030
        s.livenessMonitor = healthcheck.NewMonitor(
2✔
2031
                &healthcheck.Config{
2✔
2032
                        Checks:   checks,
2033
                        Shutdown: srvrLog.Criticalf,
2034
                },
2035
        )
2036
}
2037

2✔
2038
// Started returns true if the server has been started, and false otherwise.
×
2039
// NOTE: This function is safe for concurrent access.
×
2040
func (s *server) Started() bool {
×
2041
        return atomic.LoadInt32(&s.active) != 0
×
2042
}
×
2043

×
2044
// cleaner is used to aggregate "cleanup" functions during an operation that
×
2045
// starts several subsystems. In case one of the subsystem fails to start
×
2046
// and a proper resource cleanup is required, the "run" method achieves this
×
2047
// by running all these added "cleanup" functions.
×
2048
type cleaner []func() error
×
2049

×
2050
// add is used to add a cleanup function to be called when
×
2051
// the run function is executed.
×
2052
func (c cleaner) add(cleanup func() error) cleaner {
×
2053
        return append(c, cleanup)
×
2054
}
×
2055

×
2056
// run is used to run all the previousely added cleanup functions.
×
2057
func (c cleaner) run() {
×
2058
        for i := len(c) - 1; i >= 0; i-- {
2059
                if err := c[i](); err != nil {
×
2060
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2061
                }
×
2062
        }
×
2063
}
×
2064

2065
// Start starts the main daemon server, all requested listeners, and any helper
×
2066
// goroutines.
2067
// NOTE: This function is safe for concurrent access.
2068
//
2069
//nolint:funlen
2070
func (s *server) Start() error {
2071
        var startErr error
2072

2073
        // If one sub system fails to start, the following code ensures that the
×
2074
        // previous started ones are stopped. It also ensures a proper wallet
2075
        // shutdown which is important for releasing its resources (boltdb, etc...)
2076
        cleanup := cleaner{}
2077

2078
        s.start.Do(func() {
2✔
2079
                cleanup = cleanup.add(s.customMessageServer.Stop)
2✔
2080
                if err := s.customMessageServer.Start(); err != nil {
2✔
2081
                        startErr = err
2✔
2082
                        return
2✔
2083
                }
2✔
2084

2085
                if s.hostAnn != nil {
2086
                        cleanup = cleanup.add(s.hostAnn.Stop)
2087
                        if err := s.hostAnn.Start(); err != nil {
2088
                                startErr = err
2✔
2089
                                return
2✔
2090
                        }
2✔
2091
                }
2092

2093
                if s.livenessMonitor != nil {
2094
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
2095
                        if err := s.livenessMonitor.Start(); err != nil {
2096
                                startErr = err
2097
                                return
2098
                        }
2099
                }
2100

2✔
2101
                // Start the notification server. This is used so channel
2✔
2102
                // management goroutines can be notified when a funding
2✔
2103
                // transaction reaches a sufficient number of confirmations, or
2104
                // when the input for the funding transaction is spent in an
2105
                // attempt at an uncooperative close by the counterparty.
×
2106
                cleanup = cleanup.add(s.sigPool.Stop)
×
2107
                if err := s.sigPool.Start(); err != nil {
×
2108
                        startErr = err
×
2109
                        return
×
2110
                }
2111

2112
                cleanup = cleanup.add(s.writePool.Stop)
2113
                if err := s.writePool.Start(); err != nil {
2114
                        startErr = err
2115
                        return
2116
                }
2117

2118
                cleanup = cleanup.add(s.readPool.Stop)
2119
                if err := s.readPool.Start(); err != nil {
2✔
2120
                        startErr = err
2✔
2121
                        return
2✔
2122
                }
2✔
2123

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

2✔
2130
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
×
2131
                if err := s.cc.BestBlockTracker.Start(); err != nil {
×
2132
                        startErr = err
2133
                        return
2✔
2134
                }
2135

2136
                cleanup = cleanup.add(s.channelNotifier.Stop)
2137
                if err := s.channelNotifier.Start(); err != nil {
2138
                        startErr = err
2139
                        return
2140
                }
2141

2✔
2142
                cleanup = cleanup.add(func() error {
2✔
2143
                        return s.peerNotifier.Stop()
2✔
2144
                })
2✔
2145
                if err := s.peerNotifier.Start(); err != nil {
×
2146
                        startErr = err
×
2147
                        return
2148
                }
2✔
2149

2✔
2150
                cleanup = cleanup.add(s.htlcNotifier.Stop)
2✔
2151
                if err := s.htlcNotifier.Start(); err != nil {
2✔
2152
                        startErr = err
2✔
2153
                        return
2✔
2154
                }
2✔
2155

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

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

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

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

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

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

×
2194
                // htlcSwitch must be started before chainArb since the latter
2195
                // relies on htlcSwitch to deliver resolution message upon
2✔
2196
                // start.
2✔
2197
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
2198
                if err := s.htlcSwitch.Start(); err != nil {
×
2199
                        startErr = err
×
2200
                        return
2201
                }
2✔
2202

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

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

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

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

2227
                cleanup = cleanup.add(s.chanRouter.Stop)
4✔
2228
                if err := s.chanRouter.Start(); err != nil {
2✔
2229
                        startErr = err
2✔
2230
                        return
×
2231
                }
×
2232
                // The authGossiper depends on the chanRouter and therefore
×
2233
                // should be started after it.
2234
                cleanup = cleanup.add(s.authGossiper.Stop)
2235
                if err := s.authGossiper.Start(); err != nil {
2✔
2236
                        startErr = err
2✔
2237
                        return
×
2238
                }
×
2239

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

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

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

×
2258
                cleanup = cleanup.add(s.chanEventStore.Stop)
2259
                if err := s.chanEventStore.Start(); err != nil {
2✔
2260
                        startErr = err
2✔
2261
                        return
×
2262
                }
×
2263

×
2264
                cleanup.add(func() error {
2265
                        s.missionController.StopStoreTickers()
2266
                        return nil
2267
                })
2268
                s.missionController.RunStoreTickers()
2✔
2269

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

×
2302
                // chanSubSwapper must be started after the `channelNotifier`
×
2303
                // because it depends on channel events as a synchronization
2304
                // point.
2305
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
2✔
2306
                if err := s.chanSubSwapper.Start(); err != nil {
2✔
2307
                        startErr = err
×
2308
                        return
×
2309
                }
×
2310

2311
                if s.torController != nil {
2✔
2312
                        cleanup = cleanup.add(s.torController.Stop)
2✔
2313
                        if err := s.createNewHiddenService(); err != nil {
×
2314
                                startErr = err
×
2315
                                return
×
2316
                        }
2317
                }
2✔
2318

2✔
2319
                if s.natTraversal != nil {
×
2320
                        s.wg.Add(1)
×
2321
                        go s.watchExternalIP()
×
2322
                }
2323

2✔
2324
                // Start connmgr last to prevent connections before init.
2✔
2325
                cleanup = cleanup.add(func() error {
×
2326
                        s.connMgr.Stop()
×
2327
                        return nil
×
2328
                })
2329
                s.connMgr.Start()
2✔
2330

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

2✔
2350
                        peerAddr := &lnwire.NetAddress{
2✔
2351
                                IdentityKey: parsedPubkey,
×
2352
                                Address:     addr,
×
2353
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
2354
                        }
×
2355

×
2356
                        err = s.ConnectToPeer(
×
2357
                                peerAddr, true,
×
2358
                                s.cfg.ConnectionTimeout,
×
2359
                        )
×
2360
                        if err != nil {
2361
                                startErr = fmt.Errorf("unable to connect to "+
4✔
2362
                                        "peer address provided as a config "+
2✔
2363
                                        "option: %v", err)
2✔
2364
                                return
2✔
2365
                        }
2✔
2366
                }
2✔
2367

×
2368
                // Subscribe to NodeAnnouncements that advertise new addresses
×
2369
                // our persistent peers.
×
2370
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2371
                        startErr = err
2372
                        return
2373
                }
2374

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

2390
                // setSeedList is a helper function that turns multiple DNS seed
2✔
2391
                // server tuples from the command line or config file into the
×
2392
                // data structure we need and does a basic formal sanity check
×
2393
                // in the process.
×
2394
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
2395
                        if len(tuples) == 0 {
2396
                                return
2✔
2397
                        }
×
2398

×
2399
                        result := make([][2]string, len(tuples))
×
2400
                        for idx, tuple := range tuples {
2✔
2401
                                tuple = strings.TrimSpace(tuple)
2✔
2402
                                if len(tuple) == 0 {
2✔
2403
                                        return
2✔
2404
                                }
4✔
2405

2✔
2406
                                servers := strings.Split(tuple, ",")
2✔
2407
                                if len(servers) > 2 || len(servers) == 0 {
2✔
2408
                                        srvrLog.Warnf("Ignoring invalid DNS "+
2✔
2409
                                                "seed tuple: %v", servers)
×
2410
                                        return
×
2411
                                }
×
2412

×
2413
                                copy(result[idx][:], servers)
2✔
2414
                        }
2✔
2415

×
2416
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2417
                }
×
2418

×
2419
                // Let users overwrite the DNS seed nodes. We only allow them
×
2420
                // for bitcoin mainnet/testnet/signet.
2421
                if s.cfg.Bitcoin.MainNet {
2✔
2422
                        setSeedList(
2✔
2423
                                s.cfg.Bitcoin.DNSSeeds,
2✔
2424
                                chainreg.BitcoinMainnetGenesis,
2✔
2425
                        )
2✔
2426
                }
2✔
2427
                if s.cfg.Bitcoin.TestNet3 {
2✔
2428
                        setSeedList(
2✔
2429
                                s.cfg.Bitcoin.DNSSeeds,
2✔
2430
                                chainreg.BitcoinTestnetGenesis,
2✔
2431
                        )
2✔
2432
                }
×
2433
                if s.cfg.Bitcoin.SigNet {
×
2434
                        setSeedList(
×
2435
                                s.cfg.Bitcoin.DNSSeeds,
×
2436
                                chainreg.BitcoinSignetGenesis,
×
2437
                        )
2438
                }
2439

2440
                // If network bootstrapping hasn't been disabled, then we'll
2441
                // configure the set of active bootstrappers, and launch a
2✔
2442
                // dedicated goroutine to maintain a set of persistent
×
2443
                // connections.
×
2444
                if shouldPeerBootstrap(s.cfg) {
×
2445
                        bootstrappers, err := initNetworkBootstrappers(s)
2446
                        if err != nil {
2447
                                startErr = err
2448
                                return
2449
                        }
2450

2451
                        s.wg.Add(1)
2452
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
2✔
2453
                } else {
×
2454
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
2455
                }
×
2456

2✔
2457
                // Set the active flag now that we've completed the full
×
2458
                // startup.
×
2459
                atomic.StoreInt32(&s.active, 1)
×
2460
        })
2461

2462
        if startErr != nil {
2463
                cleanup.run()
2464
        }
2465
        return startErr
2✔
2466
}
×
2467

×
2468
// Stop gracefully shutsdown the main daemon server. This function will signal
×
2469
// any active goroutines, or helper objects to exit, then blocks until they've
2470
// all successfully exited. Additionally, any/all listeners are closed.
×
2471
// NOTE: This function is safe for concurrent access.
×
2472
func (s *server) Stop() error {
×
2473
        s.stop.Do(func() {
×
2474
                atomic.StoreInt32(&s.stopping, 1)
×
2475

×
2476
                close(s.quit)
2477

×
2478
                // Shutdown connMgr first to prevent conns during shutdown.
×
2479
                s.connMgr.Stop()
×
2480

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

2540
                // Update channel.backup file. Make sure to do it before
2541
                // stopping chanSubSwapper.
2✔
2542
                singles, err := chanbackup.FetchStaticChanBackups(
2543
                        s.chanStateDB, s.addrSource,
2544
                )
2✔
2545
                if err != nil {
×
2546
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2547
                                err)
2✔
2548
                } else {
2549
                        err := s.chanSubSwapper.ManualUpdate(singles)
2550
                        if err != nil {
2551
                                srvrLog.Warnf("Manual update of channel "+
2552
                                        "backup failed: %v", err)
2553
                        }
2554
                }
2✔
2555

4✔
2556
                if err := s.chanSubSwapper.Stop(); err != nil {
2✔
2557
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
2✔
2558
                }
2✔
2559
                if err := s.cc.ChainNotifier.Stop(); err != nil {
2✔
2560
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
2✔
2561
                }
2✔
2562
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
2✔
2563
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
2✔
2564
                                err)
2✔
2565
                }
2✔
2566
                if err := s.chanEventStore.Stop(); err != nil {
2✔
2567
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
2✔
2568
                                err)
×
2569
                }
×
2570
                s.missionController.StopStoreTickers()
2✔
2571

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

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

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

×
2602
                if s.livenessMonitor != nil {
×
2603
                        if err := s.livenessMonitor.Stop(); err != nil {
2✔
2604
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2605
                                        "monitor: %v", err)
×
2606
                        }
2✔
2607
                }
×
2608

×
2609
                // Wait for all lingering goroutines to quit.
2✔
2610
                srvrLog.Debug("Waiting for server to shutdown...")
×
2611
                s.wg.Wait()
×
2612

2✔
2613
                srvrLog.Debug("Stopping buffer pools...")
×
2614
                s.sigPool.Stop()
×
2615
                s.writePool.Stop()
2✔
2616
                s.readPool.Stop()
×
2617
        })
×
2618

2✔
2619
        return nil
×
2620
}
×
2621

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

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

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

×
2647
                hostIP := fmt.Sprintf("%v:%d", ip, port)
2✔
2648
                externalIPs = append(externalIPs, hostIP)
×
2649
        }
×
2650

×
2651
        return externalIPs, nil
2✔
2652
}
×
2653

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

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

×
2678
        // Before exiting, we'll make sure to remove the forwarding rules set
2679
        // up by the server.
2680
        defer s.removePortForwarding()
2✔
2681

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

2✔
2689
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2690

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

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

×
2721
                        if ip.Equal(s.lastDetectedIP) {
×
2722
                                continue
×
2723
                        }
×
2724

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

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

2742
                                newAddrs = append(newAddrs, addr)
2743
                        }
2744

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

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

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

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

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

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

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

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

×
2811
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2812

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

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

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

×
2834
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2835
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2836
                        )
×
2837
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
2838
                }
2839
        }
2840

2841
        return bootStrappers, nil
2842
}
2843

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

2854
        ignore := make(map[autopilot.NodeID]struct{})
2855

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

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

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

2874
        return ignore
2875
}
×
2876

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

×
2885
        defer s.wg.Done()
×
2886

2887
        // Before we continue, init the ignore peers map.
2888
        ignoreList := s.createBootstrapIgnorePeers()
2889

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

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

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

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

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

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

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

2935
                        if epochAttempts > 0 &&
×
2936
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2937

×
2938
                                sampleTicker.Stop()
×
2939

×
2940
                                backOff *= 2
×
2941
                                if backOff > bootstrapBackOffCeiling {
×
2942
                                        backOff = bootstrapBackOffCeiling
×
2943
                                }
×
2944

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

2951
                        atomic.StoreUint32(&epochErrors, 0)
2952
                        epochAttempts = 0
2953

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

×
2958
                        srvrLog.Debugf("Attempting to obtain %v more network "+
2959
                                "peers", numNeeded)
×
2960

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

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

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

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

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

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

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

×
3023
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3024
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3025

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

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

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

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

×
3048
                if numActivePeers >= numTargetPeers {
×
3049
                        return
×
3050
                }
×
3051

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

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

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

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

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

3095
                                errChan := make(chan error, 1)
3096
                                go s.connectToPeer(
3097
                                        addr, errChan, s.cfg.ConnectionTimeout,
3098
                                )
3099

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

×
3123
                wg.Wait()
×
3124
        }
×
3125
}
×
3126

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

×
3139
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3140
        if err != nil {
×
3141
                return err
×
3142
        }
×
3143

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

×
3156
        switch {
×
3157
        case s.cfg.Tor.V2:
×
3158
                onionCfg.Type = tor.V2
3159
        case s.cfg.Tor.V3:
3160
                onionCfg.Type = tor.V3
3161
        }
3162

×
3163
        addr, err := s.torController.AddOnion(onionCfg)
×
3164
        if err != nil {
×
3165
                return err
×
3166
        }
×
3167

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

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

3198
        return nil
×
3199
}
×
3200

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

3207
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3208
        if err != nil {
×
3209
                return nil, err
3210
        }
3211

3212
        for _, channel := range nodeChans {
3213
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
3214
                        return channel, nil
×
3215
                }
×
3216
        }
×
3217

×
3218
        return nil, fmt.Errorf("unable to find channel")
×
3219
}
×
3220

×
3221
// getNodeAnnouncement fetches the current, fully signed node announcement.
×
3222
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
3223
        s.mu.Lock()
3224
        defer s.mu.Unlock()
×
3225

×
3226
        return *s.currentNodeAnn
×
3227
}
×
3228

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

×
3235
        s.mu.Lock()
×
3236
        defer s.mu.Unlock()
×
3237

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

×
3249
                // If we could successfully update our feature manager, add
×
3250
                // an update modifier to include these new features to our
×
3251
                // set.
×
3252
                modifiers = append(
3253
                        modifiers, netann.NodeAnnSetFeatures(features),
3254
                )
3255
        }
×
3256

×
3257
        // Always update the timestamp when refreshing to ensure the update
×
3258
        // propagates.
×
3259
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3260

×
3261
        // Apply the requested changes to the node announcement.
×
3262
        for _, modifier := range modifiers {
×
3263
                modifier(s.currentNodeAnn)
×
3264
        }
3265

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

×
3274
        return *s.currentNodeAnn, nil
×
3275
}
×
3276

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

×
3284
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3285
        if err != nil {
3286
                return fmt.Errorf("unable to generate new node "+
3287
                        "announcement: %v", err)
3288
        }
3289

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

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

3306
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
3307

2✔
3308
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
2✔
3309
                return fmt.Errorf("can't set self node: %w", err)
2✔
3310
        }
2✔
3311

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

2✔
3320
        return nil
2✔
3321
}
2✔
3322

2✔
3323
type nodeAddresses struct {
2✔
3324
        pubKey    *btcec.PublicKey
2✔
3325
        addresses []net.Addr
4✔
3326
}
2✔
3327

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

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

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

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

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

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

2✔
3389
                pubStr := string(channelPeer.PubKeyBytes[:])
2✔
3390

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

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

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

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

2✔
3428
                // Construct a slice of the deduped addresses.
×
3429
                var addrs []net.Addr
×
3430
                for _, addr := range addrSet {
4✔
3431
                        addrs = append(addrs, addr)
2✔
3432
                }
2✔
3433

2✔
3434
                n := &nodeAddresses{
2✔
3435
                        addresses: addrs,
2✔
3436
                }
2✔
3437
                n.pubKey, err = channelPeer.PubKey()
2✔
3438
                if err != nil {
3439
                        return err
3440
                }
3441

3442
                nodeAddrsMap[pubStr] = n
2✔
3443
                return nil
2✔
3444
        })
×
3445
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
×
3446
                return err
3447
        }
3448

3449
        srvrLog.Debugf("Establishing %v persistent connections on start",
2✔
3450
                len(nodeAddrsMap))
2✔
3451

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

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

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

2✔
3480
                        s.persistentPeerAddrs[pubStr] = append(
4✔
3481
                                s.persistentPeerAddrs[pubStr], lnAddr)
2✔
3482
                }
2✔
3483

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

3494
                        go s.connectToPersistentPeer(pubStr)
3495
                } else {
3496
                        go s.delayInitialReconnect(pubStr)
2✔
3497
                }
4✔
3498

4✔
3499
                numOutboundConns++
2✔
3500
        }
2✔
3501

2✔
3502
        return nil
3503
}
3504

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

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

2✔
3524
        s.mu.Lock()
×
3525
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
3526
                delete(s.persistentPeers, pubKeyStr)
3527
                delete(s.persistentPeersBackoff, pubKeyStr)
2✔
3528
                delete(s.persistentPeerAddrs, pubKeyStr)
2✔
3529
                s.cancelConnReqs(pubKeyStr, nil)
3530
                s.mu.Unlock()
2✔
3531

×
3532
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
3533
                        "peer has no open channels", compressedPubKey)
3534

2✔
3535
                return
2✔
3536
        }
2✔
3537
        s.mu.Unlock()
2✔
3538
}
2✔
3539

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

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

2✔
3563
                peers = append(peers, sPeer)
2✔
3564
        }
2✔
3565
        s.mu.RUnlock()
2✔
3566

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

3574
                // Dispatch a go routine to enqueue all messages to this peer.
3575
                wg.Add(1)
3576
                s.wg.Add(1)
2✔
3577
                go func(p lnpeer.Peer) {
4✔
3578
                        defer s.wg.Done()
2✔
3579
                        defer wg.Done()
2✔
3580

2✔
3581
                        p.SendMessageLazy(false, msgs...)
×
3582
                }(sPeer)
×
3583
        }
3584

2✔
3585
        // Wait for all messages to have been dispatched before returning to
3586
        // caller.
3587
        wg.Wait()
2✔
3588

3589
        return nil
3590
}
3591

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

×
3599
        s.mu.Lock()
×
3600

3601
        // Compute the target peer's identifier.
3602
        pubStr := string(peerKey[:])
3603

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

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

3626
                // Connected, can return early.
3627
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3628

3629
                select {
3630
                case peerChan <- peer:
3631
                case <-s.quit:
3632
                }
2✔
3633

2✔
3634
                return
2✔
3635
        }
2✔
3636

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

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

2✔
3652
        c := make(chan struct{})
2✔
3653

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

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

3670
        return c
3671
}
3672

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

3682
        pubStr := string(peerKey.SerializeCompressed())
2✔
3683

2✔
3684
        return s.findPeerByPubStr(pubStr)
2✔
3685
}
2✔
3686

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

2✔
3696
        return s.findPeerByPubStr(pubStr)
2✔
3697
}
2✔
3698

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

×
3707
        return peer, nil
×
3708
}
×
3709

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

2✔
3716
        // Now, determine the appropriate backoff to use for the retry.
×
3717
        backoff, ok := s.persistentPeersBackoff[pubStr]
3718
        if !ok {
3719
                // If an existing backoff was unknown, use the default.
2✔
3720
                return s.cfg.MinBackoff
3721
        }
3722

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

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

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

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

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

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

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

2✔
3782
        nodePub := conn.(*brontide.Conn).RemotePub()
2✔
3783
        pubSer := nodePub.SerializeCompressed()
3784
        pubStr := string(pubSer)
3785

3786
        var pubBytes [33]byte
2✔
3787
        copy(pubBytes[:], pubSer)
2✔
3788

4✔
3789
        s.mu.Lock()
2✔
3790
        defer s.mu.Unlock()
2✔
3791

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

3799
                return
2✔
3800
        }
2✔
3801

2✔
3802
        if shouldDc {
2✔
3803
                srvrLog.Debugf("Dropping connection for %v since they are "+
4✔
3804
                        "banned.", pubSer)
2✔
3805

2✔
3806
                conn.Close()
2✔
3807

3808
                return
3809
        }
3810

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

3818
                conn.Close()
2✔
3819
                return
4✔
3820
        }
2✔
3821

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

×
3832
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
3833

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

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

3857
                        srvrLog.Warnf("Received inbound connection from "+
3858
                                "peer %v, but already have outbound "+
3859
                                "connection, dropping conn", connectedPeer)
3860
                        conn.Close()
2✔
3861
                        return
2✔
3862
                }
2✔
3863

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

2✔
3869
                s.cancelConnReqs(pubStr, nil)
2✔
3870

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

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

×
3892
        nodePub := conn.(*brontide.Conn).RemotePub()
×
3893
        pubSer := nodePub.SerializeCompressed()
×
3894
        pubStr := string(pubSer)
×
3895

3896
        var pubBytes [33]byte
3897
        copy(pubBytes[:], pubSer)
3898

4✔
3899
        s.mu.Lock()
2✔
3900
        defer s.mu.Unlock()
2✔
3901

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

3909
                return
3910
        }
2✔
3911

×
3912
        if shouldDc {
×
3913
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3914
                        "banned.", pubSer)
×
3915

×
3916
                if connReq != nil {
3917
                        s.connMgr.Remove(connReq.ID())
2✔
3918
                }
2✔
3919

2✔
3920
                conn.Close()
2✔
3921

2✔
3922
                return
2✔
3923
        }
2✔
3924

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

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

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

3951
                if connReq != nil {
×
3952
                        s.connMgr.Remove(connReq.ID())
×
3953
                }
×
3954

×
3955
                conn.Close()
×
3956
                return
×
3957
        }
×
3958

×
3959
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
×
3960
                conn.RemoteAddr())
×
3961

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

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

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

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

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

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

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

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

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

2✔
4050
        for _, connReq := range connReqs {
2✔
4051
                srvrLog.Tracef("Canceling %s:", connReqs)
2✔
4052

2✔
4053
                // Atomically capture the current request identifier.
4✔
4054
                connID := connReq.ID()
2✔
4055

2✔
4056
                // Skip any zero IDs, this indicates the request has not
2✔
4057
                // yet been schedule.
2✔
4058
                if connID == UnassignedConnID {
4059
                        continue
4060
                }
4061

4062
                // Skip a particular connection ID if instructed.
4063
                if skip != nil && connID == *skip {
2✔
4064
                        continue
2✔
4065
                }
2✔
4066

2✔
4067
                s.connMgr.Remove(connID)
2✔
4068
        }
2✔
4069

4070
        delete(s.persistentConnReqs, pubStr)
×
4071
}
×
4072

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

×
4079
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
4080
                Peer: peer,
×
4081
                Msg:  msg,
×
4082
        })
×
4083
}
×
4084

×
4085
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
×
4086
// messages.
×
4087
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
4088
        return s.customMessageServer.Subscribe()
4089
}
4090

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

×
4098
        brontideConn := conn.(*brontide.Conn)
×
4099
        addr := conn.RemoteAddr()
×
4100
        pubKey := brontideConn.RemotePub()
×
4101

×
4102
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
4103
                pubKey.SerializeCompressed(), addr, inbound)
×
4104

4105
        peerAddr := &lnwire.NetAddress{
4106
                IdentityKey: pubKey,
4107
                Address:     addr,
4108
                ChainNet:    s.cfg.ActiveNetParams.Net,
4109
        }
4110

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

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

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

2✔
4140
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
2✔
4141
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
2✔
4142

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

2✔
4186
                        return s.genNodeAnnouncement(nil)
2✔
4187
                },
2✔
4188

2✔
4189
                PongBuf: s.pongBuf,
2✔
4190

2✔
4191
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
2✔
4192

2✔
4193
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
2✔
4194

2✔
4195
                FundingManager: s.fundingMgr,
2✔
4196

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

2✔
4221
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
4✔
4222
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
2✔
4223

2✔
4224
        p := peer.NewBrontide(pCfg)
4225

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

2✔
4229
        s.addPeer(p)
2✔
4230

2✔
4231
        // Once we have successfully added the peer to the server, we can
2✔
4232
        // delete the previous error buffer from the server's map of error
2✔
4233
        // buffers.
2✔
4234
        delete(s.peerErrors, pkStr)
2✔
4235

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

2✔
4243
// addPeer adds the passed peer to the server's global state of all active
2✔
4244
// peers.
2✔
4245
func (s *server) addPeer(p *peer.Brontide) {
2✔
4246
        if p == nil {
2✔
4247
                return
2✔
4248
        }
2✔
4249

2✔
4250
        pubBytes := p.IdentityKey().SerializeCompressed()
2✔
4251

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

2✔
4258
                return
2✔
4259
        }
2✔
4260

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

2✔
4266
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
2✔
4267
        // be human-readable.
2✔
4268
        pubStr := string(pubBytes)
2✔
4269

4✔
4270
        s.peersByPub[pubStr] = p
2✔
4271

2✔
4272
        if p.Inbound() {
2✔
4273
                s.inboundPeers[pubStr] = p
4274
        } else {
4275
                s.outboundPeers[pubStr] = p
4276
        }
4277

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

4283
        s.peerNotifier.NotifyPeerOnline(pubKey)
4284
}
4285

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

4298
        pubBytes := p.IdentityKey().SerializeCompressed()
4299

4300
        // Avoid initializing peers while the server is exiting.
4301
        if s.Stopped() {
4302
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
4303
                        pubBytes)
4304
                return
4305
        }
4306

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

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

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

2✔
4326
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
2✔
4327
                return
2✔
4328
        }
2✔
4329

2✔
4330
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
2✔
4331
        // was successful, and to begin watching the peer's wait group.
2✔
4332
        close(ready)
2✔
4333

2✔
4334
        s.mu.Lock()
2✔
4335
        defer s.mu.Unlock()
2✔
4336

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

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

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

2✔
4367
        p.WaitForDisconnect(ready)
2✔
4368

4✔
4369
        srvrLog.Debugf("Peer %v has been disconnected", p)
2✔
4370

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

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

4384
        pubKey := p.IdentityKey()
4385

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

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

×
4400
        for _, link := range links {
×
4401
                s.htlcSwitch.RemoveLink(link.ChanID())
×
4402
        }
4403

4404
        s.mu.Lock()
4405
        defer s.mu.Unlock()
4406

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

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

×
4421
                pubKey := p.PubKey()
×
4422
                pubStr := string(pubKey[:])
×
4423

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

2✔
4437
        // First, cleanup any remaining state the server has regarding the peer
2✔
4438
        // in question.
2✔
4439
        s.removePeer(p)
4✔
4440

2✔
4441
        // Next, check to see if this is a persistent peer or not.
2✔
4442
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
4443
                return
×
4444
        }
4445

4446
        // Get the last address that we used to connect to the peer.
2✔
4447
        addrs := []net.Addr{
4448
                p.NetAddress().Address,
4449
        }
4450

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

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

2✔
4467
                // Fall back to the existing peer address if
2✔
4468
                // we're not accepting connections over Tor.
2✔
4469
                if s.torController == nil {
4✔
4470
                        break
2✔
4471
                }
2✔
4472

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

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

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

2✔
4499
        // Add any missing addresses for this peer to persistentPeerAddr.
4500
        for _, addr := range addrs {
2✔
4501
                if existingAddrs[addr.String()] {
2✔
4502
                        continue
2✔
4503
                }
2✔
4504

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

2✔
4515
        // Record the computed backoff in the backoff map.
×
4516
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
4517
        s.persistentPeersBackoff[pubStr] = backoff
×
4518

×
4519
        // Initialize a retry canceller for this peer if one does not
×
4520
        // exist.
×
4521
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
4522
        if !ok {
×
4523
                cancelChan = make(chan struct{})
×
4524
                s.persistentRetryCancels[pubStr] = cancelChan
×
4525
        }
×
4526

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

4535
                select {
2✔
4536
                case <-time.After(backoff):
2✔
4537
                case <-cancelChan:
2✔
4538
                        return
4✔
4539
                case <-s.quit:
2✔
4540
                        return
2✔
4541
                }
4542

4543
                srvrLog.Debugf("Attempting to re-establish persistent "+
2✔
4544
                        "connection to peer %x",
2✔
4545
                        p.IdentityKey().SerializeCompressed())
2✔
4546

2✔
4547
                s.connectToPersistentPeer(pubStr)
2✔
4548
        }()
2✔
4549
}
2✔
4550

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

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

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

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

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

4601
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
2✔
4602

2✔
4603
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
2✔
4604
        if !ok {
2✔
4605
                cancelChan = make(chan struct{})
2✔
4606
                s.persistentRetryCancels[pubKeyStr] = cancelChan
2✔
4607
        }
2✔
4608

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

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

4626
                        s.mu.Lock()
4✔
4627
                        s.persistentConnReqs[pubKeyStr] = append(
2✔
4628
                                s.persistentConnReqs[pubKeyStr], connReq,
2✔
4629
                        )
2✔
4630
                        s.mu.Unlock()
2✔
4631

2✔
4632
                        srvrLog.Debugf("Attempting persistent connection to "+
2✔
4633
                                "channel peer %v", addr)
2✔
4634

2✔
4635
                        go s.connMgr.Connect(connReq)
2✔
4636

2✔
4637
                        select {
4638
                        case <-s.quit:
4639
                                return
2✔
4640
                        case <-cancelChan:
2✔
4641
                                return
2✔
4642
                        case <-ticker.C:
2✔
4643
                        }
2✔
4644
                }
4645
        }()
4646
}
4647

4648
// removePeer removes the passed peer from the server's state of all active
4649
// peers.
4650
func (s *server) removePeer(p *peer.Brontide) {
4651
        if p == nil {
4652
                return
2✔
4653
        }
2✔
4654

2✔
4655
        srvrLog.Debugf("removing peer %v", p)
2✔
4656

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

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

4666
        // Ignore deleting peers if we're shutting down.
4667
        if s.Stopped() {
4668
                return
4669
        }
4670

2✔
4671
        pKey := p.PubKey()
4✔
4672
        pubSer := pKey[:]
2✔
4673
        pubStr := string(pubSer)
2✔
4674

2✔
4675
        delete(s.peersByPub, pubStr)
4676

4677
        if p.Inbound() {
4678
                delete(s.inboundPeers, pubStr)
4679
        } else {
×
4680
                delete(s.outboundPeers, pubStr)
×
4681
        }
×
4682

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

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

2✔
4694
        s.peerNotifier.NotifyPeerOffline(pubKey)
4695
}
4696

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

4705
        targetPub := string(addr.IdentityKey.SerializeCompressed())
4706

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

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

2✔
4720
        // Peer was not found, continue to pursue connection with peer.
2✔
4721

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

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

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

2✔
4753
                go s.connMgr.Connect(connReq)
2✔
4754

2✔
4755
                return nil
2✔
4756
        }
2✔
4757
        s.mu.Unlock()
2✔
4758

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

×
4766
        select {
4767
        case err := <-errChan:
2✔
4768
                return err
2✔
4769
        case <-s.quit:
2✔
4770
                return ErrServerShuttingDown
2✔
4771
        }
2✔
4772
}
2✔
4773

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

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

4792
        close(errChan)
4793

4794
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
4795
                conn.LocalAddr(), conn.RemoteAddr())
4796

4797
        s.OutboundPeerConnected(nil, conn)
4798
}
4799

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

2✔
4808
        s.mu.Lock()
2✔
4809
        defer s.mu.Unlock()
2✔
4810

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

4819
        srvrLog.Infof("Disconnecting from %v", peer)
4820

4821
        s.cancelConnReqs(pubStr, nil)
4✔
4822

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

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

2✔
4833
        return nil
2✔
4834
}
2✔
4835

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

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

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

2✔
4857
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
2✔
4858
                return req.Updates, req.Err
2✔
4859
        }
2✔
4860
        req.Peer = peer
2✔
4861
        s.mu.RUnlock()
2✔
4862

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

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

2✔
4883
                return req.Updates, req.Err
×
4884
        }
4885

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

2✔
4892
        return req.Updates, req.Err
2✔
4893
}
2✔
4894

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

2✔
4902
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
2✔
4903
        for _, peer := range s.peersByPub {
2✔
4904
                peers = append(peers, peer)
2✔
4905
        }
2✔
4906

2✔
4907
        return peers
2✔
4908
}
2✔
4909

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

2✔
4921
        // Using 1/10 of our duration as a margin, compute a random offset to
2✔
4922
        // avoid the nodes entering connection cycles.
2✔
4923
        margin := nextBackoff / 10
2✔
4924

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

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

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

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

2✔
4949
        node, err := s.graphDB.FetchLightningNode(vertex)
2✔
4950
        if err != nil {
2✔
4951
                return nil, err
×
4952
        }
×
4953

×
4954
        if len(node.Addresses) == 0 {
×
4955
                return nil, errNoAdvertisedAddr
×
4956
        }
2✔
4957

2✔
4958
        return node.Addresses, nil
2✔
4959
}
2✔
4960

2✔
4961
// fetchLastChanUpdate returns a function which is able to retrieve our latest
2✔
4962
// channel update for a target channel.
2✔
4963
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
×
4964
        *lnwire.ChannelUpdate1, error) {
×
4965

×
4966
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
4967
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
4968
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
4969
                if err != nil {
4970
                        return nil, err
4971
                }
4972

4973
                return netann.ExtractChannelUpdate(
4974
                        ourPubKey[:], info, edge1, edge2,
4975
                )
2✔
4976
        }
×
4977
}
×
4978

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

4985
        var (
4986
                peerAlias    *lnwire.ShortChannelID
2✔
4987
                defaultAlias lnwire.ShortChannelID
2✔
4988
        )
2✔
4989

4990
        chanID := lnwire.NewChanIDFromOutPoint(*op)
4991

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

2✔
5001
        errChan := s.authGossiper.ProcessLocalAnnouncement(
2✔
5002
                update, discovery.RemoteAlias(peerAlias),
5003
        )
2✔
5004
        select {
5005
        case err := <-errChan:
5006
                return err
5007
        case <-s.quit:
5008
                return ErrServerShuttingDown
5009
        }
5010
}
2✔
5011

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

5017
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
5018
        if err != nil {
5019
                return err
2✔
5020
        }
2✔
5021

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

5031
        msg, err := lnwire.NewCustom(msgType, data)
2✔
5032
        if err != nil {
5033
                return err
5034
        }
5035

5036
        // Send the message as low-priority. For now we assume that all
5037
        // application-defined message are low priority.
5038
        return peer.SendMessageLazy(true, msg)
5039
}
2✔
5040

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

2✔
5049
        return func() fn.Result[lnwallet.AddrWithKey] {
5050
                sweepAddr, err := wallet.NewAddress(
4✔
5051
                        lnwallet.TaprootPubkey, false,
2✔
5052
                        lnwallet.DefaultAccountName,
2✔
5053
                )
5054
                if err != nil {
2✔
5055
                        return fn.Err[lnwallet.AddrWithKey](err)
5056
                }
5057

5058
                addr, err := txscript.PayToAddrScript(sweepAddr)
5059
                if err != nil {
5060
                        return fn.Err[lnwallet.AddrWithKey](err)
2✔
5061
                }
2✔
5062

2✔
5063
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
4✔
5064
                        wallet, netParams, addr,
2✔
5065
                )
4✔
5066
                if err != nil {
2✔
5067
                        return fn.Err[lnwallet.AddrWithKey](err)
2✔
5068
                }
5069

2✔
5070
                return fn.Ok(lnwallet.AddrWithKey{
2✔
5071
                        DeliveryAddress: addr,
2✔
5072
                        InternalKey:     internalKeyDesc,
5073
                })
5074
        }
5075
}
5076

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

2✔
5086
        // TODO(yy): remove the check on simnet/regtest such that the itest is
2✔
5087
        // covering the bootstrapping process.
2✔
5088
        return !cfg.NoNetBootstrap && !isDevNetwork
2✔
5089
}
2✔
5090

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

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

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

×
5124
        for _, c := range pendings {
×
5125
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
5126
                        continue
5127
                }
2✔
5128

4✔
5129
                // If the channel is still reported as pending, remove it from
2✔
5130
                // the map.
2✔
5131
                delete(closedSCIDs, c.ShortChannelID)
5132

5133
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
5134
                        c.ShortChannelID)
2✔
5135
        }
5136

5137
        return closedSCIDs
5138
}
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