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

lightningnetwork / lnd / 11388202384

17 Oct 2024 03:31PM UTC coverage: 58.81% (-0.07%) from 58.884%
11388202384

push

github

web-flow
Merge pull request #9196 from lightningnetwork/fn-context-guard

fn: add ContextGuard from tapd repo

131011 of 222771 relevant lines covered (58.81%)

28214.75 hits per line

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

63.65
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

159
        start sync.Once
160
        stop  sync.Once
161

162
        cfg *Config
163

164
        implCfg *ImplementationCfg
165

166
        // identityECDH is an ECDH capable wrapper for the private key used
167
        // to authenticate any incoming connections.
168
        identityECDH keychain.SingleKeyECDH
169

170
        // identityKeyLoc is the key locator for the above wrapped identity key.
171
        identityKeyLoc keychain.KeyLocator
172

173
        // nodeSigner is an implementation of the MessageSigner implementation
174
        // that's backed by the identity private key of the running lnd node.
175
        nodeSigner *netann.NodeSigner
176

177
        chanStatusMgr *netann.ChanStatusManager
178

179
        // listenAddrs is the list of addresses the server is currently
180
        // listening on.
181
        listenAddrs []net.Addr
182

183
        // torController is a client that will communicate with a locally
184
        // running Tor server. This client will handle initiating and
185
        // authenticating the connection to the Tor server, automatically
186
        // creating and setting up onion services, etc.
187
        torController *tor.Controller
188

189
        // natTraversal is the specific NAT traversal technique used to
190
        // automatically set up port forwarding rules in order to advertise to
191
        // the network that the node is accepting inbound connections.
192
        natTraversal nat.Traversal
193

194
        // lastDetectedIP is the last IP detected by the NAT traversal technique
195
        // above. This IP will be watched periodically in a goroutine in order
196
        // to handle dynamic IP changes.
197
        lastDetectedIP net.IP
198

199
        mu         sync.RWMutex
200
        peersByPub map[string]*peer.Brontide
201

202
        inboundPeers  map[string]*peer.Brontide
203
        outboundPeers map[string]*peer.Brontide
204

205
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
206
        peerDisconnectedListeners map[string][]chan<- struct{}
207

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

218
        // peerErrors keeps a set of peer error buffers for peers that have
219
        // disconnected from us. This allows us to track historic peer errors
220
        // over connections. The string of the peer's compressed pubkey is used
221
        // as a key for this map.
222
        peerErrors map[string]*queue.CircularBuffer
223

224
        // ignorePeerTermination tracks peers for which the server has initiated
225
        // a disconnect. Adding a peer to this map causes the peer termination
226
        // watcher to short circuit in the event that peers are purposefully
227
        // disconnected.
228
        ignorePeerTermination map[*peer.Brontide]struct{}
229

230
        // scheduledPeerConnection maps a pubkey string to a callback that
231
        // should be executed in the peerTerminationWatcher the prior peer with
232
        // the same pubkey exits.  This allows the server to wait until the
233
        // prior peer has cleaned up successfully, before adding the new peer
234
        // intended to replace it.
235
        scheduledPeerConnection map[string]func()
236

237
        // pongBuf is a shared pong reply buffer we'll use across all active
238
        // peer goroutines. We know the max size of a pong message
239
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
240
        // avoid allocations each time we need to send a pong message.
241
        pongBuf []byte
242

243
        cc *chainreg.ChainControl
244

245
        fundingMgr *funding.Manager
246

247
        graphDB *channeldb.ChannelGraph
248

249
        chanStateDB *channeldb.ChannelStateDB
250

251
        addrSource chanbackup.AddressSource
252

253
        // miscDB is the DB that contains all "other" databases within the main
254
        // channel DB that haven't been separated out yet.
255
        miscDB *channeldb.DB
256

257
        invoicesDB invoices.InvoiceDB
258

259
        aliasMgr *aliasmgr.Manager
260

261
        htlcSwitch *htlcswitch.Switch
262

263
        interceptableSwitch *htlcswitch.InterceptableSwitch
264

265
        invoices *invoices.InvoiceRegistry
266

267
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
268

269
        channelNotifier *channelnotifier.ChannelNotifier
270

271
        peerNotifier *peernotifier.PeerNotifier
272

273
        htlcNotifier *htlcswitch.HtlcNotifier
274

275
        witnessBeacon contractcourt.WitnessBeacon
276

277
        breachArbitrator *contractcourt.BreachArbitrator
278

279
        missionController *routing.MissionController
280
        defaultMC         *routing.MissionControl
281

282
        graphBuilder *graph.Builder
283

284
        chanRouter *routing.ChannelRouter
285

286
        controlTower routing.ControlTower
287

288
        authGossiper *discovery.AuthenticatedGossiper
289

290
        localChanMgr *localchans.Manager
291

292
        utxoNursery *contractcourt.UtxoNursery
293

294
        sweeper *sweep.UtxoSweeper
295

296
        chainArb *contractcourt.ChainArbitrator
297

298
        sphinx *hop.OnionProcessor
299

300
        towerClientMgr *wtclient.Manager
301

302
        connMgr *connmgr.ConnManager
303

304
        sigPool *lnwallet.SigPool
305

306
        writePool *pool.Write
307

308
        readPool *pool.Read
309

310
        tlsManager *TLSManager
311

312
        // featureMgr dispatches feature vectors for various contexts within the
313
        // daemon.
314
        featureMgr *feature.Manager
315

316
        // currentNodeAnn is the node announcement that has been broadcast to
317
        // the network upon startup, if the attributes of the node (us) has
318
        // changed since last start.
319
        currentNodeAnn *lnwire.NodeAnnouncement
320

321
        // chansToRestore is the set of channels that upon starting, the server
322
        // should attempt to restore/recover.
323
        chansToRestore walletunlocker.ChannelsToRecover
324

325
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
326
        // backups are consistent at all times. It interacts with the
327
        // channelNotifier to be notified of newly opened and closed channels.
328
        chanSubSwapper *chanbackup.SubSwapper
329

330
        // chanEventStore tracks the behaviour of channels and their remote peers to
331
        // provide insights into their health and performance.
332
        chanEventStore *chanfitness.ChannelEventStore
333

334
        hostAnn *netann.HostAnnouncer
335

336
        // livenessMonitor monitors that lnd has access to critical resources.
337
        livenessMonitor *healthcheck.Monitor
338

339
        customMessageServer *subscribe.Server
340

341
        // txPublisher is a publisher with fee-bumping capability.
342
        txPublisher *sweep.TxPublisher
343

344
        quit chan struct{}
345

346
        wg sync.WaitGroup
347
}
348

349
// updatePersistentPeerAddrs subscribes to topology changes and stores
350
// advertised addresses for any NodeAnnouncements from our persisted peers.
351
func (s *server) updatePersistentPeerAddrs() error {
3✔
352
        graphSub, err := s.graphBuilder.SubscribeTopology()
3✔
353
        if err != nil {
3✔
354
                return err
×
355
        }
×
356

357
        s.wg.Add(1)
3✔
358
        go func() {
6✔
359
                defer func() {
6✔
360
                        graphSub.Cancel()
3✔
361
                        s.wg.Done()
3✔
362
                }()
3✔
363

364
                for {
6✔
365
                        select {
3✔
366
                        case <-s.quit:
3✔
367
                                return
3✔
368

369
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
370
                                // If the router is shutting down, then we will
3✔
371
                                // as well.
3✔
372
                                if !ok {
3✔
373
                                        return
×
374
                                }
×
375

376
                                for _, update := range topChange.NodeUpdates {
6✔
377
                                        pubKeyStr := string(
3✔
378
                                                update.IdentityKey.
3✔
379
                                                        SerializeCompressed(),
3✔
380
                                        )
3✔
381

3✔
382
                                        // We only care about updates from
3✔
383
                                        // our persistentPeers.
3✔
384
                                        s.mu.RLock()
3✔
385
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
386
                                        s.mu.RUnlock()
3✔
387
                                        if !ok {
6✔
388
                                                continue
3✔
389
                                        }
390

391
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
392
                                                len(update.Addresses))
3✔
393

3✔
394
                                        for _, addr := range update.Addresses {
6✔
395
                                                addrs = append(addrs,
3✔
396
                                                        &lnwire.NetAddress{
3✔
397
                                                                IdentityKey: update.IdentityKey,
3✔
398
                                                                Address:     addr,
3✔
399
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
400
                                                        },
3✔
401
                                                )
3✔
402
                                        }
3✔
403

404
                                        s.mu.Lock()
3✔
405

3✔
406
                                        // Update the stored addresses for this
3✔
407
                                        // to peer to reflect the new set.
3✔
408
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
409

3✔
410
                                        // If there are no outstanding
3✔
411
                                        // connection requests for this peer
3✔
412
                                        // then our work is done since we are
3✔
413
                                        // not currently trying to connect to
3✔
414
                                        // them.
3✔
415
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
6✔
416
                                                s.mu.Unlock()
3✔
417
                                                continue
3✔
418
                                        }
419

420
                                        s.mu.Unlock()
3✔
421

3✔
422
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
423
                                }
424
                        }
425
                }
426
        }()
427

428
        return nil
3✔
429
}
430

431
// CustomMessage is a custom message that is received from a peer.
432
type CustomMessage struct {
433
        // Peer is the peer pubkey
434
        Peer [33]byte
435

436
        // Msg is the custom wire message.
437
        Msg *lnwire.Custom
438
}
439

440
// parseAddr parses an address from its string format to a net.Addr.
441
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
442
        var (
3✔
443
                host string
3✔
444
                port int
3✔
445
        )
3✔
446

3✔
447
        // Split the address into its host and port components.
3✔
448
        h, p, err := net.SplitHostPort(address)
3✔
449
        if err != nil {
3✔
450
                // If a port wasn't specified, we'll assume the address only
×
451
                // contains the host so we'll use the default port.
×
452
                host = address
×
453
                port = defaultPeerPort
×
454
        } else {
3✔
455
                // Otherwise, we'll note both the host and ports.
3✔
456
                host = h
3✔
457
                portNum, err := strconv.Atoi(p)
3✔
458
                if err != nil {
3✔
459
                        return nil, err
×
460
                }
×
461
                port = portNum
3✔
462
        }
463

464
        if tor.IsOnionHost(host) {
3✔
465
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
466
        }
×
467

468
        // If the host is part of a TCP address, we'll use the network
469
        // specific ResolveTCPAddr function in order to resolve these
470
        // addresses over Tor in order to prevent leaking your real IP
471
        // address.
472
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
473
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
474
}
475

476
// noiseDial is a factory function which creates a connmgr compliant dialing
477
// function by returning a closure which includes the server's identity key.
478
func noiseDial(idKey keychain.SingleKeyECDH,
479
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
3✔
480

3✔
481
        return func(a net.Addr) (net.Conn, error) {
6✔
482
                lnAddr := a.(*lnwire.NetAddress)
3✔
483
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
484
        }
3✔
485
}
486

487
// newServer creates a new instance of the server which is to listen using the
488
// passed listener address.
489
func newServer(cfg *Config, listenAddrs []net.Addr,
490
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
491
        nodeKeyDesc *keychain.KeyDescriptor,
492
        chansToRestore walletunlocker.ChannelsToRecover,
493
        chanPredicate chanacceptor.ChannelAcceptor,
494
        torController *tor.Controller, tlsManager *TLSManager,
495
        leaderElector cluster.LeaderElector,
496
        implCfg *ImplementationCfg) (*server, error) {
3✔
497

3✔
498
        var (
3✔
499
                err         error
3✔
500
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
501

3✔
502
                // We just derived the full descriptor, so we know the public
3✔
503
                // key is set on it.
3✔
504
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
505
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
506
                )
3✔
507
        )
3✔
508

3✔
509
        listeners := make([]net.Listener, len(listenAddrs))
3✔
510
        for i, listenAddr := range listenAddrs {
6✔
511
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
512
                // doesn't need to call the general lndResolveTCP function
3✔
513
                // since we are resolving a local address.
3✔
514
                listeners[i], err = brontide.NewListener(
3✔
515
                        nodeKeyECDH, listenAddr.String(),
3✔
516
                )
3✔
517
                if err != nil {
3✔
518
                        return nil, err
×
519
                }
×
520
        }
521

522
        var serializedPubKey [33]byte
3✔
523
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
524

3✔
525
        netParams := cfg.ActiveNetParams.Params
3✔
526

3✔
527
        // Initialize the sphinx router.
3✔
528
        replayLog := htlcswitch.NewDecayedLog(
3✔
529
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
530
        )
3✔
531
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
532

3✔
533
        writeBufferPool := pool.NewWriteBuffer(
3✔
534
                pool.DefaultWriteBufferGCInterval,
3✔
535
                pool.DefaultWriteBufferExpiryInterval,
3✔
536
        )
3✔
537

3✔
538
        writePool := pool.NewWrite(
3✔
539
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
540
        )
3✔
541

3✔
542
        readBufferPool := pool.NewReadBuffer(
3✔
543
                pool.DefaultReadBufferGCInterval,
3✔
544
                pool.DefaultReadBufferExpiryInterval,
3✔
545
        )
3✔
546

3✔
547
        readPool := pool.NewRead(
3✔
548
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
549
        )
3✔
550

3✔
551
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
552
        // controller, then we'll exit as this is incompatible.
3✔
553
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
554
                implCfg.AuxFundingController.IsNone() {
3✔
555

×
556
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
557
                        "aux controllers")
×
558
        }
×
559

560
        //nolint:lll
561
        featureMgr, err := feature.NewManager(feature.Config{
3✔
562
                NoTLVOnion:               cfg.ProtocolOptions.LegacyOnion(),
3✔
563
                NoStaticRemoteKey:        cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
564
                NoAnchors:                cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
565
                NoWumbo:                  !cfg.ProtocolOptions.Wumbo(),
3✔
566
                NoScriptEnforcementLease: cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
567
                NoKeysend:                !cfg.AcceptKeySend,
3✔
568
                NoOptionScidAlias:        !cfg.ProtocolOptions.ScidAlias(),
3✔
569
                NoZeroConf:               !cfg.ProtocolOptions.ZeroConf(),
3✔
570
                NoAnySegwit:              cfg.ProtocolOptions.NoAnySegwit(),
3✔
571
                CustomFeatures:           cfg.ProtocolOptions.CustomFeatures(),
3✔
572
                NoTaprootChans:           !cfg.ProtocolOptions.TaprootChans,
3✔
573
                NoTaprootOverlay:         !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
574
                NoRouteBlinding:          cfg.ProtocolOptions.NoRouteBlinding(),
3✔
575
        })
3✔
576
        if err != nil {
3✔
577
                return nil, err
×
578
        }
×
579

580
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
581
        registryConfig := invoices.RegistryConfig{
3✔
582
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
583
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
584
                Clock:                       clock.NewDefaultClock(),
3✔
585
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
586
                AcceptAMP:                   cfg.AcceptAMP,
3✔
587
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
588
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
589
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
590
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
591
        }
3✔
592

3✔
593
        s := &server{
3✔
594
                cfg:            cfg,
3✔
595
                implCfg:        implCfg,
3✔
596
                graphDB:        dbs.GraphDB.ChannelGraph(),
3✔
597
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
598
                addrSource:     dbs.ChanStateDB,
3✔
599
                miscDB:         dbs.ChanStateDB,
3✔
600
                invoicesDB:     dbs.InvoiceDB,
3✔
601
                cc:             cc,
3✔
602
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
603
                writePool:      writePool,
3✔
604
                readPool:       readPool,
3✔
605
                chansToRestore: chansToRestore,
3✔
606

3✔
607
                channelNotifier: channelnotifier.New(
3✔
608
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
609
                ),
3✔
610

3✔
611
                identityECDH:   nodeKeyECDH,
3✔
612
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
613
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
614

3✔
615
                listenAddrs: listenAddrs,
3✔
616

3✔
617
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
618
                // schedule
3✔
619
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
620

3✔
621
                torController: torController,
3✔
622

3✔
623
                persistentPeers:         make(map[string]bool),
3✔
624
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
625
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
626
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
627
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
628
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
629
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
630
                scheduledPeerConnection: make(map[string]func()),
3✔
631
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
632

3✔
633
                peersByPub:                make(map[string]*peer.Brontide),
3✔
634
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
635
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
636
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
637
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
638

3✔
639
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
640

3✔
641
                customMessageServer: subscribe.NewServer(),
3✔
642

3✔
643
                tlsManager: tlsManager,
3✔
644

3✔
645
                featureMgr: featureMgr,
3✔
646
                quit:       make(chan struct{}),
3✔
647
        }
3✔
648

3✔
649
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
650
        if err != nil {
3✔
651
                return nil, err
×
652
        }
×
653

654
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
655
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
656
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
657
        )
3✔
658
        s.invoices = invoices.NewRegistry(
3✔
659
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
660
        )
3✔
661

3✔
662
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
663

3✔
664
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
665
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
666

3✔
667
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
668
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
669
                if err != nil {
3✔
670
                        return err
×
671
                }
×
672

673
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
674

3✔
675
                return nil
3✔
676
        }
677

678
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
679
        if err != nil {
3✔
680
                return nil, err
×
681
        }
×
682

683
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
684
                DB:                   dbs.ChanStateDB,
3✔
685
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
686
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
687
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
688
                LocalChannelClose: func(pubKey []byte,
3✔
689
                        request *htlcswitch.ChanClose) {
6✔
690

3✔
691
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
692
                        if err != nil {
3✔
693
                                srvrLog.Errorf("unable to close channel, peer"+
×
694
                                        " with %v id can't be found: %v",
×
695
                                        pubKey, err,
×
696
                                )
×
697
                                return
×
698
                        }
×
699

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

735
        s.witnessBeacon = newPreimageBeacon(
3✔
736
                dbs.ChanStateDB.NewWitnessCache(),
3✔
737
                s.interceptableSwitch.ForwardPacket,
3✔
738
        )
3✔
739

3✔
740
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
741
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
742
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
743
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
744
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
745
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
746
                MessageSigner:            s.nodeSigner,
3✔
747
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
748
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
749
                DB:                       s.chanStateDB,
3✔
750
                Graph:                    dbs.GraphDB.ChannelGraph(),
3✔
751
        }
3✔
752

3✔
753
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
754
        if err != nil {
3✔
755
                return nil, err
×
756
        }
×
757
        s.chanStatusMgr = chanStatusMgr
3✔
758

3✔
759
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
760
        // port forwarding for users behind a NAT.
3✔
761
        if cfg.NAT {
3✔
762
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
763

×
764
                discoveryTimeout := time.Duration(10 * time.Second)
×
765

×
766
                ctx, cancel := context.WithTimeout(
×
767
                        context.Background(), discoveryTimeout,
×
768
                )
×
769
                defer cancel()
×
770
                upnp, err := nat.DiscoverUPnP(ctx)
×
771
                if err == nil {
×
772
                        s.natTraversal = upnp
×
773
                } else {
×
774
                        // If we were not able to discover a UPnP enabled device
×
775
                        // on the local network, we'll fall back to attempting
×
776
                        // to discover a NAT-PMP enabled device.
×
777
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
778
                                "device on the local network: %v", err)
×
779

×
780
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
781
                                "enabled device")
×
782

×
783
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
784
                        if err != nil {
×
785
                                err := fmt.Errorf("unable to discover a "+
×
786
                                        "NAT-PMP enabled device on the local "+
×
787
                                        "network: %v", err)
×
788
                                srvrLog.Error(err)
×
789
                                return nil, err
×
790
                        }
×
791

792
                        s.natTraversal = pmp
×
793
                }
794
        }
795

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

×
811
                        listenPorts = append(listenPorts, uint16(port))
×
812
                }
×
813

814
                ips, err := s.configurePortForwarding(listenPorts...)
×
815
                if err != nil {
×
816
                        srvrLog.Errorf("Unable to automatically set up port "+
×
817
                                "forwarding using %s: %v",
×
818
                                s.natTraversal.Name(), err)
×
819
                } else {
×
820
                        srvrLog.Infof("Automatically set up port forwarding "+
×
821
                                "using %s to advertise external IP",
×
822
                                s.natTraversal.Name())
×
823
                        externalIPStrings = append(externalIPStrings, ips...)
×
824
                }
×
825
        }
826

827
        // If external IP addresses have been specified, add those to the list
828
        // of this server's addresses.
829
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
830
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
831
                cfg.net.ResolveTCPAddr,
3✔
832
        )
3✔
833
        if err != nil {
3✔
834
                return nil, err
×
835
        }
×
836

837
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
838
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
839

3✔
840
        // As the graph can be obtained at anytime from the network, we won't
3✔
841
        // replicate it, and instead it'll only be stored locally.
3✔
842
        chanGraph := dbs.GraphDB.ChannelGraph()
3✔
843

3✔
844
        // We'll now reconstruct a node announcement based on our current
3✔
845
        // configuration so we can send it out as a sort of heart beat within
3✔
846
        // the network.
3✔
847
        //
3✔
848
        // We'll start by parsing the node color from configuration.
3✔
849
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
850
        if err != nil {
3✔
851
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
852
                return nil, err
×
853
        }
×
854

855
        // If no alias is provided, default to first 10 characters of public
856
        // key.
857
        alias := cfg.Alias
3✔
858
        if alias == "" {
6✔
859
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
860
        }
3✔
861
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
862
        if err != nil {
3✔
863
                return nil, err
×
864
        }
×
865
        selfNode := &channeldb.LightningNode{
3✔
866
                HaveNodeAnnouncement: true,
3✔
867
                LastUpdate:           time.Now(),
3✔
868
                Addresses:            selfAddrs,
3✔
869
                Alias:                nodeAlias.String(),
3✔
870
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
871
                Color:                color,
3✔
872
        }
3✔
873
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
874

3✔
875
        // Based on the disk representation of the node announcement generated
3✔
876
        // above, we'll generate a node announcement that can go out on the
3✔
877
        // network so we can properly sign it.
3✔
878
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
879
        if err != nil {
3✔
880
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
881
        }
×
882

883
        // With the announcement generated, we'll sign it to properly
884
        // authenticate the message on the network.
885
        authSig, err := netann.SignAnnouncement(
3✔
886
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
887
        )
3✔
888
        if err != nil {
3✔
889
                return nil, fmt.Errorf("unable to generate signature for "+
×
890
                        "self node announcement: %v", err)
×
891
        }
×
892
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
893
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
894
                selfNode.AuthSigBytes,
3✔
895
        )
3✔
896
        if err != nil {
3✔
897
                return nil, err
×
898
        }
×
899

900
        // Finally, we'll update the representation on disk, and update our
901
        // cached in-memory version as well.
902
        if err := chanGraph.SetSourceNode(selfNode); err != nil {
3✔
903
                return nil, fmt.Errorf("can't set self node: %w", err)
×
904
        }
×
905
        s.currentNodeAnn = nodeAnn
3✔
906

3✔
907
        // The router will get access to the payment ID sequencer, such that it
3✔
908
        // can generate unique payment IDs.
3✔
909
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
910
        if err != nil {
3✔
911
                return nil, err
×
912
        }
×
913

914
        // Instantiate mission control with config from the sub server.
915
        //
916
        // TODO(joostjager): When we are further in the process of moving to sub
917
        // servers, the mission control instance itself can be moved there too.
918
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
919

3✔
920
        // We only initialize a probability estimator if there's no custom one.
3✔
921
        var estimator routing.Estimator
3✔
922
        if cfg.Estimator != nil {
3✔
923
                estimator = cfg.Estimator
×
924
        } else {
3✔
925
                switch routingConfig.ProbabilityEstimatorType {
3✔
926
                case routing.AprioriEstimatorName:
3✔
927
                        aCfg := routingConfig.AprioriConfig
3✔
928
                        aprioriConfig := routing.AprioriConfig{
3✔
929
                                AprioriHopProbability: aCfg.HopProbability,
3✔
930
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
931
                                AprioriWeight:         aCfg.Weight,
3✔
932
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
933
                        }
3✔
934

3✔
935
                        estimator, err = routing.NewAprioriEstimator(
3✔
936
                                aprioriConfig,
3✔
937
                        )
3✔
938
                        if err != nil {
3✔
939
                                return nil, err
×
940
                        }
×
941

942
                case routing.BimodalEstimatorName:
×
943
                        bCfg := routingConfig.BimodalConfig
×
944
                        bimodalConfig := routing.BimodalConfig{
×
945
                                BimodalNodeWeight: bCfg.NodeWeight,
×
946
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
947
                                        bCfg.Scale,
×
948
                                ),
×
949
                                BimodalDecayTime: bCfg.DecayTime,
×
950
                        }
×
951

×
952
                        estimator, err = routing.NewBimodalEstimator(
×
953
                                bimodalConfig,
×
954
                        )
×
955
                        if err != nil {
×
956
                                return nil, err
×
957
                        }
×
958

959
                default:
×
960
                        return nil, fmt.Errorf("unknown estimator type %v",
×
961
                                routingConfig.ProbabilityEstimatorType)
×
962
                }
963
        }
964

965
        mcCfg := &routing.MissionControlConfig{
3✔
966
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
967
                Estimator:               estimator,
3✔
968
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
969
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
970
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
971
        }
3✔
972

3✔
973
        s.missionController, err = routing.NewMissionController(
3✔
974
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
975
        )
3✔
976
        if err != nil {
3✔
977
                return nil, fmt.Errorf("can't create mission control "+
×
978
                        "manager: %w", err)
×
979
        }
×
980
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
981
                routing.DefaultMissionControlNamespace,
3✔
982
        )
3✔
983
        if err != nil {
3✔
984
                return nil, fmt.Errorf("can't create mission control in the "+
×
985
                        "default namespace: %w", err)
×
986
        }
×
987

988
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
989
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
990
                int64(routingConfig.AttemptCost),
3✔
991
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
992
                routingConfig.MinRouteProbability)
3✔
993

3✔
994
        pathFindingConfig := routing.PathFindingConfig{
3✔
995
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
996
                        routingConfig.AttemptCost,
3✔
997
                ),
3✔
998
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
999
                MinProbability: routingConfig.MinRouteProbability,
3✔
1000
        }
3✔
1001

3✔
1002
        sourceNode, err := chanGraph.SourceNode()
3✔
1003
        if err != nil {
3✔
1004
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1005
        }
×
1006
        paymentSessionSource := &routing.SessionSource{
3✔
1007
                GraphSessionFactory: graphsession.NewGraphSessionFactory(
3✔
1008
                        chanGraph,
3✔
1009
                ),
3✔
1010
                SourceNode:        sourceNode,
3✔
1011
                MissionControl:    s.defaultMC,
3✔
1012
                GetLink:           s.htlcSwitch.GetLinkByShortID,
3✔
1013
                PathFindingConfig: pathFindingConfig,
3✔
1014
        }
3✔
1015

3✔
1016
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1017

3✔
1018
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1019

3✔
1020
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1021
                cfg.Routing.StrictZombiePruning
3✔
1022

3✔
1023
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1024
                SelfNode:            selfNode.PubKeyBytes,
3✔
1025
                Graph:               chanGraph,
3✔
1026
                Chain:               cc.ChainIO,
3✔
1027
                ChainView:           cc.ChainView,
3✔
1028
                Notifier:            cc.ChainNotifier,
3✔
1029
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1030
                GraphPruneInterval:  time.Hour,
3✔
1031
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1032
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1033
                StrictZombiePruning: strictPruning,
3✔
1034
                IsAlias:             aliasmgr.IsAlias,
3✔
1035
        })
3✔
1036
        if err != nil {
3✔
1037
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1038
        }
×
1039

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

1060
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1061
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1062
        if err != nil {
3✔
1063
                return nil, err
×
1064
        }
×
1065
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1066
        if err != nil {
3✔
1067
                return nil, err
×
1068
        }
×
1069

1070
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1071

3✔
1072
        s.authGossiper = discovery.New(discovery.Config{
3✔
1073
                Graph:                 s.graphBuilder,
3✔
1074
                ChainIO:               s.cc.ChainIO,
3✔
1075
                Notifier:              s.cc.ChainNotifier,
3✔
1076
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1077
                Broadcast:             s.BroadcastMessage,
3✔
1078
                ChanSeries:            chanSeries,
3✔
1079
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1080
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1081
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1082
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1083
                        error) {
3✔
1084

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

1113
        //nolint:lll
1114
        s.localChanMgr = &localchans.Manager{
3✔
1115
                ForAllOutgoingChannels:    s.graphBuilder.ForAllOutgoingChannels,
3✔
1116
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
3✔
1117
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
3✔
1118
                FetchChannel:              s.chanStateDB.FetchChannel,
3✔
1119
        }
3✔
1120

3✔
1121
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1122
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1123
        )
3✔
1124
        if err != nil {
3✔
1125
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1126
                return nil, err
×
1127
        }
×
1128

1129
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1130
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1131
        )
3✔
1132
        if err != nil {
3✔
1133
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1134
                return nil, err
×
1135
        }
×
1136

1137
        aggregator := sweep.NewBudgetAggregator(
3✔
1138
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1139
                s.implCfg.AuxSweeper,
3✔
1140
        )
3✔
1141

3✔
1142
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1143
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1144
                Wallet:     cc.Wallet,
3✔
1145
                Estimator:  cc.FeeEstimator,
3✔
1146
                Notifier:   cc.ChainNotifier,
3✔
1147
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1148
        })
3✔
1149

3✔
1150
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1151
                FeeEstimator: cc.FeeEstimator,
3✔
1152
                GenSweepScript: newSweepPkScriptGen(
3✔
1153
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1154
                ),
3✔
1155
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1156
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1157
                Mempool:              cc.MempoolNotifier,
3✔
1158
                Notifier:             cc.ChainNotifier,
3✔
1159
                Store:                sweeperStore,
3✔
1160
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1161
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1162
                Aggregator:           aggregator,
3✔
1163
                Publisher:            s.txPublisher,
3✔
1164
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1165
        })
3✔
1166

3✔
1167
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1168
                ChainIO:             cc.ChainIO,
3✔
1169
                ConfDepth:           1,
3✔
1170
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1171
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1172
                Notifier:            cc.ChainNotifier,
3✔
1173
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1174
                Store:               utxnStore,
3✔
1175
                SweepInput:          s.sweeper.SweepInput,
3✔
1176
                Budget:              s.cfg.Sweeper.Budget,
3✔
1177
        })
3✔
1178

3✔
1179
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1180
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1181
                closureType contractcourt.ChannelCloseType) {
6✔
1182
                // TODO(conner): Properly respect the update and error channels
3✔
1183
                // returned by CloseLink.
3✔
1184

3✔
1185
                // Instruct the switch to close the channel.  Provide no close out
3✔
1186
                // delivery script or target fee per kw because user input is not
3✔
1187
                // available when the remote peer closes the channel.
3✔
1188
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
3✔
1189
        }
3✔
1190

1191
        // We will use the following channel to reliably hand off contract
1192
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1193
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
3✔
1194

3✔
1195
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1196
                &contractcourt.BreachConfig{
3✔
1197
                        CloseLink: closeLink,
3✔
1198
                        DB:        s.chanStateDB,
3✔
1199
                        Estimator: s.cc.FeeEstimator,
3✔
1200
                        GenSweepScript: newSweepPkScriptGen(
3✔
1201
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1202
                        ),
3✔
1203
                        Notifier:           cc.ChainNotifier,
3✔
1204
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1205
                        ContractBreaches:   contractBreaches,
3✔
1206
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1207
                        Store: contractcourt.NewRetributionStore(
3✔
1208
                                dbs.ChanStateDB,
3✔
1209
                        ),
3✔
1210
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1211
                },
3✔
1212
        )
3✔
1213

3✔
1214
        //nolint:lll
3✔
1215
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1216
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1217
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1218
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1219
                NewSweepAddr: func() ([]byte, error) {
3✔
1220
                        addr, err := newSweepPkScriptGen(
×
1221
                                cc.Wallet, netParams,
×
1222
                        )().Unpack()
×
1223
                        if err != nil {
×
1224
                                return nil, err
×
1225
                        }
×
1226

1227
                        return addr.DeliveryAddress, nil
×
1228
                },
1229
                PublishTx: cc.Wallet.PublishTransaction,
1230
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1231
                        for _, msg := range msgs {
6✔
1232
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1233
                                if err != nil {
3✔
1234
                                        return err
×
1235
                                }
×
1236
                        }
1237
                        return nil
3✔
1238
                },
1239
                IncubateOutputs: func(chanPoint wire.OutPoint,
1240
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1241
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1242
                        broadcastHeight uint32,
1243
                        deadlineHeight fn.Option[int32]) error {
3✔
1244

3✔
1245
                        return s.utxoNursery.IncubateOutputs(
3✔
1246
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1247
                                broadcastHeight, deadlineHeight,
3✔
1248
                        )
3✔
1249
                },
3✔
1250
                PreimageDB:   s.witnessBeacon,
1251
                Notifier:     cc.ChainNotifier,
1252
                Mempool:      cc.MempoolNotifier,
1253
                Signer:       cc.Wallet.Cfg.Signer,
1254
                FeeEstimator: cc.FeeEstimator,
1255
                ChainIO:      cc.ChainIO,
1256
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1257
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1258
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1259
                        return nil
3✔
1260
                },
3✔
1261
                IsOurAddress: cc.Wallet.IsOurAddress,
1262
                ContractBreach: func(chanPoint wire.OutPoint,
1263
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1264

3✔
1265
                        // processACK will handle the BreachArbitrator ACKing
3✔
1266
                        // the event.
3✔
1267
                        finalErr := make(chan error, 1)
3✔
1268
                        processACK := func(brarErr error) {
6✔
1269
                                if brarErr != nil {
3✔
1270
                                        finalErr <- brarErr
×
1271
                                        return
×
1272
                                }
×
1273

1274
                                // If the BreachArbitrator successfully handled
1275
                                // the event, we can signal that the handoff
1276
                                // was successful.
1277
                                finalErr <- nil
3✔
1278
                        }
1279

1280
                        event := &contractcourt.ContractBreachEvent{
3✔
1281
                                ChanPoint:         chanPoint,
3✔
1282
                                ProcessACK:        processACK,
3✔
1283
                                BreachRetribution: breachRet,
3✔
1284
                        }
3✔
1285

3✔
1286
                        // Send the contract breach event to the
3✔
1287
                        // BreachArbitrator.
3✔
1288
                        select {
3✔
1289
                        case contractBreaches <- event:
3✔
1290
                        case <-s.quit:
×
1291
                                return ErrServerShuttingDown
×
1292
                        }
1293

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

1319
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1320
                QueryIncomingCircuit: func(
1321
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1322

3✔
1323
                        // Get the circuit map.
3✔
1324
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1325

3✔
1326
                        // Lookup the outgoing circuit.
3✔
1327
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1328
                        if pc == nil {
6✔
1329
                                return nil
3✔
1330
                        }
3✔
1331

1332
                        return &pc.Incoming
3✔
1333
                },
1334
                AuxLeafStore: implCfg.AuxLeafStore,
1335
                AuxSigner:    implCfg.AuxSigner,
1336
                AuxResolver:  implCfg.AuxContractResolver,
1337
        }, dbs.ChanStateDB)
1338

1339
        // Select the configuration and funding parameters for Bitcoin.
1340
        chainCfg := cfg.Bitcoin
3✔
1341
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1342
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1343

3✔
1344
        var chanIDSeed [32]byte
3✔
1345
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1346
                return nil, err
×
1347
        }
×
1348

1349
        // Wrap the DeleteChannelEdges method so that the funding manager can
1350
        // use it without depending on several layers of indirection.
1351
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1352
                *models.ChannelEdgePolicy, error) {
6✔
1353

3✔
1354
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1355
                        scid.ToUint64(),
3✔
1356
                )
3✔
1357
                if errors.Is(err, channeldb.ErrEdgeNotFound) {
3✔
1358
                        // This is unlikely but there is a slim chance of this
×
1359
                        // being hit if lnd was killed via SIGKILL and the
×
1360
                        // funding manager was stepping through the delete
×
1361
                        // alias edge logic.
×
1362
                        return nil, nil
×
1363
                } else if err != nil {
3✔
1364
                        return nil, err
×
1365
                }
×
1366

1367
                // Grab our key to find our policy.
1368
                var ourKey [33]byte
3✔
1369
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1370

3✔
1371
                var ourPolicy *models.ChannelEdgePolicy
3✔
1372
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1373
                        ourPolicy = e1
3✔
1374
                } else {
6✔
1375
                        ourPolicy = e2
3✔
1376
                }
3✔
1377

1378
                if ourPolicy == nil {
3✔
1379
                        // Something is wrong, so return an error.
×
1380
                        return nil, fmt.Errorf("we don't have an edge")
×
1381
                }
×
1382

1383
                err = s.graphDB.DeleteChannelEdges(
3✔
1384
                        false, false, scid.ToUint64(),
3✔
1385
                )
3✔
1386
                return ourPolicy, err
3✔
1387
        }
1388

1389
        // For the reservationTimeout and the zombieSweeperInterval different
1390
        // values are set in case we are in a dev environment so enhance test
1391
        // capacilities.
1392
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1393
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1394

3✔
1395
        // Get the development config for funding manager. If we are not in
3✔
1396
        // development mode, this would be nil.
3✔
1397
        var devCfg *funding.DevConfig
3✔
1398
        if lncfg.IsDevBuild() {
6✔
1399
                devCfg = &funding.DevConfig{
3✔
1400
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1401
                }
3✔
1402

3✔
1403
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1404
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1405

3✔
1406
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1407
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1408
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1409
        }
3✔
1410

1411
        //nolint:lll
1412
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1413
                Dev:                devCfg,
3✔
1414
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1415
                IDKey:              nodeKeyDesc.PubKey,
3✔
1416
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1417
                Wallet:             cc.Wallet,
3✔
1418
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1419
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1420
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1421
                },
3✔
1422
                Notifier:     cc.ChainNotifier,
1423
                ChannelDB:    s.chanStateDB,
1424
                FeeEstimator: cc.FeeEstimator,
1425
                SignMessage:  cc.MsgSigner.SignMessage,
1426
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1427
                        error) {
3✔
1428

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

3✔
1449
                        // In case the user has explicitly specified
3✔
1450
                        // a default value for the number of
3✔
1451
                        // confirmations, we use it.
3✔
1452
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1453
                        if defaultConf != 0 {
6✔
1454
                                return defaultConf
3✔
1455
                        }
3✔
1456

1457
                        minConf := uint64(3)
×
1458
                        maxConf := uint64(6)
×
1459

×
1460
                        // If this is a wumbo channel, then we'll require the
×
1461
                        // max amount of confirmations.
×
1462
                        if chanAmt > MaxFundingAmount {
×
1463
                                return uint16(maxConf)
×
1464
                        }
×
1465

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

3✔
1488
                        // In case the user has explicitly specified
3✔
1489
                        // a default value for the remote delay, we
3✔
1490
                        // use it.
3✔
1491
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1492
                        if defaultDelay > 0 {
6✔
1493
                                return defaultDelay
3✔
1494
                        }
3✔
1495

1496
                        // If this is a wumbo channel, then we'll require the
1497
                        // max value.
1498
                        if chanAmt > MaxFundingAmount {
×
1499
                                return maxRemoteDelay
×
1500
                        }
×
1501

1502
                        // If not we scale according to channel size.
1503
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1504
                                chanAmt / MaxFundingAmount)
×
1505
                        if delay < minRemoteDelay {
×
1506
                                delay = minRemoteDelay
×
1507
                        }
×
1508
                        if delay > maxRemoteDelay {
×
1509
                                delay = maxRemoteDelay
×
1510
                        }
×
1511
                        return delay
×
1512
                },
1513
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1514
                        peerKey *btcec.PublicKey) error {
3✔
1515

3✔
1516
                        // First, we'll mark this new peer as a persistent peer
3✔
1517
                        // for re-connection purposes. If the peer is not yet
3✔
1518
                        // tracked or the user hasn't requested it to be perm,
3✔
1519
                        // we'll set false to prevent the server from continuing
3✔
1520
                        // to connect to this peer even if the number of
3✔
1521
                        // channels with this peer is zero.
3✔
1522
                        s.mu.Lock()
3✔
1523
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1524
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1525
                                s.persistentPeers[pubStr] = false
3✔
1526
                        }
3✔
1527
                        s.mu.Unlock()
3✔
1528

3✔
1529
                        // With that taken care of, we'll send this channel to
3✔
1530
                        // the chain arb so it can react to on-chain events.
3✔
1531
                        return s.chainArb.WatchNewChannel(channel)
3✔
1532
                },
1533
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1534
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1535
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1536
                },
3✔
1537
                RequiredRemoteChanReserve: func(chanAmt,
1538
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1539

3✔
1540
                        // By default, we'll require the remote peer to maintain
3✔
1541
                        // at least 1% of the total channel capacity at all
3✔
1542
                        // times. If this value ends up dipping below the dust
3✔
1543
                        // limit, then we'll use the dust limit itself as the
3✔
1544
                        // reserve as required by BOLT #2.
3✔
1545
                        reserve := chanAmt / 100
3✔
1546
                        if reserve < dustLimit {
6✔
1547
                                reserve = dustLimit
3✔
1548
                        }
3✔
1549

1550
                        return reserve
3✔
1551
                },
1552
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1553
                        // By default, we'll allow the remote peer to fully
3✔
1554
                        // utilize the full bandwidth of the channel, minus our
3✔
1555
                        // required reserve.
3✔
1556
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1557
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1558
                },
3✔
1559
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1560
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1561
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1562
                        }
3✔
1563

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

1592
        // Next, we'll assemble the sub-system that will maintain an on-disk
1593
        // static backup of the latest channel state.
1594
        chanNotifier := &channelNotifier{
3✔
1595
                chanNotifier: s.channelNotifier,
3✔
1596
                addrs:        dbs.ChanStateDB,
3✔
1597
        }
3✔
1598
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
3✔
1599
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1600
                s.chanStateDB, s.addrSource,
3✔
1601
        )
3✔
1602
        if err != nil {
3✔
1603
                return nil, err
×
1604
        }
×
1605
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1606
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1607
        )
3✔
1608
        if err != nil {
3✔
1609
                return nil, err
×
1610
        }
×
1611

1612
        // Assemble a peer notifier which will provide clients with subscriptions
1613
        // to peer online and offline events.
1614
        s.peerNotifier = peernotifier.New()
3✔
1615

3✔
1616
        // Create a channel event store which monitors all open channels.
3✔
1617
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1618
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1619
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1620
                },
3✔
1621
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1622
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1623
                },
3✔
1624
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1625
                Clock:           clock.NewDefaultClock(),
1626
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1627
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1628
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1629
        })
1630

1631
        if cfg.WtClient.Active {
6✔
1632
                policy := wtpolicy.DefaultPolicy()
3✔
1633
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1634

3✔
1635
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1636
                // protocol operations on sat/kw.
3✔
1637
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1638
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1639
                )
3✔
1640

3✔
1641
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1642

3✔
1643
                if err := policy.Validate(); err != nil {
3✔
1644
                        return nil, err
×
1645
                }
×
1646

1647
                // authDial is the wrapper around the btrontide.Dial for the
1648
                // watchtower.
1649
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1650
                        netAddr *lnwire.NetAddress,
3✔
1651
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1652

3✔
1653
                        return brontide.Dial(
3✔
1654
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1655
                        )
3✔
1656
                }
3✔
1657

1658
                // buildBreachRetribution is a call-back that can be used to
1659
                // query the BreachRetribution info and channel type given a
1660
                // channel ID and commitment height.
1661
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1662
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1663
                        channeldb.ChannelType, error) {
6✔
1664

3✔
1665
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1666
                                nil, chanID,
3✔
1667
                        )
3✔
1668
                        if err != nil {
3✔
1669
                                return nil, 0, err
×
1670
                        }
×
1671

1672
                        br, err := lnwallet.NewBreachRetribution(
3✔
1673
                                channel, commitHeight, 0, nil,
3✔
1674
                                implCfg.AuxLeafStore,
3✔
1675
                                implCfg.AuxContractResolver,
3✔
1676
                        )
3✔
1677
                        if err != nil {
3✔
1678
                                return nil, 0, err
×
1679
                        }
×
1680

1681
                        return br, channel.ChanType, nil
3✔
1682
                }
1683

1684
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1685

3✔
1686
                // Copy the policy for legacy channels and set the blob flag
3✔
1687
                // signalling support for anchor channels.
3✔
1688
                anchorPolicy := policy
3✔
1689
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1690

3✔
1691
                // Copy the policy for legacy channels and set the blob flag
3✔
1692
                // signalling support for taproot channels.
3✔
1693
                taprootPolicy := policy
3✔
1694
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1695
                        blob.FlagTaprootChannel,
3✔
1696
                )
3✔
1697

3✔
1698
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1699
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1700
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1701
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1702
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1703
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1704
                                error) {
6✔
1705

3✔
1706
                                return s.channelNotifier.
3✔
1707
                                        SubscribeChannelEvents()
3✔
1708
                        },
3✔
1709
                        Signer: cc.Wallet.Cfg.Signer,
1710
                        NewAddress: func() ([]byte, error) {
3✔
1711
                                addr, err := newSweepPkScriptGen(
3✔
1712
                                        cc.Wallet, netParams,
3✔
1713
                                )().Unpack()
3✔
1714
                                if err != nil {
3✔
1715
                                        return nil, err
×
1716
                                }
×
1717

1718
                                return addr.DeliveryAddress, nil
3✔
1719
                        },
1720
                        SecretKeyRing:      s.cc.KeyRing,
1721
                        Dial:               cfg.net.Dial,
1722
                        AuthDial:           authDial,
1723
                        DB:                 dbs.TowerClientDB,
1724
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1725
                        MinBackoff:         10 * time.Second,
1726
                        MaxBackoff:         5 * time.Minute,
1727
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1728
                }, policy, anchorPolicy, taprootPolicy)
1729
                if err != nil {
3✔
1730
                        return nil, err
×
1731
                }
×
1732
        }
1733

1734
        if len(cfg.ExternalHosts) != 0 {
3✔
1735
                advertisedIPs := make(map[string]struct{})
×
1736
                for _, addr := range s.currentNodeAnn.Addresses {
×
1737
                        advertisedIPs[addr.String()] = struct{}{}
×
1738
                }
×
1739

1740
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1741
                        Hosts:         cfg.ExternalHosts,
×
1742
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1743
                        LookupHost: func(host string) (net.Addr, error) {
×
1744
                                return lncfg.ParseAddressString(
×
1745
                                        host, strconv.Itoa(defaultPeerPort),
×
1746
                                        cfg.net.ResolveTCPAddr,
×
1747
                                )
×
1748
                        },
×
1749
                        AdvertisedIPs: advertisedIPs,
1750
                        AnnounceNewIPs: netann.IPAnnouncer(
1751
                                func(modifier ...netann.NodeAnnModifier) (
1752
                                        lnwire.NodeAnnouncement, error) {
×
1753

×
1754
                                        return s.genNodeAnnouncement(
×
1755
                                                nil, modifier...,
×
1756
                                        )
×
1757
                                }),
×
1758
                })
1759
        }
1760

1761
        // Create liveness monitor.
1762
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1763

3✔
1764
        // Create the connection manager which will be responsible for
3✔
1765
        // maintaining persistent outbound connections and also accepting new
3✔
1766
        // incoming connections
3✔
1767
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1768
                Listeners:      listeners,
3✔
1769
                OnAccept:       s.InboundPeerConnected,
3✔
1770
                RetryDuration:  time.Second * 5,
3✔
1771
                TargetOutbound: 100,
3✔
1772
                Dial: noiseDial(
3✔
1773
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1774
                ),
3✔
1775
                OnConnection: s.OutboundPeerConnected,
3✔
1776
        })
3✔
1777
        if err != nil {
3✔
1778
                return nil, err
×
1779
        }
×
1780
        s.connMgr = cmgr
3✔
1781

3✔
1782
        return s, nil
3✔
1783
}
1784

1785
// UpdateRoutingConfig is a callback function to update the routing config
1786
// values in the main cfg.
1787
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1788
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1789

3✔
1790
        switch c := cfg.Estimator.Config().(type) {
3✔
1791
        case routing.AprioriConfig:
3✔
1792
                routerCfg.ProbabilityEstimatorType =
3✔
1793
                        routing.AprioriEstimatorName
3✔
1794

3✔
1795
                targetCfg := routerCfg.AprioriConfig
3✔
1796
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1797
                targetCfg.Weight = c.AprioriWeight
3✔
1798
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1799
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1800

1801
        case routing.BimodalConfig:
3✔
1802
                routerCfg.ProbabilityEstimatorType =
3✔
1803
                        routing.BimodalEstimatorName
3✔
1804

3✔
1805
                targetCfg := routerCfg.BimodalConfig
3✔
1806
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1807
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1808
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1809
        }
1810

1811
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1812
}
1813

1814
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1815
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1816
// may differ from what is on disk.
1817
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1818
        error) {
3✔
1819

3✔
1820
        data, err := u.DataToSign()
3✔
1821
        if err != nil {
3✔
1822
                return nil, err
×
1823
        }
×
1824

1825
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1826
}
1827

1828
// createLivenessMonitor creates a set of health checks using our configured
1829
// values and uses these checks to create a liveness monitor. Available
1830
// health checks,
1831
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1832
//   - diskCheck
1833
//   - tlsHealthCheck
1834
//   - torController, only created when tor is enabled.
1835
//
1836
// If a health check has been disabled by setting attempts to 0, our monitor
1837
// will not run it.
1838
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1839
        leaderElector cluster.LeaderElector) {
3✔
1840

3✔
1841
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1842
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1843
                srvrLog.Info("Disabling chain backend checks for " +
×
1844
                        "nochainbackend mode")
×
1845

×
1846
                chainBackendAttempts = 0
×
1847
        }
×
1848

1849
        chainHealthCheck := healthcheck.NewObservation(
3✔
1850
                "chain backend",
3✔
1851
                cc.HealthCheck,
3✔
1852
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1853
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1854
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1855
                chainBackendAttempts,
3✔
1856
        )
3✔
1857

3✔
1858
        diskCheck := healthcheck.NewObservation(
3✔
1859
                "disk space",
3✔
1860
                func() error {
3✔
1861
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1862
                                cfg.LndDir,
×
1863
                        )
×
1864
                        if err != nil {
×
1865
                                return err
×
1866
                        }
×
1867

1868
                        // If we have more free space than we require,
1869
                        // we return a nil error.
1870
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1871
                                return nil
×
1872
                        }
×
1873

1874
                        return fmt.Errorf("require: %v free space, got: %v",
×
1875
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1876
                                free)
×
1877
                },
1878
                cfg.HealthChecks.DiskCheck.Interval,
1879
                cfg.HealthChecks.DiskCheck.Timeout,
1880
                cfg.HealthChecks.DiskCheck.Backoff,
1881
                cfg.HealthChecks.DiskCheck.Attempts,
1882
        )
1883

1884
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1885
                "tls",
3✔
1886
                func() error {
3✔
1887
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1888
                                s.cc.KeyRing,
×
1889
                        )
×
1890
                        if err != nil {
×
1891
                                return err
×
1892
                        }
×
1893
                        if expired {
×
1894
                                return fmt.Errorf("TLS certificate is "+
×
1895
                                        "expired as of %v", expTime)
×
1896
                        }
×
1897

1898
                        // If the certificate is not outdated, no error needs
1899
                        // to be returned
1900
                        return nil
×
1901
                },
1902
                cfg.HealthChecks.TLSCheck.Interval,
1903
                cfg.HealthChecks.TLSCheck.Timeout,
1904
                cfg.HealthChecks.TLSCheck.Backoff,
1905
                cfg.HealthChecks.TLSCheck.Attempts,
1906
        )
1907

1908
        checks := []*healthcheck.Observation{
3✔
1909
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1910
        }
3✔
1911

3✔
1912
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
1913
        if s.torController != nil {
3✔
1914
                torConnectionCheck := healthcheck.NewObservation(
×
1915
                        "tor connection",
×
1916
                        func() error {
×
1917
                                return healthcheck.CheckTorServiceStatus(
×
1918
                                        s.torController,
×
1919
                                        s.createNewHiddenService,
×
1920
                                )
×
1921
                        },
×
1922
                        cfg.HealthChecks.TorConnection.Interval,
1923
                        cfg.HealthChecks.TorConnection.Timeout,
1924
                        cfg.HealthChecks.TorConnection.Backoff,
1925
                        cfg.HealthChecks.TorConnection.Attempts,
1926
                )
1927
                checks = append(checks, torConnectionCheck)
×
1928
        }
1929

1930
        // If remote signing is enabled, add the healthcheck for the remote
1931
        // signing RPC interface.
1932
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
1933
                // Because we have two cascading timeouts here, we need to add
3✔
1934
                // some slack to the "outer" one of them in case the "inner"
3✔
1935
                // returns exactly on time.
3✔
1936
                overhead := time.Millisecond * 10
3✔
1937

3✔
1938
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
1939
                        "remote signer connection",
3✔
1940
                        rpcwallet.HealthCheck(
3✔
1941
                                s.cfg.RemoteSigner,
3✔
1942

3✔
1943
                                // For the health check we might to be even
3✔
1944
                                // stricter than the initial/normal connect, so
3✔
1945
                                // we use the health check timeout here.
3✔
1946
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
1947
                        ),
3✔
1948
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
1949
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
1950
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
1951
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
1952
                )
3✔
1953
                checks = append(checks, remoteSignerConnectionCheck)
3✔
1954
        }
3✔
1955

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

×
1974
                                leader, err := leaderElector.IsLeader(
×
1975
                                        timeoutCtx,
×
1976
                                )
×
1977
                                if err != nil {
×
1978
                                        return fmt.Errorf("unable to check if "+
×
1979
                                                "still leader: %v", err)
×
1980
                                }
×
1981

1982
                                if !leader {
×
1983
                                        srvrLog.Debug("Not the current leader")
×
1984
                                        return fmt.Errorf("not the current " +
×
1985
                                                "leader")
×
1986
                                }
×
1987

1988
                                return nil
×
1989
                        },
1990
                        cfg.HealthChecks.LeaderCheck.Interval,
1991
                        cfg.HealthChecks.LeaderCheck.Timeout,
1992
                        cfg.HealthChecks.LeaderCheck.Backoff,
1993
                        cfg.HealthChecks.LeaderCheck.Attempts,
1994
                )
1995

1996
                checks = append(checks, leaderCheck)
×
1997
        }
1998

1999
        // If we have not disabled all of our health checks, we create a
2000
        // liveness monitor with our configured checks.
2001
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2002
                &healthcheck.Config{
3✔
2003
                        Checks:   checks,
3✔
2004
                        Shutdown: srvrLog.Criticalf,
3✔
2005
                },
3✔
2006
        )
3✔
2007
}
2008

2009
// Started returns true if the server has been started, and false otherwise.
2010
// NOTE: This function is safe for concurrent access.
2011
func (s *server) Started() bool {
3✔
2012
        return atomic.LoadInt32(&s.active) != 0
3✔
2013
}
3✔
2014

2015
// cleaner is used to aggregate "cleanup" functions during an operation that
2016
// starts several subsystems. In case one of the subsystem fails to start
2017
// and a proper resource cleanup is required, the "run" method achieves this
2018
// by running all these added "cleanup" functions.
2019
type cleaner []func() error
2020

2021
// add is used to add a cleanup function to be called when
2022
// the run function is executed.
2023
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2024
        return append(c, cleanup)
3✔
2025
}
3✔
2026

2027
// run is used to run all the previousely added cleanup functions.
2028
func (c cleaner) run() {
×
2029
        for i := len(c) - 1; i >= 0; i-- {
×
2030
                if err := c[i](); err != nil {
×
2031
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2032
                }
×
2033
        }
2034
}
2035

2036
// Start starts the main daemon server, all requested listeners, and any helper
2037
// goroutines.
2038
// NOTE: This function is safe for concurrent access.
2039
//
2040
//nolint:funlen
2041
func (s *server) Start() error {
3✔
2042
        var startErr error
3✔
2043

3✔
2044
        // If one sub system fails to start, the following code ensures that the
3✔
2045
        // previous started ones are stopped. It also ensures a proper wallet
3✔
2046
        // shutdown which is important for releasing its resources (boltdb, etc...)
3✔
2047
        cleanup := cleaner{}
3✔
2048

3✔
2049
        s.start.Do(func() {
6✔
2050
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2051
                if err := s.customMessageServer.Start(); err != nil {
3✔
2052
                        startErr = err
×
2053
                        return
×
2054
                }
×
2055

2056
                if s.hostAnn != nil {
3✔
2057
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2058
                        if err := s.hostAnn.Start(); err != nil {
×
2059
                                startErr = err
×
2060
                                return
×
2061
                        }
×
2062
                }
2063

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

2072
                // Start the notification server. This is used so channel
2073
                // management goroutines can be notified when a funding
2074
                // transaction reaches a sufficient number of confirmations, or
2075
                // when the input for the funding transaction is spent in an
2076
                // attempt at an uncooperative close by the counterparty.
2077
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2078
                if err := s.sigPool.Start(); err != nil {
3✔
2079
                        startErr = err
×
2080
                        return
×
2081
                }
×
2082

2083
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2084
                if err := s.writePool.Start(); err != nil {
3✔
2085
                        startErr = err
×
2086
                        return
×
2087
                }
×
2088

2089
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2090
                if err := s.readPool.Start(); err != nil {
3✔
2091
                        startErr = err
×
2092
                        return
×
2093
                }
×
2094

2095
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2096
                if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2097
                        startErr = err
×
2098
                        return
×
2099
                }
×
2100

2101
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2102
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2103
                        startErr = err
×
2104
                        return
×
2105
                }
×
2106

2107
                cleanup = cleanup.add(s.channelNotifier.Stop)
3✔
2108
                if err := s.channelNotifier.Start(); err != nil {
3✔
2109
                        startErr = err
×
2110
                        return
×
2111
                }
×
2112

2113
                cleanup = cleanup.add(func() error {
3✔
2114
                        return s.peerNotifier.Stop()
×
2115
                })
×
2116
                if err := s.peerNotifier.Start(); err != nil {
3✔
2117
                        startErr = err
×
2118
                        return
×
2119
                }
×
2120

2121
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
2122
                if err := s.htlcNotifier.Start(); err != nil {
3✔
2123
                        startErr = err
×
2124
                        return
×
2125
                }
×
2126

2127
                if s.towerClientMgr != nil {
6✔
2128
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2129
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2130
                                startErr = err
×
2131
                                return
×
2132
                        }
×
2133
                }
2134

2135
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2136
                if err := s.txPublisher.Start(); err != nil {
3✔
2137
                        startErr = err
×
2138
                        return
×
2139
                }
×
2140

2141
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2142
                if err := s.sweeper.Start(); err != nil {
3✔
2143
                        startErr = err
×
2144
                        return
×
2145
                }
×
2146

2147
                cleanup = cleanup.add(s.utxoNursery.Stop)
3✔
2148
                if err := s.utxoNursery.Start(); err != nil {
3✔
2149
                        startErr = err
×
2150
                        return
×
2151
                }
×
2152

2153
                cleanup = cleanup.add(s.breachArbitrator.Stop)
3✔
2154
                if err := s.breachArbitrator.Start(); err != nil {
3✔
2155
                        startErr = err
×
2156
                        return
×
2157
                }
×
2158

2159
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
2160
                if err := s.fundingMgr.Start(); err != nil {
3✔
2161
                        startErr = err
×
2162
                        return
×
2163
                }
×
2164

2165
                // htlcSwitch must be started before chainArb since the latter
2166
                // relies on htlcSwitch to deliver resolution message upon
2167
                // start.
2168
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2169
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2170
                        startErr = err
×
2171
                        return
×
2172
                }
×
2173

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

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

2186
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2187
                if err := s.chainArb.Start(); err != nil {
3✔
2188
                        startErr = err
×
2189
                        return
×
2190
                }
×
2191

2192
                cleanup = cleanup.add(s.graphBuilder.Stop)
3✔
2193
                if err := s.graphBuilder.Start(); err != nil {
3✔
2194
                        startErr = err
×
2195
                        return
×
2196
                }
×
2197

2198
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2199
                if err := s.chanRouter.Start(); err != nil {
3✔
2200
                        startErr = err
×
2201
                        return
×
2202
                }
×
2203
                // The authGossiper depends on the chanRouter and therefore
2204
                // should be started after it.
2205
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2206
                if err := s.authGossiper.Start(); err != nil {
3✔
2207
                        startErr = err
×
2208
                        return
×
2209
                }
×
2210

2211
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2212
                if err := s.invoices.Start(); err != nil {
3✔
2213
                        startErr = err
×
2214
                        return
×
2215
                }
×
2216

2217
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2218
                if err := s.sphinx.Start(); err != nil {
3✔
2219
                        startErr = err
×
2220
                        return
×
2221
                }
×
2222

2223
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2224
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2225
                        startErr = err
×
2226
                        return
×
2227
                }
×
2228

2229
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2230
                if err := s.chanEventStore.Start(); err != nil {
3✔
2231
                        startErr = err
×
2232
                        return
×
2233
                }
×
2234

2235
                cleanup.add(func() error {
3✔
2236
                        s.missionController.StopStoreTickers()
×
2237
                        return nil
×
2238
                })
×
2239
                s.missionController.RunStoreTickers()
3✔
2240

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

2273
                // chanSubSwapper must be started after the `channelNotifier`
2274
                // because it depends on channel events as a synchronization
2275
                // point.
2276
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2277
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2278
                        startErr = err
×
2279
                        return
×
2280
                }
×
2281

2282
                if s.torController != nil {
3✔
2283
                        cleanup = cleanup.add(s.torController.Stop)
×
2284
                        if err := s.createNewHiddenService(); err != nil {
×
2285
                                startErr = err
×
2286
                                return
×
2287
                        }
×
2288
                }
2289

2290
                if s.natTraversal != nil {
3✔
2291
                        s.wg.Add(1)
×
2292
                        go s.watchExternalIP()
×
2293
                }
×
2294

2295
                // Start connmgr last to prevent connections before init.
2296
                cleanup = cleanup.add(func() error {
3✔
2297
                        s.connMgr.Stop()
×
2298
                        return nil
×
2299
                })
×
2300
                s.connMgr.Start()
3✔
2301

3✔
2302
                // If peers are specified as a config option, we'll add those
3✔
2303
                // peers first.
3✔
2304
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2305
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2306
                                peerAddrCfg,
3✔
2307
                        )
3✔
2308
                        if err != nil {
3✔
2309
                                startErr = fmt.Errorf("unable to parse peer "+
×
2310
                                        "pubkey from config: %v", err)
×
2311
                                return
×
2312
                        }
×
2313
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2314
                        if err != nil {
3✔
2315
                                startErr = fmt.Errorf("unable to parse peer "+
×
2316
                                        "address provided as a config option: "+
×
2317
                                        "%v", err)
×
2318
                                return
×
2319
                        }
×
2320

2321
                        peerAddr := &lnwire.NetAddress{
3✔
2322
                                IdentityKey: parsedPubkey,
3✔
2323
                                Address:     addr,
3✔
2324
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2325
                        }
3✔
2326

3✔
2327
                        err = s.ConnectToPeer(
3✔
2328
                                peerAddr, true,
3✔
2329
                                s.cfg.ConnectionTimeout,
3✔
2330
                        )
3✔
2331
                        if err != nil {
3✔
2332
                                startErr = fmt.Errorf("unable to connect to "+
×
2333
                                        "peer address provided as a config "+
×
2334
                                        "option: %v", err)
×
2335
                                return
×
2336
                        }
×
2337
                }
2338

2339
                // Subscribe to NodeAnnouncements that advertise new addresses
2340
                // our persistent peers.
2341
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2342
                        startErr = err
×
2343
                        return
×
2344
                }
×
2345

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

2361
                // setSeedList is a helper function that turns multiple DNS seed
2362
                // server tuples from the command line or config file into the
2363
                // data structure we need and does a basic formal sanity check
2364
                // in the process.
2365
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2366
                        if len(tuples) == 0 {
×
2367
                                return
×
2368
                        }
×
2369

2370
                        result := make([][2]string, len(tuples))
×
2371
                        for idx, tuple := range tuples {
×
2372
                                tuple = strings.TrimSpace(tuple)
×
2373
                                if len(tuple) == 0 {
×
2374
                                        return
×
2375
                                }
×
2376

2377
                                servers := strings.Split(tuple, ",")
×
2378
                                if len(servers) > 2 || len(servers) == 0 {
×
2379
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2380
                                                "seed tuple: %v", servers)
×
2381
                                        return
×
2382
                                }
×
2383

2384
                                copy(result[idx][:], servers)
×
2385
                        }
2386

2387
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2388
                }
2389

2390
                // Let users overwrite the DNS seed nodes. We only allow them
2391
                // for bitcoin mainnet/testnet/signet.
2392
                if s.cfg.Bitcoin.MainNet {
3✔
2393
                        setSeedList(
×
2394
                                s.cfg.Bitcoin.DNSSeeds,
×
2395
                                chainreg.BitcoinMainnetGenesis,
×
2396
                        )
×
2397
                }
×
2398
                if s.cfg.Bitcoin.TestNet3 {
3✔
2399
                        setSeedList(
×
2400
                                s.cfg.Bitcoin.DNSSeeds,
×
2401
                                chainreg.BitcoinTestnetGenesis,
×
2402
                        )
×
2403
                }
×
2404
                if s.cfg.Bitcoin.SigNet {
3✔
2405
                        setSeedList(
×
2406
                                s.cfg.Bitcoin.DNSSeeds,
×
2407
                                chainreg.BitcoinSignetGenesis,
×
2408
                        )
×
2409
                }
×
2410

2411
                // If network bootstrapping hasn't been disabled, then we'll
2412
                // configure the set of active bootstrappers, and launch a
2413
                // dedicated goroutine to maintain a set of persistent
2414
                // connections.
2415
                if shouldPeerBootstrap(s.cfg) {
3✔
2416
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2417
                        if err != nil {
×
2418
                                startErr = err
×
2419
                                return
×
2420
                        }
×
2421

2422
                        s.wg.Add(1)
×
2423
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2424
                } else {
3✔
2425
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2426
                }
3✔
2427

2428
                // Set the active flag now that we've completed the full
2429
                // startup.
2430
                atomic.StoreInt32(&s.active, 1)
3✔
2431
        })
2432

2433
        if startErr != nil {
3✔
2434
                cleanup.run()
×
2435
        }
×
2436
        return startErr
3✔
2437
}
2438

2439
// Stop gracefully shutsdown the main daemon server. This function will signal
2440
// any active goroutines, or helper objects to exit, then blocks until they've
2441
// all successfully exited. Additionally, any/all listeners are closed.
2442
// NOTE: This function is safe for concurrent access.
2443
func (s *server) Stop() error {
3✔
2444
        s.stop.Do(func() {
6✔
2445
                atomic.StoreInt32(&s.stopping, 1)
3✔
2446

3✔
2447
                close(s.quit)
3✔
2448

3✔
2449
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2450
                s.connMgr.Stop()
3✔
2451

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

2508
                // Update channel.backup file. Make sure to do it before
2509
                // stopping chanSubSwapper.
2510
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2511
                        s.chanStateDB, s.addrSource,
3✔
2512
                )
3✔
2513
                if err != nil {
3✔
2514
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2515
                                err)
×
2516
                } else {
3✔
2517
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2518
                        if err != nil {
6✔
2519
                                srvrLog.Warnf("Manual update of channel "+
3✔
2520
                                        "backup failed: %v", err)
3✔
2521
                        }
3✔
2522
                }
2523

2524
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2525
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2526
                }
×
2527
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2528
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2529
                }
×
2530
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2531
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2532
                                err)
×
2533
                }
×
2534
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2535
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2536
                                err)
×
2537
                }
×
2538
                s.missionController.StopStoreTickers()
3✔
2539

3✔
2540
                // Disconnect from each active peers to ensure that
3✔
2541
                // peerTerminationWatchers signal completion to each peer.
3✔
2542
                for _, peer := range s.Peers() {
6✔
2543
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2544
                        if err != nil {
3✔
2545
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2546
                                        "received error: %v", peer.IdentityKey(),
×
2547
                                        err,
×
2548
                                )
×
2549
                        }
×
2550
                }
2551

2552
                // Now that all connections have been torn down, stop the tower
2553
                // client which will reliably flush all queued states to the
2554
                // tower. If this is halted for any reason, the force quit timer
2555
                // will kick in and abort to allow this method to return.
2556
                if s.towerClientMgr != nil {
6✔
2557
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2558
                                srvrLog.Warnf("Unable to shut down tower "+
×
2559
                                        "client manager: %v", err)
×
2560
                        }
×
2561
                }
2562

2563
                if s.hostAnn != nil {
3✔
2564
                        if err := s.hostAnn.Stop(); err != nil {
×
2565
                                srvrLog.Warnf("unable to shut down host "+
×
2566
                                        "annoucner: %v", err)
×
2567
                        }
×
2568
                }
2569

2570
                if s.livenessMonitor != nil {
6✔
2571
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2572
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2573
                                        "monitor: %v", err)
×
2574
                        }
×
2575
                }
2576

2577
                // Wait for all lingering goroutines to quit.
2578
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2579
                s.wg.Wait()
3✔
2580

3✔
2581
                srvrLog.Debug("Stopping buffer pools...")
3✔
2582
                s.sigPool.Stop()
3✔
2583
                s.writePool.Stop()
3✔
2584
                s.readPool.Stop()
3✔
2585
        })
2586

2587
        return nil
3✔
2588
}
2589

2590
// Stopped returns true if the server has been instructed to shutdown.
2591
// NOTE: This function is safe for concurrent access.
2592
func (s *server) Stopped() bool {
3✔
2593
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2594
}
3✔
2595

2596
// configurePortForwarding attempts to set up port forwarding for the different
2597
// ports that the server will be listening on.
2598
//
2599
// NOTE: This should only be used when using some kind of NAT traversal to
2600
// automatically set up forwarding rules.
2601
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2602
        ip, err := s.natTraversal.ExternalIP()
×
2603
        if err != nil {
×
2604
                return nil, err
×
2605
        }
×
2606
        s.lastDetectedIP = ip
×
2607

×
2608
        externalIPs := make([]string, 0, len(ports))
×
2609
        for _, port := range ports {
×
2610
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2611
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2612
                        continue
×
2613
                }
2614

2615
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2616
                externalIPs = append(externalIPs, hostIP)
×
2617
        }
2618

2619
        return externalIPs, nil
×
2620
}
2621

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

2637
// watchExternalIP continuously checks for an updated external IP address every
2638
// 15 minutes. Once a new IP address has been detected, it will automatically
2639
// handle port forwarding rules and send updated node announcements to the
2640
// currently connected peers.
2641
//
2642
// NOTE: This MUST be run as a goroutine.
2643
func (s *server) watchExternalIP() {
×
2644
        defer s.wg.Done()
×
2645

×
2646
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2647
        // up by the server.
×
2648
        defer s.removePortForwarding()
×
2649

×
2650
        // Keep track of the external IPs set by the user to avoid replacing
×
2651
        // them when detecting a new IP.
×
2652
        ipsSetByUser := make(map[string]struct{})
×
2653
        for _, ip := range s.cfg.ExternalIPs {
×
2654
                ipsSetByUser[ip.String()] = struct{}{}
×
2655
        }
×
2656

2657
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2658

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

2674
                        // Periodically renew the NAT port forwarding.
2675
                        for _, port := range forwardedPorts {
×
2676
                                err := s.natTraversal.AddPortMapping(port)
×
2677
                                if err != nil {
×
2678
                                        srvrLog.Warnf("Unable to automatically "+
×
2679
                                                "re-create port forwarding using %s: %v",
×
2680
                                                s.natTraversal.Name(), err)
×
2681
                                } else {
×
2682
                                        srvrLog.Debugf("Automatically re-created "+
×
2683
                                                "forwarding for port %d using %s to "+
×
2684
                                                "advertise external IP",
×
2685
                                                port, s.natTraversal.Name())
×
2686
                                }
×
2687
                        }
2688

2689
                        if ip.Equal(s.lastDetectedIP) {
×
2690
                                continue
×
2691
                        }
2692

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

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

2710
                                newAddrs = append(newAddrs, addr)
×
2711
                        }
2712

2713
                        // Skip the update if we weren't able to resolve any of
2714
                        // the new addresses.
2715
                        if len(newAddrs) == 0 {
×
2716
                                srvrLog.Debug("Skipping node announcement " +
×
2717
                                        "update due to not being able to " +
×
2718
                                        "resolve any new addresses")
×
2719
                                continue
×
2720
                        }
2721

2722
                        // Now, we'll need to update the addresses in our node's
2723
                        // announcement in order to propagate the update
2724
                        // throughout the network. We'll only include addresses
2725
                        // that have a different IP from the previous one, as
2726
                        // the previous IP is no longer valid.
2727
                        currentNodeAnn := s.getNodeAnnouncement()
×
2728

×
2729
                        for _, addr := range currentNodeAnn.Addresses {
×
2730
                                host, _, err := net.SplitHostPort(addr.String())
×
2731
                                if err != nil {
×
2732
                                        srvrLog.Debugf("Unable to determine "+
×
2733
                                                "host from address %v: %v",
×
2734
                                                addr, err)
×
2735
                                        continue
×
2736
                                }
2737

2738
                                // We'll also make sure to include external IPs
2739
                                // set manually by the user.
2740
                                _, setByUser := ipsSetByUser[addr.String()]
×
2741
                                if setByUser || host != s.lastDetectedIP.String() {
×
2742
                                        newAddrs = append(newAddrs, addr)
×
2743
                                }
×
2744
                        }
2745

2746
                        // Then, we'll generate a new timestamped node
2747
                        // announcement with the updated addresses and broadcast
2748
                        // it to our peers.
2749
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2750
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2751
                        )
×
2752
                        if err != nil {
×
2753
                                srvrLog.Debugf("Unable to generate new node "+
×
2754
                                        "announcement: %v", err)
×
2755
                                continue
×
2756
                        }
2757

2758
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2759
                        if err != nil {
×
2760
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2761
                                        "announcement to peers: %v", err)
×
2762
                                continue
×
2763
                        }
2764

2765
                        // Finally, update the last IP seen to the current one.
2766
                        s.lastDetectedIP = ip
×
2767
                case <-s.quit:
×
2768
                        break out
×
2769
                }
2770
        }
2771
}
2772

2773
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2774
// based on the server, and currently active bootstrap mechanisms as defined
2775
// within the current configuration.
2776
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2777
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2778

×
2779
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2780

×
2781
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2782
        // this can be used by default if we've already partially seeded the
×
2783
        // network.
×
2784
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2785
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2786
        if err != nil {
×
2787
                return nil, err
×
2788
        }
×
2789
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2790

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

×
2796
                // If we have a set of DNS seeds for this chain, then we'll add
×
2797
                // it as an additional bootstrapping source.
×
2798
                if ok {
×
2799
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2800
                                "seeds: %v", dnsSeeds)
×
2801

×
2802
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2803
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2804
                        )
×
2805
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2806
                }
×
2807
        }
2808

2809
        return bootStrappers, nil
×
2810
}
2811

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

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

×
2824
        // We should ignore ourselves from bootstrapping.
×
2825
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2826
        ignore[selfKey] = struct{}{}
×
2827

×
2828
        // Ignore all connected peers.
×
2829
        for _, peer := range s.peersByPub {
×
2830
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2831
                ignore[nID] = struct{}{}
×
2832
        }
×
2833

2834
        // Ignore all persistent peers as they have a dedicated reconnecting
2835
        // process.
2836
        for pubKeyStr := range s.persistentPeers {
×
2837
                var nID autopilot.NodeID
×
2838
                copy(nID[:], []byte(pubKeyStr))
×
2839
                ignore[nID] = struct{}{}
×
2840
        }
×
2841

2842
        return ignore
×
2843
}
2844

2845
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2846
// and maintain a target minimum number of outbound connections. With this
2847
// invariant, we ensure that our node is connected to a diverse set of peers
2848
// and that nodes newly joining the network receive an up to date network view
2849
// as soon as possible.
2850
func (s *server) peerBootstrapper(numTargetPeers uint32,
2851
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2852

×
2853
        defer s.wg.Done()
×
2854

×
2855
        // Before we continue, init the ignore peers map.
×
2856
        ignoreList := s.createBootstrapIgnorePeers()
×
2857

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

×
2862
        // Once done, we'll attempt to maintain our target minimum number of
×
2863
        // peers.
×
2864
        //
×
2865
        // We'll use a 15 second backoff, and double the time every time an
×
2866
        // epoch fails up to a ceiling.
×
2867
        backOff := time.Second * 15
×
2868

×
2869
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2870
        // see if we've reached our minimum number of peers.
×
2871
        sampleTicker := time.NewTicker(backOff)
×
2872
        defer sampleTicker.Stop()
×
2873

×
2874
        // We'll use the number of attempts and errors to determine if we need
×
2875
        // to increase the time between discovery epochs.
×
2876
        var epochErrors uint32 // To be used atomically.
×
2877
        var epochAttempts uint32
×
2878

×
2879
        for {
×
2880
                select {
×
2881
                // The ticker has just woken us up, so we'll need to check if
2882
                // we need to attempt to connect our to any more peers.
2883
                case <-sampleTicker.C:
×
2884
                        // Obtain the current number of peers, so we can gauge
×
2885
                        // if we need to sample more peers or not.
×
2886
                        s.mu.RLock()
×
2887
                        numActivePeers := uint32(len(s.peersByPub))
×
2888
                        s.mu.RUnlock()
×
2889

×
2890
                        // If we have enough peers, then we can loop back
×
2891
                        // around to the next round as we're done here.
×
2892
                        if numActivePeers >= numTargetPeers {
×
2893
                                continue
×
2894
                        }
2895

2896
                        // If all of our attempts failed during this last back
2897
                        // off period, then will increase our backoff to 5
2898
                        // minute ceiling to avoid an excessive number of
2899
                        // queries
2900
                        //
2901
                        // TODO(roasbeef): add reverse policy too?
2902

2903
                        if epochAttempts > 0 &&
×
2904
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2905

×
2906
                                sampleTicker.Stop()
×
2907

×
2908
                                backOff *= 2
×
2909
                                if backOff > bootstrapBackOffCeiling {
×
2910
                                        backOff = bootstrapBackOffCeiling
×
2911
                                }
×
2912

2913
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2914
                                        "%v", backOff)
×
2915
                                sampleTicker = time.NewTicker(backOff)
×
2916
                                continue
×
2917
                        }
2918

2919
                        atomic.StoreUint32(&epochErrors, 0)
×
2920
                        epochAttempts = 0
×
2921

×
2922
                        // Since we know need more peers, we'll compute the
×
2923
                        // exact number we need to reach our threshold.
×
2924
                        numNeeded := numTargetPeers - numActivePeers
×
2925

×
2926
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2927
                                "peers", numNeeded)
×
2928

×
2929
                        // With the number of peers we need calculated, we'll
×
2930
                        // query the network bootstrappers to sample a set of
×
2931
                        // random addrs for us.
×
2932
                        //
×
2933
                        // Before we continue, get a copy of the ignore peers
×
2934
                        // map.
×
2935
                        ignoreList = s.createBootstrapIgnorePeers()
×
2936

×
2937
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2938
                                ignoreList, numNeeded*2, bootstrappers...,
×
2939
                        )
×
2940
                        if err != nil {
×
2941
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2942
                                        "peers: %v", err)
×
2943
                                continue
×
2944
                        }
2945

2946
                        // Finally, we'll launch a new goroutine for each
2947
                        // prospective peer candidates.
2948
                        for _, addr := range peerAddrs {
×
2949
                                epochAttempts++
×
2950

×
2951
                                go func(a *lnwire.NetAddress) {
×
2952
                                        // TODO(roasbeef): can do AS, subnet,
×
2953
                                        // country diversity, etc
×
2954
                                        errChan := make(chan error, 1)
×
2955
                                        s.connectToPeer(
×
2956
                                                a, errChan,
×
2957
                                                s.cfg.ConnectionTimeout,
×
2958
                                        )
×
2959
                                        select {
×
2960
                                        case err := <-errChan:
×
2961
                                                if err == nil {
×
2962
                                                        return
×
2963
                                                }
×
2964

2965
                                                srvrLog.Errorf("Unable to "+
×
2966
                                                        "connect to %v: %v",
×
2967
                                                        a, err)
×
2968
                                                atomic.AddUint32(&epochErrors, 1)
×
2969
                                        case <-s.quit:
×
2970
                                        }
2971
                                }(addr)
2972
                        }
2973
                case <-s.quit:
×
2974
                        return
×
2975
                }
2976
        }
2977
}
2978

2979
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
2980
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
2981
// query back off each time we encounter a failure.
2982
const bootstrapBackOffCeiling = time.Minute * 5
2983

2984
// initialPeerBootstrap attempts to continuously connect to peers on startup
2985
// until the target number of peers has been reached. This ensures that nodes
2986
// receive an up to date network view as soon as possible.
2987
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2988
        numTargetPeers uint32,
2989
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2990

×
2991
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
2992
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
2993

×
2994
        // We'll start off by waiting 2 seconds between failed attempts, then
×
2995
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
2996
        var delaySignal <-chan time.Time
×
2997
        delayTime := time.Second * 2
×
2998

×
2999
        // As want to be more aggressive, we'll use a lower back off celling
×
3000
        // then the main peer bootstrap logic.
×
3001
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3002

×
3003
        for attempts := 0; ; attempts++ {
×
3004
                // Check if the server has been requested to shut down in order
×
3005
                // to prevent blocking.
×
3006
                if s.Stopped() {
×
3007
                        return
×
3008
                }
×
3009

3010
                // We can exit our aggressive initial peer bootstrapping stage
3011
                // if we've reached out target number of peers.
3012
                s.mu.RLock()
×
3013
                numActivePeers := uint32(len(s.peersByPub))
×
3014
                s.mu.RUnlock()
×
3015

×
3016
                if numActivePeers >= numTargetPeers {
×
3017
                        return
×
3018
                }
×
3019

3020
                if attempts > 0 {
×
3021
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3022
                                "bootstrap peers (attempt #%v)", delayTime,
×
3023
                                attempts)
×
3024

×
3025
                        // We've completed at least one iterating and haven't
×
3026
                        // finished, so we'll start to insert a delay period
×
3027
                        // between each attempt.
×
3028
                        delaySignal = time.After(delayTime)
×
3029
                        select {
×
3030
                        case <-delaySignal:
×
3031
                        case <-s.quit:
×
3032
                                return
×
3033
                        }
3034

3035
                        // After our delay, we'll double the time we wait up to
3036
                        // the max back off period.
3037
                        delayTime *= 2
×
3038
                        if delayTime > backOffCeiling {
×
3039
                                delayTime = backOffCeiling
×
3040
                        }
×
3041
                }
3042

3043
                // Otherwise, we'll request for the remaining number of peers
3044
                // in order to reach our target.
3045
                peersNeeded := numTargetPeers - numActivePeers
×
3046
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3047
                        ignore, peersNeeded, bootstrappers...,
×
3048
                )
×
3049
                if err != nil {
×
3050
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3051
                                "peers: %v", err)
×
3052
                        continue
×
3053
                }
3054

3055
                // Then, we'll attempt to establish a connection to the
3056
                // different peer addresses retrieved by our bootstrappers.
3057
                var wg sync.WaitGroup
×
3058
                for _, bootstrapAddr := range bootstrapAddrs {
×
3059
                        wg.Add(1)
×
3060
                        go func(addr *lnwire.NetAddress) {
×
3061
                                defer wg.Done()
×
3062

×
3063
                                errChan := make(chan error, 1)
×
3064
                                go s.connectToPeer(
×
3065
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3066
                                )
×
3067

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

3091
                wg.Wait()
×
3092
        }
3093
}
3094

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

3107
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3108
        if err != nil {
×
3109
                return err
×
3110
        }
×
3111

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

×
3124
        switch {
×
3125
        case s.cfg.Tor.V2:
×
3126
                onionCfg.Type = tor.V2
×
3127
        case s.cfg.Tor.V3:
×
3128
                onionCfg.Type = tor.V3
×
3129
        }
3130

3131
        addr, err := s.torController.AddOnion(onionCfg)
×
3132
        if err != nil {
×
3133
                return err
×
3134
        }
×
3135

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

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

3166
        return nil
×
3167
}
3168

3169
// findChannel finds a channel given a public key and ChannelID. It is an
3170
// optimization that is quicker than seeking for a channel given only the
3171
// ChannelID.
3172
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3173
        *channeldb.OpenChannel, error) {
3✔
3174

3✔
3175
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3176
        if err != nil {
3✔
3177
                return nil, err
×
3178
        }
×
3179

3180
        for _, channel := range nodeChans {
6✔
3181
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3182
                        return channel, nil
3✔
3183
                }
3✔
3184
        }
3185

3186
        return nil, fmt.Errorf("unable to find channel")
3✔
3187
}
3188

3189
// getNodeAnnouncement fetches the current, fully signed node announcement.
3190
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3191
        s.mu.Lock()
3✔
3192
        defer s.mu.Unlock()
3✔
3193

3✔
3194
        return *s.currentNodeAnn
3✔
3195
}
3✔
3196

3197
// genNodeAnnouncement generates and returns the current fully signed node
3198
// announcement. The time stamp of the announcement will be updated in order
3199
// to ensure it propagates through the network.
3200
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3201
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3202

3✔
3203
        s.mu.Lock()
3✔
3204
        defer s.mu.Unlock()
3✔
3205

3✔
3206
        // First, try to update our feature manager with the updated set of
3✔
3207
        // features.
3✔
3208
        if features != nil {
6✔
3209
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3210
                        feature.SetNodeAnn: features,
3✔
3211
                }
3✔
3212
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3213
                if err != nil {
6✔
3214
                        return lnwire.NodeAnnouncement{}, err
3✔
3215
                }
3✔
3216

3217
                // If we could successfully update our feature manager, add
3218
                // an update modifier to include these new features to our
3219
                // set.
3220
                modifiers = append(
3✔
3221
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3222
                )
3✔
3223
        }
3224

3225
        // Always update the timestamp when refreshing to ensure the update
3226
        // propagates.
3227
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3228

3✔
3229
        // Apply the requested changes to the node announcement.
3✔
3230
        for _, modifier := range modifiers {
6✔
3231
                modifier(s.currentNodeAnn)
3✔
3232
        }
3✔
3233

3234
        // Sign a new update after applying all of the passed modifiers.
3235
        err := netann.SignNodeAnnouncement(
3✔
3236
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3237
        )
3✔
3238
        if err != nil {
3✔
3239
                return lnwire.NodeAnnouncement{}, err
×
3240
        }
×
3241

3242
        return *s.currentNodeAnn, nil
3✔
3243
}
3244

3245
// updateAndBrodcastSelfNode generates a new node announcement
3246
// applying the giving modifiers and updating the time stamp
3247
// to ensure it propagates through the network. Then it brodcasts
3248
// it to the network.
3249
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
3250
        modifiers ...netann.NodeAnnModifier) error {
3✔
3251

3✔
3252
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3253
        if err != nil {
6✔
3254
                return fmt.Errorf("unable to generate new node "+
3✔
3255
                        "announcement: %v", err)
3✔
3256
        }
3✔
3257

3258
        // Update the on-disk version of our announcement.
3259
        // Load and modify self node istead of creating anew instance so we
3260
        // don't risk overwriting any existing values.
3261
        selfNode, err := s.graphDB.SourceNode()
3✔
3262
        if err != nil {
3✔
3263
                return fmt.Errorf("unable to get current source node: %w", err)
×
3264
        }
×
3265

3266
        selfNode.HaveNodeAnnouncement = true
3✔
3267
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3268
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3269
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3270
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3271
        selfNode.Color = newNodeAnn.RGBColor
3✔
3272
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3273

3✔
3274
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
3275

3✔
3276
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
3✔
3277
                return fmt.Errorf("can't set self node: %w", err)
×
3278
        }
×
3279

3280
        // Finally, propagate it to the nodes in the network.
3281
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3282
        if err != nil {
3✔
3283
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3284
                        "announcement to peers: %v", err)
×
3285
                return err
×
3286
        }
×
3287

3288
        return nil
3✔
3289
}
3290

3291
type nodeAddresses struct {
3292
        pubKey    *btcec.PublicKey
3293
        addresses []net.Addr
3294
}
3295

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

3✔
3306
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3307
        // attempt to connect to based on our set of previous connections. Set
3✔
3308
        // the reconnection port to the default peer port.
3✔
3309
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3310
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3311
                return err
×
3312
        }
×
3313
        for _, node := range linkNodes {
6✔
3314
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3315
                nodeAddrs := &nodeAddresses{
3✔
3316
                        pubKey:    node.IdentityPub,
3✔
3317
                        addresses: node.Addresses,
3✔
3318
                }
3✔
3319
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3320
        }
3✔
3321

3322
        // After checking our previous connections for addresses to connect to,
3323
        // iterate through the nodes in our channel graph to find addresses
3324
        // that have been added via NodeAnnouncement messages.
3325
        sourceNode, err := s.graphDB.SourceNode()
3✔
3326
        if err != nil {
3✔
3327
                return err
×
3328
        }
×
3329

3330
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3331
        // each of the nodes.
3332
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3333
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3334
                tx kvdb.RTx,
3✔
3335
                chanInfo *models.ChannelEdgeInfo,
3✔
3336
                policy, _ *models.ChannelEdgePolicy) error {
6✔
3337

3✔
3338
                // If the remote party has announced the channel to us, but we
3✔
3339
                // haven't yet, then we won't have a policy. However, we don't
3✔
3340
                // need this to connect to the peer, so we'll log it and move on.
3✔
3341
                if policy == nil {
3✔
3342
                        srvrLog.Warnf("No channel policy found for "+
×
3343
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3344
                }
×
3345

3346
                // We'll now fetch the peer opposite from us within this
3347
                // channel so we can queue up a direct connection to them.
3348
                channelPeer, err := s.graphDB.FetchOtherNode(
3✔
3349
                        tx, chanInfo, selfPub,
3✔
3350
                )
3✔
3351
                if err != nil {
3✔
3352
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3353
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3354
                                err)
×
3355
                }
×
3356

3357
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3358

3✔
3359
                // Add all unique addresses from channel
3✔
3360
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3361
                // connect to for this peer.
3✔
3362
                addrSet := make(map[string]net.Addr)
3✔
3363
                for _, addr := range channelPeer.Addresses {
6✔
3364
                        switch addr.(type) {
3✔
3365
                        case *net.TCPAddr:
3✔
3366
                                addrSet[addr.String()] = addr
3✔
3367

3368
                        // We'll only attempt to connect to Tor addresses if Tor
3369
                        // outbound support is enabled.
3370
                        case *tor.OnionAddr:
×
3371
                                if s.cfg.Tor.Active {
×
3372
                                        addrSet[addr.String()] = addr
×
3373
                                }
×
3374
                        }
3375
                }
3376

3377
                // If this peer is also recorded as a link node, we'll add any
3378
                // additional addresses that have not already been selected.
3379
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3380
                if ok {
6✔
3381
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3382
                                switch lnAddress.(type) {
3✔
3383
                                case *net.TCPAddr:
3✔
3384
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3385

3386
                                // We'll only attempt to connect to Tor
3387
                                // addresses if Tor outbound support is enabled.
3388
                                case *tor.OnionAddr:
×
3389
                                        if s.cfg.Tor.Active {
×
3390
                                                addrSet[lnAddress.String()] = lnAddress
×
3391
                                        }
×
3392
                                }
3393
                        }
3394
                }
3395

3396
                // Construct a slice of the deduped addresses.
3397
                var addrs []net.Addr
3✔
3398
                for _, addr := range addrSet {
6✔
3399
                        addrs = append(addrs, addr)
3✔
3400
                }
3✔
3401

3402
                n := &nodeAddresses{
3✔
3403
                        addresses: addrs,
3✔
3404
                }
3✔
3405
                n.pubKey, err = channelPeer.PubKey()
3✔
3406
                if err != nil {
3✔
3407
                        return err
×
3408
                }
×
3409

3410
                nodeAddrsMap[pubStr] = n
3✔
3411
                return nil
3✔
3412
        })
3413
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
3✔
3414
                return err
×
3415
        }
×
3416

3417
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3418
                len(nodeAddrsMap))
3✔
3419

3✔
3420
        // Acquire and hold server lock until all persistent connection requests
3✔
3421
        // have been recorded and sent to the connection manager.
3✔
3422
        s.mu.Lock()
3✔
3423
        defer s.mu.Unlock()
3✔
3424

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

3439
                for _, address := range nodeAddr.addresses {
6✔
3440
                        // Create a wrapper address which couples the IP and
3✔
3441
                        // the pubkey so the brontide authenticated connection
3✔
3442
                        // can be established.
3✔
3443
                        lnAddr := &lnwire.NetAddress{
3✔
3444
                                IdentityKey: nodeAddr.pubKey,
3✔
3445
                                Address:     address,
3✔
3446
                        }
3✔
3447

3✔
3448
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3449
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3450
                }
3✔
3451

3452
                // We'll connect to the first 10 peers immediately, then
3453
                // randomly stagger any remaining connections if the
3454
                // stagger initial reconnect flag is set. This ensures
3455
                // that mobile nodes or nodes with a small number of
3456
                // channels obtain connectivity quickly, but larger
3457
                // nodes are able to disperse the costs of connecting to
3458
                // all peers at once.
3459
                if numOutboundConns < numInstantInitReconnect ||
3✔
3460
                        !s.cfg.StaggerInitialReconnect {
6✔
3461

3✔
3462
                        go s.connectToPersistentPeer(pubStr)
3✔
3463
                } else {
3✔
3464
                        go s.delayInitialReconnect(pubStr)
×
3465
                }
×
3466

3467
                numOutboundConns++
3✔
3468
        }
3469

3470
        return nil
3✔
3471
}
3472

3473
// delayInitialReconnect will attempt a reconnection to the given peer after
3474
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3475
//
3476
// NOTE: This method MUST be run as a goroutine.
3477
func (s *server) delayInitialReconnect(pubStr string) {
×
3478
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3479
        select {
×
3480
        case <-time.After(delay):
×
3481
                s.connectToPersistentPeer(pubStr)
×
3482
        case <-s.quit:
×
3483
        }
3484
}
3485

3486
// prunePersistentPeerConnection removes all internal state related to
3487
// persistent connections to a peer within the server. This is used to avoid
3488
// persistent connection retries to peers we do not have any open channels with.
3489
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
3✔
3490
        pubKeyStr := string(compressedPubKey[:])
3✔
3491

3✔
3492
        s.mu.Lock()
3✔
3493
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3494
                delete(s.persistentPeers, pubKeyStr)
3✔
3495
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3496
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3497
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3498
                s.mu.Unlock()
3✔
3499

3✔
3500
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3501
                        "peer has no open channels", compressedPubKey)
3✔
3502

3✔
3503
                return
3✔
3504
        }
3✔
3505
        s.mu.Unlock()
3✔
3506
}
3507

3508
// BroadcastMessage sends a request to the server to broadcast a set of
3509
// messages to all peers other than the one specified by the `skips` parameter.
3510
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3511
// the target peers.
3512
//
3513
// NOTE: This function is safe for concurrent access.
3514
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3515
        msgs ...lnwire.Message) error {
3✔
3516

3✔
3517
        // Filter out peers found in the skips map. We synchronize access to
3✔
3518
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3519
        // exact set of peers present at the time of invocation.
3✔
3520
        s.mu.RLock()
3✔
3521
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3522
        for pubStr, sPeer := range s.peersByPub {
6✔
3523
                if skips != nil {
6✔
3524
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3525
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3526
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3527
                                continue
3✔
3528
                        }
3529
                }
3530

3531
                peers = append(peers, sPeer)
3✔
3532
        }
3533
        s.mu.RUnlock()
3✔
3534

3✔
3535
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3536
        // all messages to each of peers.
3✔
3537
        var wg sync.WaitGroup
3✔
3538
        for _, sPeer := range peers {
6✔
3539
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3540
                        sPeer.PubKey())
3✔
3541

3✔
3542
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3543
                wg.Add(1)
3✔
3544
                s.wg.Add(1)
3✔
3545
                go func(p lnpeer.Peer) {
6✔
3546
                        defer s.wg.Done()
3✔
3547
                        defer wg.Done()
3✔
3548

3✔
3549
                        p.SendMessageLazy(false, msgs...)
3✔
3550
                }(sPeer)
3✔
3551
        }
3552

3553
        // Wait for all messages to have been dispatched before returning to
3554
        // caller.
3555
        wg.Wait()
3✔
3556

3✔
3557
        return nil
3✔
3558
}
3559

3560
// NotifyWhenOnline can be called by other subsystems to get notified when a
3561
// particular peer comes online. The peer itself is sent across the peerChan.
3562
//
3563
// NOTE: This function is safe for concurrent access.
3564
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3565
        peerChan chan<- lnpeer.Peer) {
3✔
3566

3✔
3567
        s.mu.Lock()
3✔
3568

3✔
3569
        // Compute the target peer's identifier.
3✔
3570
        pubStr := string(peerKey[:])
3✔
3571

3✔
3572
        // Check if peer is connected.
3✔
3573
        peer, ok := s.peersByPub[pubStr]
3✔
3574
        if ok {
6✔
3575
                // Unlock here so that the mutex isn't held while we are
3✔
3576
                // waiting for the peer to become active.
3✔
3577
                s.mu.Unlock()
3✔
3578

3✔
3579
                // Wait until the peer signals that it is actually active
3✔
3580
                // rather than only in the server's maps.
3✔
3581
                select {
3✔
3582
                case <-peer.ActiveSignal():
3✔
3583
                case <-peer.QuitSignal():
×
3584
                        // The peer quit, so we'll add the channel to the slice
×
3585
                        // and return.
×
3586
                        s.mu.Lock()
×
3587
                        s.peerConnectedListeners[pubStr] = append(
×
3588
                                s.peerConnectedListeners[pubStr], peerChan,
×
3589
                        )
×
3590
                        s.mu.Unlock()
×
3591
                        return
×
3592
                }
3593

3594
                // Connected, can return early.
3595
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3596

3✔
3597
                select {
3✔
3598
                case peerChan <- peer:
3✔
3599
                case <-s.quit:
×
3600
                }
3601

3602
                return
3✔
3603
        }
3604

3605
        // Not connected, store this listener such that it can be notified when
3606
        // the peer comes online.
3607
        s.peerConnectedListeners[pubStr] = append(
3✔
3608
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3609
        )
3✔
3610
        s.mu.Unlock()
3✔
3611
}
3612

3613
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3614
// the given public key has been disconnected. The notification is signaled by
3615
// closing the channel returned.
3616
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3617
        s.mu.Lock()
3✔
3618
        defer s.mu.Unlock()
3✔
3619

3✔
3620
        c := make(chan struct{})
3✔
3621

3✔
3622
        // If the peer is already offline, we can immediately trigger the
3✔
3623
        // notification.
3✔
3624
        peerPubKeyStr := string(peerPubKey[:])
3✔
3625
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3626
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3627
                close(c)
×
3628
                return c
×
3629
        }
×
3630

3631
        // Otherwise, the peer is online, so we'll keep track of the channel to
3632
        // trigger the notification once the server detects the peer
3633
        // disconnects.
3634
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3635
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3636
        )
3✔
3637

3✔
3638
        return c
3✔
3639
}
3640

3641
// FindPeer will return the peer that corresponds to the passed in public key.
3642
// This function is used by the funding manager, allowing it to update the
3643
// daemon's local representation of the remote peer.
3644
//
3645
// NOTE: This function is safe for concurrent access.
3646
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3647
        s.mu.RLock()
3✔
3648
        defer s.mu.RUnlock()
3✔
3649

3✔
3650
        pubStr := string(peerKey.SerializeCompressed())
3✔
3651

3✔
3652
        return s.findPeerByPubStr(pubStr)
3✔
3653
}
3✔
3654

3655
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3656
// which should be a string representation of the peer's serialized, compressed
3657
// public key.
3658
//
3659
// NOTE: This function is safe for concurrent access.
3660
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3661
        s.mu.RLock()
3✔
3662
        defer s.mu.RUnlock()
3✔
3663

3✔
3664
        return s.findPeerByPubStr(pubStr)
3✔
3665
}
3✔
3666

3667
// findPeerByPubStr is an internal method that retrieves the specified peer from
3668
// the server's internal state using.
3669
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3670
        peer, ok := s.peersByPub[pubStr]
3✔
3671
        if !ok {
6✔
3672
                return nil, ErrPeerNotConnected
3✔
3673
        }
3✔
3674

3675
        return peer, nil
3✔
3676
}
3677

3678
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3679
// exponential backoff. If no previous backoff was known, the default is
3680
// returned.
3681
func (s *server) nextPeerBackoff(pubStr string,
3682
        startTime time.Time) time.Duration {
3✔
3683

3✔
3684
        // Now, determine the appropriate backoff to use for the retry.
3✔
3685
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3686
        if !ok {
6✔
3687
                // If an existing backoff was unknown, use the default.
3✔
3688
                return s.cfg.MinBackoff
3✔
3689
        }
3✔
3690

3691
        // If the peer failed to start properly, we'll just use the previous
3692
        // backoff to compute the subsequent randomized exponential backoff
3693
        // duration. This will roughly double on average.
3694
        if startTime.IsZero() {
3✔
3695
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3696
        }
×
3697

3698
        // The peer succeeded in starting. If the connection didn't last long
3699
        // enough to be considered stable, we'll continue to back off retries
3700
        // with this peer.
3701
        connDuration := time.Since(startTime)
3✔
3702
        if connDuration < defaultStableConnDuration {
6✔
3703
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3704
        }
3✔
3705

3706
        // The peer succeed in starting and this was stable peer, so we'll
3707
        // reduce the timeout duration by the length of the connection after
3708
        // applying randomized exponential backoff. We'll only apply this in the
3709
        // case that:
3710
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3711
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3712
        if relaxedBackoff > s.cfg.MinBackoff {
×
3713
                return relaxedBackoff
×
3714
        }
×
3715

3716
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3717
        // the stable connection lasted much longer than our previous backoff.
3718
        // To reward such good behavior, we'll reconnect after the default
3719
        // timeout.
3720
        return s.cfg.MinBackoff
×
3721
}
3722

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

×
3733
        // The connection that comes from the node with a "smaller" pubkey
×
3734
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3735
        // should drop our established connection.
×
3736
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3737
}
×
3738

3739
// InboundPeerConnected initializes a new peer in response to a new inbound
3740
// connection.
3741
//
3742
// NOTE: This function is safe for concurrent access.
3743
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3744
        // Exit early if we have already been instructed to shutdown, this
3✔
3745
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3746
        if s.Stopped() {
3✔
3747
                return
×
3748
        }
×
3749

3750
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3751
        pubSer := nodePub.SerializeCompressed()
3✔
3752
        pubStr := string(pubSer)
3✔
3753

3✔
3754
        var pubBytes [33]byte
3✔
3755
        copy(pubBytes[:], pubSer)
3✔
3756

3✔
3757
        s.mu.Lock()
3✔
3758
        defer s.mu.Unlock()
3✔
3759

3✔
3760
        // If the remote node's public key is banned, drop the connection.
3✔
3761
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
3✔
3762
        if dcErr != nil {
3✔
3763
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3764
                        "peer: %v", dcErr)
×
3765
                conn.Close()
×
3766

×
3767
                return
×
3768
        }
×
3769

3770
        if shouldDc {
3✔
3771
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3772
                        "banned.", pubSer)
×
3773

×
3774
                conn.Close()
×
3775

×
3776
                return
×
3777
        }
×
3778

3779
        // If we already have an outbound connection to this peer, then ignore
3780
        // this new connection.
3781
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3782
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3783
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3784
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3785

3✔
3786
                conn.Close()
3✔
3787
                return
3✔
3788
        }
3✔
3789

3790
        // If we already have a valid connection that is scheduled to take
3791
        // precedence once the prior peer has finished disconnecting, we'll
3792
        // ignore this connection.
3793
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3794
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3795
                        "scheduled", conn.RemoteAddr(), p)
×
3796
                conn.Close()
×
3797
                return
×
3798
        }
×
3799

3800
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
3✔
3801

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

3815
        case nil:
×
3816
                // We already have a connection with the incoming peer. If the
×
3817
                // connection we've already established should be kept and is
×
3818
                // not of the same type of the new connection (inbound), then
×
3819
                // we'll close out the new connection s.t there's only a single
×
3820
                // connection between us.
×
3821
                localPub := s.identityECDH.PubKey()
×
3822
                if !connectedPeer.Inbound() &&
×
3823
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3824

×
3825
                        srvrLog.Warnf("Received inbound connection from "+
×
3826
                                "peer %v, but already have outbound "+
×
3827
                                "connection, dropping conn", connectedPeer)
×
3828
                        conn.Close()
×
3829
                        return
×
3830
                }
×
3831

3832
                // Otherwise, if we should drop the connection, then we'll
3833
                // disconnect our already connected peer.
3834
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3835
                        connectedPeer)
×
3836

×
3837
                s.cancelConnReqs(pubStr, nil)
×
3838

×
3839
                // Remove the current peer from the server's internal state and
×
3840
                // signal that the peer termination watcher does not need to
×
3841
                // execute for this peer.
×
3842
                s.removePeer(connectedPeer)
×
3843
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3844
                s.scheduledPeerConnection[pubStr] = func() {
×
3845
                        s.peerConnected(conn, nil, true)
×
3846
                }
×
3847
        }
3848
}
3849

3850
// OutboundPeerConnected initializes a new peer in response to a new outbound
3851
// connection.
3852
// NOTE: This function is safe for concurrent access.
3853
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
3854
        // Exit early if we have already been instructed to shutdown, this
3✔
3855
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3856
        if s.Stopped() {
3✔
3857
                return
×
3858
        }
×
3859

3860
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3861
        pubSer := nodePub.SerializeCompressed()
3✔
3862
        pubStr := string(pubSer)
3✔
3863

3✔
3864
        var pubBytes [33]byte
3✔
3865
        copy(pubBytes[:], pubSer)
3✔
3866

3✔
3867
        s.mu.Lock()
3✔
3868
        defer s.mu.Unlock()
3✔
3869

3✔
3870
        // If the remote node's public key is banned, drop the connection.
3✔
3871
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
3✔
3872
        if dcErr != nil {
3✔
3873
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3874
                        "peer: %v", dcErr)
×
3875
                conn.Close()
×
3876

×
3877
                return
×
3878
        }
×
3879

3880
        if shouldDc {
3✔
3881
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3882
                        "banned.", pubSer)
×
3883

×
3884
                if connReq != nil {
×
3885
                        s.connMgr.Remove(connReq.ID())
×
3886
                }
×
3887

3888
                conn.Close()
×
3889

×
3890
                return
×
3891
        }
3892

3893
        // If we already have an inbound connection to this peer, then ignore
3894
        // this new connection.
3895
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
3896
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
3897
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
3898
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3899

3✔
3900
                if connReq != nil {
6✔
3901
                        s.connMgr.Remove(connReq.ID())
3✔
3902
                }
3✔
3903
                conn.Close()
3✔
3904
                return
3✔
3905
        }
3906
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
3907
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3908
                s.connMgr.Remove(connReq.ID())
×
3909
                conn.Close()
×
3910
                return
×
3911
        }
×
3912

3913
        // If we already have a valid connection that is scheduled to take
3914
        // precedence once the prior peer has finished disconnecting, we'll
3915
        // ignore this connection.
3916
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3917
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
3918

×
3919
                if connReq != nil {
×
3920
                        s.connMgr.Remove(connReq.ID())
×
3921
                }
×
3922

3923
                conn.Close()
×
3924
                return
×
3925
        }
3926

3927
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
3928
                conn.RemoteAddr())
3✔
3929

3✔
3930
        if connReq != nil {
6✔
3931
                // A successful connection was returned by the connmgr.
3✔
3932
                // Immediately cancel all pending requests, excluding the
3✔
3933
                // outbound connection we just established.
3✔
3934
                ignore := connReq.ID()
3✔
3935
                s.cancelConnReqs(pubStr, &ignore)
3✔
3936
        } else {
6✔
3937
                // This was a successful connection made by some other
3✔
3938
                // subsystem. Remove all requests being managed by the connmgr.
3✔
3939
                s.cancelConnReqs(pubStr, nil)
3✔
3940
        }
3✔
3941

3942
        // If we already have a connection with this peer, decide whether or not
3943
        // we need to drop the stale connection. We forgo adding a default case
3944
        // as we expect these to be the only error values returned from
3945
        // findPeerByPubStr.
3946
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3947
        switch err {
3✔
3948
        case ErrPeerNotConnected:
3✔
3949
                // We were unable to locate an existing connection with the
3✔
3950
                // target peer, proceed to connect.
3✔
3951
                s.peerConnected(conn, connReq, false)
3✔
3952

3953
        case nil:
×
3954
                // We already have a connection with the incoming peer. If the
×
3955
                // connection we've already established should be kept and is
×
3956
                // not of the same type of the new connection (outbound), then
×
3957
                // we'll close out the new connection s.t there's only a single
×
3958
                // connection between us.
×
3959
                localPub := s.identityECDH.PubKey()
×
3960
                if connectedPeer.Inbound() &&
×
3961
                        shouldDropLocalConnection(localPub, nodePub) {
×
3962

×
3963
                        srvrLog.Warnf("Established outbound connection to "+
×
3964
                                "peer %v, but already have inbound "+
×
3965
                                "connection, dropping conn", connectedPeer)
×
3966
                        if connReq != nil {
×
3967
                                s.connMgr.Remove(connReq.ID())
×
3968
                        }
×
3969
                        conn.Close()
×
3970
                        return
×
3971
                }
3972

3973
                // Otherwise, _their_ connection should be dropped. So we'll
3974
                // disconnect the peer and send the now obsolete peer to the
3975
                // server for garbage collection.
3976
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3977
                        connectedPeer)
×
3978

×
3979
                // Remove the current peer from the server's internal state and
×
3980
                // signal that the peer termination watcher does not need to
×
3981
                // execute for this peer.
×
3982
                s.removePeer(connectedPeer)
×
3983
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3984
                s.scheduledPeerConnection[pubStr] = func() {
×
3985
                        s.peerConnected(conn, connReq, false)
×
3986
                }
×
3987
        }
3988
}
3989

3990
// UnassignedConnID is the default connection ID that a request can have before
3991
// it actually is submitted to the connmgr.
3992
// TODO(conner): move into connmgr package, or better, add connmgr method for
3993
// generating atomic IDs
3994
const UnassignedConnID uint64 = 0
3995

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

4010
        // Next, check to see if we have any outstanding persistent connection
4011
        // requests to this peer. If so, then we'll remove all of these
4012
        // connection requests, and also delete the entry from the map.
4013
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4014
        if !ok {
6✔
4015
                return
3✔
4016
        }
3✔
4017

4018
        for _, connReq := range connReqs {
6✔
4019
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4020

3✔
4021
                // Atomically capture the current request identifier.
3✔
4022
                connID := connReq.ID()
3✔
4023

3✔
4024
                // Skip any zero IDs, this indicates the request has not
3✔
4025
                // yet been schedule.
3✔
4026
                if connID == UnassignedConnID {
3✔
4027
                        continue
×
4028
                }
4029

4030
                // Skip a particular connection ID if instructed.
4031
                if skip != nil && connID == *skip {
6✔
4032
                        continue
3✔
4033
                }
4034

4035
                s.connMgr.Remove(connID)
3✔
4036
        }
4037

4038
        delete(s.persistentConnReqs, pubStr)
3✔
4039
}
4040

4041
// handleCustomMessage dispatches an incoming custom peers message to
4042
// subscribers.
4043
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4044
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4045
                peer, msg.Type)
3✔
4046

3✔
4047
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4048
                Peer: peer,
3✔
4049
                Msg:  msg,
3✔
4050
        })
3✔
4051
}
3✔
4052

4053
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4054
// messages.
4055
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4056
        return s.customMessageServer.Subscribe()
3✔
4057
}
3✔
4058

4059
// peerConnected is a function that handles initialization a newly connected
4060
// peer by adding it to the server's global list of all active peers, and
4061
// starting all the goroutines the peer needs to function properly. The inbound
4062
// boolean should be true if the peer initiated the connection to us.
4063
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4064
        inbound bool) {
3✔
4065

3✔
4066
        brontideConn := conn.(*brontide.Conn)
3✔
4067
        addr := conn.RemoteAddr()
3✔
4068
        pubKey := brontideConn.RemotePub()
3✔
4069

3✔
4070
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4071
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4072

3✔
4073
        peerAddr := &lnwire.NetAddress{
3✔
4074
                IdentityKey: pubKey,
3✔
4075
                Address:     addr,
3✔
4076
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4077
        }
3✔
4078

3✔
4079
        // With the brontide connection established, we'll now craft the feature
3✔
4080
        // vectors to advertise to the remote node.
3✔
4081
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4082
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4083

3✔
4084
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4085
        // found, create a fresh buffer.
3✔
4086
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4087
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4088
        if !ok {
6✔
4089
                var err error
3✔
4090
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4091
                if err != nil {
3✔
4092
                        srvrLog.Errorf("unable to create peer %v", err)
×
4093
                        return
×
4094
                }
×
4095
        }
4096

4097
        // If we directly set the peer.Config TowerClient member to the
4098
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4099
        // the peer.Config's TowerClient member will not evaluate to nil even
4100
        // though the underlying value is nil. To avoid this gotcha which can
4101
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4102
        // TowerClient if needed.
4103
        var towerClient wtclient.ClientManager
3✔
4104
        if s.towerClientMgr != nil {
6✔
4105
                towerClient = s.towerClientMgr
3✔
4106
        }
3✔
4107

4108
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4109
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4110

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

3✔
4154
                        return s.genNodeAnnouncement(nil)
3✔
4155
                },
3✔
4156

4157
                PongBuf: s.pongBuf,
4158

4159
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4160

4161
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4162

4163
                FundingManager: s.fundingMgr,
4164

4165
                Hodl:                    s.cfg.Hodl,
4166
                UnsafeReplay:            s.cfg.UnsafeReplay,
4167
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4168
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4169
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4170
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4171
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4172
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4173
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4174
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4175
                HandleCustomMessage:    s.handleCustomMessage,
4176
                GetAliases:             s.aliasMgr.GetAliases,
4177
                RequestAlias:           s.aliasMgr.RequestAlias,
4178
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4179
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4180
                MaxFeeExposure:         thresholdMSats,
4181
                Quit:                   s.quit,
4182
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4183
                AuxSigner:              s.implCfg.AuxSigner,
4184
                MsgRouter:              s.implCfg.MsgRouter,
4185
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4186
                AuxResolver:            s.implCfg.AuxContractResolver,
4187
        }
4188

4189
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4190
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4191

3✔
4192
        p := peer.NewBrontide(pCfg)
3✔
4193

3✔
4194
        // TODO(roasbeef): update IP address for link-node
3✔
4195
        //  * also mark last-seen, do it one single transaction?
3✔
4196

3✔
4197
        s.addPeer(p)
3✔
4198

3✔
4199
        // Once we have successfully added the peer to the server, we can
3✔
4200
        // delete the previous error buffer from the server's map of error
3✔
4201
        // buffers.
3✔
4202
        delete(s.peerErrors, pkStr)
3✔
4203

3✔
4204
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4205
        // includes sending and receiving Init messages, which would be a DOS
3✔
4206
        // vector if we held the server's mutex throughout the procedure.
3✔
4207
        s.wg.Add(1)
3✔
4208
        go s.peerInitializer(p)
3✔
4209
}
4210

4211
// addPeer adds the passed peer to the server's global state of all active
4212
// peers.
4213
func (s *server) addPeer(p *peer.Brontide) {
3✔
4214
        if p == nil {
3✔
4215
                return
×
4216
        }
×
4217

4218
        // Ignore new peers if we're shutting down.
4219
        if s.Stopped() {
3✔
4220
                p.Disconnect(ErrServerShuttingDown)
×
4221
                return
×
4222
        }
×
4223

4224
        // Track the new peer in our indexes so we can quickly look it up either
4225
        // according to its public key, or its peer ID.
4226
        // TODO(roasbeef): pipe all requests through to the
4227
        // queryHandler/peerManager
4228

4229
        pubSer := p.IdentityKey().SerializeCompressed()
3✔
4230
        pubStr := string(pubSer)
3✔
4231

3✔
4232
        s.peersByPub[pubStr] = p
3✔
4233

3✔
4234
        if p.Inbound() {
6✔
4235
                s.inboundPeers[pubStr] = p
3✔
4236
        } else {
6✔
4237
                s.outboundPeers[pubStr] = p
3✔
4238
        }
3✔
4239

4240
        // Inform the peer notifier of a peer online event so that it can be reported
4241
        // to clients listening for peer events.
4242
        var pubKey [33]byte
3✔
4243
        copy(pubKey[:], pubSer)
3✔
4244

3✔
4245
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4246
}
4247

4248
// peerInitializer asynchronously starts a newly connected peer after it has
4249
// been added to the server's peer map. This method sets up a
4250
// peerTerminationWatcher for the given peer, and ensures that it executes even
4251
// if the peer failed to start. In the event of a successful connection, this
4252
// method reads the negotiated, local feature-bits and spawns the appropriate
4253
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4254
// be signaled of the new peer once the method returns.
4255
//
4256
// NOTE: This MUST be launched as a goroutine.
4257
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4258
        defer s.wg.Done()
3✔
4259

3✔
4260
        // Avoid initializing peers while the server is exiting.
3✔
4261
        if s.Stopped() {
3✔
4262
                return
×
4263
        }
×
4264

4265
        // Create a channel that will be used to signal a successful start of
4266
        // the link. This prevents the peer termination watcher from beginning
4267
        // its duty too early.
4268
        ready := make(chan struct{})
3✔
4269

3✔
4270
        // Before starting the peer, launch a goroutine to watch for the
3✔
4271
        // unexpected termination of this peer, which will ensure all resources
3✔
4272
        // are properly cleaned up, and re-establish persistent connections when
3✔
4273
        // necessary. The peer termination watcher will be short circuited if
3✔
4274
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4275
        // that the server has already handled the removal of this peer.
3✔
4276
        s.wg.Add(1)
3✔
4277
        go s.peerTerminationWatcher(p, ready)
3✔
4278

3✔
4279
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4280

3✔
4281
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4282
        // will unblock the peerTerminationWatcher.
3✔
4283
        if err := p.Start(); err != nil {
4✔
4284
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
1✔
4285

1✔
4286
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
1✔
4287
                return
1✔
4288
        }
1✔
4289

4290
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4291
        // was successful, and to begin watching the peer's wait group.
4292
        close(ready)
3✔
4293

3✔
4294
        s.mu.Lock()
3✔
4295
        defer s.mu.Unlock()
3✔
4296

3✔
4297
        // Check if there are listeners waiting for this peer to come online.
3✔
4298
        srvrLog.Debugf("Notifying that peer %v is online", p)
3✔
4299

3✔
4300
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4301
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4302
        pubStr := string(pubBytes)
3✔
4303
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4304
                select {
3✔
4305
                case peerChan <- p:
3✔
4306
                case <-s.quit:
×
4307
                        return
×
4308
                }
4309
        }
4310
        delete(s.peerConnectedListeners, pubStr)
3✔
4311
}
4312

4313
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4314
// and then cleans up all resources allocated to the peer, notifies relevant
4315
// sub-systems of its demise, and finally handles re-connecting to the peer if
4316
// it's persistent. If the server intentionally disconnects a peer, it should
4317
// have a corresponding entry in the ignorePeerTermination map which will cause
4318
// the cleanup routine to exit early. The passed `ready` chan is used to
4319
// synchronize when WaitForDisconnect should begin watching on the peer's
4320
// waitgroup. The ready chan should only be signaled if the peer starts
4321
// successfully, otherwise the peer should be disconnected instead.
4322
//
4323
// NOTE: This MUST be launched as a goroutine.
4324
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4325
        defer s.wg.Done()
3✔
4326

3✔
4327
        p.WaitForDisconnect(ready)
3✔
4328

3✔
4329
        srvrLog.Debugf("Peer %v has been disconnected", p)
3✔
4330

3✔
4331
        // If the server is exiting then we can bail out early ourselves as all
3✔
4332
        // the other sub-systems will already be shutting down.
3✔
4333
        if s.Stopped() {
6✔
4334
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4335
                return
3✔
4336
        }
3✔
4337

4338
        // Next, we'll cancel all pending funding reservations with this node.
4339
        // If we tried to initiate any funding flows that haven't yet finished,
4340
        // then we need to unlock those committed outputs so they're still
4341
        // available for use.
4342
        s.fundingMgr.CancelPeerReservations(p.PubKey())
3✔
4343

3✔
4344
        pubKey := p.IdentityKey()
3✔
4345

3✔
4346
        // We'll also inform the gossiper that this peer is no longer active,
3✔
4347
        // so we don't need to maintain sync state for it any longer.
3✔
4348
        s.authGossiper.PruneSyncState(p.PubKey())
3✔
4349

3✔
4350
        // Tell the switch to remove all links associated with this peer.
3✔
4351
        // Passing nil as the target link indicates that all links associated
3✔
4352
        // with this interface should be closed.
3✔
4353
        //
3✔
4354
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4355
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4356
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4357
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4358
        }
×
4359

4360
        for _, link := range links {
6✔
4361
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4362
        }
3✔
4363

4364
        s.mu.Lock()
3✔
4365
        defer s.mu.Unlock()
3✔
4366

3✔
4367
        // If there were any notification requests for when this peer
3✔
4368
        // disconnected, we can trigger them now.
3✔
4369
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4370
        pubStr := string(pubKey.SerializeCompressed())
3✔
4371
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4372
                close(offlineChan)
3✔
4373
        }
3✔
4374
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4375

3✔
4376
        // If the server has already removed this peer, we can short circuit the
3✔
4377
        // peer termination watcher and skip cleanup.
3✔
4378
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4379
                delete(s.ignorePeerTermination, p)
×
4380

×
4381
                pubKey := p.PubKey()
×
4382
                pubStr := string(pubKey[:])
×
4383

×
4384
                // If a connection callback is present, we'll go ahead and
×
4385
                // execute it now that previous peer has fully disconnected. If
×
4386
                // the callback is not present, this likely implies the peer was
×
4387
                // purposefully disconnected via RPC, and that no reconnect
×
4388
                // should be attempted.
×
4389
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4390
                if ok {
×
4391
                        delete(s.scheduledPeerConnection, pubStr)
×
4392
                        connCallback()
×
4393
                }
×
4394
                return
×
4395
        }
4396

4397
        // First, cleanup any remaining state the server has regarding the peer
4398
        // in question.
4399
        s.removePeer(p)
3✔
4400

3✔
4401
        // Next, check to see if this is a persistent peer or not.
3✔
4402
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4403
                return
3✔
4404
        }
3✔
4405

4406
        // Get the last address that we used to connect to the peer.
4407
        addrs := []net.Addr{
3✔
4408
                p.NetAddress().Address,
3✔
4409
        }
3✔
4410

3✔
4411
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4412
        // reconnection purposes.
3✔
4413
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4414
        switch {
3✔
4415
        // We found advertised addresses, so use them.
4416
        case err == nil:
3✔
4417
                addrs = advertisedAddrs
3✔
4418

4419
        // The peer doesn't have an advertised address.
4420
        case err == errNoAdvertisedAddr:
3✔
4421
                // If it is an outbound peer then we fall back to the existing
3✔
4422
                // peer address.
3✔
4423
                if !p.Inbound() {
6✔
4424
                        break
3✔
4425
                }
4426

4427
                // Fall back to the existing peer address if
4428
                // we're not accepting connections over Tor.
4429
                if s.torController == nil {
6✔
4430
                        break
3✔
4431
                }
4432

4433
                // If we are, the peer's address won't be known
4434
                // to us (we'll see a private address, which is
4435
                // the address used by our onion service to dial
4436
                // to lnd), so we don't have enough information
4437
                // to attempt a reconnect.
4438
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4439
                        "to inbound peer %v without "+
×
4440
                        "advertised address", p)
×
4441
                return
×
4442

4443
        // We came across an error retrieving an advertised
4444
        // address, log it, and fall back to the existing peer
4445
        // address.
4446
        default:
3✔
4447
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4448
                        "address for node %x: %v", p.PubKey(),
3✔
4449
                        err)
3✔
4450
        }
4451

4452
        // Make an easy lookup map so that we can check if an address
4453
        // is already in the address list that we have stored for this peer.
4454
        existingAddrs := make(map[string]bool)
3✔
4455
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4456
                existingAddrs[addr.String()] = true
3✔
4457
        }
3✔
4458

4459
        // Add any missing addresses for this peer to persistentPeerAddr.
4460
        for _, addr := range addrs {
6✔
4461
                if existingAddrs[addr.String()] {
3✔
4462
                        continue
×
4463
                }
4464

4465
                s.persistentPeerAddrs[pubStr] = append(
3✔
4466
                        s.persistentPeerAddrs[pubStr],
3✔
4467
                        &lnwire.NetAddress{
3✔
4468
                                IdentityKey: p.IdentityKey(),
3✔
4469
                                Address:     addr,
3✔
4470
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4471
                        },
3✔
4472
                )
3✔
4473
        }
4474

4475
        // Record the computed backoff in the backoff map.
4476
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4477
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4478

3✔
4479
        // Initialize a retry canceller for this peer if one does not
3✔
4480
        // exist.
3✔
4481
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4482
        if !ok {
6✔
4483
                cancelChan = make(chan struct{})
3✔
4484
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4485
        }
3✔
4486

4487
        // We choose not to wait group this go routine since the Connect
4488
        // call can stall for arbitrarily long if we shutdown while an
4489
        // outbound connection attempt is being made.
4490
        go func() {
6✔
4491
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4492
                        "persistent peer %x in %s",
3✔
4493
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4494

3✔
4495
                select {
3✔
4496
                case <-time.After(backoff):
3✔
4497
                case <-cancelChan:
3✔
4498
                        return
3✔
4499
                case <-s.quit:
3✔
4500
                        return
3✔
4501
                }
4502

4503
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4504
                        "connection to peer %x",
3✔
4505
                        p.IdentityKey().SerializeCompressed())
3✔
4506

3✔
4507
                s.connectToPersistentPeer(pubStr)
3✔
4508
        }()
4509
}
4510

4511
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4512
// to connect to the peer. It creates connection requests if there are
4513
// currently none for a given address and it removes old connection requests
4514
// if the associated address is no longer in the latest address list for the
4515
// peer.
4516
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4517
        s.mu.Lock()
3✔
4518
        defer s.mu.Unlock()
3✔
4519

3✔
4520
        // Create an easy lookup map of the addresses we have stored for the
3✔
4521
        // peer. We will remove entries from this map if we have existing
3✔
4522
        // connection requests for the associated address and then any leftover
3✔
4523
        // entries will indicate which addresses we should create new
3✔
4524
        // connection requests for.
3✔
4525
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4526
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4527
                addrMap[addr.String()] = addr
3✔
4528
        }
3✔
4529

4530
        // Go through each of the existing connection requests and
4531
        // check if they correspond to the latest set of addresses. If
4532
        // there is a connection requests that does not use one of the latest
4533
        // advertised addresses then remove that connection request.
4534
        var updatedConnReqs []*connmgr.ConnReq
3✔
4535
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4536
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4537

3✔
4538
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4539
                // If the existing connection request is using one of the
4540
                // latest advertised addresses for the peer then we add it to
4541
                // updatedConnReqs and remove the associated address from
4542
                // addrMap so that we don't recreate this connReq later on.
4543
                case true:
×
4544
                        updatedConnReqs = append(
×
4545
                                updatedConnReqs, connReq,
×
4546
                        )
×
4547
                        delete(addrMap, lnAddr)
×
4548

4549
                // If the existing connection request is using an address that
4550
                // is not one of the latest advertised addresses for the peer
4551
                // then we remove the connecting request from the connection
4552
                // manager.
4553
                case false:
3✔
4554
                        srvrLog.Info(
3✔
4555
                                "Removing conn req:", connReq.Addr.String(),
3✔
4556
                        )
3✔
4557
                        s.connMgr.Remove(connReq.ID())
3✔
4558
                }
4559
        }
4560

4561
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4562

3✔
4563
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4564
        if !ok {
6✔
4565
                cancelChan = make(chan struct{})
3✔
4566
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4567
        }
3✔
4568

4569
        // Any addresses left in addrMap are new ones that we have not made
4570
        // connection requests for. So create new connection requests for those.
4571
        // If there is more than one address in the address map, stagger the
4572
        // creation of the connection requests for those.
4573
        go func() {
6✔
4574
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4575
                defer ticker.Stop()
3✔
4576

3✔
4577
                for _, addr := range addrMap {
6✔
4578
                        // Send the persistent connection request to the
3✔
4579
                        // connection manager, saving the request itself so we
3✔
4580
                        // can cancel/restart the process as needed.
3✔
4581
                        connReq := &connmgr.ConnReq{
3✔
4582
                                Addr:      addr,
3✔
4583
                                Permanent: true,
3✔
4584
                        }
3✔
4585

3✔
4586
                        s.mu.Lock()
3✔
4587
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4588
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4589
                        )
3✔
4590
                        s.mu.Unlock()
3✔
4591

3✔
4592
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4593
                                "channel peer %v", addr)
3✔
4594

3✔
4595
                        go s.connMgr.Connect(connReq)
3✔
4596

3✔
4597
                        select {
3✔
4598
                        case <-s.quit:
3✔
4599
                                return
3✔
4600
                        case <-cancelChan:
3✔
4601
                                return
3✔
4602
                        case <-ticker.C:
3✔
4603
                        }
4604
                }
4605
        }()
4606
}
4607

4608
// removePeer removes the passed peer from the server's state of all active
4609
// peers.
4610
func (s *server) removePeer(p *peer.Brontide) {
3✔
4611
        if p == nil {
3✔
4612
                return
×
4613
        }
×
4614

4615
        srvrLog.Debugf("removing peer %v", p)
3✔
4616

3✔
4617
        // As the peer is now finished, ensure that the TCP connection is
3✔
4618
        // closed and all of its related goroutines have exited.
3✔
4619
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
3✔
4620

3✔
4621
        // If this peer had an active persistent connection request, remove it.
3✔
4622
        if p.ConnReq() != nil {
6✔
4623
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4624
        }
3✔
4625

4626
        // Ignore deleting peers if we're shutting down.
4627
        if s.Stopped() {
3✔
4628
                return
×
4629
        }
×
4630

4631
        pKey := p.PubKey()
3✔
4632
        pubSer := pKey[:]
3✔
4633
        pubStr := string(pubSer)
3✔
4634

3✔
4635
        delete(s.peersByPub, pubStr)
3✔
4636

3✔
4637
        if p.Inbound() {
6✔
4638
                delete(s.inboundPeers, pubStr)
3✔
4639
        } else {
6✔
4640
                delete(s.outboundPeers, pubStr)
3✔
4641
        }
3✔
4642

4643
        // Copy the peer's error buffer across to the server if it has any items
4644
        // in it so that we can restore peer errors across connections.
4645
        if p.ErrorBuffer().Total() > 0 {
6✔
4646
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4647
        }
3✔
4648

4649
        // Inform the peer notifier of a peer offline event so that it can be
4650
        // reported to clients listening for peer events.
4651
        var pubKey [33]byte
3✔
4652
        copy(pubKey[:], pubSer)
3✔
4653

3✔
4654
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4655
}
4656

4657
// ConnectToPeer requests that the server connect to a Lightning Network peer
4658
// at the specified address. This function will *block* until either a
4659
// connection is established, or the initial handshake process fails.
4660
//
4661
// NOTE: This function is safe for concurrent access.
4662
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4663
        perm bool, timeout time.Duration) error {
3✔
4664

3✔
4665
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4666

3✔
4667
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4668
        // better granularity.  In certain conditions, this method requires
3✔
4669
        // making an outbound connection to a remote peer, which requires the
3✔
4670
        // lock to be released, and subsequently reacquired.
3✔
4671
        s.mu.Lock()
3✔
4672

3✔
4673
        // Ensure we're not already connected to this peer.
3✔
4674
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4675
        if err == nil {
6✔
4676
                s.mu.Unlock()
3✔
4677
                return &errPeerAlreadyConnected{peer: peer}
3✔
4678
        }
3✔
4679

4680
        // Peer was not found, continue to pursue connection with peer.
4681

4682
        // If there's already a pending connection request for this pubkey,
4683
        // then we ignore this request to ensure we don't create a redundant
4684
        // connection.
4685
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4686
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4687
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4688
        }
3✔
4689

4690
        // If there's not already a pending or active connection to this node,
4691
        // then instruct the connection manager to attempt to establish a
4692
        // persistent connection to the peer.
4693
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4694
        if perm {
6✔
4695
                connReq := &connmgr.ConnReq{
3✔
4696
                        Addr:      addr,
3✔
4697
                        Permanent: true,
3✔
4698
                }
3✔
4699

3✔
4700
                // Since the user requested a permanent connection, we'll set
3✔
4701
                // the entry to true which will tell the server to continue
3✔
4702
                // reconnecting even if the number of channels with this peer is
3✔
4703
                // zero.
3✔
4704
                s.persistentPeers[targetPub] = true
3✔
4705
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
4706
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
4707
                }
3✔
4708
                s.persistentConnReqs[targetPub] = append(
3✔
4709
                        s.persistentConnReqs[targetPub], connReq,
3✔
4710
                )
3✔
4711
                s.mu.Unlock()
3✔
4712

3✔
4713
                go s.connMgr.Connect(connReq)
3✔
4714

3✔
4715
                return nil
3✔
4716
        }
4717
        s.mu.Unlock()
3✔
4718

3✔
4719
        // If we're not making a persistent connection, then we'll attempt to
3✔
4720
        // connect to the target peer. If the we can't make the connection, or
3✔
4721
        // the crypto negotiation breaks down, then return an error to the
3✔
4722
        // caller.
3✔
4723
        errChan := make(chan error, 1)
3✔
4724
        s.connectToPeer(addr, errChan, timeout)
3✔
4725

3✔
4726
        select {
3✔
4727
        case err := <-errChan:
3✔
4728
                return err
3✔
4729
        case <-s.quit:
×
4730
                return ErrServerShuttingDown
×
4731
        }
4732
}
4733

4734
// connectToPeer establishes a connection to a remote peer. errChan is used to
4735
// notify the caller if the connection attempt has failed. Otherwise, it will be
4736
// closed.
4737
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4738
        errChan chan<- error, timeout time.Duration) {
3✔
4739

3✔
4740
        conn, err := brontide.Dial(
3✔
4741
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
4742
        )
3✔
4743
        if err != nil {
6✔
4744
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
4745
                select {
3✔
4746
                case errChan <- err:
3✔
4747
                case <-s.quit:
×
4748
                }
4749
                return
3✔
4750
        }
4751

4752
        close(errChan)
3✔
4753

3✔
4754
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
4755
                conn.LocalAddr(), conn.RemoteAddr())
3✔
4756

3✔
4757
        s.OutboundPeerConnected(nil, conn)
3✔
4758
}
4759

4760
// DisconnectPeer sends the request to server to close the connection with peer
4761
// identified by public key.
4762
//
4763
// NOTE: This function is safe for concurrent access.
4764
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
4765
        pubBytes := pubKey.SerializeCompressed()
3✔
4766
        pubStr := string(pubBytes)
3✔
4767

3✔
4768
        s.mu.Lock()
3✔
4769
        defer s.mu.Unlock()
3✔
4770

3✔
4771
        // Check that were actually connected to this peer. If not, then we'll
3✔
4772
        // exit in an error as we can't disconnect from a peer that we're not
3✔
4773
        // currently connected to.
3✔
4774
        peer, err := s.findPeerByPubStr(pubStr)
3✔
4775
        if err == ErrPeerNotConnected {
6✔
4776
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
4777
        }
3✔
4778

4779
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
4780

3✔
4781
        s.cancelConnReqs(pubStr, nil)
3✔
4782

3✔
4783
        // If this peer was formerly a persistent connection, then we'll remove
3✔
4784
        // them from this map so we don't attempt to re-connect after we
3✔
4785
        // disconnect.
3✔
4786
        delete(s.persistentPeers, pubStr)
3✔
4787
        delete(s.persistentPeersBackoff, pubStr)
3✔
4788

3✔
4789
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
4790
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
4791
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
4792

3✔
4793
        return nil
3✔
4794
}
4795

4796
// OpenChannel sends a request to the server to open a channel to the specified
4797
// peer identified by nodeKey with the passed channel funding parameters.
4798
//
4799
// NOTE: This function is safe for concurrent access.
4800
func (s *server) OpenChannel(
4801
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
4802

3✔
4803
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
4804
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
4805
        // not blocked if the caller is not reading the updates.
3✔
4806
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
4807
        req.Err = make(chan error, 1)
3✔
4808

3✔
4809
        // First attempt to locate the target peer to open a channel with, if
3✔
4810
        // we're unable to locate the peer then this request will fail.
3✔
4811
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
4812
        s.mu.RLock()
3✔
4813
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
4814
        if !ok {
3✔
4815
                s.mu.RUnlock()
×
4816

×
4817
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4818
                return req.Updates, req.Err
×
4819
        }
×
4820
        req.Peer = peer
3✔
4821
        s.mu.RUnlock()
3✔
4822

3✔
4823
        // We'll wait until the peer is active before beginning the channel
3✔
4824
        // opening process.
3✔
4825
        select {
3✔
4826
        case <-peer.ActiveSignal():
3✔
4827
        case <-peer.QuitSignal():
×
4828
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4829
                return req.Updates, req.Err
×
4830
        case <-s.quit:
×
4831
                req.Err <- ErrServerShuttingDown
×
4832
                return req.Updates, req.Err
×
4833
        }
4834

4835
        // If the fee rate wasn't specified at this point we fail the funding
4836
        // because of the missing fee rate information. The caller of the
4837
        // `OpenChannel` method needs to make sure that default values for the
4838
        // fee rate are set beforehand.
4839
        if req.FundingFeePerKw == 0 {
3✔
4840
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4841
                        "the channel opening transaction")
×
4842

×
4843
                return req.Updates, req.Err
×
4844
        }
×
4845

4846
        // Spawn a goroutine to send the funding workflow request to the funding
4847
        // manager. This allows the server to continue handling queries instead
4848
        // of blocking on this request which is exported as a synchronous
4849
        // request to the outside world.
4850
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
4851

3✔
4852
        return req.Updates, req.Err
3✔
4853
}
4854

4855
// Peers returns a slice of all active peers.
4856
//
4857
// NOTE: This function is safe for concurrent access.
4858
func (s *server) Peers() []*peer.Brontide {
3✔
4859
        s.mu.RLock()
3✔
4860
        defer s.mu.RUnlock()
3✔
4861

3✔
4862
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
4863
        for _, peer := range s.peersByPub {
6✔
4864
                peers = append(peers, peer)
3✔
4865
        }
3✔
4866

4867
        return peers
3✔
4868
}
4869

4870
// computeNextBackoff uses a truncated exponential backoff to compute the next
4871
// backoff using the value of the exiting backoff. The returned duration is
4872
// randomized in either direction by 1/20 to prevent tight loops from
4873
// stabilizing.
4874
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
4875
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
4876
        nextBackoff := 2 * currBackoff
3✔
4877
        if nextBackoff > maxBackoff {
6✔
4878
                nextBackoff = maxBackoff
3✔
4879
        }
3✔
4880

4881
        // Using 1/10 of our duration as a margin, compute a random offset to
4882
        // avoid the nodes entering connection cycles.
4883
        margin := nextBackoff / 10
3✔
4884

3✔
4885
        var wiggle big.Int
3✔
4886
        wiggle.SetUint64(uint64(margin))
3✔
4887
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
4888
                // Randomizing is not mission critical, so we'll just return the
×
4889
                // current backoff.
×
4890
                return nextBackoff
×
4891
        }
×
4892

4893
        // Otherwise add in our wiggle, but subtract out half of the margin so
4894
        // that the backoff can tweaked by 1/20 in either direction.
4895
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
4896
}
4897

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

4902
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4903
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
4904
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
4905
        if err != nil {
3✔
4906
                return nil, err
×
4907
        }
×
4908

4909
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
4910
        if err != nil {
6✔
4911
                return nil, err
3✔
4912
        }
3✔
4913

4914
        if len(node.Addresses) == 0 {
6✔
4915
                return nil, errNoAdvertisedAddr
3✔
4916
        }
3✔
4917

4918
        return node.Addresses, nil
3✔
4919
}
4920

4921
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4922
// channel update for a target channel.
4923
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4924
        *lnwire.ChannelUpdate1, error) {
3✔
4925

3✔
4926
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
4927
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
4928
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
4929
                if err != nil {
6✔
4930
                        return nil, err
3✔
4931
                }
3✔
4932

4933
                return netann.ExtractChannelUpdate(
3✔
4934
                        ourPubKey[:], info, edge1, edge2,
3✔
4935
                )
3✔
4936
        }
4937
}
4938

4939
// applyChannelUpdate applies the channel update to the different sub-systems of
4940
// the server. The useAlias boolean denotes whether or not to send an alias in
4941
// place of the real SCID.
4942
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
4943
        op *wire.OutPoint, useAlias bool) error {
3✔
4944

3✔
4945
        var (
3✔
4946
                peerAlias    *lnwire.ShortChannelID
3✔
4947
                defaultAlias lnwire.ShortChannelID
3✔
4948
        )
3✔
4949

3✔
4950
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
4951

3✔
4952
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
4953
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
4954
        if useAlias {
6✔
4955
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
4956
                if foundAlias != defaultAlias {
6✔
4957
                        peerAlias = &foundAlias
3✔
4958
                }
3✔
4959
        }
4960

4961
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
4962
                update, discovery.RemoteAlias(peerAlias),
3✔
4963
        )
3✔
4964
        select {
3✔
4965
        case err := <-errChan:
3✔
4966
                return err
3✔
4967
        case <-s.quit:
×
4968
                return ErrServerShuttingDown
×
4969
        }
4970
}
4971

4972
// SendCustomMessage sends a custom message to the peer with the specified
4973
// pubkey.
4974
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
4975
        data []byte) error {
3✔
4976

3✔
4977
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
4978
        if err != nil {
3✔
4979
                return err
×
4980
        }
×
4981

4982
        // We'll wait until the peer is active.
4983
        select {
3✔
4984
        case <-peer.ActiveSignal():
3✔
4985
        case <-peer.QuitSignal():
×
4986
                return fmt.Errorf("peer %x disconnected", peerPub)
×
4987
        case <-s.quit:
×
4988
                return ErrServerShuttingDown
×
4989
        }
4990

4991
        msg, err := lnwire.NewCustom(msgType, data)
3✔
4992
        if err != nil {
6✔
4993
                return err
3✔
4994
        }
3✔
4995

4996
        // Send the message as low-priority. For now we assume that all
4997
        // application-defined message are low priority.
4998
        return peer.SendMessageLazy(true, msg)
3✔
4999
}
5000

5001
// newSweepPkScriptGen creates closure that generates a new public key script
5002
// which should be used to sweep any funds into the on-chain wallet.
5003
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5004
// (p2wkh) output.
5005
func newSweepPkScriptGen(
5006
        wallet lnwallet.WalletController,
5007
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5008

3✔
5009
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5010
                sweepAddr, err := wallet.NewAddress(
3✔
5011
                        lnwallet.TaprootPubkey, false,
3✔
5012
                        lnwallet.DefaultAccountName,
3✔
5013
                )
3✔
5014
                if err != nil {
3✔
5015
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5016
                }
×
5017

5018
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5019
                if err != nil {
3✔
5020
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5021
                }
×
5022

5023
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5024
                        wallet, netParams, addr,
3✔
5025
                )
3✔
5026
                if err != nil {
3✔
5027
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5028
                }
×
5029

5030
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5031
                        DeliveryAddress: addr,
3✔
5032
                        InternalKey:     internalKeyDesc,
3✔
5033
                })
3✔
5034
        }
5035
}
5036

5037
// shouldPeerBootstrap returns true if we should attempt to perform peer
5038
// bootstrapping to actively seek our peers using the set of active network
5039
// bootstrappers.
5040
func shouldPeerBootstrap(cfg *Config) bool {
9✔
5041
        isSimnet := cfg.Bitcoin.SimNet
9✔
5042
        isSignet := cfg.Bitcoin.SigNet
9✔
5043
        isRegtest := cfg.Bitcoin.RegTest
9✔
5044
        isDevNetwork := isSimnet || isSignet || isRegtest
9✔
5045

9✔
5046
        // TODO(yy): remove the check on simnet/regtest such that the itest is
9✔
5047
        // covering the bootstrapping process.
9✔
5048
        return !cfg.NoNetBootstrap && !isDevNetwork
9✔
5049
}
9✔
5050

5051
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5052
// finished.
5053
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5054
        // Get a list of closed channels.
3✔
5055
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5056
        if err != nil {
3✔
5057
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5058
                return nil
×
5059
        }
×
5060

5061
        // Save the SCIDs in a map.
5062
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5063
        for _, c := range channels {
6✔
5064
                // If the channel is not pending, its FC has been finalized.
3✔
5065
                if !c.IsPending {
6✔
5066
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5067
                }
3✔
5068
        }
5069

5070
        // Double check whether the reported closed channel has indeed finished
5071
        // closing.
5072
        //
5073
        // NOTE: There are misalignments regarding when a channel's FC is
5074
        // marked as finalized. We double check the pending channels to make
5075
        // sure the returned SCIDs are indeed terminated.
5076
        //
5077
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5078
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5079
        if err != nil {
3✔
5080
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5081
                return nil
×
5082
        }
×
5083

5084
        for _, c := range pendings {
6✔
5085
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5086
                        continue
3✔
5087
                }
5088

5089
                // If the channel is still reported as pending, remove it from
5090
                // the map.
5091
                delete(closedSCIDs, c.ShortChannelID)
×
5092

×
5093
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5094
                        c.ShortChannelID)
×
5095
        }
5096

5097
        return closedSCIDs
3✔
5098
}
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