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

lightningnetwork / lnd / 9840691252

08 Jul 2024 01:34PM UTC coverage: 58.404% (+0.08%) from 58.325%
9840691252

Pull #8900

github

guggero
Makefile: add GOCC variable
Pull Request #8900: Makefile: add GOCC variable

123350 of 211200 relevant lines covered (58.4%)

27929.2 hits per line

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

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

80
const (
81
        // defaultMinPeers is the minimum number of peers nodes should always be
82
        // connected to.
83
        defaultMinPeers = 3
84

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

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

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

103
        // multiAddrConnectionStagger is the number of seconds to wait between
104
        // attempting to a peer with each of its advertised addresses.
105
        multiAddrConnectionStagger = 10 * time.Second
106
)
107

108
var (
109
        // ErrPeerNotConnected signals that the server has no connection to the
110
        // given peer.
111
        ErrPeerNotConnected = errors.New("peer is not connected")
112

113
        // ErrServerNotActive indicates that the server has started but hasn't
114
        // fully finished the startup process.
115
        ErrServerNotActive = errors.New("server is still in the process of " +
116
                "starting")
117

118
        // ErrServerShuttingDown indicates that the server is in the process of
119
        // gracefully exiting.
120
        ErrServerShuttingDown = errors.New("server is shutting down")
121

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

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

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

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

155
        start sync.Once
156
        stop  sync.Once
157

158
        cfg *Config
159

160
        // identityECDH is an ECDH capable wrapper for the private key used
161
        // to authenticate any incoming connections.
162
        identityECDH keychain.SingleKeyECDH
163

164
        // identityKeyLoc is the key locator for the above wrapped identity key.
165
        identityKeyLoc keychain.KeyLocator
166

167
        // nodeSigner is an implementation of the MessageSigner implementation
168
        // that's backed by the identity private key of the running lnd node.
169
        nodeSigner *netann.NodeSigner
170

171
        chanStatusMgr *netann.ChanStatusManager
172

173
        // listenAddrs is the list of addresses the server is currently
174
        // listening on.
175
        listenAddrs []net.Addr
176

177
        // torController is a client that will communicate with a locally
178
        // running Tor server. This client will handle initiating and
179
        // authenticating the connection to the Tor server, automatically
180
        // creating and setting up onion services, etc.
181
        torController *tor.Controller
182

183
        // natTraversal is the specific NAT traversal technique used to
184
        // automatically set up port forwarding rules in order to advertise to
185
        // the network that the node is accepting inbound connections.
186
        natTraversal nat.Traversal
187

188
        // lastDetectedIP is the last IP detected by the NAT traversal technique
189
        // above. This IP will be watched periodically in a goroutine in order
190
        // to handle dynamic IP changes.
191
        lastDetectedIP net.IP
192

193
        mu         sync.RWMutex
194
        peersByPub map[string]*peer.Brontide
195

196
        inboundPeers  map[string]*peer.Brontide
197
        outboundPeers map[string]*peer.Brontide
198

199
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
200
        peerDisconnectedListeners map[string][]chan<- struct{}
201

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

212
        // peerErrors keeps a set of peer error buffers for peers that have
213
        // disconnected from us. This allows us to track historic peer errors
214
        // over connections. The string of the peer's compressed pubkey is used
215
        // as a key for this map.
216
        peerErrors map[string]*queue.CircularBuffer
217

218
        // ignorePeerTermination tracks peers for which the server has initiated
219
        // a disconnect. Adding a peer to this map causes the peer termination
220
        // watcher to short circuit in the event that peers are purposefully
221
        // disconnected.
222
        ignorePeerTermination map[*peer.Brontide]struct{}
223

224
        // scheduledPeerConnection maps a pubkey string to a callback that
225
        // should be executed in the peerTerminationWatcher the prior peer with
226
        // the same pubkey exits.  This allows the server to wait until the
227
        // prior peer has cleaned up successfully, before adding the new peer
228
        // intended to replace it.
229
        scheduledPeerConnection map[string]func()
230

231
        // pongBuf is a shared pong reply buffer we'll use across all active
232
        // peer goroutines. We know the max size of a pong message
233
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
234
        // avoid allocations each time we need to send a pong message.
235
        pongBuf []byte
236

237
        cc *chainreg.ChainControl
238

239
        fundingMgr *funding.Manager
240

241
        graphDB *channeldb.ChannelGraph
242

243
        chanStateDB *channeldb.ChannelStateDB
244

245
        addrSource chanbackup.AddressSource
246

247
        // miscDB is the DB that contains all "other" databases within the main
248
        // channel DB that haven't been separated out yet.
249
        miscDB *channeldb.DB
250

251
        invoicesDB invoices.InvoiceDB
252

253
        aliasMgr *aliasmgr.Manager
254

255
        htlcSwitch *htlcswitch.Switch
256

257
        interceptableSwitch *htlcswitch.InterceptableSwitch
258

259
        invoices *invoices.InvoiceRegistry
260

261
        channelNotifier *channelnotifier.ChannelNotifier
262

263
        peerNotifier *peernotifier.PeerNotifier
264

265
        htlcNotifier *htlcswitch.HtlcNotifier
266

267
        witnessBeacon contractcourt.WitnessBeacon
268

269
        breachArbitrator *contractcourt.BreachArbitrator
270

271
        missionControl *routing.MissionControl
272

273
        chanRouter *routing.ChannelRouter
274

275
        controlTower routing.ControlTower
276

277
        authGossiper *discovery.AuthenticatedGossiper
278

279
        localChanMgr *localchans.Manager
280

281
        utxoNursery *contractcourt.UtxoNursery
282

283
        sweeper *sweep.UtxoSweeper
284

285
        chainArb *contractcourt.ChainArbitrator
286

287
        sphinx *hop.OnionProcessor
288

289
        towerClientMgr *wtclient.Manager
290

291
        connMgr *connmgr.ConnManager
292

293
        sigPool *lnwallet.SigPool
294

295
        writePool *pool.Write
296

297
        readPool *pool.Read
298

299
        tlsManager *TLSManager
300

301
        // featureMgr dispatches feature vectors for various contexts within the
302
        // daemon.
303
        featureMgr *feature.Manager
304

305
        // currentNodeAnn is the node announcement that has been broadcast to
306
        // the network upon startup, if the attributes of the node (us) has
307
        // changed since last start.
308
        currentNodeAnn *lnwire.NodeAnnouncement
309

310
        // chansToRestore is the set of channels that upon starting, the server
311
        // should attempt to restore/recover.
312
        chansToRestore walletunlocker.ChannelsToRecover
313

314
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
315
        // backups are consistent at all times. It interacts with the
316
        // channelNotifier to be notified of newly opened and closed channels.
317
        chanSubSwapper *chanbackup.SubSwapper
318

319
        // chanEventStore tracks the behaviour of channels and their remote peers to
320
        // provide insights into their health and performance.
321
        chanEventStore *chanfitness.ChannelEventStore
322

323
        hostAnn *netann.HostAnnouncer
324

325
        // livenessMonitor monitors that lnd has access to critical resources.
326
        livenessMonitor *healthcheck.Monitor
327

328
        customMessageServer *subscribe.Server
329

330
        // txPublisher is a publisher with fee-bumping capability.
331
        txPublisher *sweep.TxPublisher
332

333
        quit chan struct{}
334

335
        wg sync.WaitGroup
336
}
337

338
// updatePersistentPeerAddrs subscribes to topology changes and stores
339
// advertised addresses for any NodeAnnouncements from our persisted peers.
340
func (s *server) updatePersistentPeerAddrs() error {
4✔
341
        graphSub, err := s.chanRouter.SubscribeTopology()
4✔
342
        if err != nil {
4✔
343
                return err
×
344
        }
×
345

346
        s.wg.Add(1)
4✔
347
        go func() {
8✔
348
                defer func() {
8✔
349
                        graphSub.Cancel()
4✔
350
                        s.wg.Done()
4✔
351
                }()
4✔
352

353
                for {
8✔
354
                        select {
4✔
355
                        case <-s.quit:
4✔
356
                                return
4✔
357

358
                        case topChange, ok := <-graphSub.TopologyChanges:
4✔
359
                                // If the router is shutting down, then we will
4✔
360
                                // as well.
4✔
361
                                if !ok {
4✔
362
                                        return
×
363
                                }
×
364

365
                                for _, update := range topChange.NodeUpdates {
8✔
366
                                        pubKeyStr := string(
4✔
367
                                                update.IdentityKey.
4✔
368
                                                        SerializeCompressed(),
4✔
369
                                        )
4✔
370

4✔
371
                                        // We only care about updates from
4✔
372
                                        // our persistentPeers.
4✔
373
                                        s.mu.RLock()
4✔
374
                                        _, ok := s.persistentPeers[pubKeyStr]
4✔
375
                                        s.mu.RUnlock()
4✔
376
                                        if !ok {
8✔
377
                                                continue
4✔
378
                                        }
379

380
                                        addrs := make([]*lnwire.NetAddress, 0,
4✔
381
                                                len(update.Addresses))
4✔
382

4✔
383
                                        for _, addr := range update.Addresses {
8✔
384
                                                addrs = append(addrs,
4✔
385
                                                        &lnwire.NetAddress{
4✔
386
                                                                IdentityKey: update.IdentityKey,
4✔
387
                                                                Address:     addr,
4✔
388
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
389
                                                        },
4✔
390
                                                )
4✔
391
                                        }
4✔
392

393
                                        s.mu.Lock()
4✔
394

4✔
395
                                        // Update the stored addresses for this
4✔
396
                                        // to peer to reflect the new set.
4✔
397
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
4✔
398

4✔
399
                                        // If there are no outstanding
4✔
400
                                        // connection requests for this peer
4✔
401
                                        // then our work is done since we are
4✔
402
                                        // not currently trying to connect to
4✔
403
                                        // them.
4✔
404
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
8✔
405
                                                s.mu.Unlock()
4✔
406
                                                continue
4✔
407
                                        }
408

409
                                        s.mu.Unlock()
4✔
410

4✔
411
                                        s.connectToPersistentPeer(pubKeyStr)
4✔
412
                                }
413
                        }
414
                }
415
        }()
416

417
        return nil
4✔
418
}
419

420
// CustomMessage is a custom message that is received from a peer.
421
type CustomMessage struct {
422
        // Peer is the peer pubkey
423
        Peer [33]byte
424

425
        // Msg is the custom wire message.
426
        Msg *lnwire.Custom
427
}
428

429
// parseAddr parses an address from its string format to a net.Addr.
430
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
4✔
431
        var (
4✔
432
                host string
4✔
433
                port int
4✔
434
        )
4✔
435

4✔
436
        // Split the address into its host and port components.
4✔
437
        h, p, err := net.SplitHostPort(address)
4✔
438
        if err != nil {
4✔
439
                // If a port wasn't specified, we'll assume the address only
×
440
                // contains the host so we'll use the default port.
×
441
                host = address
×
442
                port = defaultPeerPort
×
443
        } else {
4✔
444
                // Otherwise, we'll note both the host and ports.
4✔
445
                host = h
4✔
446
                portNum, err := strconv.Atoi(p)
4✔
447
                if err != nil {
4✔
448
                        return nil, err
×
449
                }
×
450
                port = portNum
4✔
451
        }
452

453
        if tor.IsOnionHost(host) {
4✔
454
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
455
        }
×
456

457
        // If the host is part of a TCP address, we'll use the network
458
        // specific ResolveTCPAddr function in order to resolve these
459
        // addresses over Tor in order to prevent leaking your real IP
460
        // address.
461
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
4✔
462
        return netCfg.ResolveTCPAddr("tcp", hostPort)
4✔
463
}
464

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

4✔
470
        return func(a net.Addr) (net.Conn, error) {
8✔
471
                lnAddr := a.(*lnwire.NetAddress)
4✔
472
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
4✔
473
        }
4✔
474
}
475

476
// newServer creates a new instance of the server which is to listen using the
477
// passed listener address.
478
func newServer(cfg *Config, listenAddrs []net.Addr,
479
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
480
        nodeKeyDesc *keychain.KeyDescriptor,
481
        chansToRestore walletunlocker.ChannelsToRecover,
482
        chanPredicate chanacceptor.ChannelAcceptor,
483
        torController *tor.Controller, tlsManager *TLSManager) (*server,
484
        error) {
4✔
485

4✔
486
        var (
4✔
487
                err         error
4✔
488
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
4✔
489

4✔
490
                // We just derived the full descriptor, so we know the public
4✔
491
                // key is set on it.
4✔
492
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
4✔
493
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
4✔
494
                )
4✔
495
        )
4✔
496

4✔
497
        listeners := make([]net.Listener, len(listenAddrs))
4✔
498
        for i, listenAddr := range listenAddrs {
8✔
499
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
4✔
500
                // doesn't need to call the general lndResolveTCP function
4✔
501
                // since we are resolving a local address.
4✔
502
                listeners[i], err = brontide.NewListener(
4✔
503
                        nodeKeyECDH, listenAddr.String(),
4✔
504
                )
4✔
505
                if err != nil {
4✔
506
                        return nil, err
×
507
                }
×
508
        }
509

510
        var serializedPubKey [33]byte
4✔
511
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
4✔
512

4✔
513
        // Initialize the sphinx router.
4✔
514
        replayLog := htlcswitch.NewDecayedLog(
4✔
515
                dbs.DecayedLogDB, cc.ChainNotifier,
4✔
516
        )
4✔
517
        sphinxRouter := sphinx.NewRouter(
4✔
518
                nodeKeyECDH, cfg.ActiveNetParams.Params, replayLog,
4✔
519
        )
4✔
520

4✔
521
        writeBufferPool := pool.NewWriteBuffer(
4✔
522
                pool.DefaultWriteBufferGCInterval,
4✔
523
                pool.DefaultWriteBufferExpiryInterval,
4✔
524
        )
4✔
525

4✔
526
        writePool := pool.NewWrite(
4✔
527
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
4✔
528
        )
4✔
529

4✔
530
        readBufferPool := pool.NewReadBuffer(
4✔
531
                pool.DefaultReadBufferGCInterval,
4✔
532
                pool.DefaultReadBufferExpiryInterval,
4✔
533
        )
4✔
534

4✔
535
        readPool := pool.NewRead(
4✔
536
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
4✔
537
        )
4✔
538

4✔
539
        //nolint:lll
4✔
540
        featureMgr, err := feature.NewManager(feature.Config{
4✔
541
                NoTLVOnion:               cfg.ProtocolOptions.LegacyOnion(),
4✔
542
                NoStaticRemoteKey:        cfg.ProtocolOptions.NoStaticRemoteKey(),
4✔
543
                NoAnchors:                cfg.ProtocolOptions.NoAnchorCommitments(),
4✔
544
                NoWumbo:                  !cfg.ProtocolOptions.Wumbo(),
4✔
545
                NoScriptEnforcementLease: cfg.ProtocolOptions.NoScriptEnforcementLease(),
4✔
546
                NoKeysend:                !cfg.AcceptKeySend,
4✔
547
                NoOptionScidAlias:        !cfg.ProtocolOptions.ScidAlias(),
4✔
548
                NoZeroConf:               !cfg.ProtocolOptions.ZeroConf(),
4✔
549
                NoAnySegwit:              cfg.ProtocolOptions.NoAnySegwit(),
4✔
550
                CustomFeatures:           cfg.ProtocolOptions.CustomFeatures(),
4✔
551
                NoTaprootChans:           !cfg.ProtocolOptions.TaprootChans,
4✔
552
                NoRouteBlinding:          cfg.ProtocolOptions.NoRouteBlinding(),
4✔
553
        })
4✔
554
        if err != nil {
4✔
555
                return nil, err
×
556
        }
×
557

558
        registryConfig := invoices.RegistryConfig{
4✔
559
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
4✔
560
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
4✔
561
                Clock:                       clock.NewDefaultClock(),
4✔
562
                AcceptKeySend:               cfg.AcceptKeySend,
4✔
563
                AcceptAMP:                   cfg.AcceptAMP,
4✔
564
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
4✔
565
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
4✔
566
                KeysendHoldTime:             cfg.KeysendHoldTime,
4✔
567
        }
4✔
568

4✔
569
        s := &server{
4✔
570
                cfg:            cfg,
4✔
571
                graphDB:        dbs.GraphDB.ChannelGraph(),
4✔
572
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
4✔
573
                addrSource:     dbs.ChanStateDB,
4✔
574
                miscDB:         dbs.ChanStateDB,
4✔
575
                invoicesDB:     dbs.InvoiceDB,
4✔
576
                cc:             cc,
4✔
577
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
4✔
578
                writePool:      writePool,
4✔
579
                readPool:       readPool,
4✔
580
                chansToRestore: chansToRestore,
4✔
581

4✔
582
                channelNotifier: channelnotifier.New(
4✔
583
                        dbs.ChanStateDB.ChannelStateDB(),
4✔
584
                ),
4✔
585

4✔
586
                identityECDH:   nodeKeyECDH,
4✔
587
                identityKeyLoc: nodeKeyDesc.KeyLocator,
4✔
588
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
4✔
589

4✔
590
                listenAddrs: listenAddrs,
4✔
591

4✔
592
                // TODO(roasbeef): derive proper onion key based on rotation
4✔
593
                // schedule
4✔
594
                sphinx: hop.NewOnionProcessor(sphinxRouter),
4✔
595

4✔
596
                torController: torController,
4✔
597

4✔
598
                persistentPeers:         make(map[string]bool),
4✔
599
                persistentPeersBackoff:  make(map[string]time.Duration),
4✔
600
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
4✔
601
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
4✔
602
                persistentRetryCancels:  make(map[string]chan struct{}),
4✔
603
                peerErrors:              make(map[string]*queue.CircularBuffer),
4✔
604
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
4✔
605
                scheduledPeerConnection: make(map[string]func()),
4✔
606
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
4✔
607

4✔
608
                peersByPub:                make(map[string]*peer.Brontide),
4✔
609
                inboundPeers:              make(map[string]*peer.Brontide),
4✔
610
                outboundPeers:             make(map[string]*peer.Brontide),
4✔
611
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
4✔
612
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
4✔
613

4✔
614
                customMessageServer: subscribe.NewServer(),
4✔
615

4✔
616
                tlsManager: tlsManager,
4✔
617

4✔
618
                featureMgr: featureMgr,
4✔
619
                quit:       make(chan struct{}),
4✔
620
        }
4✔
621

4✔
622
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
4✔
623
        if err != nil {
4✔
624
                return nil, err
×
625
        }
×
626

627
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
4✔
628
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
4✔
629
                uint32(currentHeight), currentHash, cc.ChainNotifier,
4✔
630
        )
4✔
631
        s.invoices = invoices.NewRegistry(
4✔
632
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
4✔
633
        )
4✔
634

4✔
635
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
4✔
636

4✔
637
        thresholdSats := btcutil.Amount(cfg.DustThreshold)
4✔
638
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
639

4✔
640
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB)
4✔
641
        if err != nil {
4✔
642
                return nil, err
×
643
        }
×
644

645
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
4✔
646
                DB:                   dbs.ChanStateDB,
4✔
647
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
4✔
648
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
4✔
649
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
4✔
650
                LocalChannelClose: func(pubKey []byte,
4✔
651
                        request *htlcswitch.ChanClose) {
8✔
652

4✔
653
                        peer, err := s.FindPeerByPubStr(string(pubKey))
4✔
654
                        if err != nil {
4✔
655
                                srvrLog.Errorf("unable to close channel, peer"+
×
656
                                        " with %v id can't be found: %v",
×
657
                                        pubKey, err,
×
658
                                )
×
659
                                return
×
660
                        }
×
661

662
                        peer.HandleLocalCloseChanReqs(request)
4✔
663
                },
664
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
665
                SwitchPackager:         channeldb.NewSwitchPackager(),
666
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
667
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
668
                Notifier:               s.cc.ChainNotifier,
669
                HtlcNotifier:           s.htlcNotifier,
670
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
671
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
672
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
673
                AllowCircularRoute:     cfg.AllowCircularRoute,
674
                RejectHTLC:             cfg.RejectHTLC,
675
                Clock:                  clock.NewDefaultClock(),
676
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
677
                DustThreshold:          thresholdMSats,
678
                SignAliasUpdate:        s.signAliasUpdate,
679
                IsAlias:                aliasmgr.IsAlias,
680
        }, uint32(currentHeight))
681
        if err != nil {
4✔
682
                return nil, err
×
683
        }
×
684
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
4✔
685
                &htlcswitch.InterceptableSwitchConfig{
4✔
686
                        Switch:             s.htlcSwitch,
4✔
687
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
4✔
688
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
4✔
689
                        RequireInterceptor: s.cfg.RequireInterceptor,
4✔
690
                        Notifier:           s.cc.ChainNotifier,
4✔
691
                },
4✔
692
        )
4✔
693
        if err != nil {
4✔
694
                return nil, err
×
695
        }
×
696

697
        s.witnessBeacon = newPreimageBeacon(
4✔
698
                dbs.ChanStateDB.NewWitnessCache(),
4✔
699
                s.interceptableSwitch.ForwardPacket,
4✔
700
        )
4✔
701

4✔
702
        chanStatusMgrCfg := &netann.ChanStatusConfig{
4✔
703
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
4✔
704
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
4✔
705
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
4✔
706
                OurPubKey:                nodeKeyDesc.PubKey,
4✔
707
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
4✔
708
                MessageSigner:            s.nodeSigner,
4✔
709
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
4✔
710
                ApplyChannelUpdate:       s.applyChannelUpdate,
4✔
711
                DB:                       s.chanStateDB,
4✔
712
                Graph:                    dbs.GraphDB.ChannelGraph(),
4✔
713
        }
4✔
714

4✔
715
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
4✔
716
        if err != nil {
4✔
717
                return nil, err
×
718
        }
×
719
        s.chanStatusMgr = chanStatusMgr
4✔
720

4✔
721
        // If enabled, use either UPnP or NAT-PMP to automatically configure
4✔
722
        // port forwarding for users behind a NAT.
4✔
723
        if cfg.NAT {
4✔
724
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
725

×
726
                discoveryTimeout := time.Duration(10 * time.Second)
×
727

×
728
                ctx, cancel := context.WithTimeout(
×
729
                        context.Background(), discoveryTimeout,
×
730
                )
×
731
                defer cancel()
×
732
                upnp, err := nat.DiscoverUPnP(ctx)
×
733
                if err == nil {
×
734
                        s.natTraversal = upnp
×
735
                } else {
×
736
                        // If we were not able to discover a UPnP enabled device
×
737
                        // on the local network, we'll fall back to attempting
×
738
                        // to discover a NAT-PMP enabled device.
×
739
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
740
                                "device on the local network: %v", err)
×
741

×
742
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
743
                                "enabled device")
×
744

×
745
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
746
                        if err != nil {
×
747
                                err := fmt.Errorf("unable to discover a "+
×
748
                                        "NAT-PMP enabled device on the local "+
×
749
                                        "network: %v", err)
×
750
                                srvrLog.Error(err)
×
751
                                return nil, err
×
752
                        }
×
753

754
                        s.natTraversal = pmp
×
755
                }
756
        }
757

758
        // If we were requested to automatically configure port forwarding,
759
        // we'll use the ports that the server will be listening on.
760
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
4✔
761
        for idx, ip := range cfg.ExternalIPs {
8✔
762
                externalIPStrings[idx] = ip.String()
4✔
763
        }
4✔
764
        if s.natTraversal != nil {
4✔
765
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
766
                for _, listenAddr := range listenAddrs {
×
767
                        // At this point, the listen addresses should have
×
768
                        // already been normalized, so it's safe to ignore the
×
769
                        // errors.
×
770
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
771
                        port, _ := strconv.Atoi(portStr)
×
772

×
773
                        listenPorts = append(listenPorts, uint16(port))
×
774
                }
×
775

776
                ips, err := s.configurePortForwarding(listenPorts...)
×
777
                if err != nil {
×
778
                        srvrLog.Errorf("Unable to automatically set up port "+
×
779
                                "forwarding using %s: %v",
×
780
                                s.natTraversal.Name(), err)
×
781
                } else {
×
782
                        srvrLog.Infof("Automatically set up port forwarding "+
×
783
                                "using %s to advertise external IP",
×
784
                                s.natTraversal.Name())
×
785
                        externalIPStrings = append(externalIPStrings, ips...)
×
786
                }
×
787
        }
788

789
        // If external IP addresses have been specified, add those to the list
790
        // of this server's addresses.
791
        externalIPs, err := lncfg.NormalizeAddresses(
4✔
792
                externalIPStrings, strconv.Itoa(defaultPeerPort),
4✔
793
                cfg.net.ResolveTCPAddr,
4✔
794
        )
4✔
795
        if err != nil {
4✔
796
                return nil, err
×
797
        }
×
798

799
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
4✔
800
        selfAddrs = append(selfAddrs, externalIPs...)
4✔
801

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

4✔
806
        // We'll now reconstruct a node announcement based on our current
4✔
807
        // configuration so we can send it out as a sort of heart beat within
4✔
808
        // the network.
4✔
809
        //
4✔
810
        // We'll start by parsing the node color from configuration.
4✔
811
        color, err := lncfg.ParseHexColor(cfg.Color)
4✔
812
        if err != nil {
4✔
813
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
814
                return nil, err
×
815
        }
×
816

817
        // If no alias is provided, default to first 10 characters of public
818
        // key.
819
        alias := cfg.Alias
4✔
820
        if alias == "" {
8✔
821
                alias = hex.EncodeToString(serializedPubKey[:10])
4✔
822
        }
4✔
823
        nodeAlias, err := lnwire.NewNodeAlias(alias)
4✔
824
        if err != nil {
4✔
825
                return nil, err
×
826
        }
×
827
        selfNode := &channeldb.LightningNode{
4✔
828
                HaveNodeAnnouncement: true,
4✔
829
                LastUpdate:           time.Now(),
4✔
830
                Addresses:            selfAddrs,
4✔
831
                Alias:                nodeAlias.String(),
4✔
832
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
4✔
833
                Color:                color,
4✔
834
        }
4✔
835
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
4✔
836

4✔
837
        // Based on the disk representation of the node announcement generated
4✔
838
        // above, we'll generate a node announcement that can go out on the
4✔
839
        // network so we can properly sign it.
4✔
840
        nodeAnn, err := selfNode.NodeAnnouncement(false)
4✔
841
        if err != nil {
4✔
842
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
843
        }
×
844

845
        // With the announcement generated, we'll sign it to properly
846
        // authenticate the message on the network.
847
        authSig, err := netann.SignAnnouncement(
4✔
848
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
4✔
849
        )
4✔
850
        if err != nil {
4✔
851
                return nil, fmt.Errorf("unable to generate signature for "+
×
852
                        "self node announcement: %v", err)
×
853
        }
×
854
        selfNode.AuthSigBytes = authSig.Serialize()
4✔
855
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
4✔
856
                selfNode.AuthSigBytes,
4✔
857
        )
4✔
858
        if err != nil {
4✔
859
                return nil, err
×
860
        }
×
861

862
        // Finally, we'll update the representation on disk, and update our
863
        // cached in-memory version as well.
864
        if err := chanGraph.SetSourceNode(selfNode); err != nil {
4✔
865
                return nil, fmt.Errorf("can't set self node: %w", err)
×
866
        }
×
867
        s.currentNodeAnn = nodeAnn
4✔
868

4✔
869
        // The router will get access to the payment ID sequencer, such that it
4✔
870
        // can generate unique payment IDs.
4✔
871
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
4✔
872
        if err != nil {
4✔
873
                return nil, err
×
874
        }
×
875

876
        // Instantiate mission control with config from the sub server.
877
        //
878
        // TODO(joostjager): When we are further in the process of moving to sub
879
        // servers, the mission control instance itself can be moved there too.
880
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
4✔
881

4✔
882
        // We only initialize a probability estimator if there's no custom one.
4✔
883
        var estimator routing.Estimator
4✔
884
        if cfg.Estimator != nil {
4✔
885
                estimator = cfg.Estimator
×
886
        } else {
4✔
887
                switch routingConfig.ProbabilityEstimatorType {
4✔
888
                case routing.AprioriEstimatorName:
4✔
889
                        aCfg := routingConfig.AprioriConfig
4✔
890
                        aprioriConfig := routing.AprioriConfig{
4✔
891
                                AprioriHopProbability: aCfg.HopProbability,
4✔
892
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
4✔
893
                                AprioriWeight:         aCfg.Weight,
4✔
894
                                CapacityFraction:      aCfg.CapacityFraction,
4✔
895
                        }
4✔
896

4✔
897
                        estimator, err = routing.NewAprioriEstimator(
4✔
898
                                aprioriConfig,
4✔
899
                        )
4✔
900
                        if err != nil {
4✔
901
                                return nil, err
×
902
                        }
×
903

904
                case routing.BimodalEstimatorName:
×
905
                        bCfg := routingConfig.BimodalConfig
×
906
                        bimodalConfig := routing.BimodalConfig{
×
907
                                BimodalNodeWeight: bCfg.NodeWeight,
×
908
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
909
                                        bCfg.Scale,
×
910
                                ),
×
911
                                BimodalDecayTime: bCfg.DecayTime,
×
912
                        }
×
913

×
914
                        estimator, err = routing.NewBimodalEstimator(
×
915
                                bimodalConfig,
×
916
                        )
×
917
                        if err != nil {
×
918
                                return nil, err
×
919
                        }
×
920

921
                default:
×
922
                        return nil, fmt.Errorf("unknown estimator type %v",
×
923
                                routingConfig.ProbabilityEstimatorType)
×
924
                }
925
        }
926

927
        mcCfg := &routing.MissionControlConfig{
4✔
928
                Estimator:               estimator,
4✔
929
                MaxMcHistory:            routingConfig.MaxMcHistory,
4✔
930
                McFlushInterval:         routingConfig.McFlushInterval,
4✔
931
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
4✔
932
        }
4✔
933
        s.missionControl, err = routing.NewMissionControl(
4✔
934
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
4✔
935
        )
4✔
936
        if err != nil {
4✔
937
                return nil, fmt.Errorf("can't create mission control: %w", err)
×
938
        }
×
939

940
        srvrLog.Debugf("Instantiating payment session source with config: "+
4✔
941
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
4✔
942
                int64(routingConfig.AttemptCost),
4✔
943
                float64(routingConfig.AttemptCostPPM)/10000,
4✔
944
                routingConfig.MinRouteProbability)
4✔
945

4✔
946
        pathFindingConfig := routing.PathFindingConfig{
4✔
947
                AttemptCost: lnwire.NewMSatFromSatoshis(
4✔
948
                        routingConfig.AttemptCost,
4✔
949
                ),
4✔
950
                AttemptCostPPM: routingConfig.AttemptCostPPM,
4✔
951
                MinProbability: routingConfig.MinRouteProbability,
4✔
952
        }
4✔
953

4✔
954
        sourceNode, err := chanGraph.SourceNode()
4✔
955
        if err != nil {
4✔
956
                return nil, fmt.Errorf("error getting source node: %w", err)
×
957
        }
×
958
        paymentSessionSource := &routing.SessionSource{
4✔
959
                Graph:             chanGraph,
4✔
960
                SourceNode:        sourceNode,
4✔
961
                MissionControl:    s.missionControl,
4✔
962
                GetLink:           s.htlcSwitch.GetLinkByShortID,
4✔
963
                PathFindingConfig: pathFindingConfig,
4✔
964
        }
4✔
965

4✔
966
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
4✔
967

4✔
968
        s.controlTower = routing.NewControlTower(paymentControl)
4✔
969

4✔
970
        strictPruning := (cfg.Bitcoin.Node == "neutrino" ||
4✔
971
                cfg.Routing.StrictZombiePruning)
4✔
972
        s.chanRouter, err = routing.New(routing.Config{
4✔
973
                Graph:               chanGraph,
4✔
974
                Chain:               cc.ChainIO,
4✔
975
                ChainView:           cc.ChainView,
4✔
976
                Notifier:            cc.ChainNotifier,
4✔
977
                Payer:               s.htlcSwitch,
4✔
978
                Control:             s.controlTower,
4✔
979
                MissionControl:      s.missionControl,
4✔
980
                SessionSource:       paymentSessionSource,
4✔
981
                ChannelPruneExpiry:  routing.DefaultChannelPruneExpiry,
4✔
982
                GraphPruneInterval:  time.Hour,
4✔
983
                FirstTimePruneDelay: routing.DefaultFirstTimePruneDelay,
4✔
984
                GetLink:             s.htlcSwitch.GetLinkByShortID,
4✔
985
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
4✔
986
                NextPaymentID:       sequencer.NextID,
4✔
987
                PathFindingConfig:   pathFindingConfig,
4✔
988
                Clock:               clock.NewDefaultClock(),
4✔
989
                StrictZombiePruning: strictPruning,
4✔
990
                IsAlias:             aliasmgr.IsAlias,
4✔
991
        })
4✔
992
        if err != nil {
4✔
993
                return nil, fmt.Errorf("can't create router: %w", err)
×
994
        }
×
995

996
        chanSeries := discovery.NewChanSeries(s.graphDB)
4✔
997
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
4✔
998
        if err != nil {
4✔
999
                return nil, err
×
1000
        }
×
1001
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
4✔
1002
        if err != nil {
4✔
1003
                return nil, err
×
1004
        }
×
1005

1006
        s.authGossiper = discovery.New(discovery.Config{
4✔
1007
                Router:                s.chanRouter,
4✔
1008
                Notifier:              s.cc.ChainNotifier,
4✔
1009
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
4✔
1010
                Broadcast:             s.BroadcastMessage,
4✔
1011
                ChanSeries:            chanSeries,
4✔
1012
                NotifyWhenOnline:      s.NotifyWhenOnline,
4✔
1013
                NotifyWhenOffline:     s.NotifyWhenOffline,
4✔
1014
                FetchSelfAnnouncement: s.getNodeAnnouncement,
4✔
1015
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
4✔
1016
                        error) {
4✔
1017

×
1018
                        return s.genNodeAnnouncement(nil)
×
1019
                },
×
1020
                ProofMatureDelta:        0,
1021
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1022
                RetransmitTicker:        ticker.New(time.Minute * 30),
1023
                RebroadcastInterval:     time.Hour * 24,
1024
                WaitingProofStore:       waitingProofStore,
1025
                MessageStore:            gossipMessageStore,
1026
                AnnSigner:               s.nodeSigner,
1027
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1028
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1029
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1030
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:lll
1031
                MinimumBatchSize:        10,
1032
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1033
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1034
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1035
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1036
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1037
                IsAlias:                 aliasmgr.IsAlias,
1038
                SignAliasUpdate:         s.signAliasUpdate,
1039
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1040
                GetAlias:                s.aliasMgr.GetPeerAlias,
1041
                FindChannel:             s.findChannel,
1042
                IsStillZombieChannel:    s.chanRouter.IsZombieChannel,
1043
        }, nodeKeyDesc)
1044

1045
        s.localChanMgr = &localchans.Manager{
4✔
1046
                ForAllOutgoingChannels:    s.chanRouter.ForAllOutgoingChannels,
4✔
1047
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
4✔
1048
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
4✔
1049
                FetchChannel:              s.chanStateDB.FetchChannel,
4✔
1050
        }
4✔
1051

4✔
1052
        utxnStore, err := contractcourt.NewNurseryStore(
4✔
1053
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
4✔
1054
        )
4✔
1055
        if err != nil {
4✔
1056
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1057
                return nil, err
×
1058
        }
×
1059

1060
        sweeperStore, err := sweep.NewSweeperStore(
4✔
1061
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
4✔
1062
        )
4✔
1063
        if err != nil {
4✔
1064
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1065
                return nil, err
×
1066
        }
×
1067

1068
        aggregator := sweep.NewBudgetAggregator(
4✔
1069
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
4✔
1070
        )
4✔
1071

4✔
1072
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
4✔
1073
                Signer:    cc.Wallet.Cfg.Signer,
4✔
1074
                Wallet:    cc.Wallet,
4✔
1075
                Estimator: cc.FeeEstimator,
4✔
1076
                Notifier:  cc.ChainNotifier,
4✔
1077
        })
4✔
1078

4✔
1079
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
4✔
1080
                FeeEstimator:         cc.FeeEstimator,
4✔
1081
                GenSweepScript:       newSweepPkScriptGen(cc.Wallet),
4✔
1082
                Signer:               cc.Wallet.Cfg.Signer,
4✔
1083
                Wallet:               newSweeperWallet(cc.Wallet),
4✔
1084
                Mempool:              cc.MempoolNotifier,
4✔
1085
                Notifier:             cc.ChainNotifier,
4✔
1086
                Store:                sweeperStore,
4✔
1087
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
4✔
1088
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
4✔
1089
                Aggregator:           aggregator,
4✔
1090
                Publisher:            s.txPublisher,
4✔
1091
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
4✔
1092
        })
4✔
1093

4✔
1094
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
4✔
1095
                ChainIO:             cc.ChainIO,
4✔
1096
                ConfDepth:           1,
4✔
1097
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
4✔
1098
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
4✔
1099
                Notifier:            cc.ChainNotifier,
4✔
1100
                PublishTransaction:  cc.Wallet.PublishTransaction,
4✔
1101
                Store:               utxnStore,
4✔
1102
                SweepInput:          s.sweeper.SweepInput,
4✔
1103
                Budget:              s.cfg.Sweeper.Budget,
4✔
1104
        })
4✔
1105

4✔
1106
        // Construct a closure that wraps the htlcswitch's CloseLink method.
4✔
1107
        closeLink := func(chanPoint *wire.OutPoint,
4✔
1108
                closureType contractcourt.ChannelCloseType) {
8✔
1109
                // TODO(conner): Properly respect the update and error channels
4✔
1110
                // returned by CloseLink.
4✔
1111

4✔
1112
                // Instruct the switch to close the channel.  Provide no close out
4✔
1113
                // delivery script or target fee per kw because user input is not
4✔
1114
                // available when the remote peer closes the channel.
4✔
1115
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
4✔
1116
        }
4✔
1117

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

4✔
1122
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
4✔
1123
                &contractcourt.BreachConfig{
4✔
1124
                        CloseLink:          closeLink,
4✔
1125
                        DB:                 s.chanStateDB,
4✔
1126
                        Estimator:          s.cc.FeeEstimator,
4✔
1127
                        GenSweepScript:     newSweepPkScriptGen(cc.Wallet),
4✔
1128
                        Notifier:           cc.ChainNotifier,
4✔
1129
                        PublishTransaction: cc.Wallet.PublishTransaction,
4✔
1130
                        ContractBreaches:   contractBreaches,
4✔
1131
                        Signer:             cc.Wallet.Cfg.Signer,
4✔
1132
                        Store: contractcourt.NewRetributionStore(
4✔
1133
                                dbs.ChanStateDB,
4✔
1134
                        ),
4✔
1135
                },
4✔
1136
        )
4✔
1137

4✔
1138
        //nolint:lll
4✔
1139
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
4✔
1140
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
4✔
1141
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
4✔
1142
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
4✔
1143
                NewSweepAddr:           newSweepPkScriptGen(cc.Wallet),
4✔
1144
                PublishTx:              cc.Wallet.PublishTransaction,
4✔
1145
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
8✔
1146
                        for _, msg := range msgs {
8✔
1147
                                err := s.htlcSwitch.ProcessContractResolution(msg)
4✔
1148
                                if err != nil {
4✔
1149
                                        return err
×
1150
                                }
×
1151
                        }
1152
                        return nil
4✔
1153
                },
1154
                IncubateOutputs: func(chanPoint wire.OutPoint,
1155
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1156
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1157
                        broadcastHeight uint32,
1158
                        deadlineHeight fn.Option[int32]) error {
4✔
1159

4✔
1160
                        return s.utxoNursery.IncubateOutputs(
4✔
1161
                                chanPoint, outHtlcRes, inHtlcRes,
4✔
1162
                                broadcastHeight, deadlineHeight,
4✔
1163
                        )
4✔
1164
                },
4✔
1165
                PreimageDB:   s.witnessBeacon,
1166
                Notifier:     cc.ChainNotifier,
1167
                Mempool:      cc.MempoolNotifier,
1168
                Signer:       cc.Wallet.Cfg.Signer,
1169
                FeeEstimator: cc.FeeEstimator,
1170
                ChainIO:      cc.ChainIO,
1171
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
4✔
1172
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1173
                        s.htlcSwitch.RemoveLink(chanID)
4✔
1174
                        return nil
4✔
1175
                },
4✔
1176
                IsOurAddress: cc.Wallet.IsOurAddress,
1177
                ContractBreach: func(chanPoint wire.OutPoint,
1178
                        breachRet *lnwallet.BreachRetribution) error {
4✔
1179

4✔
1180
                        // processACK will handle the BreachArbitrator ACKing
4✔
1181
                        // the event.
4✔
1182
                        finalErr := make(chan error, 1)
4✔
1183
                        processACK := func(brarErr error) {
8✔
1184
                                if brarErr != nil {
4✔
1185
                                        finalErr <- brarErr
×
1186
                                        return
×
1187
                                }
×
1188

1189
                                // If the BreachArbitrator successfully handled
1190
                                // the event, we can signal that the handoff
1191
                                // was successful.
1192
                                finalErr <- nil
4✔
1193
                        }
1194

1195
                        event := &contractcourt.ContractBreachEvent{
4✔
1196
                                ChanPoint:         chanPoint,
4✔
1197
                                ProcessACK:        processACK,
4✔
1198
                                BreachRetribution: breachRet,
4✔
1199
                        }
4✔
1200

4✔
1201
                        // Send the contract breach event to the
4✔
1202
                        // BreachArbitrator.
4✔
1203
                        select {
4✔
1204
                        case contractBreaches <- event:
4✔
1205
                        case <-s.quit:
×
1206
                                return ErrServerShuttingDown
×
1207
                        }
1208

1209
                        // We'll wait for a final error to be available from
1210
                        // the BreachArbitrator.
1211
                        select {
4✔
1212
                        case err := <-finalErr:
4✔
1213
                                return err
4✔
1214
                        case <-s.quit:
×
1215
                                return ErrServerShuttingDown
×
1216
                        }
1217
                },
1218
                DisableChannel: func(chanPoint wire.OutPoint) error {
4✔
1219
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
4✔
1220
                },
4✔
1221
                Sweeper:                       s.sweeper,
1222
                Registry:                      s.invoices,
1223
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1224
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1225
                OnionProcessor:                s.sphinx,
1226
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1227
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1228
                Clock:                         clock.NewDefaultClock(),
1229
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1230
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1231
                HtlcNotifier:                  s.htlcNotifier,
1232
                Budget:                        *s.cfg.Sweeper.Budget,
1233

1234
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1235
                QueryIncomingCircuit: func(
1236
                        circuit models.CircuitKey) *models.CircuitKey {
4✔
1237

4✔
1238
                        // Get the circuit map.
4✔
1239
                        circuits := s.htlcSwitch.CircuitLookup()
4✔
1240

4✔
1241
                        // Lookup the outgoing circuit.
4✔
1242
                        pc := circuits.LookupOpenCircuit(circuit)
4✔
1243
                        if pc == nil {
8✔
1244
                                return nil
4✔
1245
                        }
4✔
1246

1247
                        return &pc.Incoming
4✔
1248
                },
1249
        }, dbs.ChanStateDB)
1250

1251
        // Select the configuration and funding parameters for Bitcoin.
1252
        chainCfg := cfg.Bitcoin
4✔
1253
        minRemoteDelay := funding.MinBtcRemoteDelay
4✔
1254
        maxRemoteDelay := funding.MaxBtcRemoteDelay
4✔
1255

4✔
1256
        var chanIDSeed [32]byte
4✔
1257
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
4✔
1258
                return nil, err
×
1259
        }
×
1260

1261
        // Wrap the DeleteChannelEdges method so that the funding manager can
1262
        // use it without depending on several layers of indirection.
1263
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
4✔
1264
                *models.ChannelEdgePolicy, error) {
8✔
1265

4✔
1266
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
4✔
1267
                        scid.ToUint64(),
4✔
1268
                )
4✔
1269
                if errors.Is(err, channeldb.ErrEdgeNotFound) {
4✔
1270
                        // This is unlikely but there is a slim chance of this
×
1271
                        // being hit if lnd was killed via SIGKILL and the
×
1272
                        // funding manager was stepping through the delete
×
1273
                        // alias edge logic.
×
1274
                        return nil, nil
×
1275
                } else if err != nil {
4✔
1276
                        return nil, err
×
1277
                }
×
1278

1279
                // Grab our key to find our policy.
1280
                var ourKey [33]byte
4✔
1281
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
4✔
1282

4✔
1283
                var ourPolicy *models.ChannelEdgePolicy
4✔
1284
                if info != nil && info.NodeKey1Bytes == ourKey {
8✔
1285
                        ourPolicy = e1
4✔
1286
                } else {
8✔
1287
                        ourPolicy = e2
4✔
1288
                }
4✔
1289

1290
                if ourPolicy == nil {
4✔
1291
                        // Something is wrong, so return an error.
×
1292
                        return nil, fmt.Errorf("we don't have an edge")
×
1293
                }
×
1294

1295
                err = s.graphDB.DeleteChannelEdges(
4✔
1296
                        false, false, scid.ToUint64(),
4✔
1297
                )
4✔
1298
                return ourPolicy, err
4✔
1299
        }
1300

1301
        // For the reservationTimeout and the zombieSweeperInterval different
1302
        // values are set in case we are in a dev environment so enhance test
1303
        // capacilities.
1304
        reservationTimeout := chanfunding.DefaultReservationTimeout
4✔
1305
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
4✔
1306

4✔
1307
        // Get the development config for funding manager. If we are not in
4✔
1308
        // development mode, this would be nil.
4✔
1309
        var devCfg *funding.DevConfig
4✔
1310
        if lncfg.IsDevBuild() {
8✔
1311
                devCfg = &funding.DevConfig{
4✔
1312
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
4✔
1313
                }
4✔
1314

4✔
1315
                reservationTimeout = cfg.Dev.GetReservationTimeout()
4✔
1316
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
4✔
1317

4✔
1318
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
4✔
1319
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
4✔
1320
                        devCfg, reservationTimeout, zombieSweeperInterval)
4✔
1321
        }
4✔
1322

1323
        //nolint:lll
1324
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
4✔
1325
                Dev:                devCfg,
4✔
1326
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
4✔
1327
                IDKey:              nodeKeyDesc.PubKey,
4✔
1328
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
4✔
1329
                Wallet:             cc.Wallet,
4✔
1330
                PublishTransaction: cc.Wallet.PublishTransaction,
4✔
1331
                UpdateLabel: func(hash chainhash.Hash, label string) error {
8✔
1332
                        return cc.Wallet.LabelTransaction(hash, label, true)
4✔
1333
                },
4✔
1334
                Notifier:     cc.ChainNotifier,
1335
                ChannelDB:    s.chanStateDB,
1336
                FeeEstimator: cc.FeeEstimator,
1337
                SignMessage:  cc.MsgSigner.SignMessage,
1338
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1339
                        error) {
4✔
1340

4✔
1341
                        return s.genNodeAnnouncement(nil)
4✔
1342
                },
4✔
1343
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1344
                NotifyWhenOnline:     s.NotifyWhenOnline,
1345
                TempChanIDSeed:       chanIDSeed,
1346
                FindChannel:          s.findChannel,
1347
                DefaultRoutingPolicy: cc.RoutingPolicy,
1348
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1349
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1350
                        pushAmt lnwire.MilliSatoshi) uint16 {
4✔
1351
                        // For large channels we increase the number
4✔
1352
                        // of confirmations we require for the
4✔
1353
                        // channel to be considered open. As it is
4✔
1354
                        // always the responder that gets to choose
4✔
1355
                        // value, the pushAmt is value being pushed
4✔
1356
                        // to us. This means we have more to lose
4✔
1357
                        // in the case this gets re-orged out, and
4✔
1358
                        // we will require more confirmations before
4✔
1359
                        // we consider it open.
4✔
1360

4✔
1361
                        // In case the user has explicitly specified
4✔
1362
                        // a default value for the number of
4✔
1363
                        // confirmations, we use it.
4✔
1364
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
4✔
1365
                        if defaultConf != 0 {
8✔
1366
                                return defaultConf
4✔
1367
                        }
4✔
1368

1369
                        minConf := uint64(3)
×
1370
                        maxConf := uint64(6)
×
1371

×
1372
                        // If this is a wumbo channel, then we'll require the
×
1373
                        // max amount of confirmations.
×
1374
                        if chanAmt > MaxFundingAmount {
×
1375
                                return uint16(maxConf)
×
1376
                        }
×
1377

1378
                        // If not we return a value scaled linearly
1379
                        // between 3 and 6, depending on channel size.
1380
                        // TODO(halseth): Use 1 as minimum?
1381
                        maxChannelSize := uint64(
×
1382
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1383
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1384
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1385
                        if conf < minConf {
×
1386
                                conf = minConf
×
1387
                        }
×
1388
                        if conf > maxConf {
×
1389
                                conf = maxConf
×
1390
                        }
×
1391
                        return uint16(conf)
×
1392
                },
1393
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
4✔
1394
                        // We scale the remote CSV delay (the time the
4✔
1395
                        // remote have to claim funds in case of a unilateral
4✔
1396
                        // close) linearly from minRemoteDelay blocks
4✔
1397
                        // for small channels, to maxRemoteDelay blocks
4✔
1398
                        // for channels of size MaxFundingAmount.
4✔
1399

4✔
1400
                        // In case the user has explicitly specified
4✔
1401
                        // a default value for the remote delay, we
4✔
1402
                        // use it.
4✔
1403
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
4✔
1404
                        if defaultDelay > 0 {
8✔
1405
                                return defaultDelay
4✔
1406
                        }
4✔
1407

1408
                        // If this is a wumbo channel, then we'll require the
1409
                        // max value.
1410
                        if chanAmt > MaxFundingAmount {
×
1411
                                return maxRemoteDelay
×
1412
                        }
×
1413

1414
                        // If not we scale according to channel size.
1415
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1416
                                chanAmt / MaxFundingAmount)
×
1417
                        if delay < minRemoteDelay {
×
1418
                                delay = minRemoteDelay
×
1419
                        }
×
1420
                        if delay > maxRemoteDelay {
×
1421
                                delay = maxRemoteDelay
×
1422
                        }
×
1423
                        return delay
×
1424
                },
1425
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1426
                        peerKey *btcec.PublicKey) error {
4✔
1427

4✔
1428
                        // First, we'll mark this new peer as a persistent peer
4✔
1429
                        // for re-connection purposes. If the peer is not yet
4✔
1430
                        // tracked or the user hasn't requested it to be perm,
4✔
1431
                        // we'll set false to prevent the server from continuing
4✔
1432
                        // to connect to this peer even if the number of
4✔
1433
                        // channels with this peer is zero.
4✔
1434
                        s.mu.Lock()
4✔
1435
                        pubStr := string(peerKey.SerializeCompressed())
4✔
1436
                        if _, ok := s.persistentPeers[pubStr]; !ok {
8✔
1437
                                s.persistentPeers[pubStr] = false
4✔
1438
                        }
4✔
1439
                        s.mu.Unlock()
4✔
1440

4✔
1441
                        // With that taken care of, we'll send this channel to
4✔
1442
                        // the chain arb so it can react to on-chain events.
4✔
1443
                        return s.chainArb.WatchNewChannel(channel)
4✔
1444
                },
1445
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
4✔
1446
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1447
                        return s.htlcSwitch.UpdateShortChanID(cid)
4✔
1448
                },
4✔
1449
                RequiredRemoteChanReserve: func(chanAmt,
1450
                        dustLimit btcutil.Amount) btcutil.Amount {
4✔
1451

4✔
1452
                        // By default, we'll require the remote peer to maintain
4✔
1453
                        // at least 1% of the total channel capacity at all
4✔
1454
                        // times. If this value ends up dipping below the dust
4✔
1455
                        // limit, then we'll use the dust limit itself as the
4✔
1456
                        // reserve as required by BOLT #2.
4✔
1457
                        reserve := chanAmt / 100
4✔
1458
                        if reserve < dustLimit {
8✔
1459
                                reserve = dustLimit
4✔
1460
                        }
4✔
1461

1462
                        return reserve
4✔
1463
                },
1464
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
4✔
1465
                        // By default, we'll allow the remote peer to fully
4✔
1466
                        // utilize the full bandwidth of the channel, minus our
4✔
1467
                        // required reserve.
4✔
1468
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
4✔
1469
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
4✔
1470
                },
4✔
1471
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
4✔
1472
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
8✔
1473
                                return cfg.DefaultRemoteMaxHtlcs
4✔
1474
                        }
4✔
1475

1476
                        // By default, we'll permit them to utilize the full
1477
                        // channel bandwidth.
1478
                        return uint16(input.MaxHTLCNumber / 2)
×
1479
                },
1480
                ZombieSweeperInterval:         zombieSweeperInterval,
1481
                ReservationTimeout:            reservationTimeout,
1482
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1483
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1484
                MaxPendingChannels:            cfg.MaxPendingChannels,
1485
                RejectPush:                    cfg.RejectPush,
1486
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1487
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1488
                OpenChannelPredicate:          chanPredicate,
1489
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1490
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1491
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1492
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1493
                DeleteAliasEdge:   deleteAliasEdge,
1494
                AliasManager:      s.aliasMgr,
1495
                IsSweeperOutpoint: s.sweeper.IsSweeperOutpoint,
1496
        })
1497
        if err != nil {
4✔
1498
                return nil, err
×
1499
        }
×
1500

1501
        // Next, we'll assemble the sub-system that will maintain an on-disk
1502
        // static backup of the latest channel state.
1503
        chanNotifier := &channelNotifier{
4✔
1504
                chanNotifier: s.channelNotifier,
4✔
1505
                addrs:        dbs.ChanStateDB,
4✔
1506
        }
4✔
1507
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
4✔
1508
        startingChans, err := chanbackup.FetchStaticChanBackups(
4✔
1509
                s.chanStateDB, s.addrSource,
4✔
1510
        )
4✔
1511
        if err != nil {
4✔
1512
                return nil, err
×
1513
        }
×
1514
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
4✔
1515
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
4✔
1516
        )
4✔
1517
        if err != nil {
4✔
1518
                return nil, err
×
1519
        }
×
1520

1521
        // Assemble a peer notifier which will provide clients with subscriptions
1522
        // to peer online and offline events.
1523
        s.peerNotifier = peernotifier.New()
4✔
1524

4✔
1525
        // Create a channel event store which monitors all open channels.
4✔
1526
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
4✔
1527
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
8✔
1528
                        return s.channelNotifier.SubscribeChannelEvents()
4✔
1529
                },
4✔
1530
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
4✔
1531
                        return s.peerNotifier.SubscribePeerEvents()
4✔
1532
                },
4✔
1533
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1534
                Clock:           clock.NewDefaultClock(),
1535
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1536
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1537
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1538
        })
1539

1540
        if cfg.WtClient.Active {
8✔
1541
                policy := wtpolicy.DefaultPolicy()
4✔
1542
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
4✔
1543

4✔
1544
                // We expose the sweep fee rate in sat/vbyte, but the tower
4✔
1545
                // protocol operations on sat/kw.
4✔
1546
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
4✔
1547
                        1000 * cfg.WtClient.SweepFeeRate,
4✔
1548
                )
4✔
1549

4✔
1550
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
4✔
1551

4✔
1552
                if err := policy.Validate(); err != nil {
4✔
1553
                        return nil, err
×
1554
                }
×
1555

1556
                // authDial is the wrapper around the btrontide.Dial for the
1557
                // watchtower.
1558
                authDial := func(localKey keychain.SingleKeyECDH,
4✔
1559
                        netAddr *lnwire.NetAddress,
4✔
1560
                        dialer tor.DialFunc) (wtserver.Peer, error) {
8✔
1561

4✔
1562
                        return brontide.Dial(
4✔
1563
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
4✔
1564
                        )
4✔
1565
                }
4✔
1566

1567
                // buildBreachRetribution is a call-back that can be used to
1568
                // query the BreachRetribution info and channel type given a
1569
                // channel ID and commitment height.
1570
                buildBreachRetribution := func(chanID lnwire.ChannelID,
4✔
1571
                        commitHeight uint64) (*lnwallet.BreachRetribution,
4✔
1572
                        channeldb.ChannelType, error) {
8✔
1573

4✔
1574
                        channel, err := s.chanStateDB.FetchChannelByID(
4✔
1575
                                nil, chanID,
4✔
1576
                        )
4✔
1577
                        if err != nil {
4✔
1578
                                return nil, 0, err
×
1579
                        }
×
1580

1581
                        br, err := lnwallet.NewBreachRetribution(
4✔
1582
                                channel, commitHeight, 0, nil,
4✔
1583
                        )
4✔
1584
                        if err != nil {
4✔
1585
                                return nil, 0, err
×
1586
                        }
×
1587

1588
                        return br, channel.ChanType, nil
4✔
1589
                }
1590

1591
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
4✔
1592

4✔
1593
                // Copy the policy for legacy channels and set the blob flag
4✔
1594
                // signalling support for anchor channels.
4✔
1595
                anchorPolicy := policy
4✔
1596
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
4✔
1597

4✔
1598
                // Copy the policy for legacy channels and set the blob flag
4✔
1599
                // signalling support for taproot channels.
4✔
1600
                taprootPolicy := policy
4✔
1601
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
4✔
1602
                        blob.FlagTaprootChannel,
4✔
1603
                )
4✔
1604

4✔
1605
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
4✔
1606
                        FetchClosedChannel:     fetchClosedChannel,
4✔
1607
                        BuildBreachRetribution: buildBreachRetribution,
4✔
1608
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
4✔
1609
                        ChainNotifier:          s.cc.ChainNotifier,
4✔
1610
                        SubscribeChannelEvents: func() (subscribe.Subscription,
4✔
1611
                                error) {
8✔
1612

4✔
1613
                                return s.channelNotifier.
4✔
1614
                                        SubscribeChannelEvents()
4✔
1615
                        },
4✔
1616
                        Signer:             cc.Wallet.Cfg.Signer,
1617
                        NewAddress:         newSweepPkScriptGen(cc.Wallet),
1618
                        SecretKeyRing:      s.cc.KeyRing,
1619
                        Dial:               cfg.net.Dial,
1620
                        AuthDial:           authDial,
1621
                        DB:                 dbs.TowerClientDB,
1622
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1623
                        MinBackoff:         10 * time.Second,
1624
                        MaxBackoff:         5 * time.Minute,
1625
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1626
                }, policy, anchorPolicy, taprootPolicy)
1627
                if err != nil {
4✔
1628
                        return nil, err
×
1629
                }
×
1630
        }
1631

1632
        if len(cfg.ExternalHosts) != 0 {
4✔
1633
                advertisedIPs := make(map[string]struct{})
×
1634
                for _, addr := range s.currentNodeAnn.Addresses {
×
1635
                        advertisedIPs[addr.String()] = struct{}{}
×
1636
                }
×
1637

1638
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1639
                        Hosts:         cfg.ExternalHosts,
×
1640
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1641
                        LookupHost: func(host string) (net.Addr, error) {
×
1642
                                return lncfg.ParseAddressString(
×
1643
                                        host, strconv.Itoa(defaultPeerPort),
×
1644
                                        cfg.net.ResolveTCPAddr,
×
1645
                                )
×
1646
                        },
×
1647
                        AdvertisedIPs: advertisedIPs,
1648
                        AnnounceNewIPs: netann.IPAnnouncer(
1649
                                func(modifier ...netann.NodeAnnModifier) (
1650
                                        lnwire.NodeAnnouncement, error) {
×
1651

×
1652
                                        return s.genNodeAnnouncement(
×
1653
                                                nil, modifier...,
×
1654
                                        )
×
1655
                                }),
×
1656
                })
1657
        }
1658

1659
        // Create liveness monitor.
1660
        s.createLivenessMonitor(cfg, cc)
4✔
1661

4✔
1662
        // Create the connection manager which will be responsible for
4✔
1663
        // maintaining persistent outbound connections and also accepting new
4✔
1664
        // incoming connections
4✔
1665
        cmgr, err := connmgr.New(&connmgr.Config{
4✔
1666
                Listeners:      listeners,
4✔
1667
                OnAccept:       s.InboundPeerConnected,
4✔
1668
                RetryDuration:  time.Second * 5,
4✔
1669
                TargetOutbound: 100,
4✔
1670
                Dial: noiseDial(
4✔
1671
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
4✔
1672
                ),
4✔
1673
                OnConnection: s.OutboundPeerConnected,
4✔
1674
        })
4✔
1675
        if err != nil {
4✔
1676
                return nil, err
×
1677
        }
×
1678
        s.connMgr = cmgr
4✔
1679

4✔
1680
        return s, nil
4✔
1681
}
1682

1683
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1684
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1685
// may differ from what is on disk.
1686
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate) (*ecdsa.Signature,
1687
        error) {
4✔
1688

4✔
1689
        data, err := u.DataToSign()
4✔
1690
        if err != nil {
4✔
1691
                return nil, err
×
1692
        }
×
1693

1694
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
4✔
1695
}
1696

1697
// createLivenessMonitor creates a set of health checks using our configured
1698
// values and uses these checks to create a liveness monitor. Available
1699
// health checks,
1700
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1701
//   - diskCheck
1702
//   - tlsHealthCheck
1703
//   - torController, only created when tor is enabled.
1704
//
1705
// If a health check has been disabled by setting attempts to 0, our monitor
1706
// will not run it.
1707
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl) {
4✔
1708
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
4✔
1709
        if cfg.Bitcoin.Node == "nochainbackend" {
4✔
1710
                srvrLog.Info("Disabling chain backend checks for " +
×
1711
                        "nochainbackend mode")
×
1712

×
1713
                chainBackendAttempts = 0
×
1714
        }
×
1715

1716
        chainHealthCheck := healthcheck.NewObservation(
4✔
1717
                "chain backend",
4✔
1718
                cc.HealthCheck,
4✔
1719
                cfg.HealthChecks.ChainCheck.Interval,
4✔
1720
                cfg.HealthChecks.ChainCheck.Timeout,
4✔
1721
                cfg.HealthChecks.ChainCheck.Backoff,
4✔
1722
                chainBackendAttempts,
4✔
1723
        )
4✔
1724

4✔
1725
        diskCheck := healthcheck.NewObservation(
4✔
1726
                "disk space",
4✔
1727
                func() error {
4✔
1728
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1729
                                cfg.LndDir,
×
1730
                        )
×
1731
                        if err != nil {
×
1732
                                return err
×
1733
                        }
×
1734

1735
                        // If we have more free space than we require,
1736
                        // we return a nil error.
1737
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1738
                                return nil
×
1739
                        }
×
1740

1741
                        return fmt.Errorf("require: %v free space, got: %v",
×
1742
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1743
                                free)
×
1744
                },
1745
                cfg.HealthChecks.DiskCheck.Interval,
1746
                cfg.HealthChecks.DiskCheck.Timeout,
1747
                cfg.HealthChecks.DiskCheck.Backoff,
1748
                cfg.HealthChecks.DiskCheck.Attempts,
1749
        )
1750

1751
        tlsHealthCheck := healthcheck.NewObservation(
4✔
1752
                "tls",
4✔
1753
                func() error {
4✔
1754
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1755
                                s.cc.KeyRing,
×
1756
                        )
×
1757
                        if err != nil {
×
1758
                                return err
×
1759
                        }
×
1760
                        if expired {
×
1761
                                return fmt.Errorf("TLS certificate is "+
×
1762
                                        "expired as of %v", expTime)
×
1763
                        }
×
1764

1765
                        // If the certificate is not outdated, no error needs
1766
                        // to be returned
1767
                        return nil
×
1768
                },
1769
                cfg.HealthChecks.TLSCheck.Interval,
1770
                cfg.HealthChecks.TLSCheck.Timeout,
1771
                cfg.HealthChecks.TLSCheck.Backoff,
1772
                cfg.HealthChecks.TLSCheck.Attempts,
1773
        )
1774

1775
        checks := []*healthcheck.Observation{
4✔
1776
                chainHealthCheck, diskCheck, tlsHealthCheck,
4✔
1777
        }
4✔
1778

4✔
1779
        // If Tor is enabled, add the healthcheck for tor connection.
4✔
1780
        if s.torController != nil {
4✔
1781
                torConnectionCheck := healthcheck.NewObservation(
×
1782
                        "tor connection",
×
1783
                        func() error {
×
1784
                                return healthcheck.CheckTorServiceStatus(
×
1785
                                        s.torController,
×
1786
                                        s.createNewHiddenService,
×
1787
                                )
×
1788
                        },
×
1789
                        cfg.HealthChecks.TorConnection.Interval,
1790
                        cfg.HealthChecks.TorConnection.Timeout,
1791
                        cfg.HealthChecks.TorConnection.Backoff,
1792
                        cfg.HealthChecks.TorConnection.Attempts,
1793
                )
1794
                checks = append(checks, torConnectionCheck)
×
1795
        }
1796

1797
        // If remote signing is enabled, add the healthcheck for the remote
1798
        // signing RPC interface.
1799
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
8✔
1800
                // Because we have two cascading timeouts here, we need to add
4✔
1801
                // some slack to the "outer" one of them in case the "inner"
4✔
1802
                // returns exactly on time.
4✔
1803
                overhead := time.Millisecond * 10
4✔
1804

4✔
1805
                remoteSignerConnectionCheck := healthcheck.NewObservation(
4✔
1806
                        "remote signer connection",
4✔
1807
                        rpcwallet.HealthCheck(
4✔
1808
                                s.cfg.RemoteSigner,
4✔
1809

4✔
1810
                                // For the health check we might to be even
4✔
1811
                                // stricter than the initial/normal connect, so
4✔
1812
                                // we use the health check timeout here.
4✔
1813
                                cfg.HealthChecks.RemoteSigner.Timeout,
4✔
1814
                        ),
4✔
1815
                        cfg.HealthChecks.RemoteSigner.Interval,
4✔
1816
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
4✔
1817
                        cfg.HealthChecks.RemoteSigner.Backoff,
4✔
1818
                        cfg.HealthChecks.RemoteSigner.Attempts,
4✔
1819
                )
4✔
1820
                checks = append(checks, remoteSignerConnectionCheck)
4✔
1821
        }
4✔
1822

1823
        // If we have not disabled all of our health checks, we create a
1824
        // liveness monitor with our configured checks.
1825
        s.livenessMonitor = healthcheck.NewMonitor(
4✔
1826
                &healthcheck.Config{
4✔
1827
                        Checks:   checks,
4✔
1828
                        Shutdown: srvrLog.Criticalf,
4✔
1829
                },
4✔
1830
        )
4✔
1831
}
1832

1833
// Started returns true if the server has been started, and false otherwise.
1834
// NOTE: This function is safe for concurrent access.
1835
func (s *server) Started() bool {
4✔
1836
        return atomic.LoadInt32(&s.active) != 0
4✔
1837
}
4✔
1838

1839
// cleaner is used to aggregate "cleanup" functions during an operation that
1840
// starts several subsystems. In case one of the subsystem fails to start
1841
// and a proper resource cleanup is required, the "run" method achieves this
1842
// by running all these added "cleanup" functions.
1843
type cleaner []func() error
1844

1845
// add is used to add a cleanup function to be called when
1846
// the run function is executed.
1847
func (c cleaner) add(cleanup func() error) cleaner {
4✔
1848
        return append(c, cleanup)
4✔
1849
}
4✔
1850

1851
// run is used to run all the previousely added cleanup functions.
1852
func (c cleaner) run() {
×
1853
        for i := len(c) - 1; i >= 0; i-- {
×
1854
                if err := c[i](); err != nil {
×
1855
                        srvrLog.Infof("Cleanup failed: %v", err)
×
1856
                }
×
1857
        }
1858
}
1859

1860
// Start starts the main daemon server, all requested listeners, and any helper
1861
// goroutines.
1862
// NOTE: This function is safe for concurrent access.
1863
func (s *server) Start() error {
4✔
1864
        var startErr error
4✔
1865

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

4✔
1871
        s.start.Do(func() {
8✔
1872
                if err := s.customMessageServer.Start(); err != nil {
4✔
1873
                        startErr = err
×
1874
                        return
×
1875
                }
×
1876
                cleanup = cleanup.add(s.customMessageServer.Stop)
4✔
1877

4✔
1878
                if s.hostAnn != nil {
4✔
1879
                        if err := s.hostAnn.Start(); err != nil {
×
1880
                                startErr = err
×
1881
                                return
×
1882
                        }
×
1883
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
1884
                }
1885

1886
                if s.livenessMonitor != nil {
8✔
1887
                        if err := s.livenessMonitor.Start(); err != nil {
4✔
1888
                                startErr = err
×
1889
                                return
×
1890
                        }
×
1891
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
4✔
1892
                }
1893

1894
                // Start the notification server. This is used so channel
1895
                // management goroutines can be notified when a funding
1896
                // transaction reaches a sufficient number of confirmations, or
1897
                // when the input for the funding transaction is spent in an
1898
                // attempt at an uncooperative close by the counterparty.
1899
                if err := s.sigPool.Start(); err != nil {
4✔
1900
                        startErr = err
×
1901
                        return
×
1902
                }
×
1903
                cleanup = cleanup.add(s.sigPool.Stop)
4✔
1904

4✔
1905
                if err := s.writePool.Start(); err != nil {
4✔
1906
                        startErr = err
×
1907
                        return
×
1908
                }
×
1909
                cleanup = cleanup.add(s.writePool.Stop)
4✔
1910

4✔
1911
                if err := s.readPool.Start(); err != nil {
4✔
1912
                        startErr = err
×
1913
                        return
×
1914
                }
×
1915
                cleanup = cleanup.add(s.readPool.Stop)
4✔
1916

4✔
1917
                if err := s.cc.ChainNotifier.Start(); err != nil {
4✔
1918
                        startErr = err
×
1919
                        return
×
1920
                }
×
1921
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
4✔
1922

4✔
1923
                if err := s.cc.BestBlockTracker.Start(); err != nil {
4✔
1924
                        startErr = err
×
1925
                        return
×
1926
                }
×
1927
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
4✔
1928

4✔
1929
                if err := s.channelNotifier.Start(); err != nil {
4✔
1930
                        startErr = err
×
1931
                        return
×
1932
                }
×
1933
                cleanup = cleanup.add(s.channelNotifier.Stop)
4✔
1934

4✔
1935
                if err := s.peerNotifier.Start(); err != nil {
4✔
1936
                        startErr = err
×
1937
                        return
×
1938
                }
×
1939
                cleanup = cleanup.add(func() error {
4✔
1940
                        return s.peerNotifier.Stop()
×
1941
                })
×
1942
                if err := s.htlcNotifier.Start(); err != nil {
4✔
1943
                        startErr = err
×
1944
                        return
×
1945
                }
×
1946
                cleanup = cleanup.add(s.htlcNotifier.Stop)
4✔
1947

4✔
1948
                if s.towerClientMgr != nil {
8✔
1949
                        if err := s.towerClientMgr.Start(); err != nil {
4✔
1950
                                startErr = err
×
1951
                                return
×
1952
                        }
×
1953
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
4✔
1954
                }
1955

1956
                if err := s.txPublisher.Start(); err != nil {
4✔
1957
                        startErr = err
×
1958
                        return
×
1959
                }
×
1960
                cleanup = cleanup.add(func() error {
4✔
1961
                        s.txPublisher.Stop()
×
1962
                        return nil
×
1963
                })
×
1964

1965
                if err := s.sweeper.Start(); err != nil {
4✔
1966
                        startErr = err
×
1967
                        return
×
1968
                }
×
1969
                cleanup = cleanup.add(s.sweeper.Stop)
4✔
1970

4✔
1971
                if err := s.utxoNursery.Start(); err != nil {
4✔
1972
                        startErr = err
×
1973
                        return
×
1974
                }
×
1975
                cleanup = cleanup.add(s.utxoNursery.Stop)
4✔
1976

4✔
1977
                if err := s.breachArbitrator.Start(); err != nil {
4✔
1978
                        startErr = err
×
1979
                        return
×
1980
                }
×
1981
                cleanup = cleanup.add(s.breachArbitrator.Stop)
4✔
1982

4✔
1983
                if err := s.fundingMgr.Start(); err != nil {
4✔
1984
                        startErr = err
×
1985
                        return
×
1986
                }
×
1987
                cleanup = cleanup.add(s.fundingMgr.Stop)
4✔
1988

4✔
1989
                // htlcSwitch must be started before chainArb since the latter
4✔
1990
                // relies on htlcSwitch to deliver resolution message upon
4✔
1991
                // start.
4✔
1992
                if err := s.htlcSwitch.Start(); err != nil {
4✔
1993
                        startErr = err
×
1994
                        return
×
1995
                }
×
1996
                cleanup = cleanup.add(s.htlcSwitch.Stop)
4✔
1997

4✔
1998
                if err := s.interceptableSwitch.Start(); err != nil {
4✔
1999
                        startErr = err
×
2000
                        return
×
2001
                }
×
2002
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
4✔
2003

4✔
2004
                if err := s.chainArb.Start(); err != nil {
4✔
2005
                        startErr = err
×
2006
                        return
×
2007
                }
×
2008
                cleanup = cleanup.add(s.chainArb.Stop)
4✔
2009

4✔
2010
                if err := s.authGossiper.Start(); err != nil {
4✔
2011
                        startErr = err
×
2012
                        return
×
2013
                }
×
2014
                cleanup = cleanup.add(s.authGossiper.Stop)
4✔
2015

4✔
2016
                if err := s.chanRouter.Start(); err != nil {
4✔
2017
                        startErr = err
×
2018
                        return
×
2019
                }
×
2020
                cleanup = cleanup.add(s.chanRouter.Stop)
4✔
2021

4✔
2022
                if err := s.invoices.Start(); err != nil {
4✔
2023
                        startErr = err
×
2024
                        return
×
2025
                }
×
2026
                cleanup = cleanup.add(s.invoices.Stop)
4✔
2027

4✔
2028
                if err := s.sphinx.Start(); err != nil {
4✔
2029
                        startErr = err
×
2030
                        return
×
2031
                }
×
2032
                cleanup = cleanup.add(s.sphinx.Stop)
4✔
2033

4✔
2034
                if err := s.chanStatusMgr.Start(); err != nil {
4✔
2035
                        startErr = err
×
2036
                        return
×
2037
                }
×
2038
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
4✔
2039

4✔
2040
                if err := s.chanEventStore.Start(); err != nil {
4✔
2041
                        startErr = err
×
2042
                        return
×
2043
                }
×
2044
                cleanup = cleanup.add(func() error {
4✔
2045
                        s.chanEventStore.Stop()
×
2046
                        return nil
×
2047
                })
×
2048

2049
                s.missionControl.RunStoreTicker()
4✔
2050
                cleanup.add(func() error {
4✔
2051
                        s.missionControl.StopStoreTicker()
×
2052
                        return nil
×
2053
                })
×
2054

2055
                // Before we start the connMgr, we'll check to see if we have
2056
                // any backups to recover. We do this now as we want to ensure
2057
                // that have all the information we need to handle channel
2058
                // recovery _before_ we even accept connections from any peers.
2059
                chanRestorer := &chanDBRestorer{
4✔
2060
                        db:         s.chanStateDB,
4✔
2061
                        secretKeys: s.cc.KeyRing,
4✔
2062
                        chainArb:   s.chainArb,
4✔
2063
                }
4✔
2064
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
4✔
2065
                        err := chanbackup.UnpackAndRecoverSingles(
×
2066
                                s.chansToRestore.PackedSingleChanBackups,
×
2067
                                s.cc.KeyRing, chanRestorer, s,
×
2068
                        )
×
2069
                        if err != nil {
×
2070
                                startErr = fmt.Errorf("unable to unpack single "+
×
2071
                                        "backups: %v", err)
×
2072
                                return
×
2073
                        }
×
2074
                }
2075
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
8✔
2076
                        err := chanbackup.UnpackAndRecoverMulti(
4✔
2077
                                s.chansToRestore.PackedMultiChanBackup,
4✔
2078
                                s.cc.KeyRing, chanRestorer, s,
4✔
2079
                        )
4✔
2080
                        if err != nil {
4✔
2081
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2082
                                        "backup: %v", err)
×
2083
                                return
×
2084
                        }
×
2085
                }
2086

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

4✔
2093
                if s.torController != nil {
4✔
2094
                        if err := s.createNewHiddenService(); err != nil {
×
2095
                                startErr = err
×
2096
                                return
×
2097
                        }
×
2098
                        cleanup = cleanup.add(s.torController.Stop)
×
2099
                }
2100

2101
                if s.natTraversal != nil {
4✔
2102
                        s.wg.Add(1)
×
2103
                        go s.watchExternalIP()
×
2104
                }
×
2105

2106
                // Start connmgr last to prevent connections before init.
2107
                s.connMgr.Start()
4✔
2108
                cleanup = cleanup.add(func() error {
4✔
2109
                        s.connMgr.Stop()
×
2110
                        return nil
×
2111
                })
×
2112

2113
                // If peers are specified as a config option, we'll add those
2114
                // peers first.
2115
                for _, peerAddrCfg := range s.cfg.AddPeers {
8✔
2116
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
4✔
2117
                                peerAddrCfg,
4✔
2118
                        )
4✔
2119
                        if err != nil {
4✔
2120
                                startErr = fmt.Errorf("unable to parse peer "+
×
2121
                                        "pubkey from config: %v", err)
×
2122
                                return
×
2123
                        }
×
2124
                        addr, err := parseAddr(parsedHost, s.cfg.net)
4✔
2125
                        if err != nil {
4✔
2126
                                startErr = fmt.Errorf("unable to parse peer "+
×
2127
                                        "address provided as a config option: "+
×
2128
                                        "%v", err)
×
2129
                                return
×
2130
                        }
×
2131

2132
                        peerAddr := &lnwire.NetAddress{
4✔
2133
                                IdentityKey: parsedPubkey,
4✔
2134
                                Address:     addr,
4✔
2135
                                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
2136
                        }
4✔
2137

4✔
2138
                        err = s.ConnectToPeer(
4✔
2139
                                peerAddr, true,
4✔
2140
                                s.cfg.ConnectionTimeout,
4✔
2141
                        )
4✔
2142
                        if err != nil {
4✔
2143
                                startErr = fmt.Errorf("unable to connect to "+
×
2144
                                        "peer address provided as a config "+
×
2145
                                        "option: %v", err)
×
2146
                                return
×
2147
                        }
×
2148
                }
2149

2150
                // Subscribe to NodeAnnouncements that advertise new addresses
2151
                // our persistent peers.
2152
                if err := s.updatePersistentPeerAddrs(); err != nil {
4✔
2153
                        startErr = err
×
2154
                        return
×
2155
                }
×
2156

2157
                // With all the relevant sub-systems started, we'll now attempt
2158
                // to establish persistent connections to our direct channel
2159
                // collaborators within the network. Before doing so however,
2160
                // we'll prune our set of link nodes found within the database
2161
                // to ensure we don't reconnect to any nodes we no longer have
2162
                // open channels with.
2163
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
4✔
2164
                        startErr = err
×
2165
                        return
×
2166
                }
×
2167
                if err := s.establishPersistentConnections(); err != nil {
4✔
2168
                        startErr = err
×
2169
                        return
×
2170
                }
×
2171

2172
                // setSeedList is a helper function that turns multiple DNS seed
2173
                // server tuples from the command line or config file into the
2174
                // data structure we need and does a basic formal sanity check
2175
                // in the process.
2176
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
4✔
2177
                        if len(tuples) == 0 {
×
2178
                                return
×
2179
                        }
×
2180

2181
                        result := make([][2]string, len(tuples))
×
2182
                        for idx, tuple := range tuples {
×
2183
                                tuple = strings.TrimSpace(tuple)
×
2184
                                if len(tuple) == 0 {
×
2185
                                        return
×
2186
                                }
×
2187

2188
                                servers := strings.Split(tuple, ",")
×
2189
                                if len(servers) > 2 || len(servers) == 0 {
×
2190
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2191
                                                "seed tuple: %v", servers)
×
2192
                                        return
×
2193
                                }
×
2194

2195
                                copy(result[idx][:], servers)
×
2196
                        }
2197

2198
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2199
                }
2200

2201
                // Let users overwrite the DNS seed nodes. We only allow them
2202
                // for bitcoin mainnet/testnet/signet.
2203
                if s.cfg.Bitcoin.MainNet {
4✔
2204
                        setSeedList(
×
2205
                                s.cfg.Bitcoin.DNSSeeds,
×
2206
                                chainreg.BitcoinMainnetGenesis,
×
2207
                        )
×
2208
                }
×
2209
                if s.cfg.Bitcoin.TestNet3 {
4✔
2210
                        setSeedList(
×
2211
                                s.cfg.Bitcoin.DNSSeeds,
×
2212
                                chainreg.BitcoinTestnetGenesis,
×
2213
                        )
×
2214
                }
×
2215
                if s.cfg.Bitcoin.SigNet {
4✔
2216
                        setSeedList(
×
2217
                                s.cfg.Bitcoin.DNSSeeds,
×
2218
                                chainreg.BitcoinSignetGenesis,
×
2219
                        )
×
2220
                }
×
2221

2222
                // If network bootstrapping hasn't been disabled, then we'll
2223
                // configure the set of active bootstrappers, and launch a
2224
                // dedicated goroutine to maintain a set of persistent
2225
                // connections.
2226
                if shouldPeerBootstrap(s.cfg) {
4✔
2227
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2228
                        if err != nil {
×
2229
                                startErr = err
×
2230
                                return
×
2231
                        }
×
2232

2233
                        s.wg.Add(1)
×
2234
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2235
                } else {
4✔
2236
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
4✔
2237
                }
4✔
2238

2239
                // Set the active flag now that we've completed the full
2240
                // startup.
2241
                atomic.StoreInt32(&s.active, 1)
4✔
2242
        })
2243

2244
        if startErr != nil {
4✔
2245
                cleanup.run()
×
2246
        }
×
2247
        return startErr
4✔
2248
}
2249

2250
// Stop gracefully shutsdown the main daemon server. This function will signal
2251
// any active goroutines, or helper objects to exit, then blocks until they've
2252
// all successfully exited. Additionally, any/all listeners are closed.
2253
// NOTE: This function is safe for concurrent access.
2254
func (s *server) Stop() error {
4✔
2255
        s.stop.Do(func() {
8✔
2256
                atomic.StoreInt32(&s.stopping, 1)
4✔
2257

4✔
2258
                close(s.quit)
4✔
2259

4✔
2260
                // Shutdown connMgr first to prevent conns during shutdown.
4✔
2261
                s.connMgr.Stop()
4✔
2262

4✔
2263
                // Shutdown the wallet, funding manager, and the rpc server.
4✔
2264
                if err := s.chanStatusMgr.Stop(); err != nil {
4✔
2265
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2266
                }
×
2267
                if err := s.htlcSwitch.Stop(); err != nil {
4✔
2268
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2269
                }
×
2270
                if err := s.sphinx.Stop(); err != nil {
4✔
2271
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2272
                }
×
2273
                if err := s.invoices.Stop(); err != nil {
4✔
2274
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2275
                }
×
2276
                if err := s.chanRouter.Stop(); err != nil {
4✔
2277
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2278
                }
×
2279
                if err := s.chainArb.Stop(); err != nil {
4✔
2280
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2281
                }
×
2282
                if err := s.fundingMgr.Stop(); err != nil {
4✔
2283
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2284
                }
×
2285
                if err := s.breachArbitrator.Stop(); err != nil {
4✔
2286
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2287
                                err)
×
2288
                }
×
2289
                if err := s.utxoNursery.Stop(); err != nil {
4✔
2290
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2291
                }
×
2292
                if err := s.authGossiper.Stop(); err != nil {
4✔
2293
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2294
                }
×
2295
                if err := s.sweeper.Stop(); err != nil {
4✔
2296
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2297
                }
×
2298

2299
                s.txPublisher.Stop()
4✔
2300

4✔
2301
                if err := s.channelNotifier.Stop(); err != nil {
4✔
2302
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2303
                }
×
2304
                if err := s.peerNotifier.Stop(); err != nil {
4✔
2305
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2306
                }
×
2307
                if err := s.htlcNotifier.Stop(); err != nil {
4✔
2308
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2309
                }
×
2310
                if err := s.chanSubSwapper.Stop(); err != nil {
4✔
2311
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2312
                }
×
2313
                if err := s.cc.ChainNotifier.Stop(); err != nil {
4✔
2314
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2315
                }
×
2316
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
4✔
2317
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2318
                                err)
×
2319
                }
×
2320
                s.chanEventStore.Stop()
4✔
2321
                s.missionControl.StopStoreTicker()
4✔
2322

4✔
2323
                // Disconnect from each active peers to ensure that
4✔
2324
                // peerTerminationWatchers signal completion to each peer.
4✔
2325
                for _, peer := range s.Peers() {
8✔
2326
                        err := s.DisconnectPeer(peer.IdentityKey())
4✔
2327
                        if err != nil {
4✔
2328
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2329
                                        "received error: %v", peer.IdentityKey(),
×
2330
                                        err,
×
2331
                                )
×
2332
                        }
×
2333
                }
2334

2335
                // Now that all connections have been torn down, stop the tower
2336
                // client which will reliably flush all queued states to the
2337
                // tower. If this is halted for any reason, the force quit timer
2338
                // will kick in and abort to allow this method to return.
2339
                if s.towerClientMgr != nil {
8✔
2340
                        if err := s.towerClientMgr.Stop(); err != nil {
4✔
2341
                                srvrLog.Warnf("Unable to shut down tower "+
×
2342
                                        "client manager: %v", err)
×
2343
                        }
×
2344
                }
2345

2346
                if s.hostAnn != nil {
4✔
2347
                        if err := s.hostAnn.Stop(); err != nil {
×
2348
                                srvrLog.Warnf("unable to shut down host "+
×
2349
                                        "annoucner: %v", err)
×
2350
                        }
×
2351
                }
2352

2353
                if s.livenessMonitor != nil {
8✔
2354
                        if err := s.livenessMonitor.Stop(); err != nil {
4✔
2355
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2356
                                        "monitor: %v", err)
×
2357
                        }
×
2358
                }
2359

2360
                // Wait for all lingering goroutines to quit.
2361
                srvrLog.Debug("Waiting for server to shutdown...")
4✔
2362
                s.wg.Wait()
4✔
2363

4✔
2364
                srvrLog.Debug("Stopping buffer pools...")
4✔
2365
                s.sigPool.Stop()
4✔
2366
                s.writePool.Stop()
4✔
2367
                s.readPool.Stop()
4✔
2368
        })
2369

2370
        return nil
4✔
2371
}
2372

2373
// Stopped returns true if the server has been instructed to shutdown.
2374
// NOTE: This function is safe for concurrent access.
2375
func (s *server) Stopped() bool {
4✔
2376
        return atomic.LoadInt32(&s.stopping) != 0
4✔
2377
}
4✔
2378

2379
// configurePortForwarding attempts to set up port forwarding for the different
2380
// ports that the server will be listening on.
2381
//
2382
// NOTE: This should only be used when using some kind of NAT traversal to
2383
// automatically set up forwarding rules.
2384
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2385
        ip, err := s.natTraversal.ExternalIP()
×
2386
        if err != nil {
×
2387
                return nil, err
×
2388
        }
×
2389
        s.lastDetectedIP = ip
×
2390

×
2391
        externalIPs := make([]string, 0, len(ports))
×
2392
        for _, port := range ports {
×
2393
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2394
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2395
                        continue
×
2396
                }
2397

2398
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2399
                externalIPs = append(externalIPs, hostIP)
×
2400
        }
2401

2402
        return externalIPs, nil
×
2403
}
2404

2405
// removePortForwarding attempts to clear the forwarding rules for the different
2406
// ports the server is currently listening on.
2407
//
2408
// NOTE: This should only be used when using some kind of NAT traversal to
2409
// automatically set up forwarding rules.
2410
func (s *server) removePortForwarding() {
×
2411
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2412
        for _, port := range forwardedPorts {
×
2413
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2414
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2415
                                "port %d: %v", port, err)
×
2416
                }
×
2417
        }
2418
}
2419

2420
// watchExternalIP continuously checks for an updated external IP address every
2421
// 15 minutes. Once a new IP address has been detected, it will automatically
2422
// handle port forwarding rules and send updated node announcements to the
2423
// currently connected peers.
2424
//
2425
// NOTE: This MUST be run as a goroutine.
2426
func (s *server) watchExternalIP() {
×
2427
        defer s.wg.Done()
×
2428

×
2429
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2430
        // up by the server.
×
2431
        defer s.removePortForwarding()
×
2432

×
2433
        // Keep track of the external IPs set by the user to avoid replacing
×
2434
        // them when detecting a new IP.
×
2435
        ipsSetByUser := make(map[string]struct{})
×
2436
        for _, ip := range s.cfg.ExternalIPs {
×
2437
                ipsSetByUser[ip.String()] = struct{}{}
×
2438
        }
×
2439

2440
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2441

×
2442
        ticker := time.NewTicker(15 * time.Minute)
×
2443
        defer ticker.Stop()
×
2444
out:
×
2445
        for {
×
2446
                select {
×
2447
                case <-ticker.C:
×
2448
                        // We'll start off by making sure a new IP address has
×
2449
                        // been detected.
×
2450
                        ip, err := s.natTraversal.ExternalIP()
×
2451
                        if err != nil {
×
2452
                                srvrLog.Debugf("Unable to retrieve the "+
×
2453
                                        "external IP address: %v", err)
×
2454
                                continue
×
2455
                        }
2456

2457
                        // Periodically renew the NAT port forwarding.
2458
                        for _, port := range forwardedPorts {
×
2459
                                err := s.natTraversal.AddPortMapping(port)
×
2460
                                if err != nil {
×
2461
                                        srvrLog.Warnf("Unable to automatically "+
×
2462
                                                "re-create port forwarding using %s: %v",
×
2463
                                                s.natTraversal.Name(), err)
×
2464
                                } else {
×
2465
                                        srvrLog.Debugf("Automatically re-created "+
×
2466
                                                "forwarding for port %d using %s to "+
×
2467
                                                "advertise external IP",
×
2468
                                                port, s.natTraversal.Name())
×
2469
                                }
×
2470
                        }
2471

2472
                        if ip.Equal(s.lastDetectedIP) {
×
2473
                                continue
×
2474
                        }
2475

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

×
2478
                        // Next, we'll craft the new addresses that will be
×
2479
                        // included in the new node announcement and advertised
×
2480
                        // to the network. Each address will consist of the new
×
2481
                        // IP detected and one of the currently advertised
×
2482
                        // ports.
×
2483
                        var newAddrs []net.Addr
×
2484
                        for _, port := range forwardedPorts {
×
2485
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2486
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2487
                                if err != nil {
×
2488
                                        srvrLog.Debugf("Unable to resolve "+
×
2489
                                                "host %v: %v", addr, err)
×
2490
                                        continue
×
2491
                                }
2492

2493
                                newAddrs = append(newAddrs, addr)
×
2494
                        }
2495

2496
                        // Skip the update if we weren't able to resolve any of
2497
                        // the new addresses.
2498
                        if len(newAddrs) == 0 {
×
2499
                                srvrLog.Debug("Skipping node announcement " +
×
2500
                                        "update due to not being able to " +
×
2501
                                        "resolve any new addresses")
×
2502
                                continue
×
2503
                        }
2504

2505
                        // Now, we'll need to update the addresses in our node's
2506
                        // announcement in order to propagate the update
2507
                        // throughout the network. We'll only include addresses
2508
                        // that have a different IP from the previous one, as
2509
                        // the previous IP is no longer valid.
2510
                        currentNodeAnn := s.getNodeAnnouncement()
×
2511

×
2512
                        for _, addr := range currentNodeAnn.Addresses {
×
2513
                                host, _, err := net.SplitHostPort(addr.String())
×
2514
                                if err != nil {
×
2515
                                        srvrLog.Debugf("Unable to determine "+
×
2516
                                                "host from address %v: %v",
×
2517
                                                addr, err)
×
2518
                                        continue
×
2519
                                }
2520

2521
                                // We'll also make sure to include external IPs
2522
                                // set manually by the user.
2523
                                _, setByUser := ipsSetByUser[addr.String()]
×
2524
                                if setByUser || host != s.lastDetectedIP.String() {
×
2525
                                        newAddrs = append(newAddrs, addr)
×
2526
                                }
×
2527
                        }
2528

2529
                        // Then, we'll generate a new timestamped node
2530
                        // announcement with the updated addresses and broadcast
2531
                        // it to our peers.
2532
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2533
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2534
                        )
×
2535
                        if err != nil {
×
2536
                                srvrLog.Debugf("Unable to generate new node "+
×
2537
                                        "announcement: %v", err)
×
2538
                                continue
×
2539
                        }
2540

2541
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2542
                        if err != nil {
×
2543
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2544
                                        "announcement to peers: %v", err)
×
2545
                                continue
×
2546
                        }
2547

2548
                        // Finally, update the last IP seen to the current one.
2549
                        s.lastDetectedIP = ip
×
2550
                case <-s.quit:
×
2551
                        break out
×
2552
                }
2553
        }
2554
}
2555

2556
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2557
// based on the server, and currently active bootstrap mechanisms as defined
2558
// within the current configuration.
2559
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2560
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2561

×
2562
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2563

×
2564
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2565
        // this can be used by default if we've already partially seeded the
×
2566
        // network.
×
2567
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2568
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2569
        if err != nil {
×
2570
                return nil, err
×
2571
        }
×
2572
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2573

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

×
2579
                // If we have a set of DNS seeds for this chain, then we'll add
×
2580
                // it as an additional bootstrapping source.
×
2581
                if ok {
×
2582
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2583
                                "seeds: %v", dnsSeeds)
×
2584

×
2585
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2586
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2587
                        )
×
2588
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2589
                }
×
2590
        }
2591

2592
        return bootStrappers, nil
×
2593
}
2594

2595
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2596
// needs to ignore, which is made of three parts,
2597
//   - the node itself needs to be skipped as it doesn't make sense to connect
2598
//     to itself.
2599
//   - the peers that already have connections with, as in s.peersByPub.
2600
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2601
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2602
        s.mu.RLock()
×
2603
        defer s.mu.RUnlock()
×
2604

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

×
2607
        // We should ignore ourselves from bootstrapping.
×
2608
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2609
        ignore[selfKey] = struct{}{}
×
2610

×
2611
        // Ignore all connected peers.
×
2612
        for _, peer := range s.peersByPub {
×
2613
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2614
                ignore[nID] = struct{}{}
×
2615
        }
×
2616

2617
        // Ignore all persistent peers as they have a dedicated reconnecting
2618
        // process.
2619
        for pubKeyStr := range s.persistentPeers {
×
2620
                var nID autopilot.NodeID
×
2621
                copy(nID[:], []byte(pubKeyStr))
×
2622
                ignore[nID] = struct{}{}
×
2623
        }
×
2624

2625
        return ignore
×
2626
}
2627

2628
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2629
// and maintain a target minimum number of outbound connections. With this
2630
// invariant, we ensure that our node is connected to a diverse set of peers
2631
// and that nodes newly joining the network receive an up to date network view
2632
// as soon as possible.
2633
func (s *server) peerBootstrapper(numTargetPeers uint32,
2634
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2635

×
2636
        defer s.wg.Done()
×
2637

×
2638
        // Before we continue, init the ignore peers map.
×
2639
        ignoreList := s.createBootstrapIgnorePeers()
×
2640

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

×
2645
        // Once done, we'll attempt to maintain our target minimum number of
×
2646
        // peers.
×
2647
        //
×
2648
        // We'll use a 15 second backoff, and double the time every time an
×
2649
        // epoch fails up to a ceiling.
×
2650
        backOff := time.Second * 15
×
2651

×
2652
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2653
        // see if we've reached our minimum number of peers.
×
2654
        sampleTicker := time.NewTicker(backOff)
×
2655
        defer sampleTicker.Stop()
×
2656

×
2657
        // We'll use the number of attempts and errors to determine if we need
×
2658
        // to increase the time between discovery epochs.
×
2659
        var epochErrors uint32 // To be used atomically.
×
2660
        var epochAttempts uint32
×
2661

×
2662
        for {
×
2663
                select {
×
2664
                // The ticker has just woken us up, so we'll need to check if
2665
                // we need to attempt to connect our to any more peers.
2666
                case <-sampleTicker.C:
×
2667
                        // Obtain the current number of peers, so we can gauge
×
2668
                        // if we need to sample more peers or not.
×
2669
                        s.mu.RLock()
×
2670
                        numActivePeers := uint32(len(s.peersByPub))
×
2671
                        s.mu.RUnlock()
×
2672

×
2673
                        // If we have enough peers, then we can loop back
×
2674
                        // around to the next round as we're done here.
×
2675
                        if numActivePeers >= numTargetPeers {
×
2676
                                continue
×
2677
                        }
2678

2679
                        // If all of our attempts failed during this last back
2680
                        // off period, then will increase our backoff to 5
2681
                        // minute ceiling to avoid an excessive number of
2682
                        // queries
2683
                        //
2684
                        // TODO(roasbeef): add reverse policy too?
2685

2686
                        if epochAttempts > 0 &&
×
2687
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2688

×
2689
                                sampleTicker.Stop()
×
2690

×
2691
                                backOff *= 2
×
2692
                                if backOff > bootstrapBackOffCeiling {
×
2693
                                        backOff = bootstrapBackOffCeiling
×
2694
                                }
×
2695

2696
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2697
                                        "%v", backOff)
×
2698
                                sampleTicker = time.NewTicker(backOff)
×
2699
                                continue
×
2700
                        }
2701

2702
                        atomic.StoreUint32(&epochErrors, 0)
×
2703
                        epochAttempts = 0
×
2704

×
2705
                        // Since we know need more peers, we'll compute the
×
2706
                        // exact number we need to reach our threshold.
×
2707
                        numNeeded := numTargetPeers - numActivePeers
×
2708

×
2709
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2710
                                "peers", numNeeded)
×
2711

×
2712
                        // With the number of peers we need calculated, we'll
×
2713
                        // query the network bootstrappers to sample a set of
×
2714
                        // random addrs for us.
×
2715
                        //
×
2716
                        // Before we continue, get a copy of the ignore peers
×
2717
                        // map.
×
2718
                        ignoreList = s.createBootstrapIgnorePeers()
×
2719

×
2720
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2721
                                ignoreList, numNeeded*2, bootstrappers...,
×
2722
                        )
×
2723
                        if err != nil {
×
2724
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2725
                                        "peers: %v", err)
×
2726
                                continue
×
2727
                        }
2728

2729
                        // Finally, we'll launch a new goroutine for each
2730
                        // prospective peer candidates.
2731
                        for _, addr := range peerAddrs {
×
2732
                                epochAttempts++
×
2733

×
2734
                                go func(a *lnwire.NetAddress) {
×
2735
                                        // TODO(roasbeef): can do AS, subnet,
×
2736
                                        // country diversity, etc
×
2737
                                        errChan := make(chan error, 1)
×
2738
                                        s.connectToPeer(
×
2739
                                                a, errChan,
×
2740
                                                s.cfg.ConnectionTimeout,
×
2741
                                        )
×
2742
                                        select {
×
2743
                                        case err := <-errChan:
×
2744
                                                if err == nil {
×
2745
                                                        return
×
2746
                                                }
×
2747

2748
                                                srvrLog.Errorf("Unable to "+
×
2749
                                                        "connect to %v: %v",
×
2750
                                                        a, err)
×
2751
                                                atomic.AddUint32(&epochErrors, 1)
×
2752
                                        case <-s.quit:
×
2753
                                        }
2754
                                }(addr)
2755
                        }
2756
                case <-s.quit:
×
2757
                        return
×
2758
                }
2759
        }
2760
}
2761

2762
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
2763
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
2764
// query back off each time we encounter a failure.
2765
const bootstrapBackOffCeiling = time.Minute * 5
2766

2767
// initialPeerBootstrap attempts to continuously connect to peers on startup
2768
// until the target number of peers has been reached. This ensures that nodes
2769
// receive an up to date network view as soon as possible.
2770
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2771
        numTargetPeers uint32,
2772
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2773

×
2774
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
2775
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
2776

×
2777
        // We'll start off by waiting 2 seconds between failed attempts, then
×
2778
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
2779
        var delaySignal <-chan time.Time
×
2780
        delayTime := time.Second * 2
×
2781

×
2782
        // As want to be more aggressive, we'll use a lower back off celling
×
2783
        // then the main peer bootstrap logic.
×
2784
        backOffCeiling := bootstrapBackOffCeiling / 5
×
2785

×
2786
        for attempts := 0; ; attempts++ {
×
2787
                // Check if the server has been requested to shut down in order
×
2788
                // to prevent blocking.
×
2789
                if s.Stopped() {
×
2790
                        return
×
2791
                }
×
2792

2793
                // We can exit our aggressive initial peer bootstrapping stage
2794
                // if we've reached out target number of peers.
2795
                s.mu.RLock()
×
2796
                numActivePeers := uint32(len(s.peersByPub))
×
2797
                s.mu.RUnlock()
×
2798

×
2799
                if numActivePeers >= numTargetPeers {
×
2800
                        return
×
2801
                }
×
2802

2803
                if attempts > 0 {
×
2804
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
2805
                                "bootstrap peers (attempt #%v)", delayTime,
×
2806
                                attempts)
×
2807

×
2808
                        // We've completed at least one iterating and haven't
×
2809
                        // finished, so we'll start to insert a delay period
×
2810
                        // between each attempt.
×
2811
                        delaySignal = time.After(delayTime)
×
2812
                        select {
×
2813
                        case <-delaySignal:
×
2814
                        case <-s.quit:
×
2815
                                return
×
2816
                        }
2817

2818
                        // After our delay, we'll double the time we wait up to
2819
                        // the max back off period.
2820
                        delayTime *= 2
×
2821
                        if delayTime > backOffCeiling {
×
2822
                                delayTime = backOffCeiling
×
2823
                        }
×
2824
                }
2825

2826
                // Otherwise, we'll request for the remaining number of peers
2827
                // in order to reach our target.
2828
                peersNeeded := numTargetPeers - numActivePeers
×
2829
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
2830
                        ignore, peersNeeded, bootstrappers...,
×
2831
                )
×
2832
                if err != nil {
×
2833
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
2834
                                "peers: %v", err)
×
2835
                        continue
×
2836
                }
2837

2838
                // Then, we'll attempt to establish a connection to the
2839
                // different peer addresses retrieved by our bootstrappers.
2840
                var wg sync.WaitGroup
×
2841
                for _, bootstrapAddr := range bootstrapAddrs {
×
2842
                        wg.Add(1)
×
2843
                        go func(addr *lnwire.NetAddress) {
×
2844
                                defer wg.Done()
×
2845

×
2846
                                errChan := make(chan error, 1)
×
2847
                                go s.connectToPeer(
×
2848
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
2849
                                )
×
2850

×
2851
                                // We'll only allow this connection attempt to
×
2852
                                // take up to 3 seconds. This allows us to move
×
2853
                                // quickly by discarding peers that are slowing
×
2854
                                // us down.
×
2855
                                select {
×
2856
                                case err := <-errChan:
×
2857
                                        if err == nil {
×
2858
                                                return
×
2859
                                        }
×
2860
                                        srvrLog.Errorf("Unable to connect to "+
×
2861
                                                "%v: %v", addr, err)
×
2862
                                // TODO: tune timeout? 3 seconds might be *too*
2863
                                // aggressive but works well.
2864
                                case <-time.After(3 * time.Second):
×
2865
                                        srvrLog.Tracef("Skipping peer %v due "+
×
2866
                                                "to not establishing a "+
×
2867
                                                "connection within 3 seconds",
×
2868
                                                addr)
×
2869
                                case <-s.quit:
×
2870
                                }
2871
                        }(bootstrapAddr)
2872
                }
2873

2874
                wg.Wait()
×
2875
        }
2876
}
2877

2878
// createNewHiddenService automatically sets up a v2 or v3 onion service in
2879
// order to listen for inbound connections over Tor.
2880
func (s *server) createNewHiddenService() error {
×
2881
        // Determine the different ports the server is listening on. The onion
×
2882
        // service's virtual port will map to these ports and one will be picked
×
2883
        // at random when the onion service is being accessed.
×
2884
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
2885
        for _, listenAddr := range s.listenAddrs {
×
2886
                port := listenAddr.(*net.TCPAddr).Port
×
2887
                listenPorts = append(listenPorts, port)
×
2888
        }
×
2889

2890
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
2891
        if err != nil {
×
2892
                return err
×
2893
        }
×
2894

2895
        // Once the port mapping has been set, we can go ahead and automatically
2896
        // create our onion service. The service's private key will be saved to
2897
        // disk in order to regain access to this service when restarting `lnd`.
2898
        onionCfg := tor.AddOnionConfig{
×
2899
                VirtualPort: defaultPeerPort,
×
2900
                TargetPorts: listenPorts,
×
2901
                Store: tor.NewOnionFile(
×
2902
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
2903
                        encrypter,
×
2904
                ),
×
2905
        }
×
2906

×
2907
        switch {
×
2908
        case s.cfg.Tor.V2:
×
2909
                onionCfg.Type = tor.V2
×
2910
        case s.cfg.Tor.V3:
×
2911
                onionCfg.Type = tor.V3
×
2912
        }
2913

2914
        addr, err := s.torController.AddOnion(onionCfg)
×
2915
        if err != nil {
×
2916
                return err
×
2917
        }
×
2918

2919
        // Now that the onion service has been created, we'll add the onion
2920
        // address it can be reached at to our list of advertised addresses.
2921
        newNodeAnn, err := s.genNodeAnnouncement(
×
2922
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
2923
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
2924
                },
×
2925
        )
2926
        if err != nil {
×
2927
                return fmt.Errorf("unable to generate new node "+
×
2928
                        "announcement: %v", err)
×
2929
        }
×
2930

2931
        // Finally, we'll update the on-disk version of our announcement so it
2932
        // will eventually propagate to nodes in the network.
2933
        selfNode := &channeldb.LightningNode{
×
2934
                HaveNodeAnnouncement: true,
×
2935
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
2936
                Addresses:            newNodeAnn.Addresses,
×
2937
                Alias:                newNodeAnn.Alias.String(),
×
2938
                Features: lnwire.NewFeatureVector(
×
2939
                        newNodeAnn.Features, lnwire.Features,
×
2940
                ),
×
2941
                Color:        newNodeAnn.RGBColor,
×
2942
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
2943
        }
×
2944
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
2945
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
2946
                return fmt.Errorf("can't set self node: %w", err)
×
2947
        }
×
2948

2949
        return nil
×
2950
}
2951

2952
// findChannel finds a channel given a public key and ChannelID. It is an
2953
// optimization that is quicker than seeking for a channel given only the
2954
// ChannelID.
2955
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
2956
        *channeldb.OpenChannel, error) {
4✔
2957

4✔
2958
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
4✔
2959
        if err != nil {
4✔
2960
                return nil, err
×
2961
        }
×
2962

2963
        for _, channel := range nodeChans {
8✔
2964
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
8✔
2965
                        return channel, nil
4✔
2966
                }
4✔
2967
        }
2968

2969
        return nil, fmt.Errorf("unable to find channel")
4✔
2970
}
2971

2972
// getNodeAnnouncement fetches the current, fully signed node announcement.
2973
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
4✔
2974
        s.mu.Lock()
4✔
2975
        defer s.mu.Unlock()
4✔
2976

4✔
2977
        return *s.currentNodeAnn
4✔
2978
}
4✔
2979

2980
// genNodeAnnouncement generates and returns the current fully signed node
2981
// announcement. The time stamp of the announcement will be updated in order
2982
// to ensure it propagates through the network.
2983
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
2984
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
4✔
2985

4✔
2986
        s.mu.Lock()
4✔
2987
        defer s.mu.Unlock()
4✔
2988

4✔
2989
        // First, try to update our feature manager with the updated set of
4✔
2990
        // features.
4✔
2991
        if features != nil {
8✔
2992
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
4✔
2993
                        feature.SetNodeAnn: features,
4✔
2994
                }
4✔
2995
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
4✔
2996
                if err != nil {
8✔
2997
                        return lnwire.NodeAnnouncement{}, err
4✔
2998
                }
4✔
2999

3000
                // If we could successfully update our feature manager, add
3001
                // an update modifier to include these new features to our
3002
                // set.
3003
                modifiers = append(
4✔
3004
                        modifiers, netann.NodeAnnSetFeatures(features),
4✔
3005
                )
4✔
3006
        }
3007

3008
        // Always update the timestamp when refreshing to ensure the update
3009
        // propagates.
3010
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
4✔
3011

4✔
3012
        // Apply the requested changes to the node announcement.
4✔
3013
        for _, modifier := range modifiers {
8✔
3014
                modifier(s.currentNodeAnn)
4✔
3015
        }
4✔
3016

3017
        // Sign a new update after applying all of the passed modifiers.
3018
        err := netann.SignNodeAnnouncement(
4✔
3019
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
4✔
3020
        )
4✔
3021
        if err != nil {
4✔
3022
                return lnwire.NodeAnnouncement{}, err
×
3023
        }
×
3024

3025
        return *s.currentNodeAnn, nil
4✔
3026
}
3027

3028
// updateAndBrodcastSelfNode generates a new node announcement
3029
// applying the giving modifiers and updating the time stamp
3030
// to ensure it propagates through the network. Then it brodcasts
3031
// it to the network.
3032
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
3033
        modifiers ...netann.NodeAnnModifier) error {
4✔
3034

4✔
3035
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
4✔
3036
        if err != nil {
8✔
3037
                return fmt.Errorf("unable to generate new node "+
4✔
3038
                        "announcement: %v", err)
4✔
3039
        }
4✔
3040

3041
        // Update the on-disk version of our announcement.
3042
        // Load and modify self node istead of creating anew instance so we
3043
        // don't risk overwriting any existing values.
3044
        selfNode, err := s.graphDB.SourceNode()
4✔
3045
        if err != nil {
4✔
3046
                return fmt.Errorf("unable to get current source node: %w", err)
×
3047
        }
×
3048

3049
        selfNode.HaveNodeAnnouncement = true
4✔
3050
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
4✔
3051
        selfNode.Addresses = newNodeAnn.Addresses
4✔
3052
        selfNode.Alias = newNodeAnn.Alias.String()
4✔
3053
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
4✔
3054
        selfNode.Color = newNodeAnn.RGBColor
4✔
3055
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
4✔
3056

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

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

3063
        // Finally, propagate it to the nodes in the network.
3064
        err = s.BroadcastMessage(nil, &newNodeAnn)
4✔
3065
        if err != nil {
4✔
3066
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3067
                        "announcement to peers: %v", err)
×
3068
                return err
×
3069
        }
×
3070

3071
        return nil
4✔
3072
}
3073

3074
type nodeAddresses struct {
3075
        pubKey    *btcec.PublicKey
3076
        addresses []net.Addr
3077
}
3078

3079
// establishPersistentConnections attempts to establish persistent connections
3080
// to all our direct channel collaborators. In order to promote liveness of our
3081
// active channels, we instruct the connection manager to attempt to establish
3082
// and maintain persistent connections to all our direct channel counterparties.
3083
func (s *server) establishPersistentConnections() error {
4✔
3084
        // nodeAddrsMap stores the combination of node public keys and addresses
4✔
3085
        // that we'll attempt to reconnect to. PubKey strings are used as keys
4✔
3086
        // since other PubKey forms can't be compared.
4✔
3087
        nodeAddrsMap := map[string]*nodeAddresses{}
4✔
3088

4✔
3089
        // Iterate through the list of LinkNodes to find addresses we should
4✔
3090
        // attempt to connect to based on our set of previous connections. Set
4✔
3091
        // the reconnection port to the default peer port.
4✔
3092
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
4✔
3093
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
4✔
3094
                return err
×
3095
        }
×
3096
        for _, node := range linkNodes {
8✔
3097
                pubStr := string(node.IdentityPub.SerializeCompressed())
4✔
3098
                nodeAddrs := &nodeAddresses{
4✔
3099
                        pubKey:    node.IdentityPub,
4✔
3100
                        addresses: node.Addresses,
4✔
3101
                }
4✔
3102
                nodeAddrsMap[pubStr] = nodeAddrs
4✔
3103
        }
4✔
3104

3105
        // After checking our previous connections for addresses to connect to,
3106
        // iterate through the nodes in our channel graph to find addresses
3107
        // that have been added via NodeAnnouncement messages.
3108
        sourceNode, err := s.graphDB.SourceNode()
4✔
3109
        if err != nil {
4✔
3110
                return err
×
3111
        }
×
3112

3113
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3114
        // each of the nodes.
3115
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
4✔
3116
        err = s.graphDB.ForEachNodeChannel(nil, sourceNode.PubKeyBytes, func(
4✔
3117
                tx kvdb.RTx,
4✔
3118
                chanInfo *models.ChannelEdgeInfo,
4✔
3119
                policy, _ *models.ChannelEdgePolicy) error {
8✔
3120

4✔
3121
                // If the remote party has announced the channel to us, but we
4✔
3122
                // haven't yet, then we won't have a policy. However, we don't
4✔
3123
                // need this to connect to the peer, so we'll log it and move on.
4✔
3124
                if policy == nil {
4✔
3125
                        srvrLog.Warnf("No channel policy found for "+
×
3126
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3127
                }
×
3128

3129
                // We'll now fetch the peer opposite from us within this
3130
                // channel so we can queue up a direct connection to them.
3131
                channelPeer, err := s.graphDB.FetchOtherNode(
4✔
3132
                        tx, chanInfo, selfPub,
4✔
3133
                )
4✔
3134
                if err != nil {
4✔
3135
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3136
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3137
                                err)
×
3138
                }
×
3139

3140
                pubStr := string(channelPeer.PubKeyBytes[:])
4✔
3141

4✔
3142
                // Add all unique addresses from channel
4✔
3143
                // graph/NodeAnnouncements to the list of addresses we'll
4✔
3144
                // connect to for this peer.
4✔
3145
                addrSet := make(map[string]net.Addr)
4✔
3146
                for _, addr := range channelPeer.Addresses {
8✔
3147
                        switch addr.(type) {
4✔
3148
                        case *net.TCPAddr:
4✔
3149
                                addrSet[addr.String()] = addr
4✔
3150

3151
                        // We'll only attempt to connect to Tor addresses if Tor
3152
                        // outbound support is enabled.
3153
                        case *tor.OnionAddr:
×
3154
                                if s.cfg.Tor.Active {
×
3155
                                        addrSet[addr.String()] = addr
×
3156
                                }
×
3157
                        }
3158
                }
3159

3160
                // If this peer is also recorded as a link node, we'll add any
3161
                // additional addresses that have not already been selected.
3162
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
4✔
3163
                if ok {
8✔
3164
                        for _, lnAddress := range linkNodeAddrs.addresses {
8✔
3165
                                switch lnAddress.(type) {
4✔
3166
                                case *net.TCPAddr:
4✔
3167
                                        addrSet[lnAddress.String()] = lnAddress
4✔
3168

3169
                                // We'll only attempt to connect to Tor
3170
                                // addresses if Tor outbound support is enabled.
3171
                                case *tor.OnionAddr:
×
3172
                                        if s.cfg.Tor.Active {
×
3173
                                                addrSet[lnAddress.String()] = lnAddress
×
3174
                                        }
×
3175
                                }
3176
                        }
3177
                }
3178

3179
                // Construct a slice of the deduped addresses.
3180
                var addrs []net.Addr
4✔
3181
                for _, addr := range addrSet {
8✔
3182
                        addrs = append(addrs, addr)
4✔
3183
                }
4✔
3184

3185
                n := &nodeAddresses{
4✔
3186
                        addresses: addrs,
4✔
3187
                }
4✔
3188
                n.pubKey, err = channelPeer.PubKey()
4✔
3189
                if err != nil {
4✔
3190
                        return err
×
3191
                }
×
3192

3193
                nodeAddrsMap[pubStr] = n
4✔
3194
                return nil
4✔
3195
        })
3196
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
4✔
3197
                return err
×
3198
        }
×
3199

3200
        srvrLog.Debugf("Establishing %v persistent connections on start",
4✔
3201
                len(nodeAddrsMap))
4✔
3202

4✔
3203
        // Acquire and hold server lock until all persistent connection requests
4✔
3204
        // have been recorded and sent to the connection manager.
4✔
3205
        s.mu.Lock()
4✔
3206
        defer s.mu.Unlock()
4✔
3207

4✔
3208
        // Iterate through the combined list of addresses from prior links and
4✔
3209
        // node announcements and attempt to reconnect to each node.
4✔
3210
        var numOutboundConns int
4✔
3211
        for pubStr, nodeAddr := range nodeAddrsMap {
8✔
3212
                // Add this peer to the set of peers we should maintain a
4✔
3213
                // persistent connection with. We set the value to false to
4✔
3214
                // indicate that we should not continue to reconnect if the
4✔
3215
                // number of channels returns to zero, since this peer has not
4✔
3216
                // been requested as perm by the user.
4✔
3217
                s.persistentPeers[pubStr] = false
4✔
3218
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
8✔
3219
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
4✔
3220
                }
4✔
3221

3222
                for _, address := range nodeAddr.addresses {
8✔
3223
                        // Create a wrapper address which couples the IP and
4✔
3224
                        // the pubkey so the brontide authenticated connection
4✔
3225
                        // can be established.
4✔
3226
                        lnAddr := &lnwire.NetAddress{
4✔
3227
                                IdentityKey: nodeAddr.pubKey,
4✔
3228
                                Address:     address,
4✔
3229
                        }
4✔
3230

4✔
3231
                        s.persistentPeerAddrs[pubStr] = append(
4✔
3232
                                s.persistentPeerAddrs[pubStr], lnAddr)
4✔
3233
                }
4✔
3234

3235
                // We'll connect to the first 10 peers immediately, then
3236
                // randomly stagger any remaining connections if the
3237
                // stagger initial reconnect flag is set. This ensures
3238
                // that mobile nodes or nodes with a small number of
3239
                // channels obtain connectivity quickly, but larger
3240
                // nodes are able to disperse the costs of connecting to
3241
                // all peers at once.
3242
                if numOutboundConns < numInstantInitReconnect ||
4✔
3243
                        !s.cfg.StaggerInitialReconnect {
8✔
3244

4✔
3245
                        go s.connectToPersistentPeer(pubStr)
4✔
3246
                } else {
4✔
3247
                        go s.delayInitialReconnect(pubStr)
×
3248
                }
×
3249

3250
                numOutboundConns++
4✔
3251
        }
3252

3253
        return nil
4✔
3254
}
3255

3256
// delayInitialReconnect will attempt a reconnection to the given peer after
3257
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3258
//
3259
// NOTE: This method MUST be run as a goroutine.
3260
func (s *server) delayInitialReconnect(pubStr string) {
×
3261
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3262
        select {
×
3263
        case <-time.After(delay):
×
3264
                s.connectToPersistentPeer(pubStr)
×
3265
        case <-s.quit:
×
3266
        }
3267
}
3268

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

4✔
3275
        s.mu.Lock()
4✔
3276
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
8✔
3277
                delete(s.persistentPeers, pubKeyStr)
4✔
3278
                delete(s.persistentPeersBackoff, pubKeyStr)
4✔
3279
                delete(s.persistentPeerAddrs, pubKeyStr)
4✔
3280
                s.cancelConnReqs(pubKeyStr, nil)
4✔
3281
                s.mu.Unlock()
4✔
3282

4✔
3283
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
4✔
3284
                        "peer has no open channels", compressedPubKey)
4✔
3285

4✔
3286
                return
4✔
3287
        }
4✔
3288
        s.mu.Unlock()
4✔
3289
}
3290

3291
// BroadcastMessage sends a request to the server to broadcast a set of
3292
// messages to all peers other than the one specified by the `skips` parameter.
3293
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3294
// the target peers.
3295
//
3296
// NOTE: This function is safe for concurrent access.
3297
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3298
        msgs ...lnwire.Message) error {
4✔
3299

4✔
3300
        // Filter out peers found in the skips map. We synchronize access to
4✔
3301
        // peersByPub throughout this process to ensure we deliver messages to
4✔
3302
        // exact set of peers present at the time of invocation.
4✔
3303
        s.mu.RLock()
4✔
3304
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
3305
        for pubStr, sPeer := range s.peersByPub {
8✔
3306
                if skips != nil {
8✔
3307
                        if _, ok := skips[sPeer.PubKey()]; ok {
8✔
3308
                                srvrLog.Tracef("Skipping %x in broadcast with "+
4✔
3309
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
4✔
3310
                                continue
4✔
3311
                        }
3312
                }
3313

3314
                peers = append(peers, sPeer)
4✔
3315
        }
3316
        s.mu.RUnlock()
4✔
3317

4✔
3318
        // Iterate over all known peers, dispatching a go routine to enqueue
4✔
3319
        // all messages to each of peers.
4✔
3320
        var wg sync.WaitGroup
4✔
3321
        for _, sPeer := range peers {
8✔
3322
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
4✔
3323
                        sPeer.PubKey())
4✔
3324

4✔
3325
                // Dispatch a go routine to enqueue all messages to this peer.
4✔
3326
                wg.Add(1)
4✔
3327
                s.wg.Add(1)
4✔
3328
                go func(p lnpeer.Peer) {
8✔
3329
                        defer s.wg.Done()
4✔
3330
                        defer wg.Done()
4✔
3331

4✔
3332
                        p.SendMessageLazy(false, msgs...)
4✔
3333
                }(sPeer)
4✔
3334
        }
3335

3336
        // Wait for all messages to have been dispatched before returning to
3337
        // caller.
3338
        wg.Wait()
4✔
3339

4✔
3340
        return nil
4✔
3341
}
3342

3343
// NotifyWhenOnline can be called by other subsystems to get notified when a
3344
// particular peer comes online. The peer itself is sent across the peerChan.
3345
//
3346
// NOTE: This function is safe for concurrent access.
3347
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3348
        peerChan chan<- lnpeer.Peer) {
4✔
3349

4✔
3350
        s.mu.Lock()
4✔
3351

4✔
3352
        // Compute the target peer's identifier.
4✔
3353
        pubStr := string(peerKey[:])
4✔
3354

4✔
3355
        // Check if peer is connected.
4✔
3356
        peer, ok := s.peersByPub[pubStr]
4✔
3357
        if ok {
8✔
3358
                // Unlock here so that the mutex isn't held while we are
4✔
3359
                // waiting for the peer to become active.
4✔
3360
                s.mu.Unlock()
4✔
3361

4✔
3362
                // Wait until the peer signals that it is actually active
4✔
3363
                // rather than only in the server's maps.
4✔
3364
                select {
4✔
3365
                case <-peer.ActiveSignal():
4✔
3366
                case <-peer.QuitSignal():
×
3367
                        // The peer quit, so we'll add the channel to the slice
×
3368
                        // and return.
×
3369
                        s.mu.Lock()
×
3370
                        s.peerConnectedListeners[pubStr] = append(
×
3371
                                s.peerConnectedListeners[pubStr], peerChan,
×
3372
                        )
×
3373
                        s.mu.Unlock()
×
3374
                        return
×
3375
                }
3376

3377
                // Connected, can return early.
3378
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
4✔
3379

4✔
3380
                select {
4✔
3381
                case peerChan <- peer:
4✔
3382
                case <-s.quit:
×
3383
                }
3384

3385
                return
4✔
3386
        }
3387

3388
        // Not connected, store this listener such that it can be notified when
3389
        // the peer comes online.
3390
        s.peerConnectedListeners[pubStr] = append(
4✔
3391
                s.peerConnectedListeners[pubStr], peerChan,
4✔
3392
        )
4✔
3393
        s.mu.Unlock()
4✔
3394
}
3395

3396
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3397
// the given public key has been disconnected. The notification is signaled by
3398
// closing the channel returned.
3399
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
4✔
3400
        s.mu.Lock()
4✔
3401
        defer s.mu.Unlock()
4✔
3402

4✔
3403
        c := make(chan struct{})
4✔
3404

4✔
3405
        // If the peer is already offline, we can immediately trigger the
4✔
3406
        // notification.
4✔
3407
        peerPubKeyStr := string(peerPubKey[:])
4✔
3408
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
4✔
3409
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3410
                close(c)
×
3411
                return c
×
3412
        }
×
3413

3414
        // Otherwise, the peer is online, so we'll keep track of the channel to
3415
        // trigger the notification once the server detects the peer
3416
        // disconnects.
3417
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
4✔
3418
                s.peerDisconnectedListeners[peerPubKeyStr], c,
4✔
3419
        )
4✔
3420

4✔
3421
        return c
4✔
3422
}
3423

3424
// FindPeer will return the peer that corresponds to the passed in public key.
3425
// This function is used by the funding manager, allowing it to update the
3426
// daemon's local representation of the remote peer.
3427
//
3428
// NOTE: This function is safe for concurrent access.
3429
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
4✔
3430
        s.mu.RLock()
4✔
3431
        defer s.mu.RUnlock()
4✔
3432

4✔
3433
        pubStr := string(peerKey.SerializeCompressed())
4✔
3434

4✔
3435
        return s.findPeerByPubStr(pubStr)
4✔
3436
}
4✔
3437

3438
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3439
// which should be a string representation of the peer's serialized, compressed
3440
// public key.
3441
//
3442
// NOTE: This function is safe for concurrent access.
3443
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3444
        s.mu.RLock()
4✔
3445
        defer s.mu.RUnlock()
4✔
3446

4✔
3447
        return s.findPeerByPubStr(pubStr)
4✔
3448
}
4✔
3449

3450
// findPeerByPubStr is an internal method that retrieves the specified peer from
3451
// the server's internal state using.
3452
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3453
        peer, ok := s.peersByPub[pubStr]
4✔
3454
        if !ok {
8✔
3455
                return nil, ErrPeerNotConnected
4✔
3456
        }
4✔
3457

3458
        return peer, nil
4✔
3459
}
3460

3461
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3462
// exponential backoff. If no previous backoff was known, the default is
3463
// returned.
3464
func (s *server) nextPeerBackoff(pubStr string,
3465
        startTime time.Time) time.Duration {
4✔
3466

4✔
3467
        // Now, determine the appropriate backoff to use for the retry.
4✔
3468
        backoff, ok := s.persistentPeersBackoff[pubStr]
4✔
3469
        if !ok {
8✔
3470
                // If an existing backoff was unknown, use the default.
4✔
3471
                return s.cfg.MinBackoff
4✔
3472
        }
4✔
3473

3474
        // If the peer failed to start properly, we'll just use the previous
3475
        // backoff to compute the subsequent randomized exponential backoff
3476
        // duration. This will roughly double on average.
3477
        if startTime.IsZero() {
4✔
3478
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3479
        }
×
3480

3481
        // The peer succeeded in starting. If the connection didn't last long
3482
        // enough to be considered stable, we'll continue to back off retries
3483
        // with this peer.
3484
        connDuration := time.Since(startTime)
4✔
3485
        if connDuration < defaultStableConnDuration {
8✔
3486
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
4✔
3487
        }
4✔
3488

3489
        // The peer succeed in starting and this was stable peer, so we'll
3490
        // reduce the timeout duration by the length of the connection after
3491
        // applying randomized exponential backoff. We'll only apply this in the
3492
        // case that:
3493
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3494
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3495
        if relaxedBackoff > s.cfg.MinBackoff {
×
3496
                return relaxedBackoff
×
3497
        }
×
3498

3499
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3500
        // the stable connection lasted much longer than our previous backoff.
3501
        // To reward such good behavior, we'll reconnect after the default
3502
        // timeout.
3503
        return s.cfg.MinBackoff
×
3504
}
3505

3506
// shouldDropLocalConnection determines if our local connection to a remote peer
3507
// should be dropped in the case of concurrent connection establishment. In
3508
// order to deterministically decide which connection should be dropped, we'll
3509
// utilize the ordering of the local and remote public key. If we didn't use
3510
// such a tie breaker, then we risk _both_ connections erroneously being
3511
// dropped.
3512
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3513
        localPubBytes := local.SerializeCompressed()
×
3514
        remotePubPbytes := remote.SerializeCompressed()
×
3515

×
3516
        // The connection that comes from the node with a "smaller" pubkey
×
3517
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3518
        // should drop our established connection.
×
3519
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3520
}
×
3521

3522
// InboundPeerConnected initializes a new peer in response to a new inbound
3523
// connection.
3524
//
3525
// NOTE: This function is safe for concurrent access.
3526
func (s *server) InboundPeerConnected(conn net.Conn) {
4✔
3527
        // Exit early if we have already been instructed to shutdown, this
4✔
3528
        // prevents any delayed callbacks from accidentally registering peers.
4✔
3529
        if s.Stopped() {
4✔
3530
                return
×
3531
        }
×
3532

3533
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3534
        pubStr := string(nodePub.SerializeCompressed())
4✔
3535

4✔
3536
        s.mu.Lock()
4✔
3537
        defer s.mu.Unlock()
4✔
3538

4✔
3539
        // If we already have an outbound connection to this peer, then ignore
4✔
3540
        // this new connection.
4✔
3541
        if p, ok := s.outboundPeers[pubStr]; ok {
8✔
3542
                srvrLog.Debugf("Already have outbound connection for %v, "+
4✔
3543
                        "ignoring inbound connection from local=%v, remote=%v",
4✔
3544
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
3545

4✔
3546
                conn.Close()
4✔
3547
                return
4✔
3548
        }
4✔
3549

3550
        // If we already have a valid connection that is scheduled to take
3551
        // precedence once the prior peer has finished disconnecting, we'll
3552
        // ignore this connection.
3553
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
4✔
3554
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3555
                        "scheduled", conn.RemoteAddr(), p)
×
3556
                conn.Close()
×
3557
                return
×
3558
        }
×
3559

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

4✔
3562
        // Check to see if we already have a connection with this peer. If so,
4✔
3563
        // we may need to drop our existing connection. This prevents us from
4✔
3564
        // having duplicate connections to the same peer. We forgo adding a
4✔
3565
        // default case as we expect these to be the only error values returned
4✔
3566
        // from findPeerByPubStr.
4✔
3567
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
3568
        switch err {
4✔
3569
        case ErrPeerNotConnected:
4✔
3570
                // We were unable to locate an existing connection with the
4✔
3571
                // target peer, proceed to connect.
4✔
3572
                s.cancelConnReqs(pubStr, nil)
4✔
3573
                s.peerConnected(conn, nil, true)
4✔
3574

3575
        case nil:
×
3576
                // We already have a connection with the incoming peer. If the
×
3577
                // connection we've already established should be kept and is
×
3578
                // not of the same type of the new connection (inbound), then
×
3579
                // we'll close out the new connection s.t there's only a single
×
3580
                // connection between us.
×
3581
                localPub := s.identityECDH.PubKey()
×
3582
                if !connectedPeer.Inbound() &&
×
3583
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3584

×
3585
                        srvrLog.Warnf("Received inbound connection from "+
×
3586
                                "peer %v, but already have outbound "+
×
3587
                                "connection, dropping conn", connectedPeer)
×
3588
                        conn.Close()
×
3589
                        return
×
3590
                }
×
3591

3592
                // Otherwise, if we should drop the connection, then we'll
3593
                // disconnect our already connected peer.
3594
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3595
                        connectedPeer)
×
3596

×
3597
                s.cancelConnReqs(pubStr, nil)
×
3598

×
3599
                // Remove the current peer from the server's internal state and
×
3600
                // signal that the peer termination watcher does not need to
×
3601
                // execute for this peer.
×
3602
                s.removePeer(connectedPeer)
×
3603
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3604
                s.scheduledPeerConnection[pubStr] = func() {
×
3605
                        s.peerConnected(conn, nil, true)
×
3606
                }
×
3607
        }
3608
}
3609

3610
// OutboundPeerConnected initializes a new peer in response to a new outbound
3611
// connection.
3612
// NOTE: This function is safe for concurrent access.
3613
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
4✔
3614
        // Exit early if we have already been instructed to shutdown, this
4✔
3615
        // prevents any delayed callbacks from accidentally registering peers.
4✔
3616
        if s.Stopped() {
4✔
3617
                return
×
3618
        }
×
3619

3620
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3621
        pubStr := string(nodePub.SerializeCompressed())
4✔
3622

4✔
3623
        s.mu.Lock()
4✔
3624
        defer s.mu.Unlock()
4✔
3625

4✔
3626
        // If we already have an inbound connection to this peer, then ignore
4✔
3627
        // this new connection.
4✔
3628
        if p, ok := s.inboundPeers[pubStr]; ok {
8✔
3629
                srvrLog.Debugf("Already have inbound connection for %v, "+
4✔
3630
                        "ignoring outbound connection from local=%v, remote=%v",
4✔
3631
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
3632

4✔
3633
                if connReq != nil {
8✔
3634
                        s.connMgr.Remove(connReq.ID())
4✔
3635
                }
4✔
3636
                conn.Close()
4✔
3637
                return
4✔
3638
        }
3639
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
4✔
3640
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3641
                s.connMgr.Remove(connReq.ID())
×
3642
                conn.Close()
×
3643
                return
×
3644
        }
×
3645

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

×
3652
                if connReq != nil {
×
3653
                        s.connMgr.Remove(connReq.ID())
×
3654
                }
×
3655

3656
                conn.Close()
×
3657
                return
×
3658
        }
3659

3660
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
4✔
3661
                conn.RemoteAddr())
4✔
3662

4✔
3663
        if connReq != nil {
8✔
3664
                // A successful connection was returned by the connmgr.
4✔
3665
                // Immediately cancel all pending requests, excluding the
4✔
3666
                // outbound connection we just established.
4✔
3667
                ignore := connReq.ID()
4✔
3668
                s.cancelConnReqs(pubStr, &ignore)
4✔
3669
        } else {
8✔
3670
                // This was a successful connection made by some other
4✔
3671
                // subsystem. Remove all requests being managed by the connmgr.
4✔
3672
                s.cancelConnReqs(pubStr, nil)
4✔
3673
        }
4✔
3674

3675
        // If we already have a connection with this peer, decide whether or not
3676
        // we need to drop the stale connection. We forgo adding a default case
3677
        // as we expect these to be the only error values returned from
3678
        // findPeerByPubStr.
3679
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
3680
        switch err {
4✔
3681
        case ErrPeerNotConnected:
4✔
3682
                // We were unable to locate an existing connection with the
4✔
3683
                // target peer, proceed to connect.
4✔
3684
                s.peerConnected(conn, connReq, false)
4✔
3685

3686
        case nil:
×
3687
                // We already have a connection with the incoming peer. If the
×
3688
                // connection we've already established should be kept and is
×
3689
                // not of the same type of the new connection (outbound), then
×
3690
                // we'll close out the new connection s.t there's only a single
×
3691
                // connection between us.
×
3692
                localPub := s.identityECDH.PubKey()
×
3693
                if connectedPeer.Inbound() &&
×
3694
                        shouldDropLocalConnection(localPub, nodePub) {
×
3695

×
3696
                        srvrLog.Warnf("Established outbound connection to "+
×
3697
                                "peer %v, but already have inbound "+
×
3698
                                "connection, dropping conn", connectedPeer)
×
3699
                        if connReq != nil {
×
3700
                                s.connMgr.Remove(connReq.ID())
×
3701
                        }
×
3702
                        conn.Close()
×
3703
                        return
×
3704
                }
3705

3706
                // Otherwise, _their_ connection should be dropped. So we'll
3707
                // disconnect the peer and send the now obsolete peer to the
3708
                // server for garbage collection.
3709
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3710
                        connectedPeer)
×
3711

×
3712
                // Remove the current peer from the server's internal state and
×
3713
                // signal that the peer termination watcher does not need to
×
3714
                // execute for this peer.
×
3715
                s.removePeer(connectedPeer)
×
3716
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3717
                s.scheduledPeerConnection[pubStr] = func() {
×
3718
                        s.peerConnected(conn, connReq, false)
×
3719
                }
×
3720
        }
3721
}
3722

3723
// UnassignedConnID is the default connection ID that a request can have before
3724
// it actually is submitted to the connmgr.
3725
// TODO(conner): move into connmgr package, or better, add connmgr method for
3726
// generating atomic IDs
3727
const UnassignedConnID uint64 = 0
3728

3729
// cancelConnReqs stops all persistent connection requests for a given pubkey.
3730
// Any attempts initiated by the peerTerminationWatcher are canceled first.
3731
// Afterwards, each connection request removed from the connmgr. The caller can
3732
// optionally specify a connection ID to ignore, which prevents us from
3733
// canceling a successful request. All persistent connreqs for the provided
3734
// pubkey are discarded after the operationjw.
3735
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
4✔
3736
        // First, cancel any lingering persistent retry attempts, which will
4✔
3737
        // prevent retries for any with backoffs that are still maturing.
4✔
3738
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
8✔
3739
                close(cancelChan)
4✔
3740
                delete(s.persistentRetryCancels, pubStr)
4✔
3741
        }
4✔
3742

3743
        // Next, check to see if we have any outstanding persistent connection
3744
        // requests to this peer. If so, then we'll remove all of these
3745
        // connection requests, and also delete the entry from the map.
3746
        connReqs, ok := s.persistentConnReqs[pubStr]
4✔
3747
        if !ok {
8✔
3748
                return
4✔
3749
        }
4✔
3750

3751
        for _, connReq := range connReqs {
8✔
3752
                srvrLog.Tracef("Canceling %s:", connReqs)
4✔
3753

4✔
3754
                // Atomically capture the current request identifier.
4✔
3755
                connID := connReq.ID()
4✔
3756

4✔
3757
                // Skip any zero IDs, this indicates the request has not
4✔
3758
                // yet been schedule.
4✔
3759
                if connID == UnassignedConnID {
4✔
3760
                        continue
×
3761
                }
3762

3763
                // Skip a particular connection ID if instructed.
3764
                if skip != nil && connID == *skip {
8✔
3765
                        continue
4✔
3766
                }
3767

3768
                s.connMgr.Remove(connID)
4✔
3769
        }
3770

3771
        delete(s.persistentConnReqs, pubStr)
4✔
3772
}
3773

3774
// handleCustomMessage dispatches an incoming custom peers message to
3775
// subscribers.
3776
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
4✔
3777
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
4✔
3778
                peer, msg.Type)
4✔
3779

4✔
3780
        return s.customMessageServer.SendUpdate(&CustomMessage{
4✔
3781
                Peer: peer,
4✔
3782
                Msg:  msg,
4✔
3783
        })
4✔
3784
}
4✔
3785

3786
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
3787
// messages.
3788
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
4✔
3789
        return s.customMessageServer.Subscribe()
4✔
3790
}
4✔
3791

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

4✔
3799
        brontideConn := conn.(*brontide.Conn)
4✔
3800
        addr := conn.RemoteAddr()
4✔
3801
        pubKey := brontideConn.RemotePub()
4✔
3802

4✔
3803
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
4✔
3804
                pubKey.SerializeCompressed(), addr, inbound)
4✔
3805

4✔
3806
        peerAddr := &lnwire.NetAddress{
4✔
3807
                IdentityKey: pubKey,
4✔
3808
                Address:     addr,
4✔
3809
                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
3810
        }
4✔
3811

4✔
3812
        // With the brontide connection established, we'll now craft the feature
4✔
3813
        // vectors to advertise to the remote node.
4✔
3814
        initFeatures := s.featureMgr.Get(feature.SetInit)
4✔
3815
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
4✔
3816

4✔
3817
        // Lookup past error caches for the peer in the server. If no buffer is
4✔
3818
        // found, create a fresh buffer.
4✔
3819
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
4✔
3820
        errBuffer, ok := s.peerErrors[pkStr]
4✔
3821
        if !ok {
8✔
3822
                var err error
4✔
3823
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
4✔
3824
                if err != nil {
4✔
3825
                        srvrLog.Errorf("unable to create peer %v", err)
×
3826
                        return
×
3827
                }
×
3828
        }
3829

3830
        // If we directly set the peer.Config TowerClient member to the
3831
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
3832
        // the peer.Config's TowerClient member will not evaluate to nil even
3833
        // though the underlying value is nil. To avoid this gotcha which can
3834
        // cause a panic, we need to explicitly pass nil to the peer.Config's
3835
        // TowerClient if needed.
3836
        var towerClient wtclient.ClientManager
4✔
3837
        if s.towerClientMgr != nil {
8✔
3838
                towerClient = s.towerClientMgr
4✔
3839
        }
4✔
3840

3841
        // Now that we've established a connection, create a peer, and it to the
3842
        // set of currently active peers. Configure the peer with the incoming
3843
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3844
        // offered that would trigger channel closure. In case of outgoing
3845
        // htlcs, an extra block is added to prevent the channel from being
3846
        // closed when the htlc is outstanding and a new block comes in.
3847
        pCfg := peer.Config{
4✔
3848
                Conn:                    brontideConn,
4✔
3849
                ConnReq:                 connReq,
4✔
3850
                Addr:                    peerAddr,
4✔
3851
                Inbound:                 inbound,
4✔
3852
                Features:                initFeatures,
4✔
3853
                LegacyFeatures:          legacyFeatures,
4✔
3854
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
4✔
3855
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
4✔
3856
                ErrorBuffer:             errBuffer,
4✔
3857
                WritePool:               s.writePool,
4✔
3858
                ReadPool:                s.readPool,
4✔
3859
                Switch:                  s.htlcSwitch,
4✔
3860
                InterceptSwitch:         s.interceptableSwitch,
4✔
3861
                ChannelDB:               s.chanStateDB,
4✔
3862
                ChannelGraph:            s.graphDB,
4✔
3863
                ChainArb:                s.chainArb,
4✔
3864
                AuthGossiper:            s.authGossiper,
4✔
3865
                ChanStatusMgr:           s.chanStatusMgr,
4✔
3866
                ChainIO:                 s.cc.ChainIO,
4✔
3867
                FeeEstimator:            s.cc.FeeEstimator,
4✔
3868
                Signer:                  s.cc.Wallet.Cfg.Signer,
4✔
3869
                SigPool:                 s.sigPool,
4✔
3870
                Wallet:                  s.cc.Wallet,
4✔
3871
                ChainNotifier:           s.cc.ChainNotifier,
4✔
3872
                BestBlockView:           s.cc.BestBlockTracker,
4✔
3873
                RoutingPolicy:           s.cc.RoutingPolicy,
4✔
3874
                Sphinx:                  s.sphinx,
4✔
3875
                WitnessBeacon:           s.witnessBeacon,
4✔
3876
                Invoices:                s.invoices,
4✔
3877
                ChannelNotifier:         s.channelNotifier,
4✔
3878
                HtlcNotifier:            s.htlcNotifier,
4✔
3879
                TowerClient:             towerClient,
4✔
3880
                DisconnectPeer:          s.DisconnectPeer,
4✔
3881
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
4✔
3882
                        lnwire.NodeAnnouncement, error) {
8✔
3883

4✔
3884
                        return s.genNodeAnnouncement(nil)
4✔
3885
                },
4✔
3886

3887
                PongBuf: s.pongBuf,
3888

3889
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
3890

3891
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
3892

3893
                FundingManager: s.fundingMgr,
3894

3895
                Hodl:                    s.cfg.Hodl,
3896
                UnsafeReplay:            s.cfg.UnsafeReplay,
3897
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
3898
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
3899
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
3900
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
3901
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
3902
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
3903
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
3904
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
3905
                HandleCustomMessage:    s.handleCustomMessage,
3906
                GetAliases:             s.aliasMgr.GetAliases,
3907
                RequestAlias:           s.aliasMgr.RequestAlias,
3908
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
3909
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
3910
                Quit:                   s.quit,
3911
        }
3912

3913
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
4✔
3914
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
4✔
3915

4✔
3916
        p := peer.NewBrontide(pCfg)
4✔
3917

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

4✔
3921
        s.addPeer(p)
4✔
3922

4✔
3923
        // Once we have successfully added the peer to the server, we can
4✔
3924
        // delete the previous error buffer from the server's map of error
4✔
3925
        // buffers.
4✔
3926
        delete(s.peerErrors, pkStr)
4✔
3927

4✔
3928
        // Dispatch a goroutine to asynchronously start the peer. This process
4✔
3929
        // includes sending and receiving Init messages, which would be a DOS
4✔
3930
        // vector if we held the server's mutex throughout the procedure.
4✔
3931
        s.wg.Add(1)
4✔
3932
        go s.peerInitializer(p)
4✔
3933
}
3934

3935
// addPeer adds the passed peer to the server's global state of all active
3936
// peers.
3937
func (s *server) addPeer(p *peer.Brontide) {
4✔
3938
        if p == nil {
4✔
3939
                return
×
3940
        }
×
3941

3942
        // Ignore new peers if we're shutting down.
3943
        if s.Stopped() {
4✔
3944
                p.Disconnect(ErrServerShuttingDown)
×
3945
                return
×
3946
        }
×
3947

3948
        // Track the new peer in our indexes so we can quickly look it up either
3949
        // according to its public key, or its peer ID.
3950
        // TODO(roasbeef): pipe all requests through to the
3951
        // queryHandler/peerManager
3952

3953
        pubSer := p.IdentityKey().SerializeCompressed()
4✔
3954
        pubStr := string(pubSer)
4✔
3955

4✔
3956
        s.peersByPub[pubStr] = p
4✔
3957

4✔
3958
        if p.Inbound() {
8✔
3959
                s.inboundPeers[pubStr] = p
4✔
3960
        } else {
8✔
3961
                s.outboundPeers[pubStr] = p
4✔
3962
        }
4✔
3963

3964
        // Inform the peer notifier of a peer online event so that it can be reported
3965
        // to clients listening for peer events.
3966
        var pubKey [33]byte
4✔
3967
        copy(pubKey[:], pubSer)
4✔
3968

4✔
3969
        s.peerNotifier.NotifyPeerOnline(pubKey)
4✔
3970
}
3971

3972
// peerInitializer asynchronously starts a newly connected peer after it has
3973
// been added to the server's peer map. This method sets up a
3974
// peerTerminationWatcher for the given peer, and ensures that it executes even
3975
// if the peer failed to start. In the event of a successful connection, this
3976
// method reads the negotiated, local feature-bits and spawns the appropriate
3977
// graph synchronization method. Any registered clients of NotifyWhenOnline will
3978
// be signaled of the new peer once the method returns.
3979
//
3980
// NOTE: This MUST be launched as a goroutine.
3981
func (s *server) peerInitializer(p *peer.Brontide) {
4✔
3982
        defer s.wg.Done()
4✔
3983

4✔
3984
        // Avoid initializing peers while the server is exiting.
4✔
3985
        if s.Stopped() {
4✔
3986
                return
×
3987
        }
×
3988

3989
        // Create a channel that will be used to signal a successful start of
3990
        // the link. This prevents the peer termination watcher from beginning
3991
        // its duty too early.
3992
        ready := make(chan struct{})
4✔
3993

4✔
3994
        // Before starting the peer, launch a goroutine to watch for the
4✔
3995
        // unexpected termination of this peer, which will ensure all resources
4✔
3996
        // are properly cleaned up, and re-establish persistent connections when
4✔
3997
        // necessary. The peer termination watcher will be short circuited if
4✔
3998
        // the peer is ever added to the ignorePeerTermination map, indicating
4✔
3999
        // that the server has already handled the removal of this peer.
4✔
4000
        s.wg.Add(1)
4✔
4001
        go s.peerTerminationWatcher(p, ready)
4✔
4002

4✔
4003
        // Start the peer! If an error occurs, we Disconnect the peer, which
4✔
4004
        // will unblock the peerTerminationWatcher.
4✔
4005
        if err := p.Start(); err != nil {
5✔
4006
                srvrLog.Warnf("Starting peer=%v got error: %v",
1✔
4007
                        p.IdentityKey(), err)
1✔
4008

1✔
4009
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
1✔
4010
                return
1✔
4011
        }
1✔
4012

4013
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4014
        // was successful, and to begin watching the peer's wait group.
4015
        close(ready)
4✔
4016

4✔
4017
        pubStr := string(p.IdentityKey().SerializeCompressed())
4✔
4018

4✔
4019
        s.mu.Lock()
4✔
4020
        defer s.mu.Unlock()
4✔
4021

4✔
4022
        // Check if there are listeners waiting for this peer to come online.
4✔
4023
        srvrLog.Debugf("Notifying that peer %v is online", p)
4✔
4024
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
8✔
4025
                select {
4✔
4026
                case peerChan <- p:
4✔
4027
                case <-s.quit:
1✔
4028
                        return
1✔
4029
                }
4030
        }
4031
        delete(s.peerConnectedListeners, pubStr)
4✔
4032
}
4033

4034
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4035
// and then cleans up all resources allocated to the peer, notifies relevant
4036
// sub-systems of its demise, and finally handles re-connecting to the peer if
4037
// it's persistent. If the server intentionally disconnects a peer, it should
4038
// have a corresponding entry in the ignorePeerTermination map which will cause
4039
// the cleanup routine to exit early. The passed `ready` chan is used to
4040
// synchronize when WaitForDisconnect should begin watching on the peer's
4041
// waitgroup. The ready chan should only be signaled if the peer starts
4042
// successfully, otherwise the peer should be disconnected instead.
4043
//
4044
// NOTE: This MUST be launched as a goroutine.
4045
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
4✔
4046
        defer s.wg.Done()
4✔
4047

4✔
4048
        p.WaitForDisconnect(ready)
4✔
4049

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

4✔
4052
        // If the server is exiting then we can bail out early ourselves as all
4✔
4053
        // the other sub-systems will already be shutting down.
4✔
4054
        if s.Stopped() {
8✔
4055
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
4✔
4056
                return
4✔
4057
        }
4✔
4058

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

4✔
4065
        pubKey := p.IdentityKey()
4✔
4066

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

4✔
4071
        // Tell the switch to remove all links associated with this peer.
4✔
4072
        // Passing nil as the target link indicates that all links associated
4✔
4073
        // with this interface should be closed.
4✔
4074
        //
4✔
4075
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
4✔
4076
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
4✔
4077
        if err != nil && err != htlcswitch.ErrNoLinksFound {
4✔
4078
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4079
        }
×
4080

4081
        for _, link := range links {
8✔
4082
                s.htlcSwitch.RemoveLink(link.ChanID())
4✔
4083
        }
4✔
4084

4085
        s.mu.Lock()
4✔
4086
        defer s.mu.Unlock()
4✔
4087

4✔
4088
        // If there were any notification requests for when this peer
4✔
4089
        // disconnected, we can trigger them now.
4✔
4090
        srvrLog.Debugf("Notifying that peer %v is offline", p)
4✔
4091
        pubStr := string(pubKey.SerializeCompressed())
4✔
4092
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
8✔
4093
                close(offlineChan)
4✔
4094
        }
4✔
4095
        delete(s.peerDisconnectedListeners, pubStr)
4✔
4096

4✔
4097
        // If the server has already removed this peer, we can short circuit the
4✔
4098
        // peer termination watcher and skip cleanup.
4✔
4099
        if _, ok := s.ignorePeerTermination[p]; ok {
4✔
4100
                delete(s.ignorePeerTermination, p)
×
4101

×
4102
                pubKey := p.PubKey()
×
4103
                pubStr := string(pubKey[:])
×
4104

×
4105
                // If a connection callback is present, we'll go ahead and
×
4106
                // execute it now that previous peer has fully disconnected. If
×
4107
                // the callback is not present, this likely implies the peer was
×
4108
                // purposefully disconnected via RPC, and that no reconnect
×
4109
                // should be attempted.
×
4110
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4111
                if ok {
×
4112
                        delete(s.scheduledPeerConnection, pubStr)
×
4113
                        connCallback()
×
4114
                }
×
4115
                return
×
4116
        }
4117

4118
        // First, cleanup any remaining state the server has regarding the peer
4119
        // in question.
4120
        s.removePeer(p)
4✔
4121

4✔
4122
        // Next, check to see if this is a persistent peer or not.
4✔
4123
        if _, ok := s.persistentPeers[pubStr]; !ok {
8✔
4124
                return
4✔
4125
        }
4✔
4126

4127
        // Get the last address that we used to connect to the peer.
4128
        addrs := []net.Addr{
4✔
4129
                p.NetAddress().Address,
4✔
4130
        }
4✔
4131

4✔
4132
        // We'll ensure that we locate all the peers advertised addresses for
4✔
4133
        // reconnection purposes.
4✔
4134
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
4✔
4135
        switch {
4✔
4136
        // We found advertised addresses, so use them.
4137
        case err == nil:
4✔
4138
                addrs = advertisedAddrs
4✔
4139

4140
        // The peer doesn't have an advertised address.
4141
        case err == errNoAdvertisedAddr:
4✔
4142
                // If it is an outbound peer then we fall back to the existing
4✔
4143
                // peer address.
4✔
4144
                if !p.Inbound() {
8✔
4145
                        break
4✔
4146
                }
4147

4148
                // Fall back to the existing peer address if
4149
                // we're not accepting connections over Tor.
4150
                if s.torController == nil {
8✔
4151
                        break
4✔
4152
                }
4153

4154
                // If we are, the peer's address won't be known
4155
                // to us (we'll see a private address, which is
4156
                // the address used by our onion service to dial
4157
                // to lnd), so we don't have enough information
4158
                // to attempt a reconnect.
4159
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4160
                        "to inbound peer %v without "+
×
4161
                        "advertised address", p)
×
4162
                return
×
4163

4164
        // We came across an error retrieving an advertised
4165
        // address, log it, and fall back to the existing peer
4166
        // address.
4167
        default:
4✔
4168
                srvrLog.Errorf("Unable to retrieve advertised "+
4✔
4169
                        "address for node %x: %v", p.PubKey(),
4✔
4170
                        err)
4✔
4171
        }
4172

4173
        // Make an easy lookup map so that we can check if an address
4174
        // is already in the address list that we have stored for this peer.
4175
        existingAddrs := make(map[string]bool)
4✔
4176
        for _, addr := range s.persistentPeerAddrs[pubStr] {
8✔
4177
                existingAddrs[addr.String()] = true
4✔
4178
        }
4✔
4179

4180
        // Add any missing addresses for this peer to persistentPeerAddr.
4181
        for _, addr := range addrs {
8✔
4182
                if existingAddrs[addr.String()] {
4✔
4183
                        continue
×
4184
                }
4185

4186
                s.persistentPeerAddrs[pubStr] = append(
4✔
4187
                        s.persistentPeerAddrs[pubStr],
4✔
4188
                        &lnwire.NetAddress{
4✔
4189
                                IdentityKey: p.IdentityKey(),
4✔
4190
                                Address:     addr,
4✔
4191
                                ChainNet:    p.NetAddress().ChainNet,
4✔
4192
                        },
4✔
4193
                )
4✔
4194
        }
4195

4196
        // Record the computed backoff in the backoff map.
4197
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
4✔
4198
        s.persistentPeersBackoff[pubStr] = backoff
4✔
4199

4✔
4200
        // Initialize a retry canceller for this peer if one does not
4✔
4201
        // exist.
4✔
4202
        cancelChan, ok := s.persistentRetryCancels[pubStr]
4✔
4203
        if !ok {
8✔
4204
                cancelChan = make(chan struct{})
4✔
4205
                s.persistentRetryCancels[pubStr] = cancelChan
4✔
4206
        }
4✔
4207

4208
        // We choose not to wait group this go routine since the Connect
4209
        // call can stall for arbitrarily long if we shutdown while an
4210
        // outbound connection attempt is being made.
4211
        go func() {
8✔
4212
                srvrLog.Debugf("Scheduling connection re-establishment to "+
4✔
4213
                        "persistent peer %x in %s",
4✔
4214
                        p.IdentityKey().SerializeCompressed(), backoff)
4✔
4215

4✔
4216
                select {
4✔
4217
                case <-time.After(backoff):
4✔
4218
                case <-cancelChan:
4✔
4219
                        return
4✔
4220
                case <-s.quit:
4✔
4221
                        return
4✔
4222
                }
4223

4224
                srvrLog.Debugf("Attempting to re-establish persistent "+
4✔
4225
                        "connection to peer %x",
4✔
4226
                        p.IdentityKey().SerializeCompressed())
4✔
4227

4✔
4228
                s.connectToPersistentPeer(pubStr)
4✔
4229
        }()
4230
}
4231

4232
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4233
// to connect to the peer. It creates connection requests if there are
4234
// currently none for a given address and it removes old connection requests
4235
// if the associated address is no longer in the latest address list for the
4236
// peer.
4237
func (s *server) connectToPersistentPeer(pubKeyStr string) {
4✔
4238
        s.mu.Lock()
4✔
4239
        defer s.mu.Unlock()
4✔
4240

4✔
4241
        // Create an easy lookup map of the addresses we have stored for the
4✔
4242
        // peer. We will remove entries from this map if we have existing
4✔
4243
        // connection requests for the associated address and then any leftover
4✔
4244
        // entries will indicate which addresses we should create new
4✔
4245
        // connection requests for.
4✔
4246
        addrMap := make(map[string]*lnwire.NetAddress)
4✔
4247
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
8✔
4248
                addrMap[addr.String()] = addr
4✔
4249
        }
4✔
4250

4251
        // Go through each of the existing connection requests and
4252
        // check if they correspond to the latest set of addresses. If
4253
        // there is a connection requests that does not use one of the latest
4254
        // advertised addresses then remove that connection request.
4255
        var updatedConnReqs []*connmgr.ConnReq
4✔
4256
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
8✔
4257
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
4✔
4258

4✔
4259
                switch _, ok := addrMap[lnAddr]; ok {
4✔
4260
                // If the existing connection request is using one of the
4261
                // latest advertised addresses for the peer then we add it to
4262
                // updatedConnReqs and remove the associated address from
4263
                // addrMap so that we don't recreate this connReq later on.
4264
                case true:
×
4265
                        updatedConnReqs = append(
×
4266
                                updatedConnReqs, connReq,
×
4267
                        )
×
4268
                        delete(addrMap, lnAddr)
×
4269

4270
                // If the existing connection request is using an address that
4271
                // is not one of the latest advertised addresses for the peer
4272
                // then we remove the connecting request from the connection
4273
                // manager.
4274
                case false:
4✔
4275
                        srvrLog.Info(
4✔
4276
                                "Removing conn req:", connReq.Addr.String(),
4✔
4277
                        )
4✔
4278
                        s.connMgr.Remove(connReq.ID())
4✔
4279
                }
4280
        }
4281

4282
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
4✔
4283

4✔
4284
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
4✔
4285
        if !ok {
8✔
4286
                cancelChan = make(chan struct{})
4✔
4287
                s.persistentRetryCancels[pubKeyStr] = cancelChan
4✔
4288
        }
4✔
4289

4290
        // Any addresses left in addrMap are new ones that we have not made
4291
        // connection requests for. So create new connection requests for those.
4292
        // If there is more than one address in the address map, stagger the
4293
        // creation of the connection requests for those.
4294
        go func() {
8✔
4295
                ticker := time.NewTicker(multiAddrConnectionStagger)
4✔
4296
                defer ticker.Stop()
4✔
4297

4✔
4298
                for _, addr := range addrMap {
8✔
4299
                        // Send the persistent connection request to the
4✔
4300
                        // connection manager, saving the request itself so we
4✔
4301
                        // can cancel/restart the process as needed.
4✔
4302
                        connReq := &connmgr.ConnReq{
4✔
4303
                                Addr:      addr,
4✔
4304
                                Permanent: true,
4✔
4305
                        }
4✔
4306

4✔
4307
                        s.mu.Lock()
4✔
4308
                        s.persistentConnReqs[pubKeyStr] = append(
4✔
4309
                                s.persistentConnReqs[pubKeyStr], connReq,
4✔
4310
                        )
4✔
4311
                        s.mu.Unlock()
4✔
4312

4✔
4313
                        srvrLog.Debugf("Attempting persistent connection to "+
4✔
4314
                                "channel peer %v", addr)
4✔
4315

4✔
4316
                        go s.connMgr.Connect(connReq)
4✔
4317

4✔
4318
                        select {
4✔
4319
                        case <-s.quit:
4✔
4320
                                return
4✔
4321
                        case <-cancelChan:
4✔
4322
                                return
4✔
4323
                        case <-ticker.C:
4✔
4324
                        }
4325
                }
4326
        }()
4327
}
4328

4329
// removePeer removes the passed peer from the server's state of all active
4330
// peers.
4331
func (s *server) removePeer(p *peer.Brontide) {
4✔
4332
        if p == nil {
4✔
4333
                return
×
4334
        }
×
4335

4336
        srvrLog.Debugf("removing peer %v", p)
4✔
4337

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

4✔
4342
        // If this peer had an active persistent connection request, remove it.
4✔
4343
        if p.ConnReq() != nil {
8✔
4344
                s.connMgr.Remove(p.ConnReq().ID())
4✔
4345
        }
4✔
4346

4347
        // Ignore deleting peers if we're shutting down.
4348
        if s.Stopped() {
4✔
4349
                return
×
4350
        }
×
4351

4352
        pKey := p.PubKey()
4✔
4353
        pubSer := pKey[:]
4✔
4354
        pubStr := string(pubSer)
4✔
4355

4✔
4356
        delete(s.peersByPub, pubStr)
4✔
4357

4✔
4358
        if p.Inbound() {
8✔
4359
                delete(s.inboundPeers, pubStr)
4✔
4360
        } else {
8✔
4361
                delete(s.outboundPeers, pubStr)
4✔
4362
        }
4✔
4363

4364
        // Copy the peer's error buffer across to the server if it has any items
4365
        // in it so that we can restore peer errors across connections.
4366
        if p.ErrorBuffer().Total() > 0 {
8✔
4367
                s.peerErrors[pubStr] = p.ErrorBuffer()
4✔
4368
        }
4✔
4369

4370
        // Inform the peer notifier of a peer offline event so that it can be
4371
        // reported to clients listening for peer events.
4372
        var pubKey [33]byte
4✔
4373
        copy(pubKey[:], pubSer)
4✔
4374

4✔
4375
        s.peerNotifier.NotifyPeerOffline(pubKey)
4✔
4376
}
4377

4378
// ConnectToPeer requests that the server connect to a Lightning Network peer
4379
// at the specified address. This function will *block* until either a
4380
// connection is established, or the initial handshake process fails.
4381
//
4382
// NOTE: This function is safe for concurrent access.
4383
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4384
        perm bool, timeout time.Duration) error {
4✔
4385

4✔
4386
        targetPub := string(addr.IdentityKey.SerializeCompressed())
4✔
4387

4✔
4388
        // Acquire mutex, but use explicit unlocking instead of defer for
4✔
4389
        // better granularity.  In certain conditions, this method requires
4✔
4390
        // making an outbound connection to a remote peer, which requires the
4✔
4391
        // lock to be released, and subsequently reacquired.
4✔
4392
        s.mu.Lock()
4✔
4393

4✔
4394
        // Ensure we're not already connected to this peer.
4✔
4395
        peer, err := s.findPeerByPubStr(targetPub)
4✔
4396
        if err == nil {
8✔
4397
                s.mu.Unlock()
4✔
4398
                return &errPeerAlreadyConnected{peer: peer}
4✔
4399
        }
4✔
4400

4401
        // Peer was not found, continue to pursue connection with peer.
4402

4403
        // If there's already a pending connection request for this pubkey,
4404
        // then we ignore this request to ensure we don't create a redundant
4405
        // connection.
4406
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
8✔
4407
                srvrLog.Warnf("Already have %d persistent connection "+
4✔
4408
                        "requests for %v, connecting anyway.", len(reqs), addr)
4✔
4409
        }
4✔
4410

4411
        // If there's not already a pending or active connection to this node,
4412
        // then instruct the connection manager to attempt to establish a
4413
        // persistent connection to the peer.
4414
        srvrLog.Debugf("Connecting to %v", addr)
4✔
4415
        if perm {
8✔
4416
                connReq := &connmgr.ConnReq{
4✔
4417
                        Addr:      addr,
4✔
4418
                        Permanent: true,
4✔
4419
                }
4✔
4420

4✔
4421
                // Since the user requested a permanent connection, we'll set
4✔
4422
                // the entry to true which will tell the server to continue
4✔
4423
                // reconnecting even if the number of channels with this peer is
4✔
4424
                // zero.
4✔
4425
                s.persistentPeers[targetPub] = true
4✔
4426
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
8✔
4427
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
4✔
4428
                }
4✔
4429
                s.persistentConnReqs[targetPub] = append(
4✔
4430
                        s.persistentConnReqs[targetPub], connReq,
4✔
4431
                )
4✔
4432
                s.mu.Unlock()
4✔
4433

4✔
4434
                go s.connMgr.Connect(connReq)
4✔
4435

4✔
4436
                return nil
4✔
4437
        }
4438
        s.mu.Unlock()
4✔
4439

4✔
4440
        // If we're not making a persistent connection, then we'll attempt to
4✔
4441
        // connect to the target peer. If the we can't make the connection, or
4✔
4442
        // the crypto negotiation breaks down, then return an error to the
4✔
4443
        // caller.
4✔
4444
        errChan := make(chan error, 1)
4✔
4445
        s.connectToPeer(addr, errChan, timeout)
4✔
4446

4✔
4447
        select {
4✔
4448
        case err := <-errChan:
4✔
4449
                return err
4✔
4450
        case <-s.quit:
×
4451
                return ErrServerShuttingDown
×
4452
        }
4453
}
4454

4455
// connectToPeer establishes a connection to a remote peer. errChan is used to
4456
// notify the caller if the connection attempt has failed. Otherwise, it will be
4457
// closed.
4458
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4459
        errChan chan<- error, timeout time.Duration) {
4✔
4460

4✔
4461
        conn, err := brontide.Dial(
4✔
4462
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
4✔
4463
        )
4✔
4464
        if err != nil {
8✔
4465
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
4✔
4466
                select {
4✔
4467
                case errChan <- err:
4✔
4468
                case <-s.quit:
×
4469
                }
4470
                return
4✔
4471
        }
4472

4473
        close(errChan)
4✔
4474

4✔
4475
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
4✔
4476
                conn.LocalAddr(), conn.RemoteAddr())
4✔
4477

4✔
4478
        s.OutboundPeerConnected(nil, conn)
4✔
4479
}
4480

4481
// DisconnectPeer sends the request to server to close the connection with peer
4482
// identified by public key.
4483
//
4484
// NOTE: This function is safe for concurrent access.
4485
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
4✔
4486
        pubBytes := pubKey.SerializeCompressed()
4✔
4487
        pubStr := string(pubBytes)
4✔
4488

4✔
4489
        s.mu.Lock()
4✔
4490
        defer s.mu.Unlock()
4✔
4491

4✔
4492
        // Check that were actually connected to this peer. If not, then we'll
4✔
4493
        // exit in an error as we can't disconnect from a peer that we're not
4✔
4494
        // currently connected to.
4✔
4495
        peer, err := s.findPeerByPubStr(pubStr)
4✔
4496
        if err == ErrPeerNotConnected {
8✔
4497
                return fmt.Errorf("peer %x is not connected", pubBytes)
4✔
4498
        }
4✔
4499

4500
        srvrLog.Infof("Disconnecting from %v", peer)
4✔
4501

4✔
4502
        s.cancelConnReqs(pubStr, nil)
4✔
4503

4✔
4504
        // If this peer was formerly a persistent connection, then we'll remove
4✔
4505
        // them from this map so we don't attempt to re-connect after we
4✔
4506
        // disconnect.
4✔
4507
        delete(s.persistentPeers, pubStr)
4✔
4508
        delete(s.persistentPeersBackoff, pubStr)
4✔
4509

4✔
4510
        // Remove the peer by calling Disconnect. Previously this was done with
4✔
4511
        // removePeer, which bypassed the peerTerminationWatcher.
4✔
4512
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
4✔
4513

4✔
4514
        return nil
4✔
4515
}
4516

4517
// OpenChannel sends a request to the server to open a channel to the specified
4518
// peer identified by nodeKey with the passed channel funding parameters.
4519
//
4520
// NOTE: This function is safe for concurrent access.
4521
func (s *server) OpenChannel(
4522
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
4✔
4523

4✔
4524
        // The updateChan will have a buffer of 2, since we expect a ChanPending
4✔
4525
        // + a ChanOpen update, and we want to make sure the funding process is
4✔
4526
        // not blocked if the caller is not reading the updates.
4✔
4527
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
4✔
4528
        req.Err = make(chan error, 1)
4✔
4529

4✔
4530
        // First attempt to locate the target peer to open a channel with, if
4✔
4531
        // we're unable to locate the peer then this request will fail.
4✔
4532
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
4✔
4533
        s.mu.RLock()
4✔
4534
        peer, ok := s.peersByPub[string(pubKeyBytes)]
4✔
4535
        if !ok {
4✔
4536
                s.mu.RUnlock()
×
4537

×
4538
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4539
                return req.Updates, req.Err
×
4540
        }
×
4541
        req.Peer = peer
4✔
4542
        s.mu.RUnlock()
4✔
4543

4✔
4544
        // We'll wait until the peer is active before beginning the channel
4✔
4545
        // opening process.
4✔
4546
        select {
4✔
4547
        case <-peer.ActiveSignal():
4✔
4548
        case <-peer.QuitSignal():
×
4549
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4550
                return req.Updates, req.Err
×
4551
        case <-s.quit:
×
4552
                req.Err <- ErrServerShuttingDown
×
4553
                return req.Updates, req.Err
×
4554
        }
4555

4556
        // If the fee rate wasn't specified, then we'll use a default
4557
        // confirmation target.
4558
        if req.FundingFeePerKw == 0 {
8✔
4559
                estimator := s.cc.FeeEstimator
4✔
4560
                feeRate, err := estimator.EstimateFeePerKW(6)
4✔
4561
                if err != nil {
4✔
4562
                        req.Err <- err
×
4563
                        return req.Updates, req.Err
×
4564
                }
×
4565
                req.FundingFeePerKw = feeRate
4✔
4566
        }
4567

4568
        // Spawn a goroutine to send the funding workflow request to the funding
4569
        // manager. This allows the server to continue handling queries instead
4570
        // of blocking on this request which is exported as a synchronous
4571
        // request to the outside world.
4572
        go s.fundingMgr.InitFundingWorkflow(req)
4✔
4573

4✔
4574
        return req.Updates, req.Err
4✔
4575
}
4576

4577
// Peers returns a slice of all active peers.
4578
//
4579
// NOTE: This function is safe for concurrent access.
4580
func (s *server) Peers() []*peer.Brontide {
4✔
4581
        s.mu.RLock()
4✔
4582
        defer s.mu.RUnlock()
4✔
4583

4✔
4584
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
4585
        for _, peer := range s.peersByPub {
8✔
4586
                peers = append(peers, peer)
4✔
4587
        }
4✔
4588

4589
        return peers
4✔
4590
}
4591

4592
// computeNextBackoff uses a truncated exponential backoff to compute the next
4593
// backoff using the value of the exiting backoff. The returned duration is
4594
// randomized in either direction by 1/20 to prevent tight loops from
4595
// stabilizing.
4596
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
4✔
4597
        // Double the current backoff, truncating if it exceeds our maximum.
4✔
4598
        nextBackoff := 2 * currBackoff
4✔
4599
        if nextBackoff > maxBackoff {
8✔
4600
                nextBackoff = maxBackoff
4✔
4601
        }
4✔
4602

4603
        // Using 1/10 of our duration as a margin, compute a random offset to
4604
        // avoid the nodes entering connection cycles.
4605
        margin := nextBackoff / 10
4✔
4606

4✔
4607
        var wiggle big.Int
4✔
4608
        wiggle.SetUint64(uint64(margin))
4✔
4609
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
4✔
4610
                // Randomizing is not mission critical, so we'll just return the
×
4611
                // current backoff.
×
4612
                return nextBackoff
×
4613
        }
×
4614

4615
        // Otherwise add in our wiggle, but subtract out half of the margin so
4616
        // that the backoff can tweaked by 1/20 in either direction.
4617
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
4✔
4618
}
4619

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

4624
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4625
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
4✔
4626
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
4✔
4627
        if err != nil {
4✔
4628
                return nil, err
×
4629
        }
×
4630

4631
        node, err := s.graphDB.FetchLightningNode(nil, vertex)
4✔
4632
        if err != nil {
8✔
4633
                return nil, err
4✔
4634
        }
4✔
4635

4636
        if len(node.Addresses) == 0 {
8✔
4637
                return nil, errNoAdvertisedAddr
4✔
4638
        }
4✔
4639

4640
        return node.Addresses, nil
4✔
4641
}
4642

4643
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4644
// channel update for a target channel.
4645
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4646
        *lnwire.ChannelUpdate, error) {
4✔
4647

4✔
4648
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
4✔
4649
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate, error) {
8✔
4650
                info, edge1, edge2, err := s.chanRouter.GetChannelByID(cid)
4✔
4651
                if err != nil {
8✔
4652
                        return nil, err
4✔
4653
                }
4✔
4654

4655
                return netann.ExtractChannelUpdate(
4✔
4656
                        ourPubKey[:], info, edge1, edge2,
4✔
4657
                )
4✔
4658
        }
4659
}
4660

4661
// applyChannelUpdate applies the channel update to the different sub-systems of
4662
// the server. The useAlias boolean denotes whether or not to send an alias in
4663
// place of the real SCID.
4664
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate,
4665
        op *wire.OutPoint, useAlias bool) error {
4✔
4666

4✔
4667
        var (
4✔
4668
                peerAlias    *lnwire.ShortChannelID
4✔
4669
                defaultAlias lnwire.ShortChannelID
4✔
4670
        )
4✔
4671

4✔
4672
        chanID := lnwire.NewChanIDFromOutPoint(*op)
4✔
4673

4✔
4674
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
4✔
4675
        // in the ChannelUpdate if it hasn't been announced yet.
4✔
4676
        if useAlias {
8✔
4677
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
4✔
4678
                if foundAlias != defaultAlias {
8✔
4679
                        peerAlias = &foundAlias
4✔
4680
                }
4✔
4681
        }
4682

4683
        errChan := s.authGossiper.ProcessLocalAnnouncement(
4✔
4684
                update, discovery.RemoteAlias(peerAlias),
4✔
4685
        )
4✔
4686
        select {
4✔
4687
        case err := <-errChan:
4✔
4688
                return err
4✔
4689
        case <-s.quit:
×
4690
                return ErrServerShuttingDown
×
4691
        }
4692
}
4693

4694
// SendCustomMessage sends a custom message to the peer with the specified
4695
// pubkey.
4696
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
4697
        data []byte) error {
4✔
4698

4✔
4699
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
4✔
4700
        if err != nil {
4✔
4701
                return err
×
4702
        }
×
4703

4704
        // We'll wait until the peer is active.
4705
        select {
4✔
4706
        case <-peer.ActiveSignal():
4✔
4707
        case <-peer.QuitSignal():
×
4708
                return fmt.Errorf("peer %x disconnected", peerPub)
×
4709
        case <-s.quit:
×
4710
                return ErrServerShuttingDown
×
4711
        }
4712

4713
        msg, err := lnwire.NewCustom(msgType, data)
4✔
4714
        if err != nil {
8✔
4715
                return err
4✔
4716
        }
4✔
4717

4718
        // Send the message as low-priority. For now we assume that all
4719
        // application-defined message are low priority.
4720
        return peer.SendMessageLazy(true, msg)
4✔
4721
}
4722

4723
// newSweepPkScriptGen creates closure that generates a new public key script
4724
// which should be used to sweep any funds into the on-chain wallet.
4725
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
4726
// (p2wkh) output.
4727
func newSweepPkScriptGen(
4728
        wallet lnwallet.WalletController) func() ([]byte, error) {
4✔
4729

4✔
4730
        return func() ([]byte, error) {
8✔
4731
                sweepAddr, err := wallet.NewAddress(
4✔
4732
                        lnwallet.TaprootPubkey, false,
4✔
4733
                        lnwallet.DefaultAccountName,
4✔
4734
                )
4✔
4735
                if err != nil {
4✔
4736
                        return nil, err
×
4737
                }
×
4738

4739
                return txscript.PayToAddrScript(sweepAddr)
4✔
4740
        }
4741
}
4742

4743
// shouldPeerBootstrap returns true if we should attempt to perform peer
4744
// bootstrapping to actively seek our peers using the set of active network
4745
// bootstrappers.
4746
func shouldPeerBootstrap(cfg *Config) bool {
10✔
4747
        isSimnet := cfg.Bitcoin.SimNet
10✔
4748
        isSignet := cfg.Bitcoin.SigNet
10✔
4749
        isRegtest := cfg.Bitcoin.RegTest
10✔
4750
        isDevNetwork := isSimnet || isSignet || isRegtest
10✔
4751

10✔
4752
        // TODO(yy): remove the check on simnet/regtest such that the itest is
10✔
4753
        // covering the bootstrapping process.
10✔
4754
        return !cfg.NoNetBootstrap && !isDevNetwork
10✔
4755
}
10✔
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