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

lightningnetwork / lnd / 11131178835

01 Oct 2024 06:21PM UTC coverage: 58.814%. Remained the same
11131178835

push

github

web-flow
Merge pull request #9001 from ellemouton/namespacedMC

routing: Namespaced Mission Control

211 of 257 new or added lines in 8 files covered. (82.1%)

71 existing lines in 15 files now uncovered.

130409 of 221731 relevant lines covered (58.81%)

28194.48 hits per line

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

63.66
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

158
        start sync.Once
159
        stop  sync.Once
160

161
        cfg *Config
162

163
        implCfg *ImplementationCfg
164

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

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

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

176
        chanStatusMgr *netann.ChanStatusManager
177

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

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

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

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

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

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

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

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

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

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

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

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

242
        cc *chainreg.ChainControl
243

244
        fundingMgr *funding.Manager
245

246
        graphDB *channeldb.ChannelGraph
247

248
        chanStateDB *channeldb.ChannelStateDB
249

250
        addrSource chanbackup.AddressSource
251

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

256
        invoicesDB invoices.InvoiceDB
257

258
        aliasMgr *aliasmgr.Manager
259

260
        htlcSwitch *htlcswitch.Switch
261

262
        interceptableSwitch *htlcswitch.InterceptableSwitch
263

264
        invoices *invoices.InvoiceRegistry
265

266
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
267

268
        channelNotifier *channelnotifier.ChannelNotifier
269

270
        peerNotifier *peernotifier.PeerNotifier
271

272
        htlcNotifier *htlcswitch.HtlcNotifier
273

274
        witnessBeacon contractcourt.WitnessBeacon
275

276
        breachArbitrator *contractcourt.BreachArbitrator
277

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

281
        graphBuilder *graph.Builder
282

283
        chanRouter *routing.ChannelRouter
284

285
        controlTower routing.ControlTower
286

287
        authGossiper *discovery.AuthenticatedGossiper
288

289
        localChanMgr *localchans.Manager
290

291
        utxoNursery *contractcourt.UtxoNursery
292

293
        sweeper *sweep.UtxoSweeper
294

295
        chainArb *contractcourt.ChainArbitrator
296

297
        sphinx *hop.OnionProcessor
298

299
        towerClientMgr *wtclient.Manager
300

301
        connMgr *connmgr.ConnManager
302

303
        sigPool *lnwallet.SigPool
304

305
        writePool *pool.Write
306

307
        readPool *pool.Read
308

309
        tlsManager *TLSManager
310

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

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

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

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

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

333
        hostAnn *netann.HostAnnouncer
334

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

338
        customMessageServer *subscribe.Server
339

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

343
        quit chan struct{}
344

345
        wg sync.WaitGroup
346
}
347

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

356
        s.wg.Add(1)
4✔
357
        go func() {
8✔
358
                defer func() {
8✔
359
                        graphSub.Cancel()
4✔
360
                        s.wg.Done()
4✔
361
                }()
4✔
362

363
                for {
8✔
364
                        select {
4✔
365
                        case <-s.quit:
4✔
366
                                return
4✔
367

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

375
                                for _, update := range topChange.NodeUpdates {
8✔
376
                                        pubKeyStr := string(
4✔
377
                                                update.IdentityKey.
4✔
378
                                                        SerializeCompressed(),
4✔
379
                                        )
4✔
380

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

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

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

403
                                        s.mu.Lock()
4✔
404

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

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

419
                                        s.mu.Unlock()
4✔
420

4✔
421
                                        s.connectToPersistentPeer(pubKeyStr)
4✔
422
                                }
423
                        }
424
                }
425
        }()
426

427
        return nil
4✔
428
}
429

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
524
        // Initialize the sphinx router.
4✔
525
        replayLog := htlcswitch.NewDecayedLog(
4✔
526
                dbs.DecayedLogDB, cc.ChainNotifier,
4✔
527
        )
4✔
528
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
4✔
529

4✔
530
        writeBufferPool := pool.NewWriteBuffer(
4✔
531
                pool.DefaultWriteBufferGCInterval,
4✔
532
                pool.DefaultWriteBufferExpiryInterval,
4✔
533
        )
4✔
534

4✔
535
        writePool := pool.NewWrite(
4✔
536
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
4✔
537
        )
4✔
538

4✔
539
        readBufferPool := pool.NewReadBuffer(
4✔
540
                pool.DefaultReadBufferGCInterval,
4✔
541
                pool.DefaultReadBufferExpiryInterval,
4✔
542
        )
4✔
543

4✔
544
        readPool := pool.NewRead(
4✔
545
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
4✔
546
        )
4✔
547

4✔
548
        //nolint:lll
4✔
549
        featureMgr, err := feature.NewManager(feature.Config{
4✔
550
                NoTLVOnion:               cfg.ProtocolOptions.LegacyOnion(),
4✔
551
                NoStaticRemoteKey:        cfg.ProtocolOptions.NoStaticRemoteKey(),
4✔
552
                NoAnchors:                cfg.ProtocolOptions.NoAnchorCommitments(),
4✔
553
                NoWumbo:                  !cfg.ProtocolOptions.Wumbo(),
4✔
554
                NoScriptEnforcementLease: cfg.ProtocolOptions.NoScriptEnforcementLease(),
4✔
555
                NoKeysend:                !cfg.AcceptKeySend,
4✔
556
                NoOptionScidAlias:        !cfg.ProtocolOptions.ScidAlias(),
4✔
557
                NoZeroConf:               !cfg.ProtocolOptions.ZeroConf(),
4✔
558
                NoAnySegwit:              cfg.ProtocolOptions.NoAnySegwit(),
4✔
559
                CustomFeatures:           cfg.ProtocolOptions.CustomFeatures(),
4✔
560
                NoTaprootChans:           !cfg.ProtocolOptions.TaprootChans,
4✔
561
                NoRouteBlinding:          cfg.ProtocolOptions.NoRouteBlinding(),
4✔
562
        })
4✔
563
        if err != nil {
4✔
564
                return nil, err
×
565
        }
×
566

567
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
4✔
568
        registryConfig := invoices.RegistryConfig{
4✔
569
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
4✔
570
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
4✔
571
                Clock:                       clock.NewDefaultClock(),
4✔
572
                AcceptKeySend:               cfg.AcceptKeySend,
4✔
573
                AcceptAMP:                   cfg.AcceptAMP,
4✔
574
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
4✔
575
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
4✔
576
                KeysendHoldTime:             cfg.KeysendHoldTime,
4✔
577
                HtlcInterceptor:             invoiceHtlcModifier,
4✔
578
        }
4✔
579

4✔
580
        s := &server{
4✔
581
                cfg:            cfg,
4✔
582
                implCfg:        implCfg,
4✔
583
                graphDB:        dbs.GraphDB.ChannelGraph(),
4✔
584
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
4✔
585
                addrSource:     dbs.ChanStateDB,
4✔
586
                miscDB:         dbs.ChanStateDB,
4✔
587
                invoicesDB:     dbs.InvoiceDB,
4✔
588
                cc:             cc,
4✔
589
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
4✔
590
                writePool:      writePool,
4✔
591
                readPool:       readPool,
4✔
592
                chansToRestore: chansToRestore,
4✔
593

4✔
594
                channelNotifier: channelnotifier.New(
4✔
595
                        dbs.ChanStateDB.ChannelStateDB(),
4✔
596
                ),
4✔
597

4✔
598
                identityECDH:   nodeKeyECDH,
4✔
599
                identityKeyLoc: nodeKeyDesc.KeyLocator,
4✔
600
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
4✔
601

4✔
602
                listenAddrs: listenAddrs,
4✔
603

4✔
604
                // TODO(roasbeef): derive proper onion key based on rotation
4✔
605
                // schedule
4✔
606
                sphinx: hop.NewOnionProcessor(sphinxRouter),
4✔
607

4✔
608
                torController: torController,
4✔
609

4✔
610
                persistentPeers:         make(map[string]bool),
4✔
611
                persistentPeersBackoff:  make(map[string]time.Duration),
4✔
612
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
4✔
613
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
4✔
614
                persistentRetryCancels:  make(map[string]chan struct{}),
4✔
615
                peerErrors:              make(map[string]*queue.CircularBuffer),
4✔
616
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
4✔
617
                scheduledPeerConnection: make(map[string]func()),
4✔
618
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
4✔
619

4✔
620
                peersByPub:                make(map[string]*peer.Brontide),
4✔
621
                inboundPeers:              make(map[string]*peer.Brontide),
4✔
622
                outboundPeers:             make(map[string]*peer.Brontide),
4✔
623
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
4✔
624
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
4✔
625

4✔
626
                invoiceHtlcModifier: invoiceHtlcModifier,
4✔
627

4✔
628
                customMessageServer: subscribe.NewServer(),
4✔
629

4✔
630
                tlsManager: tlsManager,
4✔
631

4✔
632
                featureMgr: featureMgr,
4✔
633
                quit:       make(chan struct{}),
4✔
634
        }
4✔
635

4✔
636
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
4✔
637
        if err != nil {
4✔
638
                return nil, err
×
639
        }
×
640

641
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
4✔
642
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
4✔
643
                uint32(currentHeight), currentHash, cc.ChainNotifier,
4✔
644
        )
4✔
645
        s.invoices = invoices.NewRegistry(
4✔
646
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
4✔
647
        )
4✔
648

4✔
649
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
4✔
650

4✔
651
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
4✔
652
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
653

4✔
654
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
8✔
655
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
4✔
656
                if err != nil {
4✔
657
                        return err
×
658
                }
×
659

660
                s.htlcSwitch.UpdateLinkAliases(link)
4✔
661

4✔
662
                return nil
4✔
663
        }
664

665
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
4✔
666
        if err != nil {
4✔
667
                return nil, err
×
668
        }
×
669

670
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
4✔
671
                DB:                   dbs.ChanStateDB,
4✔
672
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
4✔
673
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
4✔
674
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
4✔
675
                LocalChannelClose: func(pubKey []byte,
4✔
676
                        request *htlcswitch.ChanClose) {
8✔
677

4✔
678
                        peer, err := s.FindPeerByPubStr(string(pubKey))
4✔
679
                        if err != nil {
4✔
680
                                srvrLog.Errorf("unable to close channel, peer"+
×
681
                                        " with %v id can't be found: %v",
×
682
                                        pubKey, err,
×
683
                                )
×
684
                                return
×
685
                        }
×
686

687
                        peer.HandleLocalCloseChanReqs(request)
4✔
688
                },
689
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
690
                SwitchPackager:         channeldb.NewSwitchPackager(),
691
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
692
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
693
                Notifier:               s.cc.ChainNotifier,
694
                HtlcNotifier:           s.htlcNotifier,
695
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
696
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
697
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
698
                AllowCircularRoute:     cfg.AllowCircularRoute,
699
                RejectHTLC:             cfg.RejectHTLC,
700
                Clock:                  clock.NewDefaultClock(),
701
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
702
                MaxFeeExposure:         thresholdMSats,
703
                SignAliasUpdate:        s.signAliasUpdate,
704
                IsAlias:                aliasmgr.IsAlias,
705
        }, uint32(currentHeight))
706
        if err != nil {
4✔
707
                return nil, err
×
708
        }
×
709
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
4✔
710
                &htlcswitch.InterceptableSwitchConfig{
4✔
711
                        Switch:             s.htlcSwitch,
4✔
712
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
4✔
713
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
4✔
714
                        RequireInterceptor: s.cfg.RequireInterceptor,
4✔
715
                        Notifier:           s.cc.ChainNotifier,
4✔
716
                },
4✔
717
        )
4✔
718
        if err != nil {
4✔
719
                return nil, err
×
720
        }
×
721

722
        s.witnessBeacon = newPreimageBeacon(
4✔
723
                dbs.ChanStateDB.NewWitnessCache(),
4✔
724
                s.interceptableSwitch.ForwardPacket,
4✔
725
        )
4✔
726

4✔
727
        chanStatusMgrCfg := &netann.ChanStatusConfig{
4✔
728
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
4✔
729
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
4✔
730
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
4✔
731
                OurPubKey:                nodeKeyDesc.PubKey,
4✔
732
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
4✔
733
                MessageSigner:            s.nodeSigner,
4✔
734
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
4✔
735
                ApplyChannelUpdate:       s.applyChannelUpdate,
4✔
736
                DB:                       s.chanStateDB,
4✔
737
                Graph:                    dbs.GraphDB.ChannelGraph(),
4✔
738
        }
4✔
739

4✔
740
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
4✔
741
        if err != nil {
4✔
742
                return nil, err
×
743
        }
×
744
        s.chanStatusMgr = chanStatusMgr
4✔
745

4✔
746
        // If enabled, use either UPnP or NAT-PMP to automatically configure
4✔
747
        // port forwarding for users behind a NAT.
4✔
748
        if cfg.NAT {
4✔
749
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
750

×
751
                discoveryTimeout := time.Duration(10 * time.Second)
×
752

×
753
                ctx, cancel := context.WithTimeout(
×
754
                        context.Background(), discoveryTimeout,
×
755
                )
×
756
                defer cancel()
×
757
                upnp, err := nat.DiscoverUPnP(ctx)
×
758
                if err == nil {
×
759
                        s.natTraversal = upnp
×
760
                } else {
×
761
                        // If we were not able to discover a UPnP enabled device
×
762
                        // on the local network, we'll fall back to attempting
×
763
                        // to discover a NAT-PMP enabled device.
×
764
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
765
                                "device on the local network: %v", err)
×
766

×
767
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
768
                                "enabled device")
×
769

×
770
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
771
                        if err != nil {
×
772
                                err := fmt.Errorf("unable to discover a "+
×
773
                                        "NAT-PMP enabled device on the local "+
×
774
                                        "network: %v", err)
×
775
                                srvrLog.Error(err)
×
776
                                return nil, err
×
777
                        }
×
778

779
                        s.natTraversal = pmp
×
780
                }
781
        }
782

783
        // If we were requested to automatically configure port forwarding,
784
        // we'll use the ports that the server will be listening on.
785
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
4✔
786
        for idx, ip := range cfg.ExternalIPs {
8✔
787
                externalIPStrings[idx] = ip.String()
4✔
788
        }
4✔
789
        if s.natTraversal != nil {
4✔
790
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
791
                for _, listenAddr := range listenAddrs {
×
792
                        // At this point, the listen addresses should have
×
793
                        // already been normalized, so it's safe to ignore the
×
794
                        // errors.
×
795
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
796
                        port, _ := strconv.Atoi(portStr)
×
797

×
798
                        listenPorts = append(listenPorts, uint16(port))
×
799
                }
×
800

801
                ips, err := s.configurePortForwarding(listenPorts...)
×
802
                if err != nil {
×
803
                        srvrLog.Errorf("Unable to automatically set up port "+
×
804
                                "forwarding using %s: %v",
×
805
                                s.natTraversal.Name(), err)
×
806
                } else {
×
807
                        srvrLog.Infof("Automatically set up port forwarding "+
×
808
                                "using %s to advertise external IP",
×
809
                                s.natTraversal.Name())
×
810
                        externalIPStrings = append(externalIPStrings, ips...)
×
811
                }
×
812
        }
813

814
        // If external IP addresses have been specified, add those to the list
815
        // of this server's addresses.
816
        externalIPs, err := lncfg.NormalizeAddresses(
4✔
817
                externalIPStrings, strconv.Itoa(defaultPeerPort),
4✔
818
                cfg.net.ResolveTCPAddr,
4✔
819
        )
4✔
820
        if err != nil {
4✔
821
                return nil, err
×
822
        }
×
823

824
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
4✔
825
        selfAddrs = append(selfAddrs, externalIPs...)
4✔
826

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

4✔
831
        // We'll now reconstruct a node announcement based on our current
4✔
832
        // configuration so we can send it out as a sort of heart beat within
4✔
833
        // the network.
4✔
834
        //
4✔
835
        // We'll start by parsing the node color from configuration.
4✔
836
        color, err := lncfg.ParseHexColor(cfg.Color)
4✔
837
        if err != nil {
4✔
838
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
839
                return nil, err
×
840
        }
×
841

842
        // If no alias is provided, default to first 10 characters of public
843
        // key.
844
        alias := cfg.Alias
4✔
845
        if alias == "" {
8✔
846
                alias = hex.EncodeToString(serializedPubKey[:10])
4✔
847
        }
4✔
848
        nodeAlias, err := lnwire.NewNodeAlias(alias)
4✔
849
        if err != nil {
4✔
850
                return nil, err
×
851
        }
×
852
        selfNode := &channeldb.LightningNode{
4✔
853
                HaveNodeAnnouncement: true,
4✔
854
                LastUpdate:           time.Now(),
4✔
855
                Addresses:            selfAddrs,
4✔
856
                Alias:                nodeAlias.String(),
4✔
857
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
4✔
858
                Color:                color,
4✔
859
        }
4✔
860
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
4✔
861

4✔
862
        // Based on the disk representation of the node announcement generated
4✔
863
        // above, we'll generate a node announcement that can go out on the
4✔
864
        // network so we can properly sign it.
4✔
865
        nodeAnn, err := selfNode.NodeAnnouncement(false)
4✔
866
        if err != nil {
4✔
867
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
868
        }
×
869

870
        // With the announcement generated, we'll sign it to properly
871
        // authenticate the message on the network.
872
        authSig, err := netann.SignAnnouncement(
4✔
873
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
4✔
874
        )
4✔
875
        if err != nil {
4✔
876
                return nil, fmt.Errorf("unable to generate signature for "+
×
877
                        "self node announcement: %v", err)
×
878
        }
×
879
        selfNode.AuthSigBytes = authSig.Serialize()
4✔
880
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
4✔
881
                selfNode.AuthSigBytes,
4✔
882
        )
4✔
883
        if err != nil {
4✔
884
                return nil, err
×
885
        }
×
886

887
        // Finally, we'll update the representation on disk, and update our
888
        // cached in-memory version as well.
889
        if err := chanGraph.SetSourceNode(selfNode); err != nil {
4✔
890
                return nil, fmt.Errorf("can't set self node: %w", err)
×
891
        }
×
892
        s.currentNodeAnn = nodeAnn
4✔
893

4✔
894
        // The router will get access to the payment ID sequencer, such that it
4✔
895
        // can generate unique payment IDs.
4✔
896
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
4✔
897
        if err != nil {
4✔
898
                return nil, err
×
899
        }
×
900

901
        // Instantiate mission control with config from the sub server.
902
        //
903
        // TODO(joostjager): When we are further in the process of moving to sub
904
        // servers, the mission control instance itself can be moved there too.
905
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
4✔
906

4✔
907
        // We only initialize a probability estimator if there's no custom one.
4✔
908
        var estimator routing.Estimator
4✔
909
        if cfg.Estimator != nil {
4✔
910
                estimator = cfg.Estimator
×
911
        } else {
4✔
912
                switch routingConfig.ProbabilityEstimatorType {
4✔
913
                case routing.AprioriEstimatorName:
4✔
914
                        aCfg := routingConfig.AprioriConfig
4✔
915
                        aprioriConfig := routing.AprioriConfig{
4✔
916
                                AprioriHopProbability: aCfg.HopProbability,
4✔
917
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
4✔
918
                                AprioriWeight:         aCfg.Weight,
4✔
919
                                CapacityFraction:      aCfg.CapacityFraction,
4✔
920
                        }
4✔
921

4✔
922
                        estimator, err = routing.NewAprioriEstimator(
4✔
923
                                aprioriConfig,
4✔
924
                        )
4✔
925
                        if err != nil {
4✔
926
                                return nil, err
×
927
                        }
×
928

929
                case routing.BimodalEstimatorName:
×
930
                        bCfg := routingConfig.BimodalConfig
×
931
                        bimodalConfig := routing.BimodalConfig{
×
932
                                BimodalNodeWeight: bCfg.NodeWeight,
×
933
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
934
                                        bCfg.Scale,
×
935
                                ),
×
936
                                BimodalDecayTime: bCfg.DecayTime,
×
937
                        }
×
938

×
939
                        estimator, err = routing.NewBimodalEstimator(
×
940
                                bimodalConfig,
×
941
                        )
×
942
                        if err != nil {
×
943
                                return nil, err
×
944
                        }
×
945

946
                default:
×
947
                        return nil, fmt.Errorf("unknown estimator type %v",
×
948
                                routingConfig.ProbabilityEstimatorType)
×
949
                }
950
        }
951

952
        mcCfg := &routing.MissionControlConfig{
4✔
953
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
4✔
954
                Estimator:               estimator,
4✔
955
                MaxMcHistory:            routingConfig.MaxMcHistory,
4✔
956
                McFlushInterval:         routingConfig.McFlushInterval,
4✔
957
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
4✔
958
        }
4✔
959

4✔
960
        s.missionController, err = routing.NewMissionController(
4✔
961
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
4✔
962
        )
4✔
963
        if err != nil {
4✔
NEW
964
                return nil, fmt.Errorf("can't create mission control "+
×
NEW
965
                        "manager: %w", err)
×
NEW
966
        }
×
967
        s.defaultMC, err = s.missionController.GetNamespacedStore(
4✔
968
                routing.DefaultMissionControlNamespace,
4✔
969
        )
4✔
970
        if err != nil {
4✔
NEW
971
                return nil, fmt.Errorf("can't create mission control in the "+
×
NEW
972
                        "default namespace: %w", err)
×
UNCOV
973
        }
×
974

975
        srvrLog.Debugf("Instantiating payment session source with config: "+
4✔
976
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
4✔
977
                int64(routingConfig.AttemptCost),
4✔
978
                float64(routingConfig.AttemptCostPPM)/10000,
4✔
979
                routingConfig.MinRouteProbability)
4✔
980

4✔
981
        pathFindingConfig := routing.PathFindingConfig{
4✔
982
                AttemptCost: lnwire.NewMSatFromSatoshis(
4✔
983
                        routingConfig.AttemptCost,
4✔
984
                ),
4✔
985
                AttemptCostPPM: routingConfig.AttemptCostPPM,
4✔
986
                MinProbability: routingConfig.MinRouteProbability,
4✔
987
        }
4✔
988

4✔
989
        sourceNode, err := chanGraph.SourceNode()
4✔
990
        if err != nil {
4✔
991
                return nil, fmt.Errorf("error getting source node: %w", err)
×
992
        }
×
993
        paymentSessionSource := &routing.SessionSource{
4✔
994
                GraphSessionFactory: graphsession.NewGraphSessionFactory(
4✔
995
                        chanGraph,
4✔
996
                ),
4✔
997
                SourceNode:        sourceNode,
4✔
998
                MissionControl:    s.defaultMC,
4✔
999
                GetLink:           s.htlcSwitch.GetLinkByShortID,
4✔
1000
                PathFindingConfig: pathFindingConfig,
4✔
1001
        }
4✔
1002

4✔
1003
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
4✔
1004

4✔
1005
        s.controlTower = routing.NewControlTower(paymentControl)
4✔
1006

4✔
1007
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
4✔
1008
                cfg.Routing.StrictZombiePruning
4✔
1009

4✔
1010
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
4✔
1011
                SelfNode:            selfNode.PubKeyBytes,
4✔
1012
                Graph:               chanGraph,
4✔
1013
                Chain:               cc.ChainIO,
4✔
1014
                ChainView:           cc.ChainView,
4✔
1015
                Notifier:            cc.ChainNotifier,
4✔
1016
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
4✔
1017
                GraphPruneInterval:  time.Hour,
4✔
1018
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
4✔
1019
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
4✔
1020
                StrictZombiePruning: strictPruning,
4✔
1021
                IsAlias:             aliasmgr.IsAlias,
4✔
1022
        })
4✔
1023
        if err != nil {
4✔
1024
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1025
        }
×
1026

1027
        s.chanRouter, err = routing.New(routing.Config{
4✔
1028
                SelfNode:           selfNode.PubKeyBytes,
4✔
1029
                RoutingGraph:       graphsession.NewRoutingGraph(chanGraph),
4✔
1030
                Chain:              cc.ChainIO,
4✔
1031
                Payer:              s.htlcSwitch,
4✔
1032
                Control:            s.controlTower,
4✔
1033
                MissionControl:     s.defaultMC,
4✔
1034
                SessionSource:      paymentSessionSource,
4✔
1035
                GetLink:            s.htlcSwitch.GetLinkByShortID,
4✔
1036
                NextPaymentID:      sequencer.NextID,
4✔
1037
                PathFindingConfig:  pathFindingConfig,
4✔
1038
                Clock:              clock.NewDefaultClock(),
4✔
1039
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
4✔
1040
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
4✔
1041
                TrafficShaper:      implCfg.TrafficShaper,
4✔
1042
        })
4✔
1043
        if err != nil {
4✔
1044
                return nil, fmt.Errorf("can't create router: %w", err)
×
1045
        }
×
1046

1047
        chanSeries := discovery.NewChanSeries(s.graphDB)
4✔
1048
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
4✔
1049
        if err != nil {
4✔
1050
                return nil, err
×
1051
        }
×
1052
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
4✔
1053
        if err != nil {
4✔
1054
                return nil, err
×
1055
        }
×
1056

1057
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
4✔
1058

4✔
1059
        s.authGossiper = discovery.New(discovery.Config{
4✔
1060
                Graph:                 s.graphBuilder,
4✔
1061
                ChainIO:               s.cc.ChainIO,
4✔
1062
                Notifier:              s.cc.ChainNotifier,
4✔
1063
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
4✔
1064
                Broadcast:             s.BroadcastMessage,
4✔
1065
                ChanSeries:            chanSeries,
4✔
1066
                NotifyWhenOnline:      s.NotifyWhenOnline,
4✔
1067
                NotifyWhenOffline:     s.NotifyWhenOffline,
4✔
1068
                FetchSelfAnnouncement: s.getNodeAnnouncement,
4✔
1069
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
4✔
1070
                        error) {
4✔
1071

×
1072
                        return s.genNodeAnnouncement(nil)
×
1073
                },
×
1074
                ProofMatureDelta:        0,
1075
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1076
                RetransmitTicker:        ticker.New(time.Minute * 30),
1077
                RebroadcastInterval:     time.Hour * 24,
1078
                WaitingProofStore:       waitingProofStore,
1079
                MessageStore:            gossipMessageStore,
1080
                AnnSigner:               s.nodeSigner,
1081
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1082
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1083
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1084
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:lll
1085
                MinimumBatchSize:        10,
1086
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1087
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1088
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1089
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1090
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1091
                IsAlias:                 aliasmgr.IsAlias,
1092
                SignAliasUpdate:         s.signAliasUpdate,
1093
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1094
                GetAlias:                s.aliasMgr.GetPeerAlias,
1095
                FindChannel:             s.findChannel,
1096
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1097
                ScidCloser:              scidCloserMan,
1098
        }, nodeKeyDesc)
1099

1100
        //nolint:lll
1101
        s.localChanMgr = &localchans.Manager{
4✔
1102
                ForAllOutgoingChannels:    s.graphBuilder.ForAllOutgoingChannels,
4✔
1103
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
4✔
1104
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
4✔
1105
                FetchChannel:              s.chanStateDB.FetchChannel,
4✔
1106
        }
4✔
1107

4✔
1108
        utxnStore, err := contractcourt.NewNurseryStore(
4✔
1109
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
4✔
1110
        )
4✔
1111
        if err != nil {
4✔
1112
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1113
                return nil, err
×
1114
        }
×
1115

1116
        sweeperStore, err := sweep.NewSweeperStore(
4✔
1117
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
4✔
1118
        )
4✔
1119
        if err != nil {
4✔
1120
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1121
                return nil, err
×
1122
        }
×
1123

1124
        aggregator := sweep.NewBudgetAggregator(
4✔
1125
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
4✔
1126
        )
4✔
1127

4✔
1128
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
4✔
1129
                Signer:    cc.Wallet.Cfg.Signer,
4✔
1130
                Wallet:    cc.Wallet,
4✔
1131
                Estimator: cc.FeeEstimator,
4✔
1132
                Notifier:  cc.ChainNotifier,
4✔
1133
        })
4✔
1134

4✔
1135
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
4✔
1136
                FeeEstimator:         cc.FeeEstimator,
4✔
1137
                GenSweepScript:       newSweepPkScriptGen(cc.Wallet),
4✔
1138
                Signer:               cc.Wallet.Cfg.Signer,
4✔
1139
                Wallet:               newSweeperWallet(cc.Wallet),
4✔
1140
                Mempool:              cc.MempoolNotifier,
4✔
1141
                Notifier:             cc.ChainNotifier,
4✔
1142
                Store:                sweeperStore,
4✔
1143
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
4✔
1144
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
4✔
1145
                Aggregator:           aggregator,
4✔
1146
                Publisher:            s.txPublisher,
4✔
1147
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
4✔
1148
        })
4✔
1149

4✔
1150
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
4✔
1151
                ChainIO:             cc.ChainIO,
4✔
1152
                ConfDepth:           1,
4✔
1153
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
4✔
1154
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
4✔
1155
                Notifier:            cc.ChainNotifier,
4✔
1156
                PublishTransaction:  cc.Wallet.PublishTransaction,
4✔
1157
                Store:               utxnStore,
4✔
1158
                SweepInput:          s.sweeper.SweepInput,
4✔
1159
                Budget:              s.cfg.Sweeper.Budget,
4✔
1160
        })
4✔
1161

4✔
1162
        // Construct a closure that wraps the htlcswitch's CloseLink method.
4✔
1163
        closeLink := func(chanPoint *wire.OutPoint,
4✔
1164
                closureType contractcourt.ChannelCloseType) {
8✔
1165
                // TODO(conner): Properly respect the update and error channels
4✔
1166
                // returned by CloseLink.
4✔
1167

4✔
1168
                // Instruct the switch to close the channel.  Provide no close out
4✔
1169
                // delivery script or target fee per kw because user input is not
4✔
1170
                // available when the remote peer closes the channel.
4✔
1171
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
4✔
1172
        }
4✔
1173

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

4✔
1178
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
4✔
1179
                &contractcourt.BreachConfig{
4✔
1180
                        CloseLink:          closeLink,
4✔
1181
                        DB:                 s.chanStateDB,
4✔
1182
                        Estimator:          s.cc.FeeEstimator,
4✔
1183
                        GenSweepScript:     newSweepPkScriptGen(cc.Wallet),
4✔
1184
                        Notifier:           cc.ChainNotifier,
4✔
1185
                        PublishTransaction: cc.Wallet.PublishTransaction,
4✔
1186
                        ContractBreaches:   contractBreaches,
4✔
1187
                        Signer:             cc.Wallet.Cfg.Signer,
4✔
1188
                        Store: contractcourt.NewRetributionStore(
4✔
1189
                                dbs.ChanStateDB,
4✔
1190
                        ),
4✔
1191
                },
4✔
1192
        )
4✔
1193

4✔
1194
        //nolint:lll
4✔
1195
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
4✔
1196
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
4✔
1197
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
4✔
1198
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
4✔
1199
                NewSweepAddr:           newSweepPkScriptGen(cc.Wallet),
4✔
1200
                PublishTx:              cc.Wallet.PublishTransaction,
4✔
1201
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
8✔
1202
                        for _, msg := range msgs {
8✔
1203
                                err := s.htlcSwitch.ProcessContractResolution(msg)
4✔
1204
                                if err != nil {
4✔
UNCOV
1205
                                        return err
×
UNCOV
1206
                                }
×
1207
                        }
1208
                        return nil
4✔
1209
                },
1210
                IncubateOutputs: func(chanPoint wire.OutPoint,
1211
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1212
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1213
                        broadcastHeight uint32,
1214
                        deadlineHeight fn.Option[int32]) error {
4✔
1215

4✔
1216
                        return s.utxoNursery.IncubateOutputs(
4✔
1217
                                chanPoint, outHtlcRes, inHtlcRes,
4✔
1218
                                broadcastHeight, deadlineHeight,
4✔
1219
                        )
4✔
1220
                },
4✔
1221
                PreimageDB:   s.witnessBeacon,
1222
                Notifier:     cc.ChainNotifier,
1223
                Mempool:      cc.MempoolNotifier,
1224
                Signer:       cc.Wallet.Cfg.Signer,
1225
                FeeEstimator: cc.FeeEstimator,
1226
                ChainIO:      cc.ChainIO,
1227
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
4✔
1228
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1229
                        s.htlcSwitch.RemoveLink(chanID)
4✔
1230
                        return nil
4✔
1231
                },
4✔
1232
                IsOurAddress: cc.Wallet.IsOurAddress,
1233
                ContractBreach: func(chanPoint wire.OutPoint,
1234
                        breachRet *lnwallet.BreachRetribution) error {
4✔
1235

4✔
1236
                        // processACK will handle the BreachArbitrator ACKing
4✔
1237
                        // the event.
4✔
1238
                        finalErr := make(chan error, 1)
4✔
1239
                        processACK := func(brarErr error) {
8✔
1240
                                if brarErr != nil {
4✔
1241
                                        finalErr <- brarErr
×
1242
                                        return
×
1243
                                }
×
1244

1245
                                // If the BreachArbitrator successfully handled
1246
                                // the event, we can signal that the handoff
1247
                                // was successful.
1248
                                finalErr <- nil
4✔
1249
                        }
1250

1251
                        event := &contractcourt.ContractBreachEvent{
4✔
1252
                                ChanPoint:         chanPoint,
4✔
1253
                                ProcessACK:        processACK,
4✔
1254
                                BreachRetribution: breachRet,
4✔
1255
                        }
4✔
1256

4✔
1257
                        // Send the contract breach event to the
4✔
1258
                        // BreachArbitrator.
4✔
1259
                        select {
4✔
1260
                        case contractBreaches <- event:
4✔
1261
                        case <-s.quit:
×
1262
                                return ErrServerShuttingDown
×
1263
                        }
1264

1265
                        // We'll wait for a final error to be available from
1266
                        // the BreachArbitrator.
1267
                        select {
4✔
1268
                        case err := <-finalErr:
4✔
1269
                                return err
4✔
1270
                        case <-s.quit:
×
1271
                                return ErrServerShuttingDown
×
1272
                        }
1273
                },
1274
                DisableChannel: func(chanPoint wire.OutPoint) error {
4✔
1275
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
4✔
1276
                },
4✔
1277
                Sweeper:                       s.sweeper,
1278
                Registry:                      s.invoices,
1279
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1280
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1281
                OnionProcessor:                s.sphinx,
1282
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1283
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1284
                Clock:                         clock.NewDefaultClock(),
1285
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1286
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1287
                HtlcNotifier:                  s.htlcNotifier,
1288
                Budget:                        *s.cfg.Sweeper.Budget,
1289

1290
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1291
                QueryIncomingCircuit: func(
1292
                        circuit models.CircuitKey) *models.CircuitKey {
4✔
1293

4✔
1294
                        // Get the circuit map.
4✔
1295
                        circuits := s.htlcSwitch.CircuitLookup()
4✔
1296

4✔
1297
                        // Lookup the outgoing circuit.
4✔
1298
                        pc := circuits.LookupOpenCircuit(circuit)
4✔
1299
                        if pc == nil {
8✔
1300
                                return nil
4✔
1301
                        }
4✔
1302

1303
                        return &pc.Incoming
4✔
1304
                },
1305
                AuxLeafStore: implCfg.AuxLeafStore,
1306
                AuxSigner:    implCfg.AuxSigner,
1307
        }, dbs.ChanStateDB)
1308

1309
        // Select the configuration and funding parameters for Bitcoin.
1310
        chainCfg := cfg.Bitcoin
4✔
1311
        minRemoteDelay := funding.MinBtcRemoteDelay
4✔
1312
        maxRemoteDelay := funding.MaxBtcRemoteDelay
4✔
1313

4✔
1314
        var chanIDSeed [32]byte
4✔
1315
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
4✔
1316
                return nil, err
×
1317
        }
×
1318

1319
        // Wrap the DeleteChannelEdges method so that the funding manager can
1320
        // use it without depending on several layers of indirection.
1321
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
4✔
1322
                *models.ChannelEdgePolicy, error) {
8✔
1323

4✔
1324
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
4✔
1325
                        scid.ToUint64(),
4✔
1326
                )
4✔
1327
                if errors.Is(err, channeldb.ErrEdgeNotFound) {
4✔
1328
                        // This is unlikely but there is a slim chance of this
×
1329
                        // being hit if lnd was killed via SIGKILL and the
×
1330
                        // funding manager was stepping through the delete
×
1331
                        // alias edge logic.
×
1332
                        return nil, nil
×
1333
                } else if err != nil {
4✔
1334
                        return nil, err
×
1335
                }
×
1336

1337
                // Grab our key to find our policy.
1338
                var ourKey [33]byte
4✔
1339
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
4✔
1340

4✔
1341
                var ourPolicy *models.ChannelEdgePolicy
4✔
1342
                if info != nil && info.NodeKey1Bytes == ourKey {
8✔
1343
                        ourPolicy = e1
4✔
1344
                } else {
8✔
1345
                        ourPolicy = e2
4✔
1346
                }
4✔
1347

1348
                if ourPolicy == nil {
4✔
1349
                        // Something is wrong, so return an error.
×
1350
                        return nil, fmt.Errorf("we don't have an edge")
×
1351
                }
×
1352

1353
                err = s.graphDB.DeleteChannelEdges(
4✔
1354
                        false, false, scid.ToUint64(),
4✔
1355
                )
4✔
1356
                return ourPolicy, err
4✔
1357
        }
1358

1359
        // For the reservationTimeout and the zombieSweeperInterval different
1360
        // values are set in case we are in a dev environment so enhance test
1361
        // capacilities.
1362
        reservationTimeout := chanfunding.DefaultReservationTimeout
4✔
1363
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
4✔
1364

4✔
1365
        // Get the development config for funding manager. If we are not in
4✔
1366
        // development mode, this would be nil.
4✔
1367
        var devCfg *funding.DevConfig
4✔
1368
        if lncfg.IsDevBuild() {
8✔
1369
                devCfg = &funding.DevConfig{
4✔
1370
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
4✔
1371
                }
4✔
1372

4✔
1373
                reservationTimeout = cfg.Dev.GetReservationTimeout()
4✔
1374
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
4✔
1375

4✔
1376
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
4✔
1377
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
4✔
1378
                        devCfg, reservationTimeout, zombieSweeperInterval)
4✔
1379
        }
4✔
1380

1381
        //nolint:lll
1382
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
4✔
1383
                Dev:                devCfg,
4✔
1384
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
4✔
1385
                IDKey:              nodeKeyDesc.PubKey,
4✔
1386
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
4✔
1387
                Wallet:             cc.Wallet,
4✔
1388
                PublishTransaction: cc.Wallet.PublishTransaction,
4✔
1389
                UpdateLabel: func(hash chainhash.Hash, label string) error {
8✔
1390
                        return cc.Wallet.LabelTransaction(hash, label, true)
4✔
1391
                },
4✔
1392
                Notifier:     cc.ChainNotifier,
1393
                ChannelDB:    s.chanStateDB,
1394
                FeeEstimator: cc.FeeEstimator,
1395
                SignMessage:  cc.MsgSigner.SignMessage,
1396
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1397
                        error) {
4✔
1398

4✔
1399
                        return s.genNodeAnnouncement(nil)
4✔
1400
                },
4✔
1401
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1402
                NotifyWhenOnline:     s.NotifyWhenOnline,
1403
                TempChanIDSeed:       chanIDSeed,
1404
                FindChannel:          s.findChannel,
1405
                DefaultRoutingPolicy: cc.RoutingPolicy,
1406
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1407
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1408
                        pushAmt lnwire.MilliSatoshi) uint16 {
4✔
1409
                        // For large channels we increase the number
4✔
1410
                        // of confirmations we require for the
4✔
1411
                        // channel to be considered open. As it is
4✔
1412
                        // always the responder that gets to choose
4✔
1413
                        // value, the pushAmt is value being pushed
4✔
1414
                        // to us. This means we have more to lose
4✔
1415
                        // in the case this gets re-orged out, and
4✔
1416
                        // we will require more confirmations before
4✔
1417
                        // we consider it open.
4✔
1418

4✔
1419
                        // In case the user has explicitly specified
4✔
1420
                        // a default value for the number of
4✔
1421
                        // confirmations, we use it.
4✔
1422
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
4✔
1423
                        if defaultConf != 0 {
8✔
1424
                                return defaultConf
4✔
1425
                        }
4✔
1426

1427
                        minConf := uint64(3)
×
1428
                        maxConf := uint64(6)
×
1429

×
1430
                        // If this is a wumbo channel, then we'll require the
×
1431
                        // max amount of confirmations.
×
1432
                        if chanAmt > MaxFundingAmount {
×
1433
                                return uint16(maxConf)
×
1434
                        }
×
1435

1436
                        // If not we return a value scaled linearly
1437
                        // between 3 and 6, depending on channel size.
1438
                        // TODO(halseth): Use 1 as minimum?
1439
                        maxChannelSize := uint64(
×
1440
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1441
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1442
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1443
                        if conf < minConf {
×
1444
                                conf = minConf
×
1445
                        }
×
1446
                        if conf > maxConf {
×
1447
                                conf = maxConf
×
1448
                        }
×
1449
                        return uint16(conf)
×
1450
                },
1451
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
4✔
1452
                        // We scale the remote CSV delay (the time the
4✔
1453
                        // remote have to claim funds in case of a unilateral
4✔
1454
                        // close) linearly from minRemoteDelay blocks
4✔
1455
                        // for small channels, to maxRemoteDelay blocks
4✔
1456
                        // for channels of size MaxFundingAmount.
4✔
1457

4✔
1458
                        // In case the user has explicitly specified
4✔
1459
                        // a default value for the remote delay, we
4✔
1460
                        // use it.
4✔
1461
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
4✔
1462
                        if defaultDelay > 0 {
8✔
1463
                                return defaultDelay
4✔
1464
                        }
4✔
1465

1466
                        // If this is a wumbo channel, then we'll require the
1467
                        // max value.
1468
                        if chanAmt > MaxFundingAmount {
×
1469
                                return maxRemoteDelay
×
1470
                        }
×
1471

1472
                        // If not we scale according to channel size.
1473
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1474
                                chanAmt / MaxFundingAmount)
×
1475
                        if delay < minRemoteDelay {
×
1476
                                delay = minRemoteDelay
×
1477
                        }
×
1478
                        if delay > maxRemoteDelay {
×
1479
                                delay = maxRemoteDelay
×
1480
                        }
×
1481
                        return delay
×
1482
                },
1483
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1484
                        peerKey *btcec.PublicKey) error {
4✔
1485

4✔
1486
                        // First, we'll mark this new peer as a persistent peer
4✔
1487
                        // for re-connection purposes. If the peer is not yet
4✔
1488
                        // tracked or the user hasn't requested it to be perm,
4✔
1489
                        // we'll set false to prevent the server from continuing
4✔
1490
                        // to connect to this peer even if the number of
4✔
1491
                        // channels with this peer is zero.
4✔
1492
                        s.mu.Lock()
4✔
1493
                        pubStr := string(peerKey.SerializeCompressed())
4✔
1494
                        if _, ok := s.persistentPeers[pubStr]; !ok {
8✔
1495
                                s.persistentPeers[pubStr] = false
4✔
1496
                        }
4✔
1497
                        s.mu.Unlock()
4✔
1498

4✔
1499
                        // With that taken care of, we'll send this channel to
4✔
1500
                        // the chain arb so it can react to on-chain events.
4✔
1501
                        return s.chainArb.WatchNewChannel(channel)
4✔
1502
                },
1503
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
4✔
1504
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1505
                        return s.htlcSwitch.UpdateShortChanID(cid)
4✔
1506
                },
4✔
1507
                RequiredRemoteChanReserve: func(chanAmt,
1508
                        dustLimit btcutil.Amount) btcutil.Amount {
4✔
1509

4✔
1510
                        // By default, we'll require the remote peer to maintain
4✔
1511
                        // at least 1% of the total channel capacity at all
4✔
1512
                        // times. If this value ends up dipping below the dust
4✔
1513
                        // limit, then we'll use the dust limit itself as the
4✔
1514
                        // reserve as required by BOLT #2.
4✔
1515
                        reserve := chanAmt / 100
4✔
1516
                        if reserve < dustLimit {
8✔
1517
                                reserve = dustLimit
4✔
1518
                        }
4✔
1519

1520
                        return reserve
4✔
1521
                },
1522
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
4✔
1523
                        // By default, we'll allow the remote peer to fully
4✔
1524
                        // utilize the full bandwidth of the channel, minus our
4✔
1525
                        // required reserve.
4✔
1526
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
4✔
1527
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
4✔
1528
                },
4✔
1529
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
4✔
1530
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
8✔
1531
                                return cfg.DefaultRemoteMaxHtlcs
4✔
1532
                        }
4✔
1533

1534
                        // By default, we'll permit them to utilize the full
1535
                        // channel bandwidth.
1536
                        return uint16(input.MaxHTLCNumber / 2)
×
1537
                },
1538
                ZombieSweeperInterval:         zombieSweeperInterval,
1539
                ReservationTimeout:            reservationTimeout,
1540
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1541
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1542
                MaxPendingChannels:            cfg.MaxPendingChannels,
1543
                RejectPush:                    cfg.RejectPush,
1544
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1545
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1546
                OpenChannelPredicate:          chanPredicate,
1547
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1548
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1549
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1550
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1551
                DeleteAliasEdge:      deleteAliasEdge,
1552
                AliasManager:         s.aliasMgr,
1553
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1554
                AuxFundingController: implCfg.AuxFundingController,
1555
                AuxSigner:            implCfg.AuxSigner,
1556
        })
1557
        if err != nil {
4✔
1558
                return nil, err
×
1559
        }
×
1560

1561
        // Next, we'll assemble the sub-system that will maintain an on-disk
1562
        // static backup of the latest channel state.
1563
        chanNotifier := &channelNotifier{
4✔
1564
                chanNotifier: s.channelNotifier,
4✔
1565
                addrs:        dbs.ChanStateDB,
4✔
1566
        }
4✔
1567
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
4✔
1568
        startingChans, err := chanbackup.FetchStaticChanBackups(
4✔
1569
                s.chanStateDB, s.addrSource,
4✔
1570
        )
4✔
1571
        if err != nil {
4✔
1572
                return nil, err
×
1573
        }
×
1574
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
4✔
1575
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
4✔
1576
        )
4✔
1577
        if err != nil {
4✔
1578
                return nil, err
×
1579
        }
×
1580

1581
        // Assemble a peer notifier which will provide clients with subscriptions
1582
        // to peer online and offline events.
1583
        s.peerNotifier = peernotifier.New()
4✔
1584

4✔
1585
        // Create a channel event store which monitors all open channels.
4✔
1586
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
4✔
1587
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
8✔
1588
                        return s.channelNotifier.SubscribeChannelEvents()
4✔
1589
                },
4✔
1590
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
4✔
1591
                        return s.peerNotifier.SubscribePeerEvents()
4✔
1592
                },
4✔
1593
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1594
                Clock:           clock.NewDefaultClock(),
1595
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1596
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1597
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1598
        })
1599

1600
        if cfg.WtClient.Active {
8✔
1601
                policy := wtpolicy.DefaultPolicy()
4✔
1602
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
4✔
1603

4✔
1604
                // We expose the sweep fee rate in sat/vbyte, but the tower
4✔
1605
                // protocol operations on sat/kw.
4✔
1606
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
4✔
1607
                        1000 * cfg.WtClient.SweepFeeRate,
4✔
1608
                )
4✔
1609

4✔
1610
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
4✔
1611

4✔
1612
                if err := policy.Validate(); err != nil {
4✔
1613
                        return nil, err
×
1614
                }
×
1615

1616
                // authDial is the wrapper around the btrontide.Dial for the
1617
                // watchtower.
1618
                authDial := func(localKey keychain.SingleKeyECDH,
4✔
1619
                        netAddr *lnwire.NetAddress,
4✔
1620
                        dialer tor.DialFunc) (wtserver.Peer, error) {
8✔
1621

4✔
1622
                        return brontide.Dial(
4✔
1623
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
4✔
1624
                        )
4✔
1625
                }
4✔
1626

1627
                // buildBreachRetribution is a call-back that can be used to
1628
                // query the BreachRetribution info and channel type given a
1629
                // channel ID and commitment height.
1630
                buildBreachRetribution := func(chanID lnwire.ChannelID,
4✔
1631
                        commitHeight uint64) (*lnwallet.BreachRetribution,
4✔
1632
                        channeldb.ChannelType, error) {
8✔
1633

4✔
1634
                        channel, err := s.chanStateDB.FetchChannelByID(
4✔
1635
                                nil, chanID,
4✔
1636
                        )
4✔
1637
                        if err != nil {
4✔
1638
                                return nil, 0, err
×
1639
                        }
×
1640

1641
                        br, err := lnwallet.NewBreachRetribution(
4✔
1642
                                channel, commitHeight, 0, nil,
4✔
1643
                                implCfg.AuxLeafStore,
4✔
1644
                        )
4✔
1645
                        if err != nil {
4✔
1646
                                return nil, 0, err
×
1647
                        }
×
1648

1649
                        return br, channel.ChanType, nil
4✔
1650
                }
1651

1652
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
4✔
1653

4✔
1654
                // Copy the policy for legacy channels and set the blob flag
4✔
1655
                // signalling support for anchor channels.
4✔
1656
                anchorPolicy := policy
4✔
1657
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
4✔
1658

4✔
1659
                // Copy the policy for legacy channels and set the blob flag
4✔
1660
                // signalling support for taproot channels.
4✔
1661
                taprootPolicy := policy
4✔
1662
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
4✔
1663
                        blob.FlagTaprootChannel,
4✔
1664
                )
4✔
1665

4✔
1666
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
4✔
1667
                        FetchClosedChannel:     fetchClosedChannel,
4✔
1668
                        BuildBreachRetribution: buildBreachRetribution,
4✔
1669
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
4✔
1670
                        ChainNotifier:          s.cc.ChainNotifier,
4✔
1671
                        SubscribeChannelEvents: func() (subscribe.Subscription,
4✔
1672
                                error) {
8✔
1673

4✔
1674
                                return s.channelNotifier.
4✔
1675
                                        SubscribeChannelEvents()
4✔
1676
                        },
4✔
1677
                        Signer:             cc.Wallet.Cfg.Signer,
1678
                        NewAddress:         newSweepPkScriptGen(cc.Wallet),
1679
                        SecretKeyRing:      s.cc.KeyRing,
1680
                        Dial:               cfg.net.Dial,
1681
                        AuthDial:           authDial,
1682
                        DB:                 dbs.TowerClientDB,
1683
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1684
                        MinBackoff:         10 * time.Second,
1685
                        MaxBackoff:         5 * time.Minute,
1686
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1687
                }, policy, anchorPolicy, taprootPolicy)
1688
                if err != nil {
4✔
1689
                        return nil, err
×
1690
                }
×
1691
        }
1692

1693
        if len(cfg.ExternalHosts) != 0 {
4✔
1694
                advertisedIPs := make(map[string]struct{})
×
1695
                for _, addr := range s.currentNodeAnn.Addresses {
×
1696
                        advertisedIPs[addr.String()] = struct{}{}
×
1697
                }
×
1698

1699
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1700
                        Hosts:         cfg.ExternalHosts,
×
1701
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1702
                        LookupHost: func(host string) (net.Addr, error) {
×
1703
                                return lncfg.ParseAddressString(
×
1704
                                        host, strconv.Itoa(defaultPeerPort),
×
1705
                                        cfg.net.ResolveTCPAddr,
×
1706
                                )
×
1707
                        },
×
1708
                        AdvertisedIPs: advertisedIPs,
1709
                        AnnounceNewIPs: netann.IPAnnouncer(
1710
                                func(modifier ...netann.NodeAnnModifier) (
1711
                                        lnwire.NodeAnnouncement, error) {
×
1712

×
1713
                                        return s.genNodeAnnouncement(
×
1714
                                                nil, modifier...,
×
1715
                                        )
×
1716
                                }),
×
1717
                })
1718
        }
1719

1720
        // Create liveness monitor.
1721
        s.createLivenessMonitor(cfg, cc, leaderElector)
4✔
1722

4✔
1723
        // Create the connection manager which will be responsible for
4✔
1724
        // maintaining persistent outbound connections and also accepting new
4✔
1725
        // incoming connections
4✔
1726
        cmgr, err := connmgr.New(&connmgr.Config{
4✔
1727
                Listeners:      listeners,
4✔
1728
                OnAccept:       s.InboundPeerConnected,
4✔
1729
                RetryDuration:  time.Second * 5,
4✔
1730
                TargetOutbound: 100,
4✔
1731
                Dial: noiseDial(
4✔
1732
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
4✔
1733
                ),
4✔
1734
                OnConnection: s.OutboundPeerConnected,
4✔
1735
        })
4✔
1736
        if err != nil {
4✔
1737
                return nil, err
×
1738
        }
×
1739
        s.connMgr = cmgr
4✔
1740

4✔
1741
        return s, nil
4✔
1742
}
1743

1744
// UpdateRoutingConfig is a callback function to update the routing config
1745
// values in the main cfg.
1746
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
4✔
1747
        routerCfg := s.cfg.SubRPCServers.RouterRPC
4✔
1748

4✔
1749
        switch c := cfg.Estimator.Config().(type) {
4✔
1750
        case routing.AprioriConfig:
4✔
1751
                routerCfg.ProbabilityEstimatorType =
4✔
1752
                        routing.AprioriEstimatorName
4✔
1753

4✔
1754
                targetCfg := routerCfg.AprioriConfig
4✔
1755
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
4✔
1756
                targetCfg.Weight = c.AprioriWeight
4✔
1757
                targetCfg.CapacityFraction = c.CapacityFraction
4✔
1758
                targetCfg.HopProbability = c.AprioriHopProbability
4✔
1759

1760
        case routing.BimodalConfig:
4✔
1761
                routerCfg.ProbabilityEstimatorType =
4✔
1762
                        routing.BimodalEstimatorName
4✔
1763

4✔
1764
                targetCfg := routerCfg.BimodalConfig
4✔
1765
                targetCfg.Scale = int64(c.BimodalScaleMsat)
4✔
1766
                targetCfg.NodeWeight = c.BimodalNodeWeight
4✔
1767
                targetCfg.DecayTime = c.BimodalDecayTime
4✔
1768
        }
1769

1770
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
4✔
1771
}
1772

1773
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1774
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1775
// may differ from what is on disk.
1776
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1777
        error) {
4✔
1778

4✔
1779
        data, err := u.DataToSign()
4✔
1780
        if err != nil {
4✔
1781
                return nil, err
×
1782
        }
×
1783

1784
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
4✔
1785
}
1786

1787
// createLivenessMonitor creates a set of health checks using our configured
1788
// values and uses these checks to create a liveness monitor. Available
1789
// health checks,
1790
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1791
//   - diskCheck
1792
//   - tlsHealthCheck
1793
//   - torController, only created when tor is enabled.
1794
//
1795
// If a health check has been disabled by setting attempts to 0, our monitor
1796
// will not run it.
1797
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1798
        leaderElector cluster.LeaderElector) {
4✔
1799

4✔
1800
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
4✔
1801
        if cfg.Bitcoin.Node == "nochainbackend" {
4✔
1802
                srvrLog.Info("Disabling chain backend checks for " +
×
1803
                        "nochainbackend mode")
×
1804

×
1805
                chainBackendAttempts = 0
×
1806
        }
×
1807

1808
        chainHealthCheck := healthcheck.NewObservation(
4✔
1809
                "chain backend",
4✔
1810
                cc.HealthCheck,
4✔
1811
                cfg.HealthChecks.ChainCheck.Interval,
4✔
1812
                cfg.HealthChecks.ChainCheck.Timeout,
4✔
1813
                cfg.HealthChecks.ChainCheck.Backoff,
4✔
1814
                chainBackendAttempts,
4✔
1815
        )
4✔
1816

4✔
1817
        diskCheck := healthcheck.NewObservation(
4✔
1818
                "disk space",
4✔
1819
                func() error {
4✔
1820
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1821
                                cfg.LndDir,
×
1822
                        )
×
1823
                        if err != nil {
×
1824
                                return err
×
1825
                        }
×
1826

1827
                        // If we have more free space than we require,
1828
                        // we return a nil error.
1829
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1830
                                return nil
×
1831
                        }
×
1832

1833
                        return fmt.Errorf("require: %v free space, got: %v",
×
1834
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1835
                                free)
×
1836
                },
1837
                cfg.HealthChecks.DiskCheck.Interval,
1838
                cfg.HealthChecks.DiskCheck.Timeout,
1839
                cfg.HealthChecks.DiskCheck.Backoff,
1840
                cfg.HealthChecks.DiskCheck.Attempts,
1841
        )
1842

1843
        tlsHealthCheck := healthcheck.NewObservation(
4✔
1844
                "tls",
4✔
1845
                func() error {
4✔
1846
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1847
                                s.cc.KeyRing,
×
1848
                        )
×
1849
                        if err != nil {
×
1850
                                return err
×
1851
                        }
×
1852
                        if expired {
×
1853
                                return fmt.Errorf("TLS certificate is "+
×
1854
                                        "expired as of %v", expTime)
×
1855
                        }
×
1856

1857
                        // If the certificate is not outdated, no error needs
1858
                        // to be returned
1859
                        return nil
×
1860
                },
1861
                cfg.HealthChecks.TLSCheck.Interval,
1862
                cfg.HealthChecks.TLSCheck.Timeout,
1863
                cfg.HealthChecks.TLSCheck.Backoff,
1864
                cfg.HealthChecks.TLSCheck.Attempts,
1865
        )
1866

1867
        checks := []*healthcheck.Observation{
4✔
1868
                chainHealthCheck, diskCheck, tlsHealthCheck,
4✔
1869
        }
4✔
1870

4✔
1871
        // If Tor is enabled, add the healthcheck for tor connection.
4✔
1872
        if s.torController != nil {
4✔
1873
                torConnectionCheck := healthcheck.NewObservation(
×
1874
                        "tor connection",
×
1875
                        func() error {
×
1876
                                return healthcheck.CheckTorServiceStatus(
×
1877
                                        s.torController,
×
1878
                                        s.createNewHiddenService,
×
1879
                                )
×
1880
                        },
×
1881
                        cfg.HealthChecks.TorConnection.Interval,
1882
                        cfg.HealthChecks.TorConnection.Timeout,
1883
                        cfg.HealthChecks.TorConnection.Backoff,
1884
                        cfg.HealthChecks.TorConnection.Attempts,
1885
                )
1886
                checks = append(checks, torConnectionCheck)
×
1887
        }
1888

1889
        // If remote signing is enabled, add the healthcheck for the remote
1890
        // signing RPC interface.
1891
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
8✔
1892
                // Because we have two cascading timeouts here, we need to add
4✔
1893
                // some slack to the "outer" one of them in case the "inner"
4✔
1894
                // returns exactly on time.
4✔
1895
                overhead := time.Millisecond * 10
4✔
1896

4✔
1897
                remoteSignerConnectionCheck := healthcheck.NewObservation(
4✔
1898
                        "remote signer connection",
4✔
1899
                        rpcwallet.HealthCheck(
4✔
1900
                                s.cfg.RemoteSigner,
4✔
1901

4✔
1902
                                // For the health check we might to be even
4✔
1903
                                // stricter than the initial/normal connect, so
4✔
1904
                                // we use the health check timeout here.
4✔
1905
                                cfg.HealthChecks.RemoteSigner.Timeout,
4✔
1906
                        ),
4✔
1907
                        cfg.HealthChecks.RemoteSigner.Interval,
4✔
1908
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
4✔
1909
                        cfg.HealthChecks.RemoteSigner.Backoff,
4✔
1910
                        cfg.HealthChecks.RemoteSigner.Attempts,
4✔
1911
                )
4✔
1912
                checks = append(checks, remoteSignerConnectionCheck)
4✔
1913
        }
4✔
1914

1915
        // If we have a leader elector, we add a health check to ensure we are
1916
        // still the leader. During normal operation, we should always be the
1917
        // leader, but there are circumstances where this may change, such as
1918
        // when we lose network connectivity for long enough expiring out lease.
1919
        if leaderElector != nil {
4✔
1920
                leaderCheck := healthcheck.NewObservation(
×
1921
                        "leader status",
×
1922
                        func() error {
×
1923
                                // Check if we are still the leader. Note that
×
1924
                                // we don't need to use a timeout context here
×
1925
                                // as the healthcheck observer will handle the
×
1926
                                // timeout case for us.
×
1927
                                timeoutCtx, cancel := context.WithTimeout(
×
1928
                                        context.Background(),
×
1929
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
1930
                                )
×
1931
                                defer cancel()
×
1932

×
1933
                                leader, err := leaderElector.IsLeader(
×
1934
                                        timeoutCtx,
×
1935
                                )
×
1936
                                if err != nil {
×
1937
                                        return fmt.Errorf("unable to check if "+
×
1938
                                                "still leader: %v", err)
×
1939
                                }
×
1940

1941
                                if !leader {
×
1942
                                        srvrLog.Debug("Not the current leader")
×
1943
                                        return fmt.Errorf("not the current " +
×
1944
                                                "leader")
×
1945
                                }
×
1946

1947
                                return nil
×
1948
                        },
1949
                        cfg.HealthChecks.LeaderCheck.Interval,
1950
                        cfg.HealthChecks.LeaderCheck.Timeout,
1951
                        cfg.HealthChecks.LeaderCheck.Backoff,
1952
                        cfg.HealthChecks.LeaderCheck.Attempts,
1953
                )
1954

1955
                checks = append(checks, leaderCheck)
×
1956
        }
1957

1958
        // If we have not disabled all of our health checks, we create a
1959
        // liveness monitor with our configured checks.
1960
        s.livenessMonitor = healthcheck.NewMonitor(
4✔
1961
                &healthcheck.Config{
4✔
1962
                        Checks:   checks,
4✔
1963
                        Shutdown: srvrLog.Criticalf,
4✔
1964
                },
4✔
1965
        )
4✔
1966
}
1967

1968
// Started returns true if the server has been started, and false otherwise.
1969
// NOTE: This function is safe for concurrent access.
1970
func (s *server) Started() bool {
4✔
1971
        return atomic.LoadInt32(&s.active) != 0
4✔
1972
}
4✔
1973

1974
// cleaner is used to aggregate "cleanup" functions during an operation that
1975
// starts several subsystems. In case one of the subsystem fails to start
1976
// and a proper resource cleanup is required, the "run" method achieves this
1977
// by running all these added "cleanup" functions.
1978
type cleaner []func() error
1979

1980
// add is used to add a cleanup function to be called when
1981
// the run function is executed.
1982
func (c cleaner) add(cleanup func() error) cleaner {
4✔
1983
        return append(c, cleanup)
4✔
1984
}
4✔
1985

1986
// run is used to run all the previousely added cleanup functions.
1987
func (c cleaner) run() {
×
1988
        for i := len(c) - 1; i >= 0; i-- {
×
1989
                if err := c[i](); err != nil {
×
1990
                        srvrLog.Infof("Cleanup failed: %v", err)
×
1991
                }
×
1992
        }
1993
}
1994

1995
// Start starts the main daemon server, all requested listeners, and any helper
1996
// goroutines.
1997
// NOTE: This function is safe for concurrent access.
1998
//
1999
//nolint:funlen
2000
func (s *server) Start() error {
4✔
2001
        var startErr error
4✔
2002

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

4✔
2008
        s.start.Do(func() {
8✔
2009
                cleanup = cleanup.add(s.customMessageServer.Stop)
4✔
2010
                if err := s.customMessageServer.Start(); err != nil {
4✔
2011
                        startErr = err
×
2012
                        return
×
2013
                }
×
2014

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

2023
                if s.livenessMonitor != nil {
8✔
2024
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
4✔
2025
                        if err := s.livenessMonitor.Start(); err != nil {
4✔
2026
                                startErr = err
×
2027
                                return
×
2028
                        }
×
2029
                }
2030

2031
                // Start the notification server. This is used so channel
2032
                // management goroutines can be notified when a funding
2033
                // transaction reaches a sufficient number of confirmations, or
2034
                // when the input for the funding transaction is spent in an
2035
                // attempt at an uncooperative close by the counterparty.
2036
                cleanup = cleanup.add(s.sigPool.Stop)
4✔
2037
                if err := s.sigPool.Start(); err != nil {
4✔
2038
                        startErr = err
×
2039
                        return
×
2040
                }
×
2041

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

2048
                cleanup = cleanup.add(s.readPool.Stop)
4✔
2049
                if err := s.readPool.Start(); err != nil {
4✔
2050
                        startErr = err
×
2051
                        return
×
2052
                }
×
2053

2054
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
4✔
2055
                if err := s.cc.ChainNotifier.Start(); err != nil {
4✔
2056
                        startErr = err
×
2057
                        return
×
2058
                }
×
2059

2060
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
4✔
2061
                if err := s.cc.BestBlockTracker.Start(); err != nil {
4✔
2062
                        startErr = err
×
2063
                        return
×
2064
                }
×
2065

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

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

2080
                cleanup = cleanup.add(s.htlcNotifier.Stop)
4✔
2081
                if err := s.htlcNotifier.Start(); err != nil {
4✔
2082
                        startErr = err
×
2083
                        return
×
2084
                }
×
2085

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

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

2100
                cleanup = cleanup.add(s.sweeper.Stop)
4✔
2101
                if err := s.sweeper.Start(); err != nil {
4✔
2102
                        startErr = err
×
2103
                        return
×
2104
                }
×
2105

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

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

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

2124
                // htlcSwitch must be started before chainArb since the latter
2125
                // relies on htlcSwitch to deliver resolution message upon
2126
                // start.
2127
                cleanup = cleanup.add(s.htlcSwitch.Stop)
4✔
2128
                if err := s.htlcSwitch.Start(); err != nil {
4✔
2129
                        startErr = err
×
2130
                        return
×
2131
                }
×
2132

2133
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
4✔
2134
                if err := s.interceptableSwitch.Start(); err != nil {
4✔
2135
                        startErr = err
×
2136
                        return
×
2137
                }
×
2138

2139
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
4✔
2140
                if err := s.invoiceHtlcModifier.Start(); err != nil {
4✔
2141
                        startErr = err
×
2142
                        return
×
2143
                }
×
2144

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

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

2157
                cleanup = cleanup.add(s.chanRouter.Stop)
4✔
2158
                if err := s.chanRouter.Start(); err != nil {
4✔
2159
                        startErr = err
×
2160
                        return
×
2161
                }
×
2162
                // The authGossiper depends on the chanRouter and therefore
2163
                // should be started after it.
2164
                cleanup = cleanup.add(s.authGossiper.Stop)
4✔
2165
                if err := s.authGossiper.Start(); err != nil {
4✔
2166
                        startErr = err
×
2167
                        return
×
2168
                }
×
2169

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

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

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

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

2194
                cleanup.add(func() error {
4✔
NEW
2195
                        s.missionController.StopStoreTickers()
×
2196
                        return nil
×
2197
                })
×
2198
                s.missionController.RunStoreTickers()
4✔
2199

4✔
2200
                // Before we start the connMgr, we'll check to see if we have
4✔
2201
                // any backups to recover. We do this now as we want to ensure
4✔
2202
                // that have all the information we need to handle channel
4✔
2203
                // recovery _before_ we even accept connections from any peers.
4✔
2204
                chanRestorer := &chanDBRestorer{
4✔
2205
                        db:         s.chanStateDB,
4✔
2206
                        secretKeys: s.cc.KeyRing,
4✔
2207
                        chainArb:   s.chainArb,
4✔
2208
                }
4✔
2209
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
4✔
2210
                        err := chanbackup.UnpackAndRecoverSingles(
×
2211
                                s.chansToRestore.PackedSingleChanBackups,
×
2212
                                s.cc.KeyRing, chanRestorer, s,
×
2213
                        )
×
2214
                        if err != nil {
×
2215
                                startErr = fmt.Errorf("unable to unpack single "+
×
2216
                                        "backups: %v", err)
×
2217
                                return
×
2218
                        }
×
2219
                }
2220
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
8✔
2221
                        err := chanbackup.UnpackAndRecoverMulti(
4✔
2222
                                s.chansToRestore.PackedMultiChanBackup,
4✔
2223
                                s.cc.KeyRing, chanRestorer, s,
4✔
2224
                        )
4✔
2225
                        if err != nil {
4✔
2226
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2227
                                        "backup: %v", err)
×
2228
                                return
×
2229
                        }
×
2230
                }
2231

2232
                // chanSubSwapper must be started after the `channelNotifier`
2233
                // because it depends on channel events as a synchronization
2234
                // point.
2235
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
4✔
2236
                if err := s.chanSubSwapper.Start(); err != nil {
4✔
2237
                        startErr = err
×
2238
                        return
×
2239
                }
×
2240

2241
                if s.torController != nil {
4✔
2242
                        cleanup = cleanup.add(s.torController.Stop)
×
2243
                        if err := s.createNewHiddenService(); err != nil {
×
2244
                                startErr = err
×
2245
                                return
×
2246
                        }
×
2247
                }
2248

2249
                if s.natTraversal != nil {
4✔
2250
                        s.wg.Add(1)
×
2251
                        go s.watchExternalIP()
×
2252
                }
×
2253

2254
                // Start connmgr last to prevent connections before init.
2255
                cleanup = cleanup.add(func() error {
4✔
2256
                        s.connMgr.Stop()
×
2257
                        return nil
×
2258
                })
×
2259
                s.connMgr.Start()
4✔
2260

4✔
2261
                // If peers are specified as a config option, we'll add those
4✔
2262
                // peers first.
4✔
2263
                for _, peerAddrCfg := range s.cfg.AddPeers {
8✔
2264
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
4✔
2265
                                peerAddrCfg,
4✔
2266
                        )
4✔
2267
                        if err != nil {
4✔
2268
                                startErr = fmt.Errorf("unable to parse peer "+
×
2269
                                        "pubkey from config: %v", err)
×
2270
                                return
×
2271
                        }
×
2272
                        addr, err := parseAddr(parsedHost, s.cfg.net)
4✔
2273
                        if err != nil {
4✔
2274
                                startErr = fmt.Errorf("unable to parse peer "+
×
2275
                                        "address provided as a config option: "+
×
2276
                                        "%v", err)
×
2277
                                return
×
2278
                        }
×
2279

2280
                        peerAddr := &lnwire.NetAddress{
4✔
2281
                                IdentityKey: parsedPubkey,
4✔
2282
                                Address:     addr,
4✔
2283
                                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
2284
                        }
4✔
2285

4✔
2286
                        err = s.ConnectToPeer(
4✔
2287
                                peerAddr, true,
4✔
2288
                                s.cfg.ConnectionTimeout,
4✔
2289
                        )
4✔
2290
                        if err != nil {
4✔
2291
                                startErr = fmt.Errorf("unable to connect to "+
×
2292
                                        "peer address provided as a config "+
×
2293
                                        "option: %v", err)
×
2294
                                return
×
2295
                        }
×
2296
                }
2297

2298
                // Subscribe to NodeAnnouncements that advertise new addresses
2299
                // our persistent peers.
2300
                if err := s.updatePersistentPeerAddrs(); err != nil {
4✔
2301
                        startErr = err
×
2302
                        return
×
2303
                }
×
2304

2305
                // With all the relevant sub-systems started, we'll now attempt
2306
                // to establish persistent connections to our direct channel
2307
                // collaborators within the network. Before doing so however,
2308
                // we'll prune our set of link nodes found within the database
2309
                // to ensure we don't reconnect to any nodes we no longer have
2310
                // open channels with.
2311
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
4✔
2312
                        startErr = err
×
2313
                        return
×
2314
                }
×
2315
                if err := s.establishPersistentConnections(); err != nil {
4✔
2316
                        startErr = err
×
2317
                        return
×
2318
                }
×
2319

2320
                // setSeedList is a helper function that turns multiple DNS seed
2321
                // server tuples from the command line or config file into the
2322
                // data structure we need and does a basic formal sanity check
2323
                // in the process.
2324
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
4✔
2325
                        if len(tuples) == 0 {
×
2326
                                return
×
2327
                        }
×
2328

2329
                        result := make([][2]string, len(tuples))
×
2330
                        for idx, tuple := range tuples {
×
2331
                                tuple = strings.TrimSpace(tuple)
×
2332
                                if len(tuple) == 0 {
×
2333
                                        return
×
2334
                                }
×
2335

2336
                                servers := strings.Split(tuple, ",")
×
2337
                                if len(servers) > 2 || len(servers) == 0 {
×
2338
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2339
                                                "seed tuple: %v", servers)
×
2340
                                        return
×
2341
                                }
×
2342

2343
                                copy(result[idx][:], servers)
×
2344
                        }
2345

2346
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2347
                }
2348

2349
                // Let users overwrite the DNS seed nodes. We only allow them
2350
                // for bitcoin mainnet/testnet/signet.
2351
                if s.cfg.Bitcoin.MainNet {
4✔
2352
                        setSeedList(
×
2353
                                s.cfg.Bitcoin.DNSSeeds,
×
2354
                                chainreg.BitcoinMainnetGenesis,
×
2355
                        )
×
2356
                }
×
2357
                if s.cfg.Bitcoin.TestNet3 {
4✔
2358
                        setSeedList(
×
2359
                                s.cfg.Bitcoin.DNSSeeds,
×
2360
                                chainreg.BitcoinTestnetGenesis,
×
2361
                        )
×
2362
                }
×
2363
                if s.cfg.Bitcoin.SigNet {
4✔
2364
                        setSeedList(
×
2365
                                s.cfg.Bitcoin.DNSSeeds,
×
2366
                                chainreg.BitcoinSignetGenesis,
×
2367
                        )
×
2368
                }
×
2369

2370
                // If network bootstrapping hasn't been disabled, then we'll
2371
                // configure the set of active bootstrappers, and launch a
2372
                // dedicated goroutine to maintain a set of persistent
2373
                // connections.
2374
                if shouldPeerBootstrap(s.cfg) {
4✔
2375
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2376
                        if err != nil {
×
2377
                                startErr = err
×
2378
                                return
×
2379
                        }
×
2380

2381
                        s.wg.Add(1)
×
2382
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2383
                } else {
4✔
2384
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
4✔
2385
                }
4✔
2386

2387
                // Set the active flag now that we've completed the full
2388
                // startup.
2389
                atomic.StoreInt32(&s.active, 1)
4✔
2390
        })
2391

2392
        if startErr != nil {
4✔
2393
                cleanup.run()
×
2394
        }
×
2395
        return startErr
4✔
2396
}
2397

2398
// Stop gracefully shutsdown the main daemon server. This function will signal
2399
// any active goroutines, or helper objects to exit, then blocks until they've
2400
// all successfully exited. Additionally, any/all listeners are closed.
2401
// NOTE: This function is safe for concurrent access.
2402
func (s *server) Stop() error {
4✔
2403
        s.stop.Do(func() {
8✔
2404
                atomic.StoreInt32(&s.stopping, 1)
4✔
2405

4✔
2406
                close(s.quit)
4✔
2407

4✔
2408
                // Shutdown connMgr first to prevent conns during shutdown.
4✔
2409
                s.connMgr.Stop()
4✔
2410

4✔
2411
                // Shutdown the wallet, funding manager, and the rpc server.
4✔
2412
                if err := s.chanStatusMgr.Stop(); err != nil {
4✔
2413
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2414
                }
×
2415
                if err := s.htlcSwitch.Stop(); err != nil {
4✔
2416
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2417
                }
×
2418
                if err := s.sphinx.Stop(); err != nil {
4✔
2419
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2420
                }
×
2421
                if err := s.invoices.Stop(); err != nil {
4✔
2422
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2423
                }
×
2424
                if err := s.interceptableSwitch.Stop(); err != nil {
4✔
2425
                        srvrLog.Warnf("failed to stop interceptable "+
×
2426
                                "switch: %v", err)
×
2427
                }
×
2428
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
4✔
2429
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2430
                                "modifier: %v", err)
×
2431
                }
×
2432
                if err := s.chanRouter.Stop(); err != nil {
4✔
2433
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2434
                }
×
2435
                if err := s.chainArb.Stop(); err != nil {
4✔
2436
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2437
                }
×
2438
                if err := s.fundingMgr.Stop(); err != nil {
4✔
2439
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2440
                }
×
2441
                if err := s.breachArbitrator.Stop(); err != nil {
4✔
2442
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2443
                                err)
×
2444
                }
×
2445
                if err := s.utxoNursery.Stop(); err != nil {
4✔
2446
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2447
                }
×
2448
                if err := s.authGossiper.Stop(); err != nil {
4✔
2449
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2450
                }
×
2451
                if err := s.sweeper.Stop(); err != nil {
4✔
2452
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2453
                }
×
2454
                if err := s.txPublisher.Stop(); err != nil {
4✔
2455
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2456
                }
×
2457
                if err := s.channelNotifier.Stop(); err != nil {
4✔
2458
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2459
                }
×
2460
                if err := s.peerNotifier.Stop(); err != nil {
4✔
2461
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2462
                }
×
2463
                if err := s.htlcNotifier.Stop(); err != nil {
4✔
2464
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2465
                }
×
2466
                if err := s.chanSubSwapper.Stop(); err != nil {
4✔
2467
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2468
                }
×
2469
                if err := s.cc.ChainNotifier.Stop(); err != nil {
4✔
2470
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2471
                }
×
2472
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
4✔
2473
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2474
                                err)
×
2475
                }
×
2476
                if err := s.chanEventStore.Stop(); err != nil {
4✔
2477
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2478
                                err)
×
2479
                }
×
2480
                s.missionController.StopStoreTickers()
4✔
2481

4✔
2482
                // Disconnect from each active peers to ensure that
4✔
2483
                // peerTerminationWatchers signal completion to each peer.
4✔
2484
                for _, peer := range s.Peers() {
8✔
2485
                        err := s.DisconnectPeer(peer.IdentityKey())
4✔
2486
                        if err != nil {
4✔
2487
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2488
                                        "received error: %v", peer.IdentityKey(),
×
2489
                                        err,
×
2490
                                )
×
2491
                        }
×
2492
                }
2493

2494
                // Now that all connections have been torn down, stop the tower
2495
                // client which will reliably flush all queued states to the
2496
                // tower. If this is halted for any reason, the force quit timer
2497
                // will kick in and abort to allow this method to return.
2498
                if s.towerClientMgr != nil {
8✔
2499
                        if err := s.towerClientMgr.Stop(); err != nil {
4✔
2500
                                srvrLog.Warnf("Unable to shut down tower "+
×
2501
                                        "client manager: %v", err)
×
2502
                        }
×
2503
                }
2504

2505
                if s.hostAnn != nil {
4✔
2506
                        if err := s.hostAnn.Stop(); err != nil {
×
2507
                                srvrLog.Warnf("unable to shut down host "+
×
2508
                                        "annoucner: %v", err)
×
2509
                        }
×
2510
                }
2511

2512
                if s.livenessMonitor != nil {
8✔
2513
                        if err := s.livenessMonitor.Stop(); err != nil {
4✔
2514
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2515
                                        "monitor: %v", err)
×
2516
                        }
×
2517
                }
2518

2519
                // Wait for all lingering goroutines to quit.
2520
                srvrLog.Debug("Waiting for server to shutdown...")
4✔
2521
                s.wg.Wait()
4✔
2522

4✔
2523
                srvrLog.Debug("Stopping buffer pools...")
4✔
2524
                s.sigPool.Stop()
4✔
2525
                s.writePool.Stop()
4✔
2526
                s.readPool.Stop()
4✔
2527
        })
2528

2529
        return nil
4✔
2530
}
2531

2532
// Stopped returns true if the server has been instructed to shutdown.
2533
// NOTE: This function is safe for concurrent access.
2534
func (s *server) Stopped() bool {
4✔
2535
        return atomic.LoadInt32(&s.stopping) != 0
4✔
2536
}
4✔
2537

2538
// configurePortForwarding attempts to set up port forwarding for the different
2539
// ports that the server will be listening on.
2540
//
2541
// NOTE: This should only be used when using some kind of NAT traversal to
2542
// automatically set up forwarding rules.
2543
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2544
        ip, err := s.natTraversal.ExternalIP()
×
2545
        if err != nil {
×
2546
                return nil, err
×
2547
        }
×
2548
        s.lastDetectedIP = ip
×
2549

×
2550
        externalIPs := make([]string, 0, len(ports))
×
2551
        for _, port := range ports {
×
2552
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2553
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2554
                        continue
×
2555
                }
2556

2557
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2558
                externalIPs = append(externalIPs, hostIP)
×
2559
        }
2560

2561
        return externalIPs, nil
×
2562
}
2563

2564
// removePortForwarding attempts to clear the forwarding rules for the different
2565
// ports the server is currently listening on.
2566
//
2567
// NOTE: This should only be used when using some kind of NAT traversal to
2568
// automatically set up forwarding rules.
2569
func (s *server) removePortForwarding() {
×
2570
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2571
        for _, port := range forwardedPorts {
×
2572
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2573
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2574
                                "port %d: %v", port, err)
×
2575
                }
×
2576
        }
2577
}
2578

2579
// watchExternalIP continuously checks for an updated external IP address every
2580
// 15 minutes. Once a new IP address has been detected, it will automatically
2581
// handle port forwarding rules and send updated node announcements to the
2582
// currently connected peers.
2583
//
2584
// NOTE: This MUST be run as a goroutine.
2585
func (s *server) watchExternalIP() {
×
2586
        defer s.wg.Done()
×
2587

×
2588
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2589
        // up by the server.
×
2590
        defer s.removePortForwarding()
×
2591

×
2592
        // Keep track of the external IPs set by the user to avoid replacing
×
2593
        // them when detecting a new IP.
×
2594
        ipsSetByUser := make(map[string]struct{})
×
2595
        for _, ip := range s.cfg.ExternalIPs {
×
2596
                ipsSetByUser[ip.String()] = struct{}{}
×
2597
        }
×
2598

2599
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2600

×
2601
        ticker := time.NewTicker(15 * time.Minute)
×
2602
        defer ticker.Stop()
×
2603
out:
×
2604
        for {
×
2605
                select {
×
2606
                case <-ticker.C:
×
2607
                        // We'll start off by making sure a new IP address has
×
2608
                        // been detected.
×
2609
                        ip, err := s.natTraversal.ExternalIP()
×
2610
                        if err != nil {
×
2611
                                srvrLog.Debugf("Unable to retrieve the "+
×
2612
                                        "external IP address: %v", err)
×
2613
                                continue
×
2614
                        }
2615

2616
                        // Periodically renew the NAT port forwarding.
2617
                        for _, port := range forwardedPorts {
×
2618
                                err := s.natTraversal.AddPortMapping(port)
×
2619
                                if err != nil {
×
2620
                                        srvrLog.Warnf("Unable to automatically "+
×
2621
                                                "re-create port forwarding using %s: %v",
×
2622
                                                s.natTraversal.Name(), err)
×
2623
                                } else {
×
2624
                                        srvrLog.Debugf("Automatically re-created "+
×
2625
                                                "forwarding for port %d using %s to "+
×
2626
                                                "advertise external IP",
×
2627
                                                port, s.natTraversal.Name())
×
2628
                                }
×
2629
                        }
2630

2631
                        if ip.Equal(s.lastDetectedIP) {
×
2632
                                continue
×
2633
                        }
2634

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

×
2637
                        // Next, we'll craft the new addresses that will be
×
2638
                        // included in the new node announcement and advertised
×
2639
                        // to the network. Each address will consist of the new
×
2640
                        // IP detected and one of the currently advertised
×
2641
                        // ports.
×
2642
                        var newAddrs []net.Addr
×
2643
                        for _, port := range forwardedPorts {
×
2644
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2645
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2646
                                if err != nil {
×
2647
                                        srvrLog.Debugf("Unable to resolve "+
×
2648
                                                "host %v: %v", addr, err)
×
2649
                                        continue
×
2650
                                }
2651

2652
                                newAddrs = append(newAddrs, addr)
×
2653
                        }
2654

2655
                        // Skip the update if we weren't able to resolve any of
2656
                        // the new addresses.
2657
                        if len(newAddrs) == 0 {
×
2658
                                srvrLog.Debug("Skipping node announcement " +
×
2659
                                        "update due to not being able to " +
×
2660
                                        "resolve any new addresses")
×
2661
                                continue
×
2662
                        }
2663

2664
                        // Now, we'll need to update the addresses in our node's
2665
                        // announcement in order to propagate the update
2666
                        // throughout the network. We'll only include addresses
2667
                        // that have a different IP from the previous one, as
2668
                        // the previous IP is no longer valid.
2669
                        currentNodeAnn := s.getNodeAnnouncement()
×
2670

×
2671
                        for _, addr := range currentNodeAnn.Addresses {
×
2672
                                host, _, err := net.SplitHostPort(addr.String())
×
2673
                                if err != nil {
×
2674
                                        srvrLog.Debugf("Unable to determine "+
×
2675
                                                "host from address %v: %v",
×
2676
                                                addr, err)
×
2677
                                        continue
×
2678
                                }
2679

2680
                                // We'll also make sure to include external IPs
2681
                                // set manually by the user.
2682
                                _, setByUser := ipsSetByUser[addr.String()]
×
2683
                                if setByUser || host != s.lastDetectedIP.String() {
×
2684
                                        newAddrs = append(newAddrs, addr)
×
2685
                                }
×
2686
                        }
2687

2688
                        // Then, we'll generate a new timestamped node
2689
                        // announcement with the updated addresses and broadcast
2690
                        // it to our peers.
2691
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2692
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2693
                        )
×
2694
                        if err != nil {
×
2695
                                srvrLog.Debugf("Unable to generate new node "+
×
2696
                                        "announcement: %v", err)
×
2697
                                continue
×
2698
                        }
2699

2700
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2701
                        if err != nil {
×
2702
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2703
                                        "announcement to peers: %v", err)
×
2704
                                continue
×
2705
                        }
2706

2707
                        // Finally, update the last IP seen to the current one.
2708
                        s.lastDetectedIP = ip
×
2709
                case <-s.quit:
×
2710
                        break out
×
2711
                }
2712
        }
2713
}
2714

2715
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2716
// based on the server, and currently active bootstrap mechanisms as defined
2717
// within the current configuration.
2718
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2719
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2720

×
2721
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2722

×
2723
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2724
        // this can be used by default if we've already partially seeded the
×
2725
        // network.
×
2726
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2727
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2728
        if err != nil {
×
2729
                return nil, err
×
2730
        }
×
2731
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2732

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

×
2738
                // If we have a set of DNS seeds for this chain, then we'll add
×
2739
                // it as an additional bootstrapping source.
×
2740
                if ok {
×
2741
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2742
                                "seeds: %v", dnsSeeds)
×
2743

×
2744
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2745
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2746
                        )
×
2747
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2748
                }
×
2749
        }
2750

2751
        return bootStrappers, nil
×
2752
}
2753

2754
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2755
// needs to ignore, which is made of three parts,
2756
//   - the node itself needs to be skipped as it doesn't make sense to connect
2757
//     to itself.
2758
//   - the peers that already have connections with, as in s.peersByPub.
2759
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2760
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2761
        s.mu.RLock()
×
2762
        defer s.mu.RUnlock()
×
2763

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

×
2766
        // We should ignore ourselves from bootstrapping.
×
2767
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2768
        ignore[selfKey] = struct{}{}
×
2769

×
2770
        // Ignore all connected peers.
×
2771
        for _, peer := range s.peersByPub {
×
2772
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2773
                ignore[nID] = struct{}{}
×
2774
        }
×
2775

2776
        // Ignore all persistent peers as they have a dedicated reconnecting
2777
        // process.
2778
        for pubKeyStr := range s.persistentPeers {
×
2779
                var nID autopilot.NodeID
×
2780
                copy(nID[:], []byte(pubKeyStr))
×
2781
                ignore[nID] = struct{}{}
×
2782
        }
×
2783

2784
        return ignore
×
2785
}
2786

2787
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2788
// and maintain a target minimum number of outbound connections. With this
2789
// invariant, we ensure that our node is connected to a diverse set of peers
2790
// and that nodes newly joining the network receive an up to date network view
2791
// as soon as possible.
2792
func (s *server) peerBootstrapper(numTargetPeers uint32,
2793
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2794

×
2795
        defer s.wg.Done()
×
2796

×
2797
        // Before we continue, init the ignore peers map.
×
2798
        ignoreList := s.createBootstrapIgnorePeers()
×
2799

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

×
2804
        // Once done, we'll attempt to maintain our target minimum number of
×
2805
        // peers.
×
2806
        //
×
2807
        // We'll use a 15 second backoff, and double the time every time an
×
2808
        // epoch fails up to a ceiling.
×
2809
        backOff := time.Second * 15
×
2810

×
2811
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2812
        // see if we've reached our minimum number of peers.
×
2813
        sampleTicker := time.NewTicker(backOff)
×
2814
        defer sampleTicker.Stop()
×
2815

×
2816
        // We'll use the number of attempts and errors to determine if we need
×
2817
        // to increase the time between discovery epochs.
×
2818
        var epochErrors uint32 // To be used atomically.
×
2819
        var epochAttempts uint32
×
2820

×
2821
        for {
×
2822
                select {
×
2823
                // The ticker has just woken us up, so we'll need to check if
2824
                // we need to attempt to connect our to any more peers.
2825
                case <-sampleTicker.C:
×
2826
                        // Obtain the current number of peers, so we can gauge
×
2827
                        // if we need to sample more peers or not.
×
2828
                        s.mu.RLock()
×
2829
                        numActivePeers := uint32(len(s.peersByPub))
×
2830
                        s.mu.RUnlock()
×
2831

×
2832
                        // If we have enough peers, then we can loop back
×
2833
                        // around to the next round as we're done here.
×
2834
                        if numActivePeers >= numTargetPeers {
×
2835
                                continue
×
2836
                        }
2837

2838
                        // If all of our attempts failed during this last back
2839
                        // off period, then will increase our backoff to 5
2840
                        // minute ceiling to avoid an excessive number of
2841
                        // queries
2842
                        //
2843
                        // TODO(roasbeef): add reverse policy too?
2844

2845
                        if epochAttempts > 0 &&
×
2846
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2847

×
2848
                                sampleTicker.Stop()
×
2849

×
2850
                                backOff *= 2
×
2851
                                if backOff > bootstrapBackOffCeiling {
×
2852
                                        backOff = bootstrapBackOffCeiling
×
2853
                                }
×
2854

2855
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2856
                                        "%v", backOff)
×
2857
                                sampleTicker = time.NewTicker(backOff)
×
2858
                                continue
×
2859
                        }
2860

2861
                        atomic.StoreUint32(&epochErrors, 0)
×
2862
                        epochAttempts = 0
×
2863

×
2864
                        // Since we know need more peers, we'll compute the
×
2865
                        // exact number we need to reach our threshold.
×
2866
                        numNeeded := numTargetPeers - numActivePeers
×
2867

×
2868
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2869
                                "peers", numNeeded)
×
2870

×
2871
                        // With the number of peers we need calculated, we'll
×
2872
                        // query the network bootstrappers to sample a set of
×
2873
                        // random addrs for us.
×
2874
                        //
×
2875
                        // Before we continue, get a copy of the ignore peers
×
2876
                        // map.
×
2877
                        ignoreList = s.createBootstrapIgnorePeers()
×
2878

×
2879
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2880
                                ignoreList, numNeeded*2, bootstrappers...,
×
2881
                        )
×
2882
                        if err != nil {
×
2883
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2884
                                        "peers: %v", err)
×
2885
                                continue
×
2886
                        }
2887

2888
                        // Finally, we'll launch a new goroutine for each
2889
                        // prospective peer candidates.
2890
                        for _, addr := range peerAddrs {
×
2891
                                epochAttempts++
×
2892

×
2893
                                go func(a *lnwire.NetAddress) {
×
2894
                                        // TODO(roasbeef): can do AS, subnet,
×
2895
                                        // country diversity, etc
×
2896
                                        errChan := make(chan error, 1)
×
2897
                                        s.connectToPeer(
×
2898
                                                a, errChan,
×
2899
                                                s.cfg.ConnectionTimeout,
×
2900
                                        )
×
2901
                                        select {
×
2902
                                        case err := <-errChan:
×
2903
                                                if err == nil {
×
2904
                                                        return
×
2905
                                                }
×
2906

2907
                                                srvrLog.Errorf("Unable to "+
×
2908
                                                        "connect to %v: %v",
×
2909
                                                        a, err)
×
2910
                                                atomic.AddUint32(&epochErrors, 1)
×
2911
                                        case <-s.quit:
×
2912
                                        }
2913
                                }(addr)
2914
                        }
2915
                case <-s.quit:
×
2916
                        return
×
2917
                }
2918
        }
2919
}
2920

2921
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
2922
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
2923
// query back off each time we encounter a failure.
2924
const bootstrapBackOffCeiling = time.Minute * 5
2925

2926
// initialPeerBootstrap attempts to continuously connect to peers on startup
2927
// until the target number of peers has been reached. This ensures that nodes
2928
// receive an up to date network view as soon as possible.
2929
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2930
        numTargetPeers uint32,
2931
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2932

×
2933
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
2934
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
2935

×
2936
        // We'll start off by waiting 2 seconds between failed attempts, then
×
2937
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
2938
        var delaySignal <-chan time.Time
×
2939
        delayTime := time.Second * 2
×
2940

×
2941
        // As want to be more aggressive, we'll use a lower back off celling
×
2942
        // then the main peer bootstrap logic.
×
2943
        backOffCeiling := bootstrapBackOffCeiling / 5
×
2944

×
2945
        for attempts := 0; ; attempts++ {
×
2946
                // Check if the server has been requested to shut down in order
×
2947
                // to prevent blocking.
×
2948
                if s.Stopped() {
×
2949
                        return
×
2950
                }
×
2951

2952
                // We can exit our aggressive initial peer bootstrapping stage
2953
                // if we've reached out target number of peers.
2954
                s.mu.RLock()
×
2955
                numActivePeers := uint32(len(s.peersByPub))
×
2956
                s.mu.RUnlock()
×
2957

×
2958
                if numActivePeers >= numTargetPeers {
×
2959
                        return
×
2960
                }
×
2961

2962
                if attempts > 0 {
×
2963
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
2964
                                "bootstrap peers (attempt #%v)", delayTime,
×
2965
                                attempts)
×
2966

×
2967
                        // We've completed at least one iterating and haven't
×
2968
                        // finished, so we'll start to insert a delay period
×
2969
                        // between each attempt.
×
2970
                        delaySignal = time.After(delayTime)
×
2971
                        select {
×
2972
                        case <-delaySignal:
×
2973
                        case <-s.quit:
×
2974
                                return
×
2975
                        }
2976

2977
                        // After our delay, we'll double the time we wait up to
2978
                        // the max back off period.
2979
                        delayTime *= 2
×
2980
                        if delayTime > backOffCeiling {
×
2981
                                delayTime = backOffCeiling
×
2982
                        }
×
2983
                }
2984

2985
                // Otherwise, we'll request for the remaining number of peers
2986
                // in order to reach our target.
2987
                peersNeeded := numTargetPeers - numActivePeers
×
2988
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
2989
                        ignore, peersNeeded, bootstrappers...,
×
2990
                )
×
2991
                if err != nil {
×
2992
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
2993
                                "peers: %v", err)
×
2994
                        continue
×
2995
                }
2996

2997
                // Then, we'll attempt to establish a connection to the
2998
                // different peer addresses retrieved by our bootstrappers.
2999
                var wg sync.WaitGroup
×
3000
                for _, bootstrapAddr := range bootstrapAddrs {
×
3001
                        wg.Add(1)
×
3002
                        go func(addr *lnwire.NetAddress) {
×
3003
                                defer wg.Done()
×
3004

×
3005
                                errChan := make(chan error, 1)
×
3006
                                go s.connectToPeer(
×
3007
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3008
                                )
×
3009

×
3010
                                // We'll only allow this connection attempt to
×
3011
                                // take up to 3 seconds. This allows us to move
×
3012
                                // quickly by discarding peers that are slowing
×
3013
                                // us down.
×
3014
                                select {
×
3015
                                case err := <-errChan:
×
3016
                                        if err == nil {
×
3017
                                                return
×
3018
                                        }
×
3019
                                        srvrLog.Errorf("Unable to connect to "+
×
3020
                                                "%v: %v", addr, err)
×
3021
                                // TODO: tune timeout? 3 seconds might be *too*
3022
                                // aggressive but works well.
3023
                                case <-time.After(3 * time.Second):
×
3024
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3025
                                                "to not establishing a "+
×
3026
                                                "connection within 3 seconds",
×
3027
                                                addr)
×
3028
                                case <-s.quit:
×
3029
                                }
3030
                        }(bootstrapAddr)
3031
                }
3032

3033
                wg.Wait()
×
3034
        }
3035
}
3036

3037
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3038
// order to listen for inbound connections over Tor.
3039
func (s *server) createNewHiddenService() error {
×
3040
        // Determine the different ports the server is listening on. The onion
×
3041
        // service's virtual port will map to these ports and one will be picked
×
3042
        // at random when the onion service is being accessed.
×
3043
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3044
        for _, listenAddr := range s.listenAddrs {
×
3045
                port := listenAddr.(*net.TCPAddr).Port
×
3046
                listenPorts = append(listenPorts, port)
×
3047
        }
×
3048

3049
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3050
        if err != nil {
×
3051
                return err
×
3052
        }
×
3053

3054
        // Once the port mapping has been set, we can go ahead and automatically
3055
        // create our onion service. The service's private key will be saved to
3056
        // disk in order to regain access to this service when restarting `lnd`.
3057
        onionCfg := tor.AddOnionConfig{
×
3058
                VirtualPort: defaultPeerPort,
×
3059
                TargetPorts: listenPorts,
×
3060
                Store: tor.NewOnionFile(
×
3061
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3062
                        encrypter,
×
3063
                ),
×
3064
        }
×
3065

×
3066
        switch {
×
3067
        case s.cfg.Tor.V2:
×
3068
                onionCfg.Type = tor.V2
×
3069
        case s.cfg.Tor.V3:
×
3070
                onionCfg.Type = tor.V3
×
3071
        }
3072

3073
        addr, err := s.torController.AddOnion(onionCfg)
×
3074
        if err != nil {
×
3075
                return err
×
3076
        }
×
3077

3078
        // Now that the onion service has been created, we'll add the onion
3079
        // address it can be reached at to our list of advertised addresses.
3080
        newNodeAnn, err := s.genNodeAnnouncement(
×
3081
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3082
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3083
                },
×
3084
        )
3085
        if err != nil {
×
3086
                return fmt.Errorf("unable to generate new node "+
×
3087
                        "announcement: %v", err)
×
3088
        }
×
3089

3090
        // Finally, we'll update the on-disk version of our announcement so it
3091
        // will eventually propagate to nodes in the network.
3092
        selfNode := &channeldb.LightningNode{
×
3093
                HaveNodeAnnouncement: true,
×
3094
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3095
                Addresses:            newNodeAnn.Addresses,
×
3096
                Alias:                newNodeAnn.Alias.String(),
×
3097
                Features: lnwire.NewFeatureVector(
×
3098
                        newNodeAnn.Features, lnwire.Features,
×
3099
                ),
×
3100
                Color:        newNodeAnn.RGBColor,
×
3101
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3102
        }
×
3103
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3104
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3105
                return fmt.Errorf("can't set self node: %w", err)
×
3106
        }
×
3107

3108
        return nil
×
3109
}
3110

3111
// findChannel finds a channel given a public key and ChannelID. It is an
3112
// optimization that is quicker than seeking for a channel given only the
3113
// ChannelID.
3114
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3115
        *channeldb.OpenChannel, error) {
4✔
3116

4✔
3117
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
4✔
3118
        if err != nil {
4✔
3119
                return nil, err
×
3120
        }
×
3121

3122
        for _, channel := range nodeChans {
8✔
3123
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
8✔
3124
                        return channel, nil
4✔
3125
                }
4✔
3126
        }
3127

3128
        return nil, fmt.Errorf("unable to find channel")
4✔
3129
}
3130

3131
// getNodeAnnouncement fetches the current, fully signed node announcement.
3132
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
4✔
3133
        s.mu.Lock()
4✔
3134
        defer s.mu.Unlock()
4✔
3135

4✔
3136
        return *s.currentNodeAnn
4✔
3137
}
4✔
3138

3139
// genNodeAnnouncement generates and returns the current fully signed node
3140
// announcement. The time stamp of the announcement will be updated in order
3141
// to ensure it propagates through the network.
3142
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3143
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
4✔
3144

4✔
3145
        s.mu.Lock()
4✔
3146
        defer s.mu.Unlock()
4✔
3147

4✔
3148
        // First, try to update our feature manager with the updated set of
4✔
3149
        // features.
4✔
3150
        if features != nil {
8✔
3151
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
4✔
3152
                        feature.SetNodeAnn: features,
4✔
3153
                }
4✔
3154
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
4✔
3155
                if err != nil {
8✔
3156
                        return lnwire.NodeAnnouncement{}, err
4✔
3157
                }
4✔
3158

3159
                // If we could successfully update our feature manager, add
3160
                // an update modifier to include these new features to our
3161
                // set.
3162
                modifiers = append(
4✔
3163
                        modifiers, netann.NodeAnnSetFeatures(features),
4✔
3164
                )
4✔
3165
        }
3166

3167
        // Always update the timestamp when refreshing to ensure the update
3168
        // propagates.
3169
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
4✔
3170

4✔
3171
        // Apply the requested changes to the node announcement.
4✔
3172
        for _, modifier := range modifiers {
8✔
3173
                modifier(s.currentNodeAnn)
4✔
3174
        }
4✔
3175

3176
        // Sign a new update after applying all of the passed modifiers.
3177
        err := netann.SignNodeAnnouncement(
4✔
3178
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
4✔
3179
        )
4✔
3180
        if err != nil {
4✔
3181
                return lnwire.NodeAnnouncement{}, err
×
3182
        }
×
3183

3184
        return *s.currentNodeAnn, nil
4✔
3185
}
3186

3187
// updateAndBrodcastSelfNode generates a new node announcement
3188
// applying the giving modifiers and updating the time stamp
3189
// to ensure it propagates through the network. Then it brodcasts
3190
// it to the network.
3191
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
3192
        modifiers ...netann.NodeAnnModifier) error {
4✔
3193

4✔
3194
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
4✔
3195
        if err != nil {
8✔
3196
                return fmt.Errorf("unable to generate new node "+
4✔
3197
                        "announcement: %v", err)
4✔
3198
        }
4✔
3199

3200
        // Update the on-disk version of our announcement.
3201
        // Load and modify self node istead of creating anew instance so we
3202
        // don't risk overwriting any existing values.
3203
        selfNode, err := s.graphDB.SourceNode()
4✔
3204
        if err != nil {
4✔
3205
                return fmt.Errorf("unable to get current source node: %w", err)
×
3206
        }
×
3207

3208
        selfNode.HaveNodeAnnouncement = true
4✔
3209
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
4✔
3210
        selfNode.Addresses = newNodeAnn.Addresses
4✔
3211
        selfNode.Alias = newNodeAnn.Alias.String()
4✔
3212
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
4✔
3213
        selfNode.Color = newNodeAnn.RGBColor
4✔
3214
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
4✔
3215

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

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

3222
        // Finally, propagate it to the nodes in the network.
3223
        err = s.BroadcastMessage(nil, &newNodeAnn)
4✔
3224
        if err != nil {
4✔
3225
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3226
                        "announcement to peers: %v", err)
×
3227
                return err
×
3228
        }
×
3229

3230
        return nil
4✔
3231
}
3232

3233
type nodeAddresses struct {
3234
        pubKey    *btcec.PublicKey
3235
        addresses []net.Addr
3236
}
3237

3238
// establishPersistentConnections attempts to establish persistent connections
3239
// to all our direct channel collaborators. In order to promote liveness of our
3240
// active channels, we instruct the connection manager to attempt to establish
3241
// and maintain persistent connections to all our direct channel counterparties.
3242
func (s *server) establishPersistentConnections() error {
4✔
3243
        // nodeAddrsMap stores the combination of node public keys and addresses
4✔
3244
        // that we'll attempt to reconnect to. PubKey strings are used as keys
4✔
3245
        // since other PubKey forms can't be compared.
4✔
3246
        nodeAddrsMap := map[string]*nodeAddresses{}
4✔
3247

4✔
3248
        // Iterate through the list of LinkNodes to find addresses we should
4✔
3249
        // attempt to connect to based on our set of previous connections. Set
4✔
3250
        // the reconnection port to the default peer port.
4✔
3251
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
4✔
3252
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
4✔
3253
                return err
×
3254
        }
×
3255
        for _, node := range linkNodes {
8✔
3256
                pubStr := string(node.IdentityPub.SerializeCompressed())
4✔
3257
                nodeAddrs := &nodeAddresses{
4✔
3258
                        pubKey:    node.IdentityPub,
4✔
3259
                        addresses: node.Addresses,
4✔
3260
                }
4✔
3261
                nodeAddrsMap[pubStr] = nodeAddrs
4✔
3262
        }
4✔
3263

3264
        // After checking our previous connections for addresses to connect to,
3265
        // iterate through the nodes in our channel graph to find addresses
3266
        // that have been added via NodeAnnouncement messages.
3267
        sourceNode, err := s.graphDB.SourceNode()
4✔
3268
        if err != nil {
4✔
3269
                return err
×
3270
        }
×
3271

3272
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3273
        // each of the nodes.
3274
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
4✔
3275
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
4✔
3276
                tx kvdb.RTx,
4✔
3277
                chanInfo *models.ChannelEdgeInfo,
4✔
3278
                policy, _ *models.ChannelEdgePolicy) error {
8✔
3279

4✔
3280
                // If the remote party has announced the channel to us, but we
4✔
3281
                // haven't yet, then we won't have a policy. However, we don't
4✔
3282
                // need this to connect to the peer, so we'll log it and move on.
4✔
3283
                if policy == nil {
4✔
3284
                        srvrLog.Warnf("No channel policy found for "+
×
3285
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3286
                }
×
3287

3288
                // We'll now fetch the peer opposite from us within this
3289
                // channel so we can queue up a direct connection to them.
3290
                channelPeer, err := s.graphDB.FetchOtherNode(
4✔
3291
                        tx, chanInfo, selfPub,
4✔
3292
                )
4✔
3293
                if err != nil {
4✔
3294
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3295
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3296
                                err)
×
3297
                }
×
3298

3299
                pubStr := string(channelPeer.PubKeyBytes[:])
4✔
3300

4✔
3301
                // Add all unique addresses from channel
4✔
3302
                // graph/NodeAnnouncements to the list of addresses we'll
4✔
3303
                // connect to for this peer.
4✔
3304
                addrSet := make(map[string]net.Addr)
4✔
3305
                for _, addr := range channelPeer.Addresses {
8✔
3306
                        switch addr.(type) {
4✔
3307
                        case *net.TCPAddr:
4✔
3308
                                addrSet[addr.String()] = addr
4✔
3309

3310
                        // We'll only attempt to connect to Tor addresses if Tor
3311
                        // outbound support is enabled.
3312
                        case *tor.OnionAddr:
×
3313
                                if s.cfg.Tor.Active {
×
3314
                                        addrSet[addr.String()] = addr
×
3315
                                }
×
3316
                        }
3317
                }
3318

3319
                // If this peer is also recorded as a link node, we'll add any
3320
                // additional addresses that have not already been selected.
3321
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
4✔
3322
                if ok {
8✔
3323
                        for _, lnAddress := range linkNodeAddrs.addresses {
8✔
3324
                                switch lnAddress.(type) {
4✔
3325
                                case *net.TCPAddr:
4✔
3326
                                        addrSet[lnAddress.String()] = lnAddress
4✔
3327

3328
                                // We'll only attempt to connect to Tor
3329
                                // addresses if Tor outbound support is enabled.
3330
                                case *tor.OnionAddr:
×
3331
                                        if s.cfg.Tor.Active {
×
3332
                                                addrSet[lnAddress.String()] = lnAddress
×
3333
                                        }
×
3334
                                }
3335
                        }
3336
                }
3337

3338
                // Construct a slice of the deduped addresses.
3339
                var addrs []net.Addr
4✔
3340
                for _, addr := range addrSet {
8✔
3341
                        addrs = append(addrs, addr)
4✔
3342
                }
4✔
3343

3344
                n := &nodeAddresses{
4✔
3345
                        addresses: addrs,
4✔
3346
                }
4✔
3347
                n.pubKey, err = channelPeer.PubKey()
4✔
3348
                if err != nil {
4✔
3349
                        return err
×
3350
                }
×
3351

3352
                nodeAddrsMap[pubStr] = n
4✔
3353
                return nil
4✔
3354
        })
3355
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
4✔
3356
                return err
×
3357
        }
×
3358

3359
        srvrLog.Debugf("Establishing %v persistent connections on start",
4✔
3360
                len(nodeAddrsMap))
4✔
3361

4✔
3362
        // Acquire and hold server lock until all persistent connection requests
4✔
3363
        // have been recorded and sent to the connection manager.
4✔
3364
        s.mu.Lock()
4✔
3365
        defer s.mu.Unlock()
4✔
3366

4✔
3367
        // Iterate through the combined list of addresses from prior links and
4✔
3368
        // node announcements and attempt to reconnect to each node.
4✔
3369
        var numOutboundConns int
4✔
3370
        for pubStr, nodeAddr := range nodeAddrsMap {
8✔
3371
                // Add this peer to the set of peers we should maintain a
4✔
3372
                // persistent connection with. We set the value to false to
4✔
3373
                // indicate that we should not continue to reconnect if the
4✔
3374
                // number of channels returns to zero, since this peer has not
4✔
3375
                // been requested as perm by the user.
4✔
3376
                s.persistentPeers[pubStr] = false
4✔
3377
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
8✔
3378
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
4✔
3379
                }
4✔
3380

3381
                for _, address := range nodeAddr.addresses {
8✔
3382
                        // Create a wrapper address which couples the IP and
4✔
3383
                        // the pubkey so the brontide authenticated connection
4✔
3384
                        // can be established.
4✔
3385
                        lnAddr := &lnwire.NetAddress{
4✔
3386
                                IdentityKey: nodeAddr.pubKey,
4✔
3387
                                Address:     address,
4✔
3388
                        }
4✔
3389

4✔
3390
                        s.persistentPeerAddrs[pubStr] = append(
4✔
3391
                                s.persistentPeerAddrs[pubStr], lnAddr)
4✔
3392
                }
4✔
3393

3394
                // We'll connect to the first 10 peers immediately, then
3395
                // randomly stagger any remaining connections if the
3396
                // stagger initial reconnect flag is set. This ensures
3397
                // that mobile nodes or nodes with a small number of
3398
                // channels obtain connectivity quickly, but larger
3399
                // nodes are able to disperse the costs of connecting to
3400
                // all peers at once.
3401
                if numOutboundConns < numInstantInitReconnect ||
4✔
3402
                        !s.cfg.StaggerInitialReconnect {
8✔
3403

4✔
3404
                        go s.connectToPersistentPeer(pubStr)
4✔
3405
                } else {
4✔
3406
                        go s.delayInitialReconnect(pubStr)
×
3407
                }
×
3408

3409
                numOutboundConns++
4✔
3410
        }
3411

3412
        return nil
4✔
3413
}
3414

3415
// delayInitialReconnect will attempt a reconnection to the given peer after
3416
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3417
//
3418
// NOTE: This method MUST be run as a goroutine.
3419
func (s *server) delayInitialReconnect(pubStr string) {
×
3420
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3421
        select {
×
3422
        case <-time.After(delay):
×
3423
                s.connectToPersistentPeer(pubStr)
×
3424
        case <-s.quit:
×
3425
        }
3426
}
3427

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

4✔
3434
        s.mu.Lock()
4✔
3435
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
8✔
3436
                delete(s.persistentPeers, pubKeyStr)
4✔
3437
                delete(s.persistentPeersBackoff, pubKeyStr)
4✔
3438
                delete(s.persistentPeerAddrs, pubKeyStr)
4✔
3439
                s.cancelConnReqs(pubKeyStr, nil)
4✔
3440
                s.mu.Unlock()
4✔
3441

4✔
3442
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
4✔
3443
                        "peer has no open channels", compressedPubKey)
4✔
3444

4✔
3445
                return
4✔
3446
        }
4✔
3447
        s.mu.Unlock()
4✔
3448
}
3449

3450
// BroadcastMessage sends a request to the server to broadcast a set of
3451
// messages to all peers other than the one specified by the `skips` parameter.
3452
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3453
// the target peers.
3454
//
3455
// NOTE: This function is safe for concurrent access.
3456
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3457
        msgs ...lnwire.Message) error {
4✔
3458

4✔
3459
        // Filter out peers found in the skips map. We synchronize access to
4✔
3460
        // peersByPub throughout this process to ensure we deliver messages to
4✔
3461
        // exact set of peers present at the time of invocation.
4✔
3462
        s.mu.RLock()
4✔
3463
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
3464
        for pubStr, sPeer := range s.peersByPub {
8✔
3465
                if skips != nil {
8✔
3466
                        if _, ok := skips[sPeer.PubKey()]; ok {
8✔
3467
                                srvrLog.Tracef("Skipping %x in broadcast with "+
4✔
3468
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
4✔
3469
                                continue
4✔
3470
                        }
3471
                }
3472

3473
                peers = append(peers, sPeer)
4✔
3474
        }
3475
        s.mu.RUnlock()
4✔
3476

4✔
3477
        // Iterate over all known peers, dispatching a go routine to enqueue
4✔
3478
        // all messages to each of peers.
4✔
3479
        var wg sync.WaitGroup
4✔
3480
        for _, sPeer := range peers {
8✔
3481
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
4✔
3482
                        sPeer.PubKey())
4✔
3483

4✔
3484
                // Dispatch a go routine to enqueue all messages to this peer.
4✔
3485
                wg.Add(1)
4✔
3486
                s.wg.Add(1)
4✔
3487
                go func(p lnpeer.Peer) {
8✔
3488
                        defer s.wg.Done()
4✔
3489
                        defer wg.Done()
4✔
3490

4✔
3491
                        p.SendMessageLazy(false, msgs...)
4✔
3492
                }(sPeer)
4✔
3493
        }
3494

3495
        // Wait for all messages to have been dispatched before returning to
3496
        // caller.
3497
        wg.Wait()
4✔
3498

4✔
3499
        return nil
4✔
3500
}
3501

3502
// NotifyWhenOnline can be called by other subsystems to get notified when a
3503
// particular peer comes online. The peer itself is sent across the peerChan.
3504
//
3505
// NOTE: This function is safe for concurrent access.
3506
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3507
        peerChan chan<- lnpeer.Peer) {
4✔
3508

4✔
3509
        s.mu.Lock()
4✔
3510

4✔
3511
        // Compute the target peer's identifier.
4✔
3512
        pubStr := string(peerKey[:])
4✔
3513

4✔
3514
        // Check if peer is connected.
4✔
3515
        peer, ok := s.peersByPub[pubStr]
4✔
3516
        if ok {
8✔
3517
                // Unlock here so that the mutex isn't held while we are
4✔
3518
                // waiting for the peer to become active.
4✔
3519
                s.mu.Unlock()
4✔
3520

4✔
3521
                // Wait until the peer signals that it is actually active
4✔
3522
                // rather than only in the server's maps.
4✔
3523
                select {
4✔
3524
                case <-peer.ActiveSignal():
4✔
3525
                case <-peer.QuitSignal():
×
3526
                        // The peer quit, so we'll add the channel to the slice
×
3527
                        // and return.
×
3528
                        s.mu.Lock()
×
3529
                        s.peerConnectedListeners[pubStr] = append(
×
3530
                                s.peerConnectedListeners[pubStr], peerChan,
×
3531
                        )
×
3532
                        s.mu.Unlock()
×
3533
                        return
×
3534
                }
3535

3536
                // Connected, can return early.
3537
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
4✔
3538

4✔
3539
                select {
4✔
3540
                case peerChan <- peer:
4✔
3541
                case <-s.quit:
×
3542
                }
3543

3544
                return
4✔
3545
        }
3546

3547
        // Not connected, store this listener such that it can be notified when
3548
        // the peer comes online.
3549
        s.peerConnectedListeners[pubStr] = append(
4✔
3550
                s.peerConnectedListeners[pubStr], peerChan,
4✔
3551
        )
4✔
3552
        s.mu.Unlock()
4✔
3553
}
3554

3555
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3556
// the given public key has been disconnected. The notification is signaled by
3557
// closing the channel returned.
3558
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
4✔
3559
        s.mu.Lock()
4✔
3560
        defer s.mu.Unlock()
4✔
3561

4✔
3562
        c := make(chan struct{})
4✔
3563

4✔
3564
        // If the peer is already offline, we can immediately trigger the
4✔
3565
        // notification.
4✔
3566
        peerPubKeyStr := string(peerPubKey[:])
4✔
3567
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
4✔
3568
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3569
                close(c)
×
3570
                return c
×
3571
        }
×
3572

3573
        // Otherwise, the peer is online, so we'll keep track of the channel to
3574
        // trigger the notification once the server detects the peer
3575
        // disconnects.
3576
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
4✔
3577
                s.peerDisconnectedListeners[peerPubKeyStr], c,
4✔
3578
        )
4✔
3579

4✔
3580
        return c
4✔
3581
}
3582

3583
// FindPeer will return the peer that corresponds to the passed in public key.
3584
// This function is used by the funding manager, allowing it to update the
3585
// daemon's local representation of the remote peer.
3586
//
3587
// NOTE: This function is safe for concurrent access.
3588
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
4✔
3589
        s.mu.RLock()
4✔
3590
        defer s.mu.RUnlock()
4✔
3591

4✔
3592
        pubStr := string(peerKey.SerializeCompressed())
4✔
3593

4✔
3594
        return s.findPeerByPubStr(pubStr)
4✔
3595
}
4✔
3596

3597
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3598
// which should be a string representation of the peer's serialized, compressed
3599
// public key.
3600
//
3601
// NOTE: This function is safe for concurrent access.
3602
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3603
        s.mu.RLock()
4✔
3604
        defer s.mu.RUnlock()
4✔
3605

4✔
3606
        return s.findPeerByPubStr(pubStr)
4✔
3607
}
4✔
3608

3609
// findPeerByPubStr is an internal method that retrieves the specified peer from
3610
// the server's internal state using.
3611
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3612
        peer, ok := s.peersByPub[pubStr]
4✔
3613
        if !ok {
8✔
3614
                return nil, ErrPeerNotConnected
4✔
3615
        }
4✔
3616

3617
        return peer, nil
4✔
3618
}
3619

3620
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3621
// exponential backoff. If no previous backoff was known, the default is
3622
// returned.
3623
func (s *server) nextPeerBackoff(pubStr string,
3624
        startTime time.Time) time.Duration {
4✔
3625

4✔
3626
        // Now, determine the appropriate backoff to use for the retry.
4✔
3627
        backoff, ok := s.persistentPeersBackoff[pubStr]
4✔
3628
        if !ok {
8✔
3629
                // If an existing backoff was unknown, use the default.
4✔
3630
                return s.cfg.MinBackoff
4✔
3631
        }
4✔
3632

3633
        // If the peer failed to start properly, we'll just use the previous
3634
        // backoff to compute the subsequent randomized exponential backoff
3635
        // duration. This will roughly double on average.
3636
        if startTime.IsZero() {
4✔
3637
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3638
        }
×
3639

3640
        // The peer succeeded in starting. If the connection didn't last long
3641
        // enough to be considered stable, we'll continue to back off retries
3642
        // with this peer.
3643
        connDuration := time.Since(startTime)
4✔
3644
        if connDuration < defaultStableConnDuration {
8✔
3645
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
4✔
3646
        }
4✔
3647

3648
        // The peer succeed in starting and this was stable peer, so we'll
3649
        // reduce the timeout duration by the length of the connection after
3650
        // applying randomized exponential backoff. We'll only apply this in the
3651
        // case that:
3652
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3653
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3654
        if relaxedBackoff > s.cfg.MinBackoff {
×
3655
                return relaxedBackoff
×
3656
        }
×
3657

3658
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3659
        // the stable connection lasted much longer than our previous backoff.
3660
        // To reward such good behavior, we'll reconnect after the default
3661
        // timeout.
3662
        return s.cfg.MinBackoff
×
3663
}
3664

3665
// shouldDropLocalConnection determines if our local connection to a remote peer
3666
// should be dropped in the case of concurrent connection establishment. In
3667
// order to deterministically decide which connection should be dropped, we'll
3668
// utilize the ordering of the local and remote public key. If we didn't use
3669
// such a tie breaker, then we risk _both_ connections erroneously being
3670
// dropped.
3671
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3672
        localPubBytes := local.SerializeCompressed()
×
3673
        remotePubPbytes := remote.SerializeCompressed()
×
3674

×
3675
        // The connection that comes from the node with a "smaller" pubkey
×
3676
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3677
        // should drop our established connection.
×
3678
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3679
}
×
3680

3681
// InboundPeerConnected initializes a new peer in response to a new inbound
3682
// connection.
3683
//
3684
// NOTE: This function is safe for concurrent access.
3685
func (s *server) InboundPeerConnected(conn net.Conn) {
4✔
3686
        // Exit early if we have already been instructed to shutdown, this
4✔
3687
        // prevents any delayed callbacks from accidentally registering peers.
4✔
3688
        if s.Stopped() {
4✔
3689
                return
×
3690
        }
×
3691

3692
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3693
        pubSer := nodePub.SerializeCompressed()
4✔
3694
        pubStr := string(pubSer)
4✔
3695

4✔
3696
        var pubBytes [33]byte
4✔
3697
        copy(pubBytes[:], pubSer)
4✔
3698

4✔
3699
        s.mu.Lock()
4✔
3700
        defer s.mu.Unlock()
4✔
3701

4✔
3702
        // If the remote node's public key is banned, drop the connection.
4✔
3703
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
4✔
3704
        if dcErr != nil {
4✔
3705
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3706
                        "peer: %v", dcErr)
×
3707
                conn.Close()
×
3708

×
3709
                return
×
3710
        }
×
3711

3712
        if shouldDc {
4✔
3713
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3714
                        "banned.", pubSer)
×
3715

×
3716
                conn.Close()
×
3717

×
3718
                return
×
3719
        }
×
3720

3721
        // If we already have an outbound connection to this peer, then ignore
3722
        // this new connection.
3723
        if p, ok := s.outboundPeers[pubStr]; ok {
8✔
3724
                srvrLog.Debugf("Already have outbound connection for %v, "+
4✔
3725
                        "ignoring inbound connection from local=%v, remote=%v",
4✔
3726
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
3727

4✔
3728
                conn.Close()
4✔
3729
                return
4✔
3730
        }
4✔
3731

3732
        // If we already have a valid connection that is scheduled to take
3733
        // precedence once the prior peer has finished disconnecting, we'll
3734
        // ignore this connection.
3735
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
4✔
3736
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3737
                        "scheduled", conn.RemoteAddr(), p)
×
3738
                conn.Close()
×
3739
                return
×
3740
        }
×
3741

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

4✔
3744
        // Check to see if we already have a connection with this peer. If so,
4✔
3745
        // we may need to drop our existing connection. This prevents us from
4✔
3746
        // having duplicate connections to the same peer. We forgo adding a
4✔
3747
        // default case as we expect these to be the only error values returned
4✔
3748
        // from findPeerByPubStr.
4✔
3749
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
3750
        switch err {
4✔
3751
        case ErrPeerNotConnected:
4✔
3752
                // We were unable to locate an existing connection with the
4✔
3753
                // target peer, proceed to connect.
4✔
3754
                s.cancelConnReqs(pubStr, nil)
4✔
3755
                s.peerConnected(conn, nil, true)
4✔
3756

3757
        case nil:
×
3758
                // We already have a connection with the incoming peer. If the
×
3759
                // connection we've already established should be kept and is
×
3760
                // not of the same type of the new connection (inbound), then
×
3761
                // we'll close out the new connection s.t there's only a single
×
3762
                // connection between us.
×
3763
                localPub := s.identityECDH.PubKey()
×
3764
                if !connectedPeer.Inbound() &&
×
3765
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3766

×
3767
                        srvrLog.Warnf("Received inbound connection from "+
×
3768
                                "peer %v, but already have outbound "+
×
3769
                                "connection, dropping conn", connectedPeer)
×
3770
                        conn.Close()
×
3771
                        return
×
3772
                }
×
3773

3774
                // Otherwise, if we should drop the connection, then we'll
3775
                // disconnect our already connected peer.
3776
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3777
                        connectedPeer)
×
3778

×
3779
                s.cancelConnReqs(pubStr, nil)
×
3780

×
3781
                // Remove the current peer from the server's internal state and
×
3782
                // signal that the peer termination watcher does not need to
×
3783
                // execute for this peer.
×
3784
                s.removePeer(connectedPeer)
×
3785
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3786
                s.scheduledPeerConnection[pubStr] = func() {
×
3787
                        s.peerConnected(conn, nil, true)
×
3788
                }
×
3789
        }
3790
}
3791

3792
// OutboundPeerConnected initializes a new peer in response to a new outbound
3793
// connection.
3794
// NOTE: This function is safe for concurrent access.
3795
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
4✔
3796
        // Exit early if we have already been instructed to shutdown, this
4✔
3797
        // prevents any delayed callbacks from accidentally registering peers.
4✔
3798
        if s.Stopped() {
4✔
3799
                return
×
3800
        }
×
3801

3802
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3803
        pubSer := nodePub.SerializeCompressed()
4✔
3804
        pubStr := string(pubSer)
4✔
3805

4✔
3806
        var pubBytes [33]byte
4✔
3807
        copy(pubBytes[:], pubSer)
4✔
3808

4✔
3809
        s.mu.Lock()
4✔
3810
        defer s.mu.Unlock()
4✔
3811

4✔
3812
        // If the remote node's public key is banned, drop the connection.
4✔
3813
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
4✔
3814
        if dcErr != nil {
4✔
3815
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3816
                        "peer: %v", dcErr)
×
3817
                conn.Close()
×
3818

×
3819
                return
×
3820
        }
×
3821

3822
        if shouldDc {
4✔
3823
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3824
                        "banned.", pubSer)
×
3825

×
3826
                if connReq != nil {
×
3827
                        s.connMgr.Remove(connReq.ID())
×
3828
                }
×
3829

3830
                conn.Close()
×
3831

×
3832
                return
×
3833
        }
3834

3835
        // If we already have an inbound connection to this peer, then ignore
3836
        // this new connection.
3837
        if p, ok := s.inboundPeers[pubStr]; ok {
8✔
3838
                srvrLog.Debugf("Already have inbound connection for %v, "+
4✔
3839
                        "ignoring outbound connection from local=%v, remote=%v",
4✔
3840
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
3841

4✔
3842
                if connReq != nil {
8✔
3843
                        s.connMgr.Remove(connReq.ID())
4✔
3844
                }
4✔
3845
                conn.Close()
4✔
3846
                return
4✔
3847
        }
3848
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
4✔
3849
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3850
                s.connMgr.Remove(connReq.ID())
×
3851
                conn.Close()
×
3852
                return
×
3853
        }
×
3854

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

×
3861
                if connReq != nil {
×
3862
                        s.connMgr.Remove(connReq.ID())
×
3863
                }
×
3864

3865
                conn.Close()
×
3866
                return
×
3867
        }
3868

3869
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
4✔
3870
                conn.RemoteAddr())
4✔
3871

4✔
3872
        if connReq != nil {
8✔
3873
                // A successful connection was returned by the connmgr.
4✔
3874
                // Immediately cancel all pending requests, excluding the
4✔
3875
                // outbound connection we just established.
4✔
3876
                ignore := connReq.ID()
4✔
3877
                s.cancelConnReqs(pubStr, &ignore)
4✔
3878
        } else {
8✔
3879
                // This was a successful connection made by some other
4✔
3880
                // subsystem. Remove all requests being managed by the connmgr.
4✔
3881
                s.cancelConnReqs(pubStr, nil)
4✔
3882
        }
4✔
3883

3884
        // If we already have a connection with this peer, decide whether or not
3885
        // we need to drop the stale connection. We forgo adding a default case
3886
        // as we expect these to be the only error values returned from
3887
        // findPeerByPubStr.
3888
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
3889
        switch err {
4✔
3890
        case ErrPeerNotConnected:
4✔
3891
                // We were unable to locate an existing connection with the
4✔
3892
                // target peer, proceed to connect.
4✔
3893
                s.peerConnected(conn, connReq, false)
4✔
3894

3895
        case nil:
×
3896
                // We already have a connection with the incoming peer. If the
×
3897
                // connection we've already established should be kept and is
×
3898
                // not of the same type of the new connection (outbound), then
×
3899
                // we'll close out the new connection s.t there's only a single
×
3900
                // connection between us.
×
3901
                localPub := s.identityECDH.PubKey()
×
3902
                if connectedPeer.Inbound() &&
×
3903
                        shouldDropLocalConnection(localPub, nodePub) {
×
3904

×
3905
                        srvrLog.Warnf("Established outbound connection to "+
×
3906
                                "peer %v, but already have inbound "+
×
3907
                                "connection, dropping conn", connectedPeer)
×
3908
                        if connReq != nil {
×
3909
                                s.connMgr.Remove(connReq.ID())
×
3910
                        }
×
3911
                        conn.Close()
×
3912
                        return
×
3913
                }
3914

3915
                // Otherwise, _their_ connection should be dropped. So we'll
3916
                // disconnect the peer and send the now obsolete peer to the
3917
                // server for garbage collection.
3918
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3919
                        connectedPeer)
×
3920

×
3921
                // Remove the current peer from the server's internal state and
×
3922
                // signal that the peer termination watcher does not need to
×
3923
                // execute for this peer.
×
3924
                s.removePeer(connectedPeer)
×
3925
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3926
                s.scheduledPeerConnection[pubStr] = func() {
×
3927
                        s.peerConnected(conn, connReq, false)
×
3928
                }
×
3929
        }
3930
}
3931

3932
// UnassignedConnID is the default connection ID that a request can have before
3933
// it actually is submitted to the connmgr.
3934
// TODO(conner): move into connmgr package, or better, add connmgr method for
3935
// generating atomic IDs
3936
const UnassignedConnID uint64 = 0
3937

3938
// cancelConnReqs stops all persistent connection requests for a given pubkey.
3939
// Any attempts initiated by the peerTerminationWatcher are canceled first.
3940
// Afterwards, each connection request removed from the connmgr. The caller can
3941
// optionally specify a connection ID to ignore, which prevents us from
3942
// canceling a successful request. All persistent connreqs for the provided
3943
// pubkey are discarded after the operationjw.
3944
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
4✔
3945
        // First, cancel any lingering persistent retry attempts, which will
4✔
3946
        // prevent retries for any with backoffs that are still maturing.
4✔
3947
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
8✔
3948
                close(cancelChan)
4✔
3949
                delete(s.persistentRetryCancels, pubStr)
4✔
3950
        }
4✔
3951

3952
        // Next, check to see if we have any outstanding persistent connection
3953
        // requests to this peer. If so, then we'll remove all of these
3954
        // connection requests, and also delete the entry from the map.
3955
        connReqs, ok := s.persistentConnReqs[pubStr]
4✔
3956
        if !ok {
8✔
3957
                return
4✔
3958
        }
4✔
3959

3960
        for _, connReq := range connReqs {
8✔
3961
                srvrLog.Tracef("Canceling %s:", connReqs)
4✔
3962

4✔
3963
                // Atomically capture the current request identifier.
4✔
3964
                connID := connReq.ID()
4✔
3965

4✔
3966
                // Skip any zero IDs, this indicates the request has not
4✔
3967
                // yet been schedule.
4✔
3968
                if connID == UnassignedConnID {
4✔
3969
                        continue
×
3970
                }
3971

3972
                // Skip a particular connection ID if instructed.
3973
                if skip != nil && connID == *skip {
8✔
3974
                        continue
4✔
3975
                }
3976

3977
                s.connMgr.Remove(connID)
4✔
3978
        }
3979

3980
        delete(s.persistentConnReqs, pubStr)
4✔
3981
}
3982

3983
// handleCustomMessage dispatches an incoming custom peers message to
3984
// subscribers.
3985
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
4✔
3986
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
4✔
3987
                peer, msg.Type)
4✔
3988

4✔
3989
        return s.customMessageServer.SendUpdate(&CustomMessage{
4✔
3990
                Peer: peer,
4✔
3991
                Msg:  msg,
4✔
3992
        })
4✔
3993
}
4✔
3994

3995
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
3996
// messages.
3997
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
4✔
3998
        return s.customMessageServer.Subscribe()
4✔
3999
}
4✔
4000

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

4✔
4008
        brontideConn := conn.(*brontide.Conn)
4✔
4009
        addr := conn.RemoteAddr()
4✔
4010
        pubKey := brontideConn.RemotePub()
4✔
4011

4✔
4012
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
4✔
4013
                pubKey.SerializeCompressed(), addr, inbound)
4✔
4014

4✔
4015
        peerAddr := &lnwire.NetAddress{
4✔
4016
                IdentityKey: pubKey,
4✔
4017
                Address:     addr,
4✔
4018
                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
4019
        }
4✔
4020

4✔
4021
        // With the brontide connection established, we'll now craft the feature
4✔
4022
        // vectors to advertise to the remote node.
4✔
4023
        initFeatures := s.featureMgr.Get(feature.SetInit)
4✔
4024
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
4✔
4025

4✔
4026
        // Lookup past error caches for the peer in the server. If no buffer is
4✔
4027
        // found, create a fresh buffer.
4✔
4028
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
4✔
4029
        errBuffer, ok := s.peerErrors[pkStr]
4✔
4030
        if !ok {
8✔
4031
                var err error
4✔
4032
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
4✔
4033
                if err != nil {
4✔
4034
                        srvrLog.Errorf("unable to create peer %v", err)
×
4035
                        return
×
4036
                }
×
4037
        }
4038

4039
        // If we directly set the peer.Config TowerClient member to the
4040
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4041
        // the peer.Config's TowerClient member will not evaluate to nil even
4042
        // though the underlying value is nil. To avoid this gotcha which can
4043
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4044
        // TowerClient if needed.
4045
        var towerClient wtclient.ClientManager
4✔
4046
        if s.towerClientMgr != nil {
8✔
4047
                towerClient = s.towerClientMgr
4✔
4048
        }
4✔
4049

4050
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
4✔
4051
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
4052

4✔
4053
        // Now that we've established a connection, create a peer, and it to the
4✔
4054
        // set of currently active peers. Configure the peer with the incoming
4✔
4055
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
4✔
4056
        // offered that would trigger channel closure. In case of outgoing
4✔
4057
        // htlcs, an extra block is added to prevent the channel from being
4✔
4058
        // closed when the htlc is outstanding and a new block comes in.
4✔
4059
        pCfg := peer.Config{
4✔
4060
                Conn:                    brontideConn,
4✔
4061
                ConnReq:                 connReq,
4✔
4062
                Addr:                    peerAddr,
4✔
4063
                Inbound:                 inbound,
4✔
4064
                Features:                initFeatures,
4✔
4065
                LegacyFeatures:          legacyFeatures,
4✔
4066
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
4✔
4067
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
4✔
4068
                ErrorBuffer:             errBuffer,
4✔
4069
                WritePool:               s.writePool,
4✔
4070
                ReadPool:                s.readPool,
4✔
4071
                Switch:                  s.htlcSwitch,
4✔
4072
                InterceptSwitch:         s.interceptableSwitch,
4✔
4073
                ChannelDB:               s.chanStateDB,
4✔
4074
                ChannelGraph:            s.graphDB,
4✔
4075
                ChainArb:                s.chainArb,
4✔
4076
                AuthGossiper:            s.authGossiper,
4✔
4077
                ChanStatusMgr:           s.chanStatusMgr,
4✔
4078
                ChainIO:                 s.cc.ChainIO,
4✔
4079
                FeeEstimator:            s.cc.FeeEstimator,
4✔
4080
                Signer:                  s.cc.Wallet.Cfg.Signer,
4✔
4081
                SigPool:                 s.sigPool,
4✔
4082
                Wallet:                  s.cc.Wallet,
4✔
4083
                ChainNotifier:           s.cc.ChainNotifier,
4✔
4084
                BestBlockView:           s.cc.BestBlockTracker,
4✔
4085
                RoutingPolicy:           s.cc.RoutingPolicy,
4✔
4086
                Sphinx:                  s.sphinx,
4✔
4087
                WitnessBeacon:           s.witnessBeacon,
4✔
4088
                Invoices:                s.invoices,
4✔
4089
                ChannelNotifier:         s.channelNotifier,
4✔
4090
                HtlcNotifier:            s.htlcNotifier,
4✔
4091
                TowerClient:             towerClient,
4✔
4092
                DisconnectPeer:          s.DisconnectPeer,
4✔
4093
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
4✔
4094
                        lnwire.NodeAnnouncement, error) {
8✔
4095

4✔
4096
                        return s.genNodeAnnouncement(nil)
4✔
4097
                },
4✔
4098

4099
                PongBuf: s.pongBuf,
4100

4101
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4102

4103
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4104

4105
                FundingManager: s.fundingMgr,
4106

4107
                Hodl:                    s.cfg.Hodl,
4108
                UnsafeReplay:            s.cfg.UnsafeReplay,
4109
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4110
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4111
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4112
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4113
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4114
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4115
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4116
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4117
                HandleCustomMessage:    s.handleCustomMessage,
4118
                GetAliases:             s.aliasMgr.GetAliases,
4119
                RequestAlias:           s.aliasMgr.RequestAlias,
4120
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4121
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4122
                MaxFeeExposure:         thresholdMSats,
4123
                Quit:                   s.quit,
4124
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4125
                AuxSigner:              s.implCfg.AuxSigner,
4126
                MsgRouter:              s.implCfg.MsgRouter,
4127
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4128
        }
4129

4130
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
4✔
4131
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
4✔
4132

4✔
4133
        p := peer.NewBrontide(pCfg)
4✔
4134

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

4✔
4138
        s.addPeer(p)
4✔
4139

4✔
4140
        // Once we have successfully added the peer to the server, we can
4✔
4141
        // delete the previous error buffer from the server's map of error
4✔
4142
        // buffers.
4✔
4143
        delete(s.peerErrors, pkStr)
4✔
4144

4✔
4145
        // Dispatch a goroutine to asynchronously start the peer. This process
4✔
4146
        // includes sending and receiving Init messages, which would be a DOS
4✔
4147
        // vector if we held the server's mutex throughout the procedure.
4✔
4148
        s.wg.Add(1)
4✔
4149
        go s.peerInitializer(p)
4✔
4150
}
4151

4152
// addPeer adds the passed peer to the server's global state of all active
4153
// peers.
4154
func (s *server) addPeer(p *peer.Brontide) {
4✔
4155
        if p == nil {
4✔
4156
                return
×
4157
        }
×
4158

4159
        // Ignore new peers if we're shutting down.
4160
        if s.Stopped() {
4✔
4161
                p.Disconnect(ErrServerShuttingDown)
×
4162
                return
×
4163
        }
×
4164

4165
        // Track the new peer in our indexes so we can quickly look it up either
4166
        // according to its public key, or its peer ID.
4167
        // TODO(roasbeef): pipe all requests through to the
4168
        // queryHandler/peerManager
4169

4170
        pubSer := p.IdentityKey().SerializeCompressed()
4✔
4171
        pubStr := string(pubSer)
4✔
4172

4✔
4173
        s.peersByPub[pubStr] = p
4✔
4174

4✔
4175
        if p.Inbound() {
8✔
4176
                s.inboundPeers[pubStr] = p
4✔
4177
        } else {
8✔
4178
                s.outboundPeers[pubStr] = p
4✔
4179
        }
4✔
4180

4181
        // Inform the peer notifier of a peer online event so that it can be reported
4182
        // to clients listening for peer events.
4183
        var pubKey [33]byte
4✔
4184
        copy(pubKey[:], pubSer)
4✔
4185

4✔
4186
        s.peerNotifier.NotifyPeerOnline(pubKey)
4✔
4187
}
4188

4189
// peerInitializer asynchronously starts a newly connected peer after it has
4190
// been added to the server's peer map. This method sets up a
4191
// peerTerminationWatcher for the given peer, and ensures that it executes even
4192
// if the peer failed to start. In the event of a successful connection, this
4193
// method reads the negotiated, local feature-bits and spawns the appropriate
4194
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4195
// be signaled of the new peer once the method returns.
4196
//
4197
// NOTE: This MUST be launched as a goroutine.
4198
func (s *server) peerInitializer(p *peer.Brontide) {
4✔
4199
        defer s.wg.Done()
4✔
4200

4✔
4201
        // Avoid initializing peers while the server is exiting.
4✔
4202
        if s.Stopped() {
4✔
4203
                return
×
4204
        }
×
4205

4206
        // Create a channel that will be used to signal a successful start of
4207
        // the link. This prevents the peer termination watcher from beginning
4208
        // its duty too early.
4209
        ready := make(chan struct{})
4✔
4210

4✔
4211
        // Before starting the peer, launch a goroutine to watch for the
4✔
4212
        // unexpected termination of this peer, which will ensure all resources
4✔
4213
        // are properly cleaned up, and re-establish persistent connections when
4✔
4214
        // necessary. The peer termination watcher will be short circuited if
4✔
4215
        // the peer is ever added to the ignorePeerTermination map, indicating
4✔
4216
        // that the server has already handled the removal of this peer.
4✔
4217
        s.wg.Add(1)
4✔
4218
        go s.peerTerminationWatcher(p, ready)
4✔
4219

4✔
4220
        pubBytes := p.IdentityKey().SerializeCompressed()
4✔
4221

4✔
4222
        // Start the peer! If an error occurs, we Disconnect the peer, which
4✔
4223
        // will unblock the peerTerminationWatcher.
4✔
4224
        if err := p.Start(); err != nil {
5✔
4225
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
1✔
4226

1✔
4227
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
1✔
4228
                return
1✔
4229
        }
1✔
4230

4231
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4232
        // was successful, and to begin watching the peer's wait group.
4233
        close(ready)
4✔
4234

4✔
4235
        s.mu.Lock()
4✔
4236
        defer s.mu.Unlock()
4✔
4237

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

4✔
4241
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
4✔
4242
        // route.Vertex as the key type of peerConnectedListeners.
4✔
4243
        pubStr := string(pubBytes)
4✔
4244
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
8✔
4245
                select {
4✔
4246
                case peerChan <- p:
4✔
4247
                case <-s.quit:
1✔
4248
                        return
1✔
4249
                }
4250
        }
4251
        delete(s.peerConnectedListeners, pubStr)
4✔
4252
}
4253

4254
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4255
// and then cleans up all resources allocated to the peer, notifies relevant
4256
// sub-systems of its demise, and finally handles re-connecting to the peer if
4257
// it's persistent. If the server intentionally disconnects a peer, it should
4258
// have a corresponding entry in the ignorePeerTermination map which will cause
4259
// the cleanup routine to exit early. The passed `ready` chan is used to
4260
// synchronize when WaitForDisconnect should begin watching on the peer's
4261
// waitgroup. The ready chan should only be signaled if the peer starts
4262
// successfully, otherwise the peer should be disconnected instead.
4263
//
4264
// NOTE: This MUST be launched as a goroutine.
4265
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
4✔
4266
        defer s.wg.Done()
4✔
4267

4✔
4268
        p.WaitForDisconnect(ready)
4✔
4269

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

4✔
4272
        // If the server is exiting then we can bail out early ourselves as all
4✔
4273
        // the other sub-systems will already be shutting down.
4✔
4274
        if s.Stopped() {
8✔
4275
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
4✔
4276
                return
4✔
4277
        }
4✔
4278

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

4✔
4285
        pubKey := p.IdentityKey()
4✔
4286

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

4✔
4291
        // Tell the switch to remove all links associated with this peer.
4✔
4292
        // Passing nil as the target link indicates that all links associated
4✔
4293
        // with this interface should be closed.
4✔
4294
        //
4✔
4295
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
4✔
4296
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
4✔
4297
        if err != nil && err != htlcswitch.ErrNoLinksFound {
4✔
4298
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4299
        }
×
4300

4301
        for _, link := range links {
8✔
4302
                s.htlcSwitch.RemoveLink(link.ChanID())
4✔
4303
        }
4✔
4304

4305
        s.mu.Lock()
4✔
4306
        defer s.mu.Unlock()
4✔
4307

4✔
4308
        // If there were any notification requests for when this peer
4✔
4309
        // disconnected, we can trigger them now.
4✔
4310
        srvrLog.Debugf("Notifying that peer %v is offline", p)
4✔
4311
        pubStr := string(pubKey.SerializeCompressed())
4✔
4312
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
8✔
4313
                close(offlineChan)
4✔
4314
        }
4✔
4315
        delete(s.peerDisconnectedListeners, pubStr)
4✔
4316

4✔
4317
        // If the server has already removed this peer, we can short circuit the
4✔
4318
        // peer termination watcher and skip cleanup.
4✔
4319
        if _, ok := s.ignorePeerTermination[p]; ok {
4✔
4320
                delete(s.ignorePeerTermination, p)
×
4321

×
4322
                pubKey := p.PubKey()
×
4323
                pubStr := string(pubKey[:])
×
4324

×
4325
                // If a connection callback is present, we'll go ahead and
×
4326
                // execute it now that previous peer has fully disconnected. If
×
4327
                // the callback is not present, this likely implies the peer was
×
4328
                // purposefully disconnected via RPC, and that no reconnect
×
4329
                // should be attempted.
×
4330
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4331
                if ok {
×
4332
                        delete(s.scheduledPeerConnection, pubStr)
×
4333
                        connCallback()
×
4334
                }
×
4335
                return
×
4336
        }
4337

4338
        // First, cleanup any remaining state the server has regarding the peer
4339
        // in question.
4340
        s.removePeer(p)
4✔
4341

4✔
4342
        // Next, check to see if this is a persistent peer or not.
4✔
4343
        if _, ok := s.persistentPeers[pubStr]; !ok {
8✔
4344
                return
4✔
4345
        }
4✔
4346

4347
        // Get the last address that we used to connect to the peer.
4348
        addrs := []net.Addr{
4✔
4349
                p.NetAddress().Address,
4✔
4350
        }
4✔
4351

4✔
4352
        // We'll ensure that we locate all the peers advertised addresses for
4✔
4353
        // reconnection purposes.
4✔
4354
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
4✔
4355
        switch {
4✔
4356
        // We found advertised addresses, so use them.
4357
        case err == nil:
4✔
4358
                addrs = advertisedAddrs
4✔
4359

4360
        // The peer doesn't have an advertised address.
4361
        case err == errNoAdvertisedAddr:
4✔
4362
                // If it is an outbound peer then we fall back to the existing
4✔
4363
                // peer address.
4✔
4364
                if !p.Inbound() {
8✔
4365
                        break
4✔
4366
                }
4367

4368
                // Fall back to the existing peer address if
4369
                // we're not accepting connections over Tor.
4370
                if s.torController == nil {
8✔
4371
                        break
4✔
4372
                }
4373

4374
                // If we are, the peer's address won't be known
4375
                // to us (we'll see a private address, which is
4376
                // the address used by our onion service to dial
4377
                // to lnd), so we don't have enough information
4378
                // to attempt a reconnect.
4379
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4380
                        "to inbound peer %v without "+
×
4381
                        "advertised address", p)
×
4382
                return
×
4383

4384
        // We came across an error retrieving an advertised
4385
        // address, log it, and fall back to the existing peer
4386
        // address.
4387
        default:
4✔
4388
                srvrLog.Errorf("Unable to retrieve advertised "+
4✔
4389
                        "address for node %x: %v", p.PubKey(),
4✔
4390
                        err)
4✔
4391
        }
4392

4393
        // Make an easy lookup map so that we can check if an address
4394
        // is already in the address list that we have stored for this peer.
4395
        existingAddrs := make(map[string]bool)
4✔
4396
        for _, addr := range s.persistentPeerAddrs[pubStr] {
8✔
4397
                existingAddrs[addr.String()] = true
4✔
4398
        }
4✔
4399

4400
        // Add any missing addresses for this peer to persistentPeerAddr.
4401
        for _, addr := range addrs {
8✔
4402
                if existingAddrs[addr.String()] {
4✔
4403
                        continue
×
4404
                }
4405

4406
                s.persistentPeerAddrs[pubStr] = append(
4✔
4407
                        s.persistentPeerAddrs[pubStr],
4✔
4408
                        &lnwire.NetAddress{
4✔
4409
                                IdentityKey: p.IdentityKey(),
4✔
4410
                                Address:     addr,
4✔
4411
                                ChainNet:    p.NetAddress().ChainNet,
4✔
4412
                        },
4✔
4413
                )
4✔
4414
        }
4415

4416
        // Record the computed backoff in the backoff map.
4417
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
4✔
4418
        s.persistentPeersBackoff[pubStr] = backoff
4✔
4419

4✔
4420
        // Initialize a retry canceller for this peer if one does not
4✔
4421
        // exist.
4✔
4422
        cancelChan, ok := s.persistentRetryCancels[pubStr]
4✔
4423
        if !ok {
8✔
4424
                cancelChan = make(chan struct{})
4✔
4425
                s.persistentRetryCancels[pubStr] = cancelChan
4✔
4426
        }
4✔
4427

4428
        // We choose not to wait group this go routine since the Connect
4429
        // call can stall for arbitrarily long if we shutdown while an
4430
        // outbound connection attempt is being made.
4431
        go func() {
8✔
4432
                srvrLog.Debugf("Scheduling connection re-establishment to "+
4✔
4433
                        "persistent peer %x in %s",
4✔
4434
                        p.IdentityKey().SerializeCompressed(), backoff)
4✔
4435

4✔
4436
                select {
4✔
4437
                case <-time.After(backoff):
4✔
4438
                case <-cancelChan:
4✔
4439
                        return
4✔
4440
                case <-s.quit:
4✔
4441
                        return
4✔
4442
                }
4443

4444
                srvrLog.Debugf("Attempting to re-establish persistent "+
4✔
4445
                        "connection to peer %x",
4✔
4446
                        p.IdentityKey().SerializeCompressed())
4✔
4447

4✔
4448
                s.connectToPersistentPeer(pubStr)
4✔
4449
        }()
4450
}
4451

4452
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4453
// to connect to the peer. It creates connection requests if there are
4454
// currently none for a given address and it removes old connection requests
4455
// if the associated address is no longer in the latest address list for the
4456
// peer.
4457
func (s *server) connectToPersistentPeer(pubKeyStr string) {
4✔
4458
        s.mu.Lock()
4✔
4459
        defer s.mu.Unlock()
4✔
4460

4✔
4461
        // Create an easy lookup map of the addresses we have stored for the
4✔
4462
        // peer. We will remove entries from this map if we have existing
4✔
4463
        // connection requests for the associated address and then any leftover
4✔
4464
        // entries will indicate which addresses we should create new
4✔
4465
        // connection requests for.
4✔
4466
        addrMap := make(map[string]*lnwire.NetAddress)
4✔
4467
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
8✔
4468
                addrMap[addr.String()] = addr
4✔
4469
        }
4✔
4470

4471
        // Go through each of the existing connection requests and
4472
        // check if they correspond to the latest set of addresses. If
4473
        // there is a connection requests that does not use one of the latest
4474
        // advertised addresses then remove that connection request.
4475
        var updatedConnReqs []*connmgr.ConnReq
4✔
4476
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
8✔
4477
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
4✔
4478

4✔
4479
                switch _, ok := addrMap[lnAddr]; ok {
4✔
4480
                // If the existing connection request is using one of the
4481
                // latest advertised addresses for the peer then we add it to
4482
                // updatedConnReqs and remove the associated address from
4483
                // addrMap so that we don't recreate this connReq later on.
4484
                case true:
×
4485
                        updatedConnReqs = append(
×
4486
                                updatedConnReqs, connReq,
×
4487
                        )
×
4488
                        delete(addrMap, lnAddr)
×
4489

4490
                // If the existing connection request is using an address that
4491
                // is not one of the latest advertised addresses for the peer
4492
                // then we remove the connecting request from the connection
4493
                // manager.
4494
                case false:
4✔
4495
                        srvrLog.Info(
4✔
4496
                                "Removing conn req:", connReq.Addr.String(),
4✔
4497
                        )
4✔
4498
                        s.connMgr.Remove(connReq.ID())
4✔
4499
                }
4500
        }
4501

4502
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
4✔
4503

4✔
4504
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
4✔
4505
        if !ok {
8✔
4506
                cancelChan = make(chan struct{})
4✔
4507
                s.persistentRetryCancels[pubKeyStr] = cancelChan
4✔
4508
        }
4✔
4509

4510
        // Any addresses left in addrMap are new ones that we have not made
4511
        // connection requests for. So create new connection requests for those.
4512
        // If there is more than one address in the address map, stagger the
4513
        // creation of the connection requests for those.
4514
        go func() {
8✔
4515
                ticker := time.NewTicker(multiAddrConnectionStagger)
4✔
4516
                defer ticker.Stop()
4✔
4517

4✔
4518
                for _, addr := range addrMap {
8✔
4519
                        // Send the persistent connection request to the
4✔
4520
                        // connection manager, saving the request itself so we
4✔
4521
                        // can cancel/restart the process as needed.
4✔
4522
                        connReq := &connmgr.ConnReq{
4✔
4523
                                Addr:      addr,
4✔
4524
                                Permanent: true,
4✔
4525
                        }
4✔
4526

4✔
4527
                        s.mu.Lock()
4✔
4528
                        s.persistentConnReqs[pubKeyStr] = append(
4✔
4529
                                s.persistentConnReqs[pubKeyStr], connReq,
4✔
4530
                        )
4✔
4531
                        s.mu.Unlock()
4✔
4532

4✔
4533
                        srvrLog.Debugf("Attempting persistent connection to "+
4✔
4534
                                "channel peer %v", addr)
4✔
4535

4✔
4536
                        go s.connMgr.Connect(connReq)
4✔
4537

4✔
4538
                        select {
4✔
4539
                        case <-s.quit:
4✔
4540
                                return
4✔
4541
                        case <-cancelChan:
4✔
4542
                                return
4✔
4543
                        case <-ticker.C:
4✔
4544
                        }
4545
                }
4546
        }()
4547
}
4548

4549
// removePeer removes the passed peer from the server's state of all active
4550
// peers.
4551
func (s *server) removePeer(p *peer.Brontide) {
4✔
4552
        if p == nil {
4✔
4553
                return
×
4554
        }
×
4555

4556
        srvrLog.Debugf("removing peer %v", p)
4✔
4557

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

4✔
4562
        // If this peer had an active persistent connection request, remove it.
4✔
4563
        if p.ConnReq() != nil {
8✔
4564
                s.connMgr.Remove(p.ConnReq().ID())
4✔
4565
        }
4✔
4566

4567
        // Ignore deleting peers if we're shutting down.
4568
        if s.Stopped() {
4✔
4569
                return
×
4570
        }
×
4571

4572
        pKey := p.PubKey()
4✔
4573
        pubSer := pKey[:]
4✔
4574
        pubStr := string(pubSer)
4✔
4575

4✔
4576
        delete(s.peersByPub, pubStr)
4✔
4577

4✔
4578
        if p.Inbound() {
8✔
4579
                delete(s.inboundPeers, pubStr)
4✔
4580
        } else {
8✔
4581
                delete(s.outboundPeers, pubStr)
4✔
4582
        }
4✔
4583

4584
        // Copy the peer's error buffer across to the server if it has any items
4585
        // in it so that we can restore peer errors across connections.
4586
        if p.ErrorBuffer().Total() > 0 {
8✔
4587
                s.peerErrors[pubStr] = p.ErrorBuffer()
4✔
4588
        }
4✔
4589

4590
        // Inform the peer notifier of a peer offline event so that it can be
4591
        // reported to clients listening for peer events.
4592
        var pubKey [33]byte
4✔
4593
        copy(pubKey[:], pubSer)
4✔
4594

4✔
4595
        s.peerNotifier.NotifyPeerOffline(pubKey)
4✔
4596
}
4597

4598
// ConnectToPeer requests that the server connect to a Lightning Network peer
4599
// at the specified address. This function will *block* until either a
4600
// connection is established, or the initial handshake process fails.
4601
//
4602
// NOTE: This function is safe for concurrent access.
4603
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4604
        perm bool, timeout time.Duration) error {
4✔
4605

4✔
4606
        targetPub := string(addr.IdentityKey.SerializeCompressed())
4✔
4607

4✔
4608
        // Acquire mutex, but use explicit unlocking instead of defer for
4✔
4609
        // better granularity.  In certain conditions, this method requires
4✔
4610
        // making an outbound connection to a remote peer, which requires the
4✔
4611
        // lock to be released, and subsequently reacquired.
4✔
4612
        s.mu.Lock()
4✔
4613

4✔
4614
        // Ensure we're not already connected to this peer.
4✔
4615
        peer, err := s.findPeerByPubStr(targetPub)
4✔
4616
        if err == nil {
8✔
4617
                s.mu.Unlock()
4✔
4618
                return &errPeerAlreadyConnected{peer: peer}
4✔
4619
        }
4✔
4620

4621
        // Peer was not found, continue to pursue connection with peer.
4622

4623
        // If there's already a pending connection request for this pubkey,
4624
        // then we ignore this request to ensure we don't create a redundant
4625
        // connection.
4626
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
8✔
4627
                srvrLog.Warnf("Already have %d persistent connection "+
4✔
4628
                        "requests for %v, connecting anyway.", len(reqs), addr)
4✔
4629
        }
4✔
4630

4631
        // If there's not already a pending or active connection to this node,
4632
        // then instruct the connection manager to attempt to establish a
4633
        // persistent connection to the peer.
4634
        srvrLog.Debugf("Connecting to %v", addr)
4✔
4635
        if perm {
8✔
4636
                connReq := &connmgr.ConnReq{
4✔
4637
                        Addr:      addr,
4✔
4638
                        Permanent: true,
4✔
4639
                }
4✔
4640

4✔
4641
                // Since the user requested a permanent connection, we'll set
4✔
4642
                // the entry to true which will tell the server to continue
4✔
4643
                // reconnecting even if the number of channels with this peer is
4✔
4644
                // zero.
4✔
4645
                s.persistentPeers[targetPub] = true
4✔
4646
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
8✔
4647
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
4✔
4648
                }
4✔
4649
                s.persistentConnReqs[targetPub] = append(
4✔
4650
                        s.persistentConnReqs[targetPub], connReq,
4✔
4651
                )
4✔
4652
                s.mu.Unlock()
4✔
4653

4✔
4654
                go s.connMgr.Connect(connReq)
4✔
4655

4✔
4656
                return nil
4✔
4657
        }
4658
        s.mu.Unlock()
4✔
4659

4✔
4660
        // If we're not making a persistent connection, then we'll attempt to
4✔
4661
        // connect to the target peer. If the we can't make the connection, or
4✔
4662
        // the crypto negotiation breaks down, then return an error to the
4✔
4663
        // caller.
4✔
4664
        errChan := make(chan error, 1)
4✔
4665
        s.connectToPeer(addr, errChan, timeout)
4✔
4666

4✔
4667
        select {
4✔
4668
        case err := <-errChan:
4✔
4669
                return err
4✔
4670
        case <-s.quit:
×
4671
                return ErrServerShuttingDown
×
4672
        }
4673
}
4674

4675
// connectToPeer establishes a connection to a remote peer. errChan is used to
4676
// notify the caller if the connection attempt has failed. Otherwise, it will be
4677
// closed.
4678
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4679
        errChan chan<- error, timeout time.Duration) {
4✔
4680

4✔
4681
        conn, err := brontide.Dial(
4✔
4682
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
4✔
4683
        )
4✔
4684
        if err != nil {
8✔
4685
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
4✔
4686
                select {
4✔
4687
                case errChan <- err:
4✔
4688
                case <-s.quit:
×
4689
                }
4690
                return
4✔
4691
        }
4692

4693
        close(errChan)
4✔
4694

4✔
4695
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
4✔
4696
                conn.LocalAddr(), conn.RemoteAddr())
4✔
4697

4✔
4698
        s.OutboundPeerConnected(nil, conn)
4✔
4699
}
4700

4701
// DisconnectPeer sends the request to server to close the connection with peer
4702
// identified by public key.
4703
//
4704
// NOTE: This function is safe for concurrent access.
4705
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
4✔
4706
        pubBytes := pubKey.SerializeCompressed()
4✔
4707
        pubStr := string(pubBytes)
4✔
4708

4✔
4709
        s.mu.Lock()
4✔
4710
        defer s.mu.Unlock()
4✔
4711

4✔
4712
        // Check that were actually connected to this peer. If not, then we'll
4✔
4713
        // exit in an error as we can't disconnect from a peer that we're not
4✔
4714
        // currently connected to.
4✔
4715
        peer, err := s.findPeerByPubStr(pubStr)
4✔
4716
        if err == ErrPeerNotConnected {
8✔
4717
                return fmt.Errorf("peer %x is not connected", pubBytes)
4✔
4718
        }
4✔
4719

4720
        srvrLog.Infof("Disconnecting from %v", peer)
4✔
4721

4✔
4722
        s.cancelConnReqs(pubStr, nil)
4✔
4723

4✔
4724
        // If this peer was formerly a persistent connection, then we'll remove
4✔
4725
        // them from this map so we don't attempt to re-connect after we
4✔
4726
        // disconnect.
4✔
4727
        delete(s.persistentPeers, pubStr)
4✔
4728
        delete(s.persistentPeersBackoff, pubStr)
4✔
4729

4✔
4730
        // Remove the peer by calling Disconnect. Previously this was done with
4✔
4731
        // removePeer, which bypassed the peerTerminationWatcher.
4✔
4732
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
4✔
4733

4✔
4734
        return nil
4✔
4735
}
4736

4737
// OpenChannel sends a request to the server to open a channel to the specified
4738
// peer identified by nodeKey with the passed channel funding parameters.
4739
//
4740
// NOTE: This function is safe for concurrent access.
4741
func (s *server) OpenChannel(
4742
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
4✔
4743

4✔
4744
        // The updateChan will have a buffer of 2, since we expect a ChanPending
4✔
4745
        // + a ChanOpen update, and we want to make sure the funding process is
4✔
4746
        // not blocked if the caller is not reading the updates.
4✔
4747
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
4✔
4748
        req.Err = make(chan error, 1)
4✔
4749

4✔
4750
        // First attempt to locate the target peer to open a channel with, if
4✔
4751
        // we're unable to locate the peer then this request will fail.
4✔
4752
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
4✔
4753
        s.mu.RLock()
4✔
4754
        peer, ok := s.peersByPub[string(pubKeyBytes)]
4✔
4755
        if !ok {
4✔
4756
                s.mu.RUnlock()
×
4757

×
4758
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4759
                return req.Updates, req.Err
×
4760
        }
×
4761
        req.Peer = peer
4✔
4762
        s.mu.RUnlock()
4✔
4763

4✔
4764
        // We'll wait until the peer is active before beginning the channel
4✔
4765
        // opening process.
4✔
4766
        select {
4✔
4767
        case <-peer.ActiveSignal():
4✔
4768
        case <-peer.QuitSignal():
×
4769
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4770
                return req.Updates, req.Err
×
4771
        case <-s.quit:
×
4772
                req.Err <- ErrServerShuttingDown
×
4773
                return req.Updates, req.Err
×
4774
        }
4775

4776
        // If the fee rate wasn't specified at this point we fail the funding
4777
        // because of the missing fee rate information. The caller of the
4778
        // `OpenChannel` method needs to make sure that default values for the
4779
        // fee rate are set beforehand.
4780
        if req.FundingFeePerKw == 0 {
4✔
4781
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4782
                        "the channel opening transaction")
×
4783

×
4784
                return req.Updates, req.Err
×
4785
        }
×
4786

4787
        // Spawn a goroutine to send the funding workflow request to the funding
4788
        // manager. This allows the server to continue handling queries instead
4789
        // of blocking on this request which is exported as a synchronous
4790
        // request to the outside world.
4791
        go s.fundingMgr.InitFundingWorkflow(req)
4✔
4792

4✔
4793
        return req.Updates, req.Err
4✔
4794
}
4795

4796
// Peers returns a slice of all active peers.
4797
//
4798
// NOTE: This function is safe for concurrent access.
4799
func (s *server) Peers() []*peer.Brontide {
4✔
4800
        s.mu.RLock()
4✔
4801
        defer s.mu.RUnlock()
4✔
4802

4✔
4803
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
4804
        for _, peer := range s.peersByPub {
8✔
4805
                peers = append(peers, peer)
4✔
4806
        }
4✔
4807

4808
        return peers
4✔
4809
}
4810

4811
// computeNextBackoff uses a truncated exponential backoff to compute the next
4812
// backoff using the value of the exiting backoff. The returned duration is
4813
// randomized in either direction by 1/20 to prevent tight loops from
4814
// stabilizing.
4815
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
4✔
4816
        // Double the current backoff, truncating if it exceeds our maximum.
4✔
4817
        nextBackoff := 2 * currBackoff
4✔
4818
        if nextBackoff > maxBackoff {
8✔
4819
                nextBackoff = maxBackoff
4✔
4820
        }
4✔
4821

4822
        // Using 1/10 of our duration as a margin, compute a random offset to
4823
        // avoid the nodes entering connection cycles.
4824
        margin := nextBackoff / 10
4✔
4825

4✔
4826
        var wiggle big.Int
4✔
4827
        wiggle.SetUint64(uint64(margin))
4✔
4828
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
4✔
4829
                // Randomizing is not mission critical, so we'll just return the
×
4830
                // current backoff.
×
4831
                return nextBackoff
×
4832
        }
×
4833

4834
        // Otherwise add in our wiggle, but subtract out half of the margin so
4835
        // that the backoff can tweaked by 1/20 in either direction.
4836
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
4✔
4837
}
4838

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

4843
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4844
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
4✔
4845
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
4✔
4846
        if err != nil {
4✔
4847
                return nil, err
×
4848
        }
×
4849

4850
        node, err := s.graphDB.FetchLightningNode(vertex)
4✔
4851
        if err != nil {
8✔
4852
                return nil, err
4✔
4853
        }
4✔
4854

4855
        if len(node.Addresses) == 0 {
8✔
4856
                return nil, errNoAdvertisedAddr
4✔
4857
        }
4✔
4858

4859
        return node.Addresses, nil
4✔
4860
}
4861

4862
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4863
// channel update for a target channel.
4864
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4865
        *lnwire.ChannelUpdate1, error) {
4✔
4866

4✔
4867
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
4✔
4868
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
8✔
4869
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
4✔
4870
                if err != nil {
8✔
4871
                        return nil, err
4✔
4872
                }
4✔
4873

4874
                return netann.ExtractChannelUpdate(
4✔
4875
                        ourPubKey[:], info, edge1, edge2,
4✔
4876
                )
4✔
4877
        }
4878
}
4879

4880
// applyChannelUpdate applies the channel update to the different sub-systems of
4881
// the server. The useAlias boolean denotes whether or not to send an alias in
4882
// place of the real SCID.
4883
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
4884
        op *wire.OutPoint, useAlias bool) error {
4✔
4885

4✔
4886
        var (
4✔
4887
                peerAlias    *lnwire.ShortChannelID
4✔
4888
                defaultAlias lnwire.ShortChannelID
4✔
4889
        )
4✔
4890

4✔
4891
        chanID := lnwire.NewChanIDFromOutPoint(*op)
4✔
4892

4✔
4893
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
4✔
4894
        // in the ChannelUpdate if it hasn't been announced yet.
4✔
4895
        if useAlias {
8✔
4896
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
4✔
4897
                if foundAlias != defaultAlias {
8✔
4898
                        peerAlias = &foundAlias
4✔
4899
                }
4✔
4900
        }
4901

4902
        errChan := s.authGossiper.ProcessLocalAnnouncement(
4✔
4903
                update, discovery.RemoteAlias(peerAlias),
4✔
4904
        )
4✔
4905
        select {
4✔
4906
        case err := <-errChan:
4✔
4907
                return err
4✔
4908
        case <-s.quit:
×
4909
                return ErrServerShuttingDown
×
4910
        }
4911
}
4912

4913
// SendCustomMessage sends a custom message to the peer with the specified
4914
// pubkey.
4915
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
4916
        data []byte) error {
4✔
4917

4✔
4918
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
4✔
4919
        if err != nil {
4✔
4920
                return err
×
4921
        }
×
4922

4923
        // We'll wait until the peer is active.
4924
        select {
4✔
4925
        case <-peer.ActiveSignal():
4✔
4926
        case <-peer.QuitSignal():
×
4927
                return fmt.Errorf("peer %x disconnected", peerPub)
×
4928
        case <-s.quit:
×
4929
                return ErrServerShuttingDown
×
4930
        }
4931

4932
        msg, err := lnwire.NewCustom(msgType, data)
4✔
4933
        if err != nil {
8✔
4934
                return err
4✔
4935
        }
4✔
4936

4937
        // Send the message as low-priority. For now we assume that all
4938
        // application-defined message are low priority.
4939
        return peer.SendMessageLazy(true, msg)
4✔
4940
}
4941

4942
// newSweepPkScriptGen creates closure that generates a new public key script
4943
// which should be used to sweep any funds into the on-chain wallet.
4944
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
4945
// (p2wkh) output.
4946
func newSweepPkScriptGen(
4947
        wallet lnwallet.WalletController) func() ([]byte, error) {
4✔
4948

4✔
4949
        return func() ([]byte, error) {
8✔
4950
                sweepAddr, err := wallet.NewAddress(
4✔
4951
                        lnwallet.TaprootPubkey, false,
4✔
4952
                        lnwallet.DefaultAccountName,
4✔
4953
                )
4✔
4954
                if err != nil {
4✔
4955
                        return nil, err
×
4956
                }
×
4957

4958
                return txscript.PayToAddrScript(sweepAddr)
4✔
4959
        }
4960
}
4961

4962
// shouldPeerBootstrap returns true if we should attempt to perform peer
4963
// bootstrapping to actively seek our peers using the set of active network
4964
// bootstrappers.
4965
func shouldPeerBootstrap(cfg *Config) bool {
10✔
4966
        isSimnet := cfg.Bitcoin.SimNet
10✔
4967
        isSignet := cfg.Bitcoin.SigNet
10✔
4968
        isRegtest := cfg.Bitcoin.RegTest
10✔
4969
        isDevNetwork := isSimnet || isSignet || isRegtest
10✔
4970

10✔
4971
        // TODO(yy): remove the check on simnet/regtest such that the itest is
10✔
4972
        // covering the bootstrapping process.
10✔
4973
        return !cfg.NoNetBootstrap && !isDevNetwork
10✔
4974
}
10✔
4975

4976
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
4977
// finished.
4978
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
4✔
4979
        // Get a list of closed channels.
4✔
4980
        channels, err := s.chanStateDB.FetchClosedChannels(false)
4✔
4981
        if err != nil {
4✔
4982
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
4983
                return nil
×
4984
        }
×
4985

4986
        // Save the SCIDs in a map.
4987
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
4✔
4988
        for _, c := range channels {
8✔
4989
                // If the channel is not pending, its FC has been finalized.
4✔
4990
                if !c.IsPending {
8✔
4991
                        closedSCIDs[c.ShortChanID] = struct{}{}
4✔
4992
                }
4✔
4993
        }
4994

4995
        // Double check whether the reported closed channel has indeed finished
4996
        // closing.
4997
        //
4998
        // NOTE: There are misalignments regarding when a channel's FC is
4999
        // marked as finalized. We double check the pending channels to make
5000
        // sure the returned SCIDs are indeed terminated.
5001
        //
5002
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5003
        pendings, err := s.chanStateDB.FetchPendingChannels()
4✔
5004
        if err != nil {
4✔
5005
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5006
                return nil
×
5007
        }
×
5008

5009
        for _, c := range pendings {
8✔
5010
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
8✔
5011
                        continue
4✔
5012
                }
5013

5014
                // If the channel is still reported as pending, remove it from
5015
                // the map.
5016
                delete(closedSCIDs, c.ShortChannelID)
×
5017

×
5018
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5019
                        c.ShortChannelID)
×
5020
        }
5021

5022
        return closedSCIDs
4✔
5023
}
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