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

lightningnetwork / lnd / 10190851021

01 Aug 2024 02:21AM UTC coverage: 58.627% (-0.01%) from 58.641%
10190851021

push

github

web-flow
Merge pull request #8764 from ellemouton/rb-send-via-multi-path

[3/4] Route Blinding: send MPP over multiple blinded paths

197 of 248 new or added lines in 7 files covered. (79.44%)

249 existing lines in 19 files now uncovered.

125259 of 213655 relevant lines covered (58.63%)

28116.45 hits per line

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

64.31
/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/contractcourt"
40
        "github.com/lightningnetwork/lnd/discovery"
41
        "github.com/lightningnetwork/lnd/feature"
42
        "github.com/lightningnetwork/lnd/fn"
43
        "github.com/lightningnetwork/lnd/funding"
44
        "github.com/lightningnetwork/lnd/graph"
45
        "github.com/lightningnetwork/lnd/healthcheck"
46
        "github.com/lightningnetwork/lnd/htlcswitch"
47
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
48
        "github.com/lightningnetwork/lnd/input"
49
        "github.com/lightningnetwork/lnd/invoices"
50
        "github.com/lightningnetwork/lnd/keychain"
51
        "github.com/lightningnetwork/lnd/kvdb"
52
        "github.com/lightningnetwork/lnd/lncfg"
53
        "github.com/lightningnetwork/lnd/lnencrypt"
54
        "github.com/lightningnetwork/lnd/lnpeer"
55
        "github.com/lightningnetwork/lnd/lnrpc"
56
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
57
        "github.com/lightningnetwork/lnd/lnwallet"
58
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
59
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
60
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
61
        "github.com/lightningnetwork/lnd/lnwire"
62
        "github.com/lightningnetwork/lnd/nat"
63
        "github.com/lightningnetwork/lnd/netann"
64
        "github.com/lightningnetwork/lnd/peer"
65
        "github.com/lightningnetwork/lnd/peernotifier"
66
        "github.com/lightningnetwork/lnd/pool"
67
        "github.com/lightningnetwork/lnd/queue"
68
        "github.com/lightningnetwork/lnd/routing"
69
        "github.com/lightningnetwork/lnd/routing/localchans"
70
        "github.com/lightningnetwork/lnd/routing/route"
71
        "github.com/lightningnetwork/lnd/subscribe"
72
        "github.com/lightningnetwork/lnd/sweep"
73
        "github.com/lightningnetwork/lnd/ticker"
74
        "github.com/lightningnetwork/lnd/tor"
75
        "github.com/lightningnetwork/lnd/walletunlocker"
76
        "github.com/lightningnetwork/lnd/watchtower/blob"
77
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
78
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
79
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
80
)
81

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

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

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

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

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

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

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

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

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

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

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

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

157
        start sync.Once
158
        stop  sync.Once
159

160
        cfg *Config
161

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

166
        // identityKeyLoc is the key locator for the above wrapped identity key.
167
        identityKeyLoc keychain.KeyLocator
168

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

173
        chanStatusMgr *netann.ChanStatusManager
174

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

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

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

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

195
        mu         sync.RWMutex
196
        peersByPub map[string]*peer.Brontide
197

198
        inboundPeers  map[string]*peer.Brontide
199
        outboundPeers map[string]*peer.Brontide
200

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

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

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

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

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

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

239
        cc *chainreg.ChainControl
240

241
        fundingMgr *funding.Manager
242

243
        graphDB *channeldb.ChannelGraph
244

245
        chanStateDB *channeldb.ChannelStateDB
246

247
        addrSource chanbackup.AddressSource
248

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

253
        invoicesDB invoices.InvoiceDB
254

255
        aliasMgr *aliasmgr.Manager
256

257
        htlcSwitch *htlcswitch.Switch
258

259
        interceptableSwitch *htlcswitch.InterceptableSwitch
260

261
        invoices *invoices.InvoiceRegistry
262

263
        channelNotifier *channelnotifier.ChannelNotifier
264

265
        peerNotifier *peernotifier.PeerNotifier
266

267
        htlcNotifier *htlcswitch.HtlcNotifier
268

269
        witnessBeacon contractcourt.WitnessBeacon
270

271
        breachArbitrator *contractcourt.BreachArbitrator
272

273
        missionControl *routing.MissionControl
274

275
        graphBuilder *graph.Builder
276

277
        chanRouter *routing.ChannelRouter
278

279
        controlTower routing.ControlTower
280

281
        authGossiper *discovery.AuthenticatedGossiper
282

283
        localChanMgr *localchans.Manager
284

285
        utxoNursery *contractcourt.UtxoNursery
286

287
        sweeper *sweep.UtxoSweeper
288

289
        chainArb *contractcourt.ChainArbitrator
290

291
        sphinx *hop.OnionProcessor
292

293
        towerClientMgr *wtclient.Manager
294

295
        connMgr *connmgr.ConnManager
296

297
        sigPool *lnwallet.SigPool
298

299
        writePool *pool.Write
300

301
        readPool *pool.Read
302

303
        tlsManager *TLSManager
304

305
        // featureMgr dispatches feature vectors for various contexts within the
306
        // daemon.
307
        featureMgr *feature.Manager
308

309
        // currentNodeAnn is the node announcement that has been broadcast to
310
        // the network upon startup, if the attributes of the node (us) has
311
        // changed since last start.
312
        currentNodeAnn *lnwire.NodeAnnouncement
313

314
        // chansToRestore is the set of channels that upon starting, the server
315
        // should attempt to restore/recover.
316
        chansToRestore walletunlocker.ChannelsToRecover
317

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

323
        // chanEventStore tracks the behaviour of channels and their remote peers to
324
        // provide insights into their health and performance.
325
        chanEventStore *chanfitness.ChannelEventStore
326

327
        hostAnn *netann.HostAnnouncer
328

329
        // livenessMonitor monitors that lnd has access to critical resources.
330
        livenessMonitor *healthcheck.Monitor
331

332
        customMessageServer *subscribe.Server
333

334
        // txPublisher is a publisher with fee-bumping capability.
335
        txPublisher *sweep.TxPublisher
336

337
        quit chan struct{}
338

339
        wg sync.WaitGroup
340
}
341

342
// updatePersistentPeerAddrs subscribes to topology changes and stores
343
// advertised addresses for any NodeAnnouncements from our persisted peers.
344
func (s *server) updatePersistentPeerAddrs() error {
3✔
345
        graphSub, err := s.graphBuilder.SubscribeTopology()
3✔
346
        if err != nil {
3✔
347
                return err
×
348
        }
×
349

350
        s.wg.Add(1)
3✔
351
        go func() {
6✔
352
                defer func() {
6✔
353
                        graphSub.Cancel()
3✔
354
                        s.wg.Done()
3✔
355
                }()
3✔
356

357
                for {
6✔
358
                        select {
3✔
359
                        case <-s.quit:
3✔
360
                                return
3✔
361

362
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
363
                                // If the router is shutting down, then we will
3✔
364
                                // as well.
3✔
365
                                if !ok {
3✔
366
                                        return
×
367
                                }
×
368

369
                                for _, update := range topChange.NodeUpdates {
6✔
370
                                        pubKeyStr := string(
3✔
371
                                                update.IdentityKey.
3✔
372
                                                        SerializeCompressed(),
3✔
373
                                        )
3✔
374

3✔
375
                                        // We only care about updates from
3✔
376
                                        // our persistentPeers.
3✔
377
                                        s.mu.RLock()
3✔
378
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
379
                                        s.mu.RUnlock()
3✔
380
                                        if !ok {
6✔
381
                                                continue
3✔
382
                                        }
383

384
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
385
                                                len(update.Addresses))
3✔
386

3✔
387
                                        for _, addr := range update.Addresses {
6✔
388
                                                addrs = append(addrs,
3✔
389
                                                        &lnwire.NetAddress{
3✔
390
                                                                IdentityKey: update.IdentityKey,
3✔
391
                                                                Address:     addr,
3✔
392
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
393
                                                        },
3✔
394
                                                )
3✔
395
                                        }
3✔
396

397
                                        s.mu.Lock()
3✔
398

3✔
399
                                        // Update the stored addresses for this
3✔
400
                                        // to peer to reflect the new set.
3✔
401
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
402

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

413
                                        s.mu.Unlock()
3✔
414

3✔
415
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
416
                                }
417
                        }
418
                }
419
        }()
420

421
        return nil
3✔
422
}
423

424
// CustomMessage is a custom message that is received from a peer.
425
type CustomMessage struct {
426
        // Peer is the peer pubkey
427
        Peer [33]byte
428

429
        // Msg is the custom wire message.
430
        Msg *lnwire.Custom
431
}
432

433
// parseAddr parses an address from its string format to a net.Addr.
434
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
435
        var (
3✔
436
                host string
3✔
437
                port int
3✔
438
        )
3✔
439

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

457
        if tor.IsOnionHost(host) {
3✔
458
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
459
        }
×
460

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

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

3✔
474
        return func(a net.Addr) (net.Conn, error) {
6✔
475
                lnAddr := a.(*lnwire.NetAddress)
3✔
476
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
477
        }
3✔
478
}
479

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

3✔
490
        var (
3✔
491
                err         error
3✔
492
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
493

3✔
494
                // We just derived the full descriptor, so we know the public
3✔
495
                // key is set on it.
3✔
496
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
497
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
498
                )
3✔
499
        )
3✔
500

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

514
        var serializedPubKey [33]byte
3✔
515
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
516

3✔
517
        // Initialize the sphinx router.
3✔
518
        replayLog := htlcswitch.NewDecayedLog(
3✔
519
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
520
        )
3✔
521
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
522

3✔
523
        writeBufferPool := pool.NewWriteBuffer(
3✔
524
                pool.DefaultWriteBufferGCInterval,
3✔
525
                pool.DefaultWriteBufferExpiryInterval,
3✔
526
        )
3✔
527

3✔
528
        writePool := pool.NewWrite(
3✔
529
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
530
        )
3✔
531

3✔
532
        readBufferPool := pool.NewReadBuffer(
3✔
533
                pool.DefaultReadBufferGCInterval,
3✔
534
                pool.DefaultReadBufferExpiryInterval,
3✔
535
        )
3✔
536

3✔
537
        readPool := pool.NewRead(
3✔
538
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
539
        )
3✔
540

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

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

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

3✔
584
                channelNotifier: channelnotifier.New(
3✔
585
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
586
                ),
3✔
587

3✔
588
                identityECDH:   nodeKeyECDH,
3✔
589
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
590
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
591

3✔
592
                listenAddrs: listenAddrs,
3✔
593

3✔
594
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
595
                // schedule
3✔
596
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
597

3✔
598
                torController: torController,
3✔
599

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

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

3✔
616
                customMessageServer: subscribe.NewServer(),
3✔
617

3✔
618
                tlsManager: tlsManager,
3✔
619

3✔
620
                featureMgr: featureMgr,
3✔
621
                quit:       make(chan struct{}),
3✔
622
        }
3✔
623

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

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

3✔
637
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
638

3✔
639
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
640
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
641

3✔
642
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB)
3✔
643
        if err != nil {
3✔
644
                return nil, err
×
645
        }
×
646

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

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

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

699
        s.witnessBeacon = newPreimageBeacon(
3✔
700
                dbs.ChanStateDB.NewWitnessCache(),
3✔
701
                s.interceptableSwitch.ForwardPacket,
3✔
702
        )
3✔
703

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

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

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

×
728
                discoveryTimeout := time.Duration(10 * time.Second)
×
729

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

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

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

756
                        s.natTraversal = pmp
×
757
                }
758
        }
759

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

×
775
                        listenPorts = append(listenPorts, uint16(port))
×
776
                }
×
777

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

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

801
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
802
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
803

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

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

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

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

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

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

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

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

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

3✔
899
                        estimator, err = routing.NewAprioriEstimator(
3✔
900
                                aprioriConfig,
3✔
901
                        )
3✔
902
                        if err != nil {
3✔
903
                                return nil, err
×
904
                        }
×
905

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

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

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

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

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

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

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

3✔
970
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
971

3✔
972
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
973

3✔
974
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
975
                cfg.Routing.StrictZombiePruning
3✔
976

3✔
977
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
978
                SelfNode:            selfNode.PubKeyBytes,
3✔
979
                Graph:               chanGraph,
3✔
980
                Chain:               cc.ChainIO,
3✔
981
                ChainView:           cc.ChainView,
3✔
982
                Notifier:            cc.ChainNotifier,
3✔
983
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
984
                GraphPruneInterval:  time.Hour,
3✔
985
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
986
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
987
                StrictZombiePruning: strictPruning,
3✔
988
                IsAlias:             aliasmgr.IsAlias,
3✔
989
        })
3✔
990
        if err != nil {
3✔
991
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
992
        }
×
993

994
        s.chanRouter, err = routing.New(routing.Config{
3✔
995
                SelfNode:           selfNode.PubKeyBytes,
3✔
996
                RoutingGraph:       graphsession.NewRoutingGraph(chanGraph),
3✔
997
                Chain:              cc.ChainIO,
3✔
998
                Payer:              s.htlcSwitch,
3✔
999
                Control:            s.controlTower,
3✔
1000
                MissionControl:     s.missionControl,
3✔
1001
                SessionSource:      paymentSessionSource,
3✔
1002
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1003
                NextPaymentID:      sequencer.NextID,
3✔
1004
                PathFindingConfig:  pathFindingConfig,
3✔
1005
                Clock:              clock.NewDefaultClock(),
3✔
1006
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1007
        })
3✔
1008
        if err != nil {
3✔
1009
                return nil, fmt.Errorf("can't create router: %w", err)
×
1010
        }
×
1011

1012
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1013
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1014
        if err != nil {
3✔
1015
                return nil, err
×
1016
        }
×
1017
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1018
        if err != nil {
3✔
1019
                return nil, err
×
1020
        }
×
1021

1022
        s.authGossiper = discovery.New(discovery.Config{
3✔
1023
                Graph:                 s.graphBuilder,
3✔
1024
                Notifier:              s.cc.ChainNotifier,
3✔
1025
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1026
                Broadcast:             s.BroadcastMessage,
3✔
1027
                ChanSeries:            chanSeries,
3✔
1028
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1029
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1030
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1031
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1032
                        error) {
3✔
1033

×
1034
                        return s.genNodeAnnouncement(nil)
×
1035
                },
×
1036
                ProofMatureDelta:        0,
1037
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1038
                RetransmitTicker:        ticker.New(time.Minute * 30),
1039
                RebroadcastInterval:     time.Hour * 24,
1040
                WaitingProofStore:       waitingProofStore,
1041
                MessageStore:            gossipMessageStore,
1042
                AnnSigner:               s.nodeSigner,
1043
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1044
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1045
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1046
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:lll
1047
                MinimumBatchSize:        10,
1048
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1049
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1050
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1051
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1052
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1053
                IsAlias:                 aliasmgr.IsAlias,
1054
                SignAliasUpdate:         s.signAliasUpdate,
1055
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1056
                GetAlias:                s.aliasMgr.GetPeerAlias,
1057
                FindChannel:             s.findChannel,
1058
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1059
        }, nodeKeyDesc)
1060

1061
        //nolint:lll
1062
        s.localChanMgr = &localchans.Manager{
3✔
1063
                ForAllOutgoingChannels:    s.graphBuilder.ForAllOutgoingChannels,
3✔
1064
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
3✔
1065
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
3✔
1066
                FetchChannel:              s.chanStateDB.FetchChannel,
3✔
1067
        }
3✔
1068

3✔
1069
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1070
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1071
        )
3✔
1072
        if err != nil {
3✔
1073
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1074
                return nil, err
×
1075
        }
×
1076

1077
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1078
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1079
        )
3✔
1080
        if err != nil {
3✔
1081
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1082
                return nil, err
×
1083
        }
×
1084

1085
        aggregator := sweep.NewBudgetAggregator(
3✔
1086
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1087
        )
3✔
1088

3✔
1089
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1090
                Signer:    cc.Wallet.Cfg.Signer,
3✔
1091
                Wallet:    cc.Wallet,
3✔
1092
                Estimator: cc.FeeEstimator,
3✔
1093
                Notifier:  cc.ChainNotifier,
3✔
1094
        })
3✔
1095

3✔
1096
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1097
                FeeEstimator:         cc.FeeEstimator,
3✔
1098
                GenSweepScript:       newSweepPkScriptGen(cc.Wallet),
3✔
1099
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1100
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1101
                Mempool:              cc.MempoolNotifier,
3✔
1102
                Notifier:             cc.ChainNotifier,
3✔
1103
                Store:                sweeperStore,
3✔
1104
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1105
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1106
                Aggregator:           aggregator,
3✔
1107
                Publisher:            s.txPublisher,
3✔
1108
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1109
        })
3✔
1110

3✔
1111
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1112
                ChainIO:             cc.ChainIO,
3✔
1113
                ConfDepth:           1,
3✔
1114
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1115
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1116
                Notifier:            cc.ChainNotifier,
3✔
1117
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1118
                Store:               utxnStore,
3✔
1119
                SweepInput:          s.sweeper.SweepInput,
3✔
1120
                Budget:              s.cfg.Sweeper.Budget,
3✔
1121
        })
3✔
1122

3✔
1123
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1124
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1125
                closureType contractcourt.ChannelCloseType) {
6✔
1126
                // TODO(conner): Properly respect the update and error channels
3✔
1127
                // returned by CloseLink.
3✔
1128

3✔
1129
                // Instruct the switch to close the channel.  Provide no close out
3✔
1130
                // delivery script or target fee per kw because user input is not
3✔
1131
                // available when the remote peer closes the channel.
3✔
1132
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
3✔
1133
        }
3✔
1134

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

3✔
1139
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1140
                &contractcourt.BreachConfig{
3✔
1141
                        CloseLink:          closeLink,
3✔
1142
                        DB:                 s.chanStateDB,
3✔
1143
                        Estimator:          s.cc.FeeEstimator,
3✔
1144
                        GenSweepScript:     newSweepPkScriptGen(cc.Wallet),
3✔
1145
                        Notifier:           cc.ChainNotifier,
3✔
1146
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1147
                        ContractBreaches:   contractBreaches,
3✔
1148
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1149
                        Store: contractcourt.NewRetributionStore(
3✔
1150
                                dbs.ChanStateDB,
3✔
1151
                        ),
3✔
1152
                },
3✔
1153
        )
3✔
1154

3✔
1155
        //nolint:lll
3✔
1156
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1157
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1158
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1159
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1160
                NewSweepAddr:           newSweepPkScriptGen(cc.Wallet),
3✔
1161
                PublishTx:              cc.Wallet.PublishTransaction,
3✔
1162
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
6✔
1163
                        for _, msg := range msgs {
6✔
1164
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1165
                                if err != nil {
4✔
1166
                                        return err
1✔
1167
                                }
1✔
1168
                        }
1169
                        return nil
3✔
1170
                },
1171
                IncubateOutputs: func(chanPoint wire.OutPoint,
1172
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1173
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1174
                        broadcastHeight uint32,
1175
                        deadlineHeight fn.Option[int32]) error {
3✔
1176

3✔
1177
                        return s.utxoNursery.IncubateOutputs(
3✔
1178
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1179
                                broadcastHeight, deadlineHeight,
3✔
1180
                        )
3✔
1181
                },
3✔
1182
                PreimageDB:   s.witnessBeacon,
1183
                Notifier:     cc.ChainNotifier,
1184
                Mempool:      cc.MempoolNotifier,
1185
                Signer:       cc.Wallet.Cfg.Signer,
1186
                FeeEstimator: cc.FeeEstimator,
1187
                ChainIO:      cc.ChainIO,
1188
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1189
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1190
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1191
                        return nil
3✔
1192
                },
3✔
1193
                IsOurAddress: cc.Wallet.IsOurAddress,
1194
                ContractBreach: func(chanPoint wire.OutPoint,
1195
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1196

3✔
1197
                        // processACK will handle the BreachArbitrator ACKing
3✔
1198
                        // the event.
3✔
1199
                        finalErr := make(chan error, 1)
3✔
1200
                        processACK := func(brarErr error) {
6✔
1201
                                if brarErr != nil {
3✔
1202
                                        finalErr <- brarErr
×
1203
                                        return
×
1204
                                }
×
1205

1206
                                // If the BreachArbitrator successfully handled
1207
                                // the event, we can signal that the handoff
1208
                                // was successful.
1209
                                finalErr <- nil
3✔
1210
                        }
1211

1212
                        event := &contractcourt.ContractBreachEvent{
3✔
1213
                                ChanPoint:         chanPoint,
3✔
1214
                                ProcessACK:        processACK,
3✔
1215
                                BreachRetribution: breachRet,
3✔
1216
                        }
3✔
1217

3✔
1218
                        // Send the contract breach event to the
3✔
1219
                        // BreachArbitrator.
3✔
1220
                        select {
3✔
1221
                        case contractBreaches <- event:
3✔
1222
                        case <-s.quit:
×
1223
                                return ErrServerShuttingDown
×
1224
                        }
1225

1226
                        // We'll wait for a final error to be available from
1227
                        // the BreachArbitrator.
1228
                        select {
3✔
1229
                        case err := <-finalErr:
3✔
1230
                                return err
3✔
1231
                        case <-s.quit:
×
1232
                                return ErrServerShuttingDown
×
1233
                        }
1234
                },
1235
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1236
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1237
                },
3✔
1238
                Sweeper:                       s.sweeper,
1239
                Registry:                      s.invoices,
1240
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1241
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1242
                OnionProcessor:                s.sphinx,
1243
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1244
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1245
                Clock:                         clock.NewDefaultClock(),
1246
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1247
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1248
                HtlcNotifier:                  s.htlcNotifier,
1249
                Budget:                        *s.cfg.Sweeper.Budget,
1250

1251
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1252
                QueryIncomingCircuit: func(
1253
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1254

3✔
1255
                        // Get the circuit map.
3✔
1256
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1257

3✔
1258
                        // Lookup the outgoing circuit.
3✔
1259
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1260
                        if pc == nil {
6✔
1261
                                return nil
3✔
1262
                        }
3✔
1263

1264
                        return &pc.Incoming
3✔
1265
                },
1266
        }, dbs.ChanStateDB)
1267

1268
        // Select the configuration and funding parameters for Bitcoin.
1269
        chainCfg := cfg.Bitcoin
3✔
1270
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1271
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1272

3✔
1273
        var chanIDSeed [32]byte
3✔
1274
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1275
                return nil, err
×
1276
        }
×
1277

1278
        // Wrap the DeleteChannelEdges method so that the funding manager can
1279
        // use it without depending on several layers of indirection.
1280
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1281
                *models.ChannelEdgePolicy, error) {
6✔
1282

3✔
1283
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1284
                        scid.ToUint64(),
3✔
1285
                )
3✔
1286
                if errors.Is(err, channeldb.ErrEdgeNotFound) {
3✔
1287
                        // This is unlikely but there is a slim chance of this
×
1288
                        // being hit if lnd was killed via SIGKILL and the
×
1289
                        // funding manager was stepping through the delete
×
1290
                        // alias edge logic.
×
1291
                        return nil, nil
×
1292
                } else if err != nil {
3✔
1293
                        return nil, err
×
1294
                }
×
1295

1296
                // Grab our key to find our policy.
1297
                var ourKey [33]byte
3✔
1298
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1299

3✔
1300
                var ourPolicy *models.ChannelEdgePolicy
3✔
1301
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1302
                        ourPolicy = e1
3✔
1303
                } else {
6✔
1304
                        ourPolicy = e2
3✔
1305
                }
3✔
1306

1307
                if ourPolicy == nil {
3✔
1308
                        // Something is wrong, so return an error.
×
1309
                        return nil, fmt.Errorf("we don't have an edge")
×
1310
                }
×
1311

1312
                err = s.graphDB.DeleteChannelEdges(
3✔
1313
                        false, false, scid.ToUint64(),
3✔
1314
                )
3✔
1315
                return ourPolicy, err
3✔
1316
        }
1317

1318
        // For the reservationTimeout and the zombieSweeperInterval different
1319
        // values are set in case we are in a dev environment so enhance test
1320
        // capacilities.
1321
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1322
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1323

3✔
1324
        // Get the development config for funding manager. If we are not in
3✔
1325
        // development mode, this would be nil.
3✔
1326
        var devCfg *funding.DevConfig
3✔
1327
        if lncfg.IsDevBuild() {
6✔
1328
                devCfg = &funding.DevConfig{
3✔
1329
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1330
                }
3✔
1331

3✔
1332
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1333
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1334

3✔
1335
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1336
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1337
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1338
        }
3✔
1339

1340
        //nolint:lll
1341
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1342
                Dev:                devCfg,
3✔
1343
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1344
                IDKey:              nodeKeyDesc.PubKey,
3✔
1345
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1346
                Wallet:             cc.Wallet,
3✔
1347
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1348
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1349
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1350
                },
3✔
1351
                Notifier:     cc.ChainNotifier,
1352
                ChannelDB:    s.chanStateDB,
1353
                FeeEstimator: cc.FeeEstimator,
1354
                SignMessage:  cc.MsgSigner.SignMessage,
1355
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1356
                        error) {
3✔
1357

3✔
1358
                        return s.genNodeAnnouncement(nil)
3✔
1359
                },
3✔
1360
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1361
                NotifyWhenOnline:     s.NotifyWhenOnline,
1362
                TempChanIDSeed:       chanIDSeed,
1363
                FindChannel:          s.findChannel,
1364
                DefaultRoutingPolicy: cc.RoutingPolicy,
1365
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1366
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1367
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1368
                        // For large channels we increase the number
3✔
1369
                        // of confirmations we require for the
3✔
1370
                        // channel to be considered open. As it is
3✔
1371
                        // always the responder that gets to choose
3✔
1372
                        // value, the pushAmt is value being pushed
3✔
1373
                        // to us. This means we have more to lose
3✔
1374
                        // in the case this gets re-orged out, and
3✔
1375
                        // we will require more confirmations before
3✔
1376
                        // we consider it open.
3✔
1377

3✔
1378
                        // In case the user has explicitly specified
3✔
1379
                        // a default value for the number of
3✔
1380
                        // confirmations, we use it.
3✔
1381
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1382
                        if defaultConf != 0 {
6✔
1383
                                return defaultConf
3✔
1384
                        }
3✔
1385

1386
                        minConf := uint64(3)
×
1387
                        maxConf := uint64(6)
×
1388

×
1389
                        // If this is a wumbo channel, then we'll require the
×
1390
                        // max amount of confirmations.
×
1391
                        if chanAmt > MaxFundingAmount {
×
1392
                                return uint16(maxConf)
×
1393
                        }
×
1394

1395
                        // If not we return a value scaled linearly
1396
                        // between 3 and 6, depending on channel size.
1397
                        // TODO(halseth): Use 1 as minimum?
1398
                        maxChannelSize := uint64(
×
1399
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1400
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1401
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1402
                        if conf < minConf {
×
1403
                                conf = minConf
×
1404
                        }
×
1405
                        if conf > maxConf {
×
1406
                                conf = maxConf
×
1407
                        }
×
1408
                        return uint16(conf)
×
1409
                },
1410
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1411
                        // We scale the remote CSV delay (the time the
3✔
1412
                        // remote have to claim funds in case of a unilateral
3✔
1413
                        // close) linearly from minRemoteDelay blocks
3✔
1414
                        // for small channels, to maxRemoteDelay blocks
3✔
1415
                        // for channels of size MaxFundingAmount.
3✔
1416

3✔
1417
                        // In case the user has explicitly specified
3✔
1418
                        // a default value for the remote delay, we
3✔
1419
                        // use it.
3✔
1420
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1421
                        if defaultDelay > 0 {
6✔
1422
                                return defaultDelay
3✔
1423
                        }
3✔
1424

1425
                        // If this is a wumbo channel, then we'll require the
1426
                        // max value.
1427
                        if chanAmt > MaxFundingAmount {
×
1428
                                return maxRemoteDelay
×
1429
                        }
×
1430

1431
                        // If not we scale according to channel size.
1432
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1433
                                chanAmt / MaxFundingAmount)
×
1434
                        if delay < minRemoteDelay {
×
1435
                                delay = minRemoteDelay
×
1436
                        }
×
1437
                        if delay > maxRemoteDelay {
×
1438
                                delay = maxRemoteDelay
×
1439
                        }
×
1440
                        return delay
×
1441
                },
1442
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1443
                        peerKey *btcec.PublicKey) error {
3✔
1444

3✔
1445
                        // First, we'll mark this new peer as a persistent peer
3✔
1446
                        // for re-connection purposes. If the peer is not yet
3✔
1447
                        // tracked or the user hasn't requested it to be perm,
3✔
1448
                        // we'll set false to prevent the server from continuing
3✔
1449
                        // to connect to this peer even if the number of
3✔
1450
                        // channels with this peer is zero.
3✔
1451
                        s.mu.Lock()
3✔
1452
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1453
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1454
                                s.persistentPeers[pubStr] = false
3✔
1455
                        }
3✔
1456
                        s.mu.Unlock()
3✔
1457

3✔
1458
                        // With that taken care of, we'll send this channel to
3✔
1459
                        // the chain arb so it can react to on-chain events.
3✔
1460
                        return s.chainArb.WatchNewChannel(channel)
3✔
1461
                },
1462
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1463
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1464
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1465
                },
3✔
1466
                RequiredRemoteChanReserve: func(chanAmt,
1467
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1468

3✔
1469
                        // By default, we'll require the remote peer to maintain
3✔
1470
                        // at least 1% of the total channel capacity at all
3✔
1471
                        // times. If this value ends up dipping below the dust
3✔
1472
                        // limit, then we'll use the dust limit itself as the
3✔
1473
                        // reserve as required by BOLT #2.
3✔
1474
                        reserve := chanAmt / 100
3✔
1475
                        if reserve < dustLimit {
6✔
1476
                                reserve = dustLimit
3✔
1477
                        }
3✔
1478

1479
                        return reserve
3✔
1480
                },
1481
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1482
                        // By default, we'll allow the remote peer to fully
3✔
1483
                        // utilize the full bandwidth of the channel, minus our
3✔
1484
                        // required reserve.
3✔
1485
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1486
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1487
                },
3✔
1488
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1489
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1490
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1491
                        }
3✔
1492

1493
                        // By default, we'll permit them to utilize the full
1494
                        // channel bandwidth.
1495
                        return uint16(input.MaxHTLCNumber / 2)
×
1496
                },
1497
                ZombieSweeperInterval:         zombieSweeperInterval,
1498
                ReservationTimeout:            reservationTimeout,
1499
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1500
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1501
                MaxPendingChannels:            cfg.MaxPendingChannels,
1502
                RejectPush:                    cfg.RejectPush,
1503
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1504
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1505
                OpenChannelPredicate:          chanPredicate,
1506
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1507
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1508
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1509
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1510
                DeleteAliasEdge:   deleteAliasEdge,
1511
                AliasManager:      s.aliasMgr,
1512
                IsSweeperOutpoint: s.sweeper.IsSweeperOutpoint,
1513
        })
1514
        if err != nil {
3✔
1515
                return nil, err
×
1516
        }
×
1517

1518
        // Next, we'll assemble the sub-system that will maintain an on-disk
1519
        // static backup of the latest channel state.
1520
        chanNotifier := &channelNotifier{
3✔
1521
                chanNotifier: s.channelNotifier,
3✔
1522
                addrs:        dbs.ChanStateDB,
3✔
1523
        }
3✔
1524
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
3✔
1525
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1526
                s.chanStateDB, s.addrSource,
3✔
1527
        )
3✔
1528
        if err != nil {
3✔
1529
                return nil, err
×
1530
        }
×
1531
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1532
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1533
        )
3✔
1534
        if err != nil {
3✔
1535
                return nil, err
×
1536
        }
×
1537

1538
        // Assemble a peer notifier which will provide clients with subscriptions
1539
        // to peer online and offline events.
1540
        s.peerNotifier = peernotifier.New()
3✔
1541

3✔
1542
        // Create a channel event store which monitors all open channels.
3✔
1543
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1544
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1545
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1546
                },
3✔
1547
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1548
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1549
                },
3✔
1550
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1551
                Clock:           clock.NewDefaultClock(),
1552
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1553
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1554
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1555
        })
1556

1557
        if cfg.WtClient.Active {
6✔
1558
                policy := wtpolicy.DefaultPolicy()
3✔
1559
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1560

3✔
1561
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1562
                // protocol operations on sat/kw.
3✔
1563
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1564
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1565
                )
3✔
1566

3✔
1567
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1568

3✔
1569
                if err := policy.Validate(); err != nil {
3✔
1570
                        return nil, err
×
1571
                }
×
1572

1573
                // authDial is the wrapper around the btrontide.Dial for the
1574
                // watchtower.
1575
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1576
                        netAddr *lnwire.NetAddress,
3✔
1577
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1578

3✔
1579
                        return brontide.Dial(
3✔
1580
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1581
                        )
3✔
1582
                }
3✔
1583

1584
                // buildBreachRetribution is a call-back that can be used to
1585
                // query the BreachRetribution info and channel type given a
1586
                // channel ID and commitment height.
1587
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1588
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1589
                        channeldb.ChannelType, error) {
6✔
1590

3✔
1591
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1592
                                nil, chanID,
3✔
1593
                        )
3✔
1594
                        if err != nil {
3✔
1595
                                return nil, 0, err
×
1596
                        }
×
1597

1598
                        br, err := lnwallet.NewBreachRetribution(
3✔
1599
                                channel, commitHeight, 0, nil,
3✔
1600
                        )
3✔
1601
                        if err != nil {
3✔
1602
                                return nil, 0, err
×
1603
                        }
×
1604

1605
                        return br, channel.ChanType, nil
3✔
1606
                }
1607

1608
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1609

3✔
1610
                // Copy the policy for legacy channels and set the blob flag
3✔
1611
                // signalling support for anchor channels.
3✔
1612
                anchorPolicy := policy
3✔
1613
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1614

3✔
1615
                // Copy the policy for legacy channels and set the blob flag
3✔
1616
                // signalling support for taproot channels.
3✔
1617
                taprootPolicy := policy
3✔
1618
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1619
                        blob.FlagTaprootChannel,
3✔
1620
                )
3✔
1621

3✔
1622
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1623
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1624
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1625
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1626
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1627
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1628
                                error) {
6✔
1629

3✔
1630
                                return s.channelNotifier.
3✔
1631
                                        SubscribeChannelEvents()
3✔
1632
                        },
3✔
1633
                        Signer:             cc.Wallet.Cfg.Signer,
1634
                        NewAddress:         newSweepPkScriptGen(cc.Wallet),
1635
                        SecretKeyRing:      s.cc.KeyRing,
1636
                        Dial:               cfg.net.Dial,
1637
                        AuthDial:           authDial,
1638
                        DB:                 dbs.TowerClientDB,
1639
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1640
                        MinBackoff:         10 * time.Second,
1641
                        MaxBackoff:         5 * time.Minute,
1642
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1643
                }, policy, anchorPolicy, taprootPolicy)
1644
                if err != nil {
3✔
1645
                        return nil, err
×
1646
                }
×
1647
        }
1648

1649
        if len(cfg.ExternalHosts) != 0 {
3✔
1650
                advertisedIPs := make(map[string]struct{})
×
1651
                for _, addr := range s.currentNodeAnn.Addresses {
×
1652
                        advertisedIPs[addr.String()] = struct{}{}
×
1653
                }
×
1654

1655
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1656
                        Hosts:         cfg.ExternalHosts,
×
1657
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1658
                        LookupHost: func(host string) (net.Addr, error) {
×
1659
                                return lncfg.ParseAddressString(
×
1660
                                        host, strconv.Itoa(defaultPeerPort),
×
1661
                                        cfg.net.ResolveTCPAddr,
×
1662
                                )
×
1663
                        },
×
1664
                        AdvertisedIPs: advertisedIPs,
1665
                        AnnounceNewIPs: netann.IPAnnouncer(
1666
                                func(modifier ...netann.NodeAnnModifier) (
1667
                                        lnwire.NodeAnnouncement, error) {
×
1668

×
1669
                                        return s.genNodeAnnouncement(
×
1670
                                                nil, modifier...,
×
1671
                                        )
×
1672
                                }),
×
1673
                })
1674
        }
1675

1676
        // Create liveness monitor.
1677
        s.createLivenessMonitor(cfg, cc)
3✔
1678

3✔
1679
        // Create the connection manager which will be responsible for
3✔
1680
        // maintaining persistent outbound connections and also accepting new
3✔
1681
        // incoming connections
3✔
1682
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1683
                Listeners:      listeners,
3✔
1684
                OnAccept:       s.InboundPeerConnected,
3✔
1685
                RetryDuration:  time.Second * 5,
3✔
1686
                TargetOutbound: 100,
3✔
1687
                Dial: noiseDial(
3✔
1688
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1689
                ),
3✔
1690
                OnConnection: s.OutboundPeerConnected,
3✔
1691
        })
3✔
1692
        if err != nil {
3✔
1693
                return nil, err
×
1694
        }
×
1695
        s.connMgr = cmgr
3✔
1696

3✔
1697
        return s, nil
3✔
1698
}
1699

1700
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1701
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1702
// may differ from what is on disk.
1703
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate) (*ecdsa.Signature,
1704
        error) {
3✔
1705

3✔
1706
        data, err := u.DataToSign()
3✔
1707
        if err != nil {
3✔
1708
                return nil, err
×
1709
        }
×
1710

1711
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1712
}
1713

1714
// createLivenessMonitor creates a set of health checks using our configured
1715
// values and uses these checks to create a liveness monitor. Available
1716
// health checks,
1717
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1718
//   - diskCheck
1719
//   - tlsHealthCheck
1720
//   - torController, only created when tor is enabled.
1721
//
1722
// If a health check has been disabled by setting attempts to 0, our monitor
1723
// will not run it.
1724
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl) {
3✔
1725
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1726
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1727
                srvrLog.Info("Disabling chain backend checks for " +
×
1728
                        "nochainbackend mode")
×
1729

×
1730
                chainBackendAttempts = 0
×
1731
        }
×
1732

1733
        chainHealthCheck := healthcheck.NewObservation(
3✔
1734
                "chain backend",
3✔
1735
                cc.HealthCheck,
3✔
1736
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1737
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1738
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1739
                chainBackendAttempts,
3✔
1740
        )
3✔
1741

3✔
1742
        diskCheck := healthcheck.NewObservation(
3✔
1743
                "disk space",
3✔
1744
                func() error {
3✔
1745
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1746
                                cfg.LndDir,
×
1747
                        )
×
1748
                        if err != nil {
×
1749
                                return err
×
1750
                        }
×
1751

1752
                        // If we have more free space than we require,
1753
                        // we return a nil error.
1754
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1755
                                return nil
×
1756
                        }
×
1757

1758
                        return fmt.Errorf("require: %v free space, got: %v",
×
1759
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1760
                                free)
×
1761
                },
1762
                cfg.HealthChecks.DiskCheck.Interval,
1763
                cfg.HealthChecks.DiskCheck.Timeout,
1764
                cfg.HealthChecks.DiskCheck.Backoff,
1765
                cfg.HealthChecks.DiskCheck.Attempts,
1766
        )
1767

1768
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1769
                "tls",
3✔
1770
                func() error {
3✔
1771
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1772
                                s.cc.KeyRing,
×
1773
                        )
×
1774
                        if err != nil {
×
1775
                                return err
×
1776
                        }
×
1777
                        if expired {
×
1778
                                return fmt.Errorf("TLS certificate is "+
×
1779
                                        "expired as of %v", expTime)
×
1780
                        }
×
1781

1782
                        // If the certificate is not outdated, no error needs
1783
                        // to be returned
1784
                        return nil
×
1785
                },
1786
                cfg.HealthChecks.TLSCheck.Interval,
1787
                cfg.HealthChecks.TLSCheck.Timeout,
1788
                cfg.HealthChecks.TLSCheck.Backoff,
1789
                cfg.HealthChecks.TLSCheck.Attempts,
1790
        )
1791

1792
        checks := []*healthcheck.Observation{
3✔
1793
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1794
        }
3✔
1795

3✔
1796
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
1797
        if s.torController != nil {
3✔
1798
                torConnectionCheck := healthcheck.NewObservation(
×
1799
                        "tor connection",
×
1800
                        func() error {
×
1801
                                return healthcheck.CheckTorServiceStatus(
×
1802
                                        s.torController,
×
1803
                                        s.createNewHiddenService,
×
1804
                                )
×
1805
                        },
×
1806
                        cfg.HealthChecks.TorConnection.Interval,
1807
                        cfg.HealthChecks.TorConnection.Timeout,
1808
                        cfg.HealthChecks.TorConnection.Backoff,
1809
                        cfg.HealthChecks.TorConnection.Attempts,
1810
                )
1811
                checks = append(checks, torConnectionCheck)
×
1812
        }
1813

1814
        // If remote signing is enabled, add the healthcheck for the remote
1815
        // signing RPC interface.
1816
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
1817
                // Because we have two cascading timeouts here, we need to add
3✔
1818
                // some slack to the "outer" one of them in case the "inner"
3✔
1819
                // returns exactly on time.
3✔
1820
                overhead := time.Millisecond * 10
3✔
1821

3✔
1822
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
1823
                        "remote signer connection",
3✔
1824
                        rpcwallet.HealthCheck(
3✔
1825
                                s.cfg.RemoteSigner,
3✔
1826

3✔
1827
                                // For the health check we might to be even
3✔
1828
                                // stricter than the initial/normal connect, so
3✔
1829
                                // we use the health check timeout here.
3✔
1830
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
1831
                        ),
3✔
1832
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
1833
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
1834
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
1835
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
1836
                )
3✔
1837
                checks = append(checks, remoteSignerConnectionCheck)
3✔
1838
        }
3✔
1839

1840
        // If we have not disabled all of our health checks, we create a
1841
        // liveness monitor with our configured checks.
1842
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
1843
                &healthcheck.Config{
3✔
1844
                        Checks:   checks,
3✔
1845
                        Shutdown: srvrLog.Criticalf,
3✔
1846
                },
3✔
1847
        )
3✔
1848
}
1849

1850
// Started returns true if the server has been started, and false otherwise.
1851
// NOTE: This function is safe for concurrent access.
1852
func (s *server) Started() bool {
3✔
1853
        return atomic.LoadInt32(&s.active) != 0
3✔
1854
}
3✔
1855

1856
// cleaner is used to aggregate "cleanup" functions during an operation that
1857
// starts several subsystems. In case one of the subsystem fails to start
1858
// and a proper resource cleanup is required, the "run" method achieves this
1859
// by running all these added "cleanup" functions.
1860
type cleaner []func() error
1861

1862
// add is used to add a cleanup function to be called when
1863
// the run function is executed.
1864
func (c cleaner) add(cleanup func() error) cleaner {
3✔
1865
        return append(c, cleanup)
3✔
1866
}
3✔
1867

1868
// run is used to run all the previousely added cleanup functions.
1869
func (c cleaner) run() {
×
1870
        for i := len(c) - 1; i >= 0; i-- {
×
1871
                if err := c[i](); err != nil {
×
1872
                        srvrLog.Infof("Cleanup failed: %v", err)
×
1873
                }
×
1874
        }
1875
}
1876

1877
// Start starts the main daemon server, all requested listeners, and any helper
1878
// goroutines.
1879
// NOTE: This function is safe for concurrent access.
1880
func (s *server) Start() error {
3✔
1881
        var startErr error
3✔
1882

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

3✔
1888
        s.start.Do(func() {
6✔
1889
                if err := s.customMessageServer.Start(); err != nil {
3✔
1890
                        startErr = err
×
1891
                        return
×
1892
                }
×
1893
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
1894

3✔
1895
                if s.hostAnn != nil {
3✔
1896
                        if err := s.hostAnn.Start(); err != nil {
×
1897
                                startErr = err
×
1898
                                return
×
1899
                        }
×
1900
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
1901
                }
1902

1903
                if s.livenessMonitor != nil {
6✔
1904
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
1905
                                startErr = err
×
1906
                                return
×
1907
                        }
×
1908
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
1909
                }
1910

1911
                // Start the notification server. This is used so channel
1912
                // management goroutines can be notified when a funding
1913
                // transaction reaches a sufficient number of confirmations, or
1914
                // when the input for the funding transaction is spent in an
1915
                // attempt at an uncooperative close by the counterparty.
1916
                if err := s.sigPool.Start(); err != nil {
3✔
1917
                        startErr = err
×
1918
                        return
×
1919
                }
×
1920
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
1921

3✔
1922
                if err := s.writePool.Start(); err != nil {
3✔
1923
                        startErr = err
×
1924
                        return
×
1925
                }
×
1926
                cleanup = cleanup.add(s.writePool.Stop)
3✔
1927

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

3✔
1934
                if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
1935
                        startErr = err
×
1936
                        return
×
1937
                }
×
1938
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
1939

3✔
1940
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
1941
                        startErr = err
×
1942
                        return
×
1943
                }
×
1944
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
1945

3✔
1946
                if err := s.channelNotifier.Start(); err != nil {
3✔
1947
                        startErr = err
×
1948
                        return
×
1949
                }
×
1950
                cleanup = cleanup.add(s.channelNotifier.Stop)
3✔
1951

3✔
1952
                if err := s.peerNotifier.Start(); err != nil {
3✔
1953
                        startErr = err
×
1954
                        return
×
1955
                }
×
1956
                cleanup = cleanup.add(func() error {
3✔
1957
                        return s.peerNotifier.Stop()
×
1958
                })
×
1959
                if err := s.htlcNotifier.Start(); err != nil {
3✔
1960
                        startErr = err
×
1961
                        return
×
1962
                }
×
1963
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
1964

3✔
1965
                if s.towerClientMgr != nil {
6✔
1966
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
1967
                                startErr = err
×
1968
                                return
×
1969
                        }
×
1970
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
1971
                }
1972

1973
                if err := s.txPublisher.Start(); err != nil {
3✔
1974
                        startErr = err
×
1975
                        return
×
1976
                }
×
1977
                cleanup = cleanup.add(func() error {
3✔
1978
                        s.txPublisher.Stop()
×
1979
                        return nil
×
1980
                })
×
1981

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

3✔
1988
                if err := s.utxoNursery.Start(); err != nil {
3✔
1989
                        startErr = err
×
1990
                        return
×
1991
                }
×
1992
                cleanup = cleanup.add(s.utxoNursery.Stop)
3✔
1993

3✔
1994
                if err := s.breachArbitrator.Start(); err != nil {
3✔
1995
                        startErr = err
×
1996
                        return
×
1997
                }
×
1998
                cleanup = cleanup.add(s.breachArbitrator.Stop)
3✔
1999

3✔
2000
                if err := s.fundingMgr.Start(); err != nil {
3✔
2001
                        startErr = err
×
2002
                        return
×
2003
                }
×
2004
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
2005

3✔
2006
                // htlcSwitch must be started before chainArb since the latter
3✔
2007
                // relies on htlcSwitch to deliver resolution message upon
3✔
2008
                // start.
3✔
2009
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2010
                        startErr = err
×
2011
                        return
×
2012
                }
×
2013
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2014

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

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

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

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

3✔
2039
                if err := s.chanRouter.Start(); err != nil {
3✔
2040
                        startErr = err
×
2041
                        return
×
2042
                }
×
2043
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2044

3✔
2045
                if err := s.invoices.Start(); err != nil {
3✔
2046
                        startErr = err
×
2047
                        return
×
2048
                }
×
2049
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2050

3✔
2051
                if err := s.sphinx.Start(); err != nil {
3✔
2052
                        startErr = err
×
2053
                        return
×
2054
                }
×
2055
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2056

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

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

2072
                s.missionControl.RunStoreTicker()
3✔
2073
                cleanup.add(func() error {
3✔
2074
                        s.missionControl.StopStoreTicker()
×
2075
                        return nil
×
2076
                })
×
2077

2078
                // Before we start the connMgr, we'll check to see if we have
2079
                // any backups to recover. We do this now as we want to ensure
2080
                // that have all the information we need to handle channel
2081
                // recovery _before_ we even accept connections from any peers.
2082
                chanRestorer := &chanDBRestorer{
3✔
2083
                        db:         s.chanStateDB,
3✔
2084
                        secretKeys: s.cc.KeyRing,
3✔
2085
                        chainArb:   s.chainArb,
3✔
2086
                }
3✔
2087
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2088
                        err := chanbackup.UnpackAndRecoverSingles(
×
2089
                                s.chansToRestore.PackedSingleChanBackups,
×
2090
                                s.cc.KeyRing, chanRestorer, s,
×
2091
                        )
×
2092
                        if err != nil {
×
2093
                                startErr = fmt.Errorf("unable to unpack single "+
×
2094
                                        "backups: %v", err)
×
2095
                                return
×
2096
                        }
×
2097
                }
2098
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2099
                        err := chanbackup.UnpackAndRecoverMulti(
3✔
2100
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2101
                                s.cc.KeyRing, chanRestorer, s,
3✔
2102
                        )
3✔
2103
                        if err != nil {
3✔
2104
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2105
                                        "backup: %v", err)
×
2106
                                return
×
2107
                        }
×
2108
                }
2109

2110
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2111
                        startErr = err
×
2112
                        return
×
2113
                }
×
2114
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2115

3✔
2116
                if s.torController != nil {
3✔
2117
                        if err := s.createNewHiddenService(); err != nil {
×
2118
                                startErr = err
×
2119
                                return
×
2120
                        }
×
2121
                        cleanup = cleanup.add(s.torController.Stop)
×
2122
                }
2123

2124
                if s.natTraversal != nil {
3✔
2125
                        s.wg.Add(1)
×
2126
                        go s.watchExternalIP()
×
2127
                }
×
2128

2129
                // Start connmgr last to prevent connections before init.
2130
                s.connMgr.Start()
3✔
2131
                cleanup = cleanup.add(func() error {
3✔
2132
                        s.connMgr.Stop()
×
2133
                        return nil
×
2134
                })
×
2135

2136
                // If peers are specified as a config option, we'll add those
2137
                // peers first.
2138
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2139
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2140
                                peerAddrCfg,
3✔
2141
                        )
3✔
2142
                        if err != nil {
3✔
2143
                                startErr = fmt.Errorf("unable to parse peer "+
×
2144
                                        "pubkey from config: %v", err)
×
2145
                                return
×
2146
                        }
×
2147
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2148
                        if err != nil {
3✔
2149
                                startErr = fmt.Errorf("unable to parse peer "+
×
2150
                                        "address provided as a config option: "+
×
2151
                                        "%v", err)
×
2152
                                return
×
2153
                        }
×
2154

2155
                        peerAddr := &lnwire.NetAddress{
3✔
2156
                                IdentityKey: parsedPubkey,
3✔
2157
                                Address:     addr,
3✔
2158
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2159
                        }
3✔
2160

3✔
2161
                        err = s.ConnectToPeer(
3✔
2162
                                peerAddr, true,
3✔
2163
                                s.cfg.ConnectionTimeout,
3✔
2164
                        )
3✔
2165
                        if err != nil {
3✔
2166
                                startErr = fmt.Errorf("unable to connect to "+
×
2167
                                        "peer address provided as a config "+
×
2168
                                        "option: %v", err)
×
2169
                                return
×
2170
                        }
×
2171
                }
2172

2173
                // Subscribe to NodeAnnouncements that advertise new addresses
2174
                // our persistent peers.
2175
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2176
                        startErr = err
×
2177
                        return
×
2178
                }
×
2179

2180
                // With all the relevant sub-systems started, we'll now attempt
2181
                // to establish persistent connections to our direct channel
2182
                // collaborators within the network. Before doing so however,
2183
                // we'll prune our set of link nodes found within the database
2184
                // to ensure we don't reconnect to any nodes we no longer have
2185
                // open channels with.
2186
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2187
                        startErr = err
×
2188
                        return
×
2189
                }
×
2190
                if err := s.establishPersistentConnections(); err != nil {
3✔
2191
                        startErr = err
×
2192
                        return
×
2193
                }
×
2194

2195
                // setSeedList is a helper function that turns multiple DNS seed
2196
                // server tuples from the command line or config file into the
2197
                // data structure we need and does a basic formal sanity check
2198
                // in the process.
2199
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2200
                        if len(tuples) == 0 {
×
2201
                                return
×
2202
                        }
×
2203

2204
                        result := make([][2]string, len(tuples))
×
2205
                        for idx, tuple := range tuples {
×
2206
                                tuple = strings.TrimSpace(tuple)
×
2207
                                if len(tuple) == 0 {
×
2208
                                        return
×
2209
                                }
×
2210

2211
                                servers := strings.Split(tuple, ",")
×
2212
                                if len(servers) > 2 || len(servers) == 0 {
×
2213
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2214
                                                "seed tuple: %v", servers)
×
2215
                                        return
×
2216
                                }
×
2217

2218
                                copy(result[idx][:], servers)
×
2219
                        }
2220

2221
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2222
                }
2223

2224
                // Let users overwrite the DNS seed nodes. We only allow them
2225
                // for bitcoin mainnet/testnet/signet.
2226
                if s.cfg.Bitcoin.MainNet {
3✔
2227
                        setSeedList(
×
2228
                                s.cfg.Bitcoin.DNSSeeds,
×
2229
                                chainreg.BitcoinMainnetGenesis,
×
2230
                        )
×
2231
                }
×
2232
                if s.cfg.Bitcoin.TestNet3 {
3✔
2233
                        setSeedList(
×
2234
                                s.cfg.Bitcoin.DNSSeeds,
×
2235
                                chainreg.BitcoinTestnetGenesis,
×
2236
                        )
×
2237
                }
×
2238
                if s.cfg.Bitcoin.SigNet {
3✔
2239
                        setSeedList(
×
2240
                                s.cfg.Bitcoin.DNSSeeds,
×
2241
                                chainreg.BitcoinSignetGenesis,
×
2242
                        )
×
2243
                }
×
2244

2245
                // If network bootstrapping hasn't been disabled, then we'll
2246
                // configure the set of active bootstrappers, and launch a
2247
                // dedicated goroutine to maintain a set of persistent
2248
                // connections.
2249
                if shouldPeerBootstrap(s.cfg) {
3✔
2250
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2251
                        if err != nil {
×
2252
                                startErr = err
×
2253
                                return
×
2254
                        }
×
2255

2256
                        s.wg.Add(1)
×
2257
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2258
                } else {
3✔
2259
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2260
                }
3✔
2261

2262
                // Set the active flag now that we've completed the full
2263
                // startup.
2264
                atomic.StoreInt32(&s.active, 1)
3✔
2265
        })
2266

2267
        if startErr != nil {
3✔
2268
                cleanup.run()
×
2269
        }
×
2270
        return startErr
3✔
2271
}
2272

2273
// Stop gracefully shutsdown the main daemon server. This function will signal
2274
// any active goroutines, or helper objects to exit, then blocks until they've
2275
// all successfully exited. Additionally, any/all listeners are closed.
2276
// NOTE: This function is safe for concurrent access.
2277
func (s *server) Stop() error {
3✔
2278
        s.stop.Do(func() {
6✔
2279
                atomic.StoreInt32(&s.stopping, 1)
3✔
2280

3✔
2281
                close(s.quit)
3✔
2282

3✔
2283
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2284
                s.connMgr.Stop()
3✔
2285

3✔
2286
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2287
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2288
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2289
                }
×
2290
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2291
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2292
                }
×
2293
                if err := s.sphinx.Stop(); err != nil {
3✔
2294
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2295
                }
×
2296
                if err := s.invoices.Stop(); err != nil {
3✔
2297
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2298
                }
×
2299
                if err := s.chanRouter.Stop(); err != nil {
3✔
2300
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2301
                }
×
2302
                if err := s.chainArb.Stop(); err != nil {
3✔
2303
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2304
                }
×
2305
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2306
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2307
                }
×
2308
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2309
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2310
                                err)
×
2311
                }
×
2312
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2313
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2314
                }
×
2315
                if err := s.authGossiper.Stop(); err != nil {
3✔
2316
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2317
                }
×
2318
                if err := s.sweeper.Stop(); err != nil {
3✔
2319
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2320
                }
×
2321

2322
                s.txPublisher.Stop()
3✔
2323

3✔
2324
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2325
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2326
                }
×
2327
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2328
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2329
                }
×
2330
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2331
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2332
                }
×
2333
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2334
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2335
                }
×
2336
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2337
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2338
                }
×
2339
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2340
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2341
                                err)
×
2342
                }
×
2343
                s.chanEventStore.Stop()
3✔
2344
                s.missionControl.StopStoreTicker()
3✔
2345

3✔
2346
                // Disconnect from each active peers to ensure that
3✔
2347
                // peerTerminationWatchers signal completion to each peer.
3✔
2348
                for _, peer := range s.Peers() {
6✔
2349
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2350
                        if err != nil {
3✔
2351
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2352
                                        "received error: %v", peer.IdentityKey(),
×
2353
                                        err,
×
2354
                                )
×
2355
                        }
×
2356
                }
2357

2358
                // Now that all connections have been torn down, stop the tower
2359
                // client which will reliably flush all queued states to the
2360
                // tower. If this is halted for any reason, the force quit timer
2361
                // will kick in and abort to allow this method to return.
2362
                if s.towerClientMgr != nil {
6✔
2363
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2364
                                srvrLog.Warnf("Unable to shut down tower "+
×
2365
                                        "client manager: %v", err)
×
2366
                        }
×
2367
                }
2368

2369
                if s.hostAnn != nil {
3✔
2370
                        if err := s.hostAnn.Stop(); err != nil {
×
2371
                                srvrLog.Warnf("unable to shut down host "+
×
2372
                                        "annoucner: %v", err)
×
2373
                        }
×
2374
                }
2375

2376
                if s.livenessMonitor != nil {
6✔
2377
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2378
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2379
                                        "monitor: %v", err)
×
2380
                        }
×
2381
                }
2382

2383
                // Wait for all lingering goroutines to quit.
2384
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2385
                s.wg.Wait()
3✔
2386

3✔
2387
                srvrLog.Debug("Stopping buffer pools...")
3✔
2388
                s.sigPool.Stop()
3✔
2389
                s.writePool.Stop()
3✔
2390
                s.readPool.Stop()
3✔
2391
        })
2392

2393
        return nil
3✔
2394
}
2395

2396
// Stopped returns true if the server has been instructed to shutdown.
2397
// NOTE: This function is safe for concurrent access.
2398
func (s *server) Stopped() bool {
3✔
2399
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2400
}
3✔
2401

2402
// configurePortForwarding attempts to set up port forwarding for the different
2403
// ports that the server will be listening on.
2404
//
2405
// NOTE: This should only be used when using some kind of NAT traversal to
2406
// automatically set up forwarding rules.
2407
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2408
        ip, err := s.natTraversal.ExternalIP()
×
2409
        if err != nil {
×
2410
                return nil, err
×
2411
        }
×
2412
        s.lastDetectedIP = ip
×
2413

×
2414
        externalIPs := make([]string, 0, len(ports))
×
2415
        for _, port := range ports {
×
2416
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2417
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2418
                        continue
×
2419
                }
2420

2421
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2422
                externalIPs = append(externalIPs, hostIP)
×
2423
        }
2424

2425
        return externalIPs, nil
×
2426
}
2427

2428
// removePortForwarding attempts to clear the forwarding rules for the different
2429
// ports the server is currently listening on.
2430
//
2431
// NOTE: This should only be used when using some kind of NAT traversal to
2432
// automatically set up forwarding rules.
2433
func (s *server) removePortForwarding() {
×
2434
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2435
        for _, port := range forwardedPorts {
×
2436
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2437
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2438
                                "port %d: %v", port, err)
×
2439
                }
×
2440
        }
2441
}
2442

2443
// watchExternalIP continuously checks for an updated external IP address every
2444
// 15 minutes. Once a new IP address has been detected, it will automatically
2445
// handle port forwarding rules and send updated node announcements to the
2446
// currently connected peers.
2447
//
2448
// NOTE: This MUST be run as a goroutine.
2449
func (s *server) watchExternalIP() {
×
2450
        defer s.wg.Done()
×
2451

×
2452
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2453
        // up by the server.
×
2454
        defer s.removePortForwarding()
×
2455

×
2456
        // Keep track of the external IPs set by the user to avoid replacing
×
2457
        // them when detecting a new IP.
×
2458
        ipsSetByUser := make(map[string]struct{})
×
2459
        for _, ip := range s.cfg.ExternalIPs {
×
2460
                ipsSetByUser[ip.String()] = struct{}{}
×
2461
        }
×
2462

2463
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2464

×
2465
        ticker := time.NewTicker(15 * time.Minute)
×
2466
        defer ticker.Stop()
×
2467
out:
×
2468
        for {
×
2469
                select {
×
2470
                case <-ticker.C:
×
2471
                        // We'll start off by making sure a new IP address has
×
2472
                        // been detected.
×
2473
                        ip, err := s.natTraversal.ExternalIP()
×
2474
                        if err != nil {
×
2475
                                srvrLog.Debugf("Unable to retrieve the "+
×
2476
                                        "external IP address: %v", err)
×
2477
                                continue
×
2478
                        }
2479

2480
                        // Periodically renew the NAT port forwarding.
2481
                        for _, port := range forwardedPorts {
×
2482
                                err := s.natTraversal.AddPortMapping(port)
×
2483
                                if err != nil {
×
2484
                                        srvrLog.Warnf("Unable to automatically "+
×
2485
                                                "re-create port forwarding using %s: %v",
×
2486
                                                s.natTraversal.Name(), err)
×
2487
                                } else {
×
2488
                                        srvrLog.Debugf("Automatically re-created "+
×
2489
                                                "forwarding for port %d using %s to "+
×
2490
                                                "advertise external IP",
×
2491
                                                port, s.natTraversal.Name())
×
2492
                                }
×
2493
                        }
2494

2495
                        if ip.Equal(s.lastDetectedIP) {
×
2496
                                continue
×
2497
                        }
2498

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

×
2501
                        // Next, we'll craft the new addresses that will be
×
2502
                        // included in the new node announcement and advertised
×
2503
                        // to the network. Each address will consist of the new
×
2504
                        // IP detected and one of the currently advertised
×
2505
                        // ports.
×
2506
                        var newAddrs []net.Addr
×
2507
                        for _, port := range forwardedPorts {
×
2508
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2509
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2510
                                if err != nil {
×
2511
                                        srvrLog.Debugf("Unable to resolve "+
×
2512
                                                "host %v: %v", addr, err)
×
2513
                                        continue
×
2514
                                }
2515

2516
                                newAddrs = append(newAddrs, addr)
×
2517
                        }
2518

2519
                        // Skip the update if we weren't able to resolve any of
2520
                        // the new addresses.
2521
                        if len(newAddrs) == 0 {
×
2522
                                srvrLog.Debug("Skipping node announcement " +
×
2523
                                        "update due to not being able to " +
×
2524
                                        "resolve any new addresses")
×
2525
                                continue
×
2526
                        }
2527

2528
                        // Now, we'll need to update the addresses in our node's
2529
                        // announcement in order to propagate the update
2530
                        // throughout the network. We'll only include addresses
2531
                        // that have a different IP from the previous one, as
2532
                        // the previous IP is no longer valid.
2533
                        currentNodeAnn := s.getNodeAnnouncement()
×
2534

×
2535
                        for _, addr := range currentNodeAnn.Addresses {
×
2536
                                host, _, err := net.SplitHostPort(addr.String())
×
2537
                                if err != nil {
×
2538
                                        srvrLog.Debugf("Unable to determine "+
×
2539
                                                "host from address %v: %v",
×
2540
                                                addr, err)
×
2541
                                        continue
×
2542
                                }
2543

2544
                                // We'll also make sure to include external IPs
2545
                                // set manually by the user.
2546
                                _, setByUser := ipsSetByUser[addr.String()]
×
2547
                                if setByUser || host != s.lastDetectedIP.String() {
×
2548
                                        newAddrs = append(newAddrs, addr)
×
2549
                                }
×
2550
                        }
2551

2552
                        // Then, we'll generate a new timestamped node
2553
                        // announcement with the updated addresses and broadcast
2554
                        // it to our peers.
2555
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2556
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2557
                        )
×
2558
                        if err != nil {
×
2559
                                srvrLog.Debugf("Unable to generate new node "+
×
2560
                                        "announcement: %v", err)
×
2561
                                continue
×
2562
                        }
2563

2564
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2565
                        if err != nil {
×
2566
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2567
                                        "announcement to peers: %v", err)
×
2568
                                continue
×
2569
                        }
2570

2571
                        // Finally, update the last IP seen to the current one.
2572
                        s.lastDetectedIP = ip
×
2573
                case <-s.quit:
×
2574
                        break out
×
2575
                }
2576
        }
2577
}
2578

2579
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2580
// based on the server, and currently active bootstrap mechanisms as defined
2581
// within the current configuration.
2582
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2583
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2584

×
2585
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2586

×
2587
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2588
        // this can be used by default if we've already partially seeded the
×
2589
        // network.
×
2590
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2591
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2592
        if err != nil {
×
2593
                return nil, err
×
2594
        }
×
2595
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2596

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

×
2602
                // If we have a set of DNS seeds for this chain, then we'll add
×
2603
                // it as an additional bootstrapping source.
×
2604
                if ok {
×
2605
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2606
                                "seeds: %v", dnsSeeds)
×
2607

×
2608
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2609
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2610
                        )
×
2611
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2612
                }
×
2613
        }
2614

2615
        return bootStrappers, nil
×
2616
}
2617

2618
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2619
// needs to ignore, which is made of three parts,
2620
//   - the node itself needs to be skipped as it doesn't make sense to connect
2621
//     to itself.
2622
//   - the peers that already have connections with, as in s.peersByPub.
2623
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2624
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2625
        s.mu.RLock()
×
2626
        defer s.mu.RUnlock()
×
2627

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

×
2630
        // We should ignore ourselves from bootstrapping.
×
2631
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2632
        ignore[selfKey] = struct{}{}
×
2633

×
2634
        // Ignore all connected peers.
×
2635
        for _, peer := range s.peersByPub {
×
2636
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2637
                ignore[nID] = struct{}{}
×
2638
        }
×
2639

2640
        // Ignore all persistent peers as they have a dedicated reconnecting
2641
        // process.
2642
        for pubKeyStr := range s.persistentPeers {
×
2643
                var nID autopilot.NodeID
×
2644
                copy(nID[:], []byte(pubKeyStr))
×
2645
                ignore[nID] = struct{}{}
×
2646
        }
×
2647

2648
        return ignore
×
2649
}
2650

2651
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2652
// and maintain a target minimum number of outbound connections. With this
2653
// invariant, we ensure that our node is connected to a diverse set of peers
2654
// and that nodes newly joining the network receive an up to date network view
2655
// as soon as possible.
2656
func (s *server) peerBootstrapper(numTargetPeers uint32,
2657
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2658

×
2659
        defer s.wg.Done()
×
2660

×
2661
        // Before we continue, init the ignore peers map.
×
2662
        ignoreList := s.createBootstrapIgnorePeers()
×
2663

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

×
2668
        // Once done, we'll attempt to maintain our target minimum number of
×
2669
        // peers.
×
2670
        //
×
2671
        // We'll use a 15 second backoff, and double the time every time an
×
2672
        // epoch fails up to a ceiling.
×
2673
        backOff := time.Second * 15
×
2674

×
2675
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2676
        // see if we've reached our minimum number of peers.
×
2677
        sampleTicker := time.NewTicker(backOff)
×
2678
        defer sampleTicker.Stop()
×
2679

×
2680
        // We'll use the number of attempts and errors to determine if we need
×
2681
        // to increase the time between discovery epochs.
×
2682
        var epochErrors uint32 // To be used atomically.
×
2683
        var epochAttempts uint32
×
2684

×
2685
        for {
×
2686
                select {
×
2687
                // The ticker has just woken us up, so we'll need to check if
2688
                // we need to attempt to connect our to any more peers.
2689
                case <-sampleTicker.C:
×
2690
                        // Obtain the current number of peers, so we can gauge
×
2691
                        // if we need to sample more peers or not.
×
2692
                        s.mu.RLock()
×
2693
                        numActivePeers := uint32(len(s.peersByPub))
×
2694
                        s.mu.RUnlock()
×
2695

×
2696
                        // If we have enough peers, then we can loop back
×
2697
                        // around to the next round as we're done here.
×
2698
                        if numActivePeers >= numTargetPeers {
×
2699
                                continue
×
2700
                        }
2701

2702
                        // If all of our attempts failed during this last back
2703
                        // off period, then will increase our backoff to 5
2704
                        // minute ceiling to avoid an excessive number of
2705
                        // queries
2706
                        //
2707
                        // TODO(roasbeef): add reverse policy too?
2708

2709
                        if epochAttempts > 0 &&
×
2710
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2711

×
2712
                                sampleTicker.Stop()
×
2713

×
2714
                                backOff *= 2
×
2715
                                if backOff > bootstrapBackOffCeiling {
×
2716
                                        backOff = bootstrapBackOffCeiling
×
2717
                                }
×
2718

2719
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2720
                                        "%v", backOff)
×
2721
                                sampleTicker = time.NewTicker(backOff)
×
2722
                                continue
×
2723
                        }
2724

2725
                        atomic.StoreUint32(&epochErrors, 0)
×
2726
                        epochAttempts = 0
×
2727

×
2728
                        // Since we know need more peers, we'll compute the
×
2729
                        // exact number we need to reach our threshold.
×
2730
                        numNeeded := numTargetPeers - numActivePeers
×
2731

×
2732
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2733
                                "peers", numNeeded)
×
2734

×
2735
                        // With the number of peers we need calculated, we'll
×
2736
                        // query the network bootstrappers to sample a set of
×
2737
                        // random addrs for us.
×
2738
                        //
×
2739
                        // Before we continue, get a copy of the ignore peers
×
2740
                        // map.
×
2741
                        ignoreList = s.createBootstrapIgnorePeers()
×
2742

×
2743
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2744
                                ignoreList, numNeeded*2, bootstrappers...,
×
2745
                        )
×
2746
                        if err != nil {
×
2747
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2748
                                        "peers: %v", err)
×
2749
                                continue
×
2750
                        }
2751

2752
                        // Finally, we'll launch a new goroutine for each
2753
                        // prospective peer candidates.
2754
                        for _, addr := range peerAddrs {
×
2755
                                epochAttempts++
×
2756

×
2757
                                go func(a *lnwire.NetAddress) {
×
2758
                                        // TODO(roasbeef): can do AS, subnet,
×
2759
                                        // country diversity, etc
×
2760
                                        errChan := make(chan error, 1)
×
2761
                                        s.connectToPeer(
×
2762
                                                a, errChan,
×
2763
                                                s.cfg.ConnectionTimeout,
×
2764
                                        )
×
2765
                                        select {
×
2766
                                        case err := <-errChan:
×
2767
                                                if err == nil {
×
2768
                                                        return
×
2769
                                                }
×
2770

2771
                                                srvrLog.Errorf("Unable to "+
×
2772
                                                        "connect to %v: %v",
×
2773
                                                        a, err)
×
2774
                                                atomic.AddUint32(&epochErrors, 1)
×
2775
                                        case <-s.quit:
×
2776
                                        }
2777
                                }(addr)
2778
                        }
2779
                case <-s.quit:
×
2780
                        return
×
2781
                }
2782
        }
2783
}
2784

2785
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
2786
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
2787
// query back off each time we encounter a failure.
2788
const bootstrapBackOffCeiling = time.Minute * 5
2789

2790
// initialPeerBootstrap attempts to continuously connect to peers on startup
2791
// until the target number of peers has been reached. This ensures that nodes
2792
// receive an up to date network view as soon as possible.
2793
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2794
        numTargetPeers uint32,
2795
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2796

×
2797
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
2798
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
2799

×
2800
        // We'll start off by waiting 2 seconds between failed attempts, then
×
2801
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
2802
        var delaySignal <-chan time.Time
×
2803
        delayTime := time.Second * 2
×
2804

×
2805
        // As want to be more aggressive, we'll use a lower back off celling
×
2806
        // then the main peer bootstrap logic.
×
2807
        backOffCeiling := bootstrapBackOffCeiling / 5
×
2808

×
2809
        for attempts := 0; ; attempts++ {
×
2810
                // Check if the server has been requested to shut down in order
×
2811
                // to prevent blocking.
×
2812
                if s.Stopped() {
×
2813
                        return
×
2814
                }
×
2815

2816
                // We can exit our aggressive initial peer bootstrapping stage
2817
                // if we've reached out target number of peers.
2818
                s.mu.RLock()
×
2819
                numActivePeers := uint32(len(s.peersByPub))
×
2820
                s.mu.RUnlock()
×
2821

×
2822
                if numActivePeers >= numTargetPeers {
×
2823
                        return
×
2824
                }
×
2825

2826
                if attempts > 0 {
×
2827
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
2828
                                "bootstrap peers (attempt #%v)", delayTime,
×
2829
                                attempts)
×
2830

×
2831
                        // We've completed at least one iterating and haven't
×
2832
                        // finished, so we'll start to insert a delay period
×
2833
                        // between each attempt.
×
2834
                        delaySignal = time.After(delayTime)
×
2835
                        select {
×
2836
                        case <-delaySignal:
×
2837
                        case <-s.quit:
×
2838
                                return
×
2839
                        }
2840

2841
                        // After our delay, we'll double the time we wait up to
2842
                        // the max back off period.
2843
                        delayTime *= 2
×
2844
                        if delayTime > backOffCeiling {
×
2845
                                delayTime = backOffCeiling
×
2846
                        }
×
2847
                }
2848

2849
                // Otherwise, we'll request for the remaining number of peers
2850
                // in order to reach our target.
2851
                peersNeeded := numTargetPeers - numActivePeers
×
2852
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
2853
                        ignore, peersNeeded, bootstrappers...,
×
2854
                )
×
2855
                if err != nil {
×
2856
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
2857
                                "peers: %v", err)
×
2858
                        continue
×
2859
                }
2860

2861
                // Then, we'll attempt to establish a connection to the
2862
                // different peer addresses retrieved by our bootstrappers.
2863
                var wg sync.WaitGroup
×
2864
                for _, bootstrapAddr := range bootstrapAddrs {
×
2865
                        wg.Add(1)
×
2866
                        go func(addr *lnwire.NetAddress) {
×
2867
                                defer wg.Done()
×
2868

×
2869
                                errChan := make(chan error, 1)
×
2870
                                go s.connectToPeer(
×
2871
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
2872
                                )
×
2873

×
2874
                                // We'll only allow this connection attempt to
×
2875
                                // take up to 3 seconds. This allows us to move
×
2876
                                // quickly by discarding peers that are slowing
×
2877
                                // us down.
×
2878
                                select {
×
2879
                                case err := <-errChan:
×
2880
                                        if err == nil {
×
2881
                                                return
×
2882
                                        }
×
2883
                                        srvrLog.Errorf("Unable to connect to "+
×
2884
                                                "%v: %v", addr, err)
×
2885
                                // TODO: tune timeout? 3 seconds might be *too*
2886
                                // aggressive but works well.
2887
                                case <-time.After(3 * time.Second):
×
2888
                                        srvrLog.Tracef("Skipping peer %v due "+
×
2889
                                                "to not establishing a "+
×
2890
                                                "connection within 3 seconds",
×
2891
                                                addr)
×
2892
                                case <-s.quit:
×
2893
                                }
2894
                        }(bootstrapAddr)
2895
                }
2896

2897
                wg.Wait()
×
2898
        }
2899
}
2900

2901
// createNewHiddenService automatically sets up a v2 or v3 onion service in
2902
// order to listen for inbound connections over Tor.
2903
func (s *server) createNewHiddenService() error {
×
2904
        // Determine the different ports the server is listening on. The onion
×
2905
        // service's virtual port will map to these ports and one will be picked
×
2906
        // at random when the onion service is being accessed.
×
2907
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
2908
        for _, listenAddr := range s.listenAddrs {
×
2909
                port := listenAddr.(*net.TCPAddr).Port
×
2910
                listenPorts = append(listenPorts, port)
×
2911
        }
×
2912

2913
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
2914
        if err != nil {
×
2915
                return err
×
2916
        }
×
2917

2918
        // Once the port mapping has been set, we can go ahead and automatically
2919
        // create our onion service. The service's private key will be saved to
2920
        // disk in order to regain access to this service when restarting `lnd`.
2921
        onionCfg := tor.AddOnionConfig{
×
2922
                VirtualPort: defaultPeerPort,
×
2923
                TargetPorts: listenPorts,
×
2924
                Store: tor.NewOnionFile(
×
2925
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
2926
                        encrypter,
×
2927
                ),
×
2928
        }
×
2929

×
2930
        switch {
×
2931
        case s.cfg.Tor.V2:
×
2932
                onionCfg.Type = tor.V2
×
2933
        case s.cfg.Tor.V3:
×
2934
                onionCfg.Type = tor.V3
×
2935
        }
2936

2937
        addr, err := s.torController.AddOnion(onionCfg)
×
2938
        if err != nil {
×
2939
                return err
×
2940
        }
×
2941

2942
        // Now that the onion service has been created, we'll add the onion
2943
        // address it can be reached at to our list of advertised addresses.
2944
        newNodeAnn, err := s.genNodeAnnouncement(
×
2945
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
2946
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
2947
                },
×
2948
        )
2949
        if err != nil {
×
2950
                return fmt.Errorf("unable to generate new node "+
×
2951
                        "announcement: %v", err)
×
2952
        }
×
2953

2954
        // Finally, we'll update the on-disk version of our announcement so it
2955
        // will eventually propagate to nodes in the network.
2956
        selfNode := &channeldb.LightningNode{
×
2957
                HaveNodeAnnouncement: true,
×
2958
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
2959
                Addresses:            newNodeAnn.Addresses,
×
2960
                Alias:                newNodeAnn.Alias.String(),
×
2961
                Features: lnwire.NewFeatureVector(
×
2962
                        newNodeAnn.Features, lnwire.Features,
×
2963
                ),
×
2964
                Color:        newNodeAnn.RGBColor,
×
2965
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
2966
        }
×
2967
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
2968
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
2969
                return fmt.Errorf("can't set self node: %w", err)
×
2970
        }
×
2971

2972
        return nil
×
2973
}
2974

2975
// findChannel finds a channel given a public key and ChannelID. It is an
2976
// optimization that is quicker than seeking for a channel given only the
2977
// ChannelID.
2978
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
2979
        *channeldb.OpenChannel, error) {
3✔
2980

3✔
2981
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
2982
        if err != nil {
3✔
2983
                return nil, err
×
2984
        }
×
2985

2986
        for _, channel := range nodeChans {
6✔
2987
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
2988
                        return channel, nil
3✔
2989
                }
3✔
2990
        }
2991

2992
        return nil, fmt.Errorf("unable to find channel")
3✔
2993
}
2994

2995
// getNodeAnnouncement fetches the current, fully signed node announcement.
2996
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
2997
        s.mu.Lock()
3✔
2998
        defer s.mu.Unlock()
3✔
2999

3✔
3000
        return *s.currentNodeAnn
3✔
3001
}
3✔
3002

3003
// genNodeAnnouncement generates and returns the current fully signed node
3004
// announcement. The time stamp of the announcement will be updated in order
3005
// to ensure it propagates through the network.
3006
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3007
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3008

3✔
3009
        s.mu.Lock()
3✔
3010
        defer s.mu.Unlock()
3✔
3011

3✔
3012
        // First, try to update our feature manager with the updated set of
3✔
3013
        // features.
3✔
3014
        if features != nil {
6✔
3015
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3016
                        feature.SetNodeAnn: features,
3✔
3017
                }
3✔
3018
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3019
                if err != nil {
6✔
3020
                        return lnwire.NodeAnnouncement{}, err
3✔
3021
                }
3✔
3022

3023
                // If we could successfully update our feature manager, add
3024
                // an update modifier to include these new features to our
3025
                // set.
3026
                modifiers = append(
3✔
3027
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3028
                )
3✔
3029
        }
3030

3031
        // Always update the timestamp when refreshing to ensure the update
3032
        // propagates.
3033
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3034

3✔
3035
        // Apply the requested changes to the node announcement.
3✔
3036
        for _, modifier := range modifiers {
6✔
3037
                modifier(s.currentNodeAnn)
3✔
3038
        }
3✔
3039

3040
        // Sign a new update after applying all of the passed modifiers.
3041
        err := netann.SignNodeAnnouncement(
3✔
3042
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3043
        )
3✔
3044
        if err != nil {
3✔
3045
                return lnwire.NodeAnnouncement{}, err
×
3046
        }
×
3047

3048
        return *s.currentNodeAnn, nil
3✔
3049
}
3050

3051
// updateAndBrodcastSelfNode generates a new node announcement
3052
// applying the giving modifiers and updating the time stamp
3053
// to ensure it propagates through the network. Then it brodcasts
3054
// it to the network.
3055
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
3056
        modifiers ...netann.NodeAnnModifier) error {
3✔
3057

3✔
3058
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3059
        if err != nil {
6✔
3060
                return fmt.Errorf("unable to generate new node "+
3✔
3061
                        "announcement: %v", err)
3✔
3062
        }
3✔
3063

3064
        // Update the on-disk version of our announcement.
3065
        // Load and modify self node istead of creating anew instance so we
3066
        // don't risk overwriting any existing values.
3067
        selfNode, err := s.graphDB.SourceNode()
3✔
3068
        if err != nil {
3✔
3069
                return fmt.Errorf("unable to get current source node: %w", err)
×
3070
        }
×
3071

3072
        selfNode.HaveNodeAnnouncement = true
3✔
3073
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3074
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3075
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3076
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3077
        selfNode.Color = newNodeAnn.RGBColor
3✔
3078
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3079

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

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

3086
        // Finally, propagate it to the nodes in the network.
3087
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3088
        if err != nil {
3✔
3089
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3090
                        "announcement to peers: %v", err)
×
3091
                return err
×
3092
        }
×
3093

3094
        return nil
3✔
3095
}
3096

3097
type nodeAddresses struct {
3098
        pubKey    *btcec.PublicKey
3099
        addresses []net.Addr
3100
}
3101

3102
// establishPersistentConnections attempts to establish persistent connections
3103
// to all our direct channel collaborators. In order to promote liveness of our
3104
// active channels, we instruct the connection manager to attempt to establish
3105
// and maintain persistent connections to all our direct channel counterparties.
3106
func (s *server) establishPersistentConnections() error {
3✔
3107
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3108
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3109
        // since other PubKey forms can't be compared.
3✔
3110
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3111

3✔
3112
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3113
        // attempt to connect to based on our set of previous connections. Set
3✔
3114
        // the reconnection port to the default peer port.
3✔
3115
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3116
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3117
                return err
×
3118
        }
×
3119
        for _, node := range linkNodes {
6✔
3120
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3121
                nodeAddrs := &nodeAddresses{
3✔
3122
                        pubKey:    node.IdentityPub,
3✔
3123
                        addresses: node.Addresses,
3✔
3124
                }
3✔
3125
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3126
        }
3✔
3127

3128
        // After checking our previous connections for addresses to connect to,
3129
        // iterate through the nodes in our channel graph to find addresses
3130
        // that have been added via NodeAnnouncement messages.
3131
        sourceNode, err := s.graphDB.SourceNode()
3✔
3132
        if err != nil {
3✔
3133
                return err
×
3134
        }
×
3135

3136
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3137
        // each of the nodes.
3138
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3139
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3140
                tx kvdb.RTx,
3✔
3141
                chanInfo *models.ChannelEdgeInfo,
3✔
3142
                policy, _ *models.ChannelEdgePolicy) error {
6✔
3143

3✔
3144
                // If the remote party has announced the channel to us, but we
3✔
3145
                // haven't yet, then we won't have a policy. However, we don't
3✔
3146
                // need this to connect to the peer, so we'll log it and move on.
3✔
3147
                if policy == nil {
3✔
3148
                        srvrLog.Warnf("No channel policy found for "+
×
3149
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3150
                }
×
3151

3152
                // We'll now fetch the peer opposite from us within this
3153
                // channel so we can queue up a direct connection to them.
3154
                channelPeer, err := s.graphDB.FetchOtherNode(
3✔
3155
                        tx, chanInfo, selfPub,
3✔
3156
                )
3✔
3157
                if err != nil {
3✔
3158
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3159
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3160
                                err)
×
3161
                }
×
3162

3163
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3164

3✔
3165
                // Add all unique addresses from channel
3✔
3166
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3167
                // connect to for this peer.
3✔
3168
                addrSet := make(map[string]net.Addr)
3✔
3169
                for _, addr := range channelPeer.Addresses {
6✔
3170
                        switch addr.(type) {
3✔
3171
                        case *net.TCPAddr:
3✔
3172
                                addrSet[addr.String()] = addr
3✔
3173

3174
                        // We'll only attempt to connect to Tor addresses if Tor
3175
                        // outbound support is enabled.
3176
                        case *tor.OnionAddr:
×
3177
                                if s.cfg.Tor.Active {
×
3178
                                        addrSet[addr.String()] = addr
×
3179
                                }
×
3180
                        }
3181
                }
3182

3183
                // If this peer is also recorded as a link node, we'll add any
3184
                // additional addresses that have not already been selected.
3185
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3186
                if ok {
6✔
3187
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3188
                                switch lnAddress.(type) {
3✔
3189
                                case *net.TCPAddr:
3✔
3190
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3191

3192
                                // We'll only attempt to connect to Tor
3193
                                // addresses if Tor outbound support is enabled.
3194
                                case *tor.OnionAddr:
×
3195
                                        if s.cfg.Tor.Active {
×
3196
                                                addrSet[lnAddress.String()] = lnAddress
×
3197
                                        }
×
3198
                                }
3199
                        }
3200
                }
3201

3202
                // Construct a slice of the deduped addresses.
3203
                var addrs []net.Addr
3✔
3204
                for _, addr := range addrSet {
6✔
3205
                        addrs = append(addrs, addr)
3✔
3206
                }
3✔
3207

3208
                n := &nodeAddresses{
3✔
3209
                        addresses: addrs,
3✔
3210
                }
3✔
3211
                n.pubKey, err = channelPeer.PubKey()
3✔
3212
                if err != nil {
3✔
3213
                        return err
×
3214
                }
×
3215

3216
                nodeAddrsMap[pubStr] = n
3✔
3217
                return nil
3✔
3218
        })
3219
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
3✔
3220
                return err
×
3221
        }
×
3222

3223
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3224
                len(nodeAddrsMap))
3✔
3225

3✔
3226
        // Acquire and hold server lock until all persistent connection requests
3✔
3227
        // have been recorded and sent to the connection manager.
3✔
3228
        s.mu.Lock()
3✔
3229
        defer s.mu.Unlock()
3✔
3230

3✔
3231
        // Iterate through the combined list of addresses from prior links and
3✔
3232
        // node announcements and attempt to reconnect to each node.
3✔
3233
        var numOutboundConns int
3✔
3234
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3235
                // Add this peer to the set of peers we should maintain a
3✔
3236
                // persistent connection with. We set the value to false to
3✔
3237
                // indicate that we should not continue to reconnect if the
3✔
3238
                // number of channels returns to zero, since this peer has not
3✔
3239
                // been requested as perm by the user.
3✔
3240
                s.persistentPeers[pubStr] = false
3✔
3241
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3242
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3243
                }
3✔
3244

3245
                for _, address := range nodeAddr.addresses {
6✔
3246
                        // Create a wrapper address which couples the IP and
3✔
3247
                        // the pubkey so the brontide authenticated connection
3✔
3248
                        // can be established.
3✔
3249
                        lnAddr := &lnwire.NetAddress{
3✔
3250
                                IdentityKey: nodeAddr.pubKey,
3✔
3251
                                Address:     address,
3✔
3252
                        }
3✔
3253

3✔
3254
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3255
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3256
                }
3✔
3257

3258
                // We'll connect to the first 10 peers immediately, then
3259
                // randomly stagger any remaining connections if the
3260
                // stagger initial reconnect flag is set. This ensures
3261
                // that mobile nodes or nodes with a small number of
3262
                // channels obtain connectivity quickly, but larger
3263
                // nodes are able to disperse the costs of connecting to
3264
                // all peers at once.
3265
                if numOutboundConns < numInstantInitReconnect ||
3✔
3266
                        !s.cfg.StaggerInitialReconnect {
6✔
3267

3✔
3268
                        go s.connectToPersistentPeer(pubStr)
3✔
3269
                } else {
3✔
3270
                        go s.delayInitialReconnect(pubStr)
×
3271
                }
×
3272

3273
                numOutboundConns++
3✔
3274
        }
3275

3276
        return nil
3✔
3277
}
3278

3279
// delayInitialReconnect will attempt a reconnection to the given peer after
3280
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3281
//
3282
// NOTE: This method MUST be run as a goroutine.
3283
func (s *server) delayInitialReconnect(pubStr string) {
×
3284
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3285
        select {
×
3286
        case <-time.After(delay):
×
3287
                s.connectToPersistentPeer(pubStr)
×
3288
        case <-s.quit:
×
3289
        }
3290
}
3291

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

3✔
3298
        s.mu.Lock()
3✔
3299
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3300
                delete(s.persistentPeers, pubKeyStr)
3✔
3301
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3302
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3303
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3304
                s.mu.Unlock()
3✔
3305

3✔
3306
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3307
                        "peer has no open channels", compressedPubKey)
3✔
3308

3✔
3309
                return
3✔
3310
        }
3✔
3311
        s.mu.Unlock()
3✔
3312
}
3313

3314
// BroadcastMessage sends a request to the server to broadcast a set of
3315
// messages to all peers other than the one specified by the `skips` parameter.
3316
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3317
// the target peers.
3318
//
3319
// NOTE: This function is safe for concurrent access.
3320
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3321
        msgs ...lnwire.Message) error {
3✔
3322

3✔
3323
        // Filter out peers found in the skips map. We synchronize access to
3✔
3324
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3325
        // exact set of peers present at the time of invocation.
3✔
3326
        s.mu.RLock()
3✔
3327
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3328
        for pubStr, sPeer := range s.peersByPub {
6✔
3329
                if skips != nil {
6✔
3330
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3331
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3332
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3333
                                continue
3✔
3334
                        }
3335
                }
3336

3337
                peers = append(peers, sPeer)
3✔
3338
        }
3339
        s.mu.RUnlock()
3✔
3340

3✔
3341
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3342
        // all messages to each of peers.
3✔
3343
        var wg sync.WaitGroup
3✔
3344
        for _, sPeer := range peers {
6✔
3345
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3346
                        sPeer.PubKey())
3✔
3347

3✔
3348
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3349
                wg.Add(1)
3✔
3350
                s.wg.Add(1)
3✔
3351
                go func(p lnpeer.Peer) {
6✔
3352
                        defer s.wg.Done()
3✔
3353
                        defer wg.Done()
3✔
3354

3✔
3355
                        p.SendMessageLazy(false, msgs...)
3✔
3356
                }(sPeer)
3✔
3357
        }
3358

3359
        // Wait for all messages to have been dispatched before returning to
3360
        // caller.
3361
        wg.Wait()
3✔
3362

3✔
3363
        return nil
3✔
3364
}
3365

3366
// NotifyWhenOnline can be called by other subsystems to get notified when a
3367
// particular peer comes online. The peer itself is sent across the peerChan.
3368
//
3369
// NOTE: This function is safe for concurrent access.
3370
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3371
        peerChan chan<- lnpeer.Peer) {
3✔
3372

3✔
3373
        s.mu.Lock()
3✔
3374

3✔
3375
        // Compute the target peer's identifier.
3✔
3376
        pubStr := string(peerKey[:])
3✔
3377

3✔
3378
        // Check if peer is connected.
3✔
3379
        peer, ok := s.peersByPub[pubStr]
3✔
3380
        if ok {
6✔
3381
                // Unlock here so that the mutex isn't held while we are
3✔
3382
                // waiting for the peer to become active.
3✔
3383
                s.mu.Unlock()
3✔
3384

3✔
3385
                // Wait until the peer signals that it is actually active
3✔
3386
                // rather than only in the server's maps.
3✔
3387
                select {
3✔
3388
                case <-peer.ActiveSignal():
3✔
3389
                case <-peer.QuitSignal():
×
3390
                        // The peer quit, so we'll add the channel to the slice
×
3391
                        // and return.
×
3392
                        s.mu.Lock()
×
3393
                        s.peerConnectedListeners[pubStr] = append(
×
3394
                                s.peerConnectedListeners[pubStr], peerChan,
×
3395
                        )
×
3396
                        s.mu.Unlock()
×
3397
                        return
×
3398
                }
3399

3400
                // Connected, can return early.
3401
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3402

3✔
3403
                select {
3✔
3404
                case peerChan <- peer:
3✔
3405
                case <-s.quit:
×
3406
                }
3407

3408
                return
3✔
3409
        }
3410

3411
        // Not connected, store this listener such that it can be notified when
3412
        // the peer comes online.
3413
        s.peerConnectedListeners[pubStr] = append(
3✔
3414
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3415
        )
3✔
3416
        s.mu.Unlock()
3✔
3417
}
3418

3419
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3420
// the given public key has been disconnected. The notification is signaled by
3421
// closing the channel returned.
3422
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3423
        s.mu.Lock()
3✔
3424
        defer s.mu.Unlock()
3✔
3425

3✔
3426
        c := make(chan struct{})
3✔
3427

3✔
3428
        // If the peer is already offline, we can immediately trigger the
3✔
3429
        // notification.
3✔
3430
        peerPubKeyStr := string(peerPubKey[:])
3✔
3431
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3432
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3433
                close(c)
×
3434
                return c
×
3435
        }
×
3436

3437
        // Otherwise, the peer is online, so we'll keep track of the channel to
3438
        // trigger the notification once the server detects the peer
3439
        // disconnects.
3440
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3441
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3442
        )
3✔
3443

3✔
3444
        return c
3✔
3445
}
3446

3447
// FindPeer will return the peer that corresponds to the passed in public key.
3448
// This function is used by the funding manager, allowing it to update the
3449
// daemon's local representation of the remote peer.
3450
//
3451
// NOTE: This function is safe for concurrent access.
3452
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3453
        s.mu.RLock()
3✔
3454
        defer s.mu.RUnlock()
3✔
3455

3✔
3456
        pubStr := string(peerKey.SerializeCompressed())
3✔
3457

3✔
3458
        return s.findPeerByPubStr(pubStr)
3✔
3459
}
3✔
3460

3461
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3462
// which should be a string representation of the peer's serialized, compressed
3463
// public key.
3464
//
3465
// NOTE: This function is safe for concurrent access.
3466
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3467
        s.mu.RLock()
3✔
3468
        defer s.mu.RUnlock()
3✔
3469

3✔
3470
        return s.findPeerByPubStr(pubStr)
3✔
3471
}
3✔
3472

3473
// findPeerByPubStr is an internal method that retrieves the specified peer from
3474
// the server's internal state using.
3475
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3476
        peer, ok := s.peersByPub[pubStr]
3✔
3477
        if !ok {
6✔
3478
                return nil, ErrPeerNotConnected
3✔
3479
        }
3✔
3480

3481
        return peer, nil
3✔
3482
}
3483

3484
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3485
// exponential backoff. If no previous backoff was known, the default is
3486
// returned.
3487
func (s *server) nextPeerBackoff(pubStr string,
3488
        startTime time.Time) time.Duration {
3✔
3489

3✔
3490
        // Now, determine the appropriate backoff to use for the retry.
3✔
3491
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3492
        if !ok {
6✔
3493
                // If an existing backoff was unknown, use the default.
3✔
3494
                return s.cfg.MinBackoff
3✔
3495
        }
3✔
3496

3497
        // If the peer failed to start properly, we'll just use the previous
3498
        // backoff to compute the subsequent randomized exponential backoff
3499
        // duration. This will roughly double on average.
3500
        if startTime.IsZero() {
3✔
UNCOV
3501
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3502
        }
×
3503

3504
        // The peer succeeded in starting. If the connection didn't last long
3505
        // enough to be considered stable, we'll continue to back off retries
3506
        // with this peer.
3507
        connDuration := time.Since(startTime)
3✔
3508
        if connDuration < defaultStableConnDuration {
6✔
3509
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3510
        }
3✔
3511

3512
        // The peer succeed in starting and this was stable peer, so we'll
3513
        // reduce the timeout duration by the length of the connection after
3514
        // applying randomized exponential backoff. We'll only apply this in the
3515
        // case that:
3516
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3517
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3518
        if relaxedBackoff > s.cfg.MinBackoff {
×
3519
                return relaxedBackoff
×
3520
        }
×
3521

3522
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3523
        // the stable connection lasted much longer than our previous backoff.
3524
        // To reward such good behavior, we'll reconnect after the default
3525
        // timeout.
3526
        return s.cfg.MinBackoff
×
3527
}
3528

3529
// shouldDropLocalConnection determines if our local connection to a remote peer
3530
// should be dropped in the case of concurrent connection establishment. In
3531
// order to deterministically decide which connection should be dropped, we'll
3532
// utilize the ordering of the local and remote public key. If we didn't use
3533
// such a tie breaker, then we risk _both_ connections erroneously being
3534
// dropped.
3535
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3536
        localPubBytes := local.SerializeCompressed()
×
3537
        remotePubPbytes := remote.SerializeCompressed()
×
3538

×
3539
        // The connection that comes from the node with a "smaller" pubkey
×
3540
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3541
        // should drop our established connection.
×
3542
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3543
}
×
3544

3545
// InboundPeerConnected initializes a new peer in response to a new inbound
3546
// connection.
3547
//
3548
// NOTE: This function is safe for concurrent access.
3549
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3550
        // Exit early if we have already been instructed to shutdown, this
3✔
3551
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3552
        if s.Stopped() {
3✔
3553
                return
×
3554
        }
×
3555

3556
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3557
        pubStr := string(nodePub.SerializeCompressed())
3✔
3558

3✔
3559
        s.mu.Lock()
3✔
3560
        defer s.mu.Unlock()
3✔
3561

3✔
3562
        // If we already have an outbound connection to this peer, then ignore
3✔
3563
        // this new connection.
3✔
3564
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3565
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3566
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3567
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3568

3✔
3569
                conn.Close()
3✔
3570
                return
3✔
3571
        }
3✔
3572

3573
        // If we already have a valid connection that is scheduled to take
3574
        // precedence once the prior peer has finished disconnecting, we'll
3575
        // ignore this connection.
3576
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3577
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3578
                        "scheduled", conn.RemoteAddr(), p)
×
3579
                conn.Close()
×
3580
                return
×
3581
        }
×
3582

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

3✔
3585
        // Check to see if we already have a connection with this peer. If so,
3✔
3586
        // we may need to drop our existing connection. This prevents us from
3✔
3587
        // having duplicate connections to the same peer. We forgo adding a
3✔
3588
        // default case as we expect these to be the only error values returned
3✔
3589
        // from findPeerByPubStr.
3✔
3590
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3591
        switch err {
3✔
3592
        case ErrPeerNotConnected:
3✔
3593
                // We were unable to locate an existing connection with the
3✔
3594
                // target peer, proceed to connect.
3✔
3595
                s.cancelConnReqs(pubStr, nil)
3✔
3596
                s.peerConnected(conn, nil, true)
3✔
3597

3598
        case nil:
×
3599
                // We already have a connection with the incoming peer. If the
×
3600
                // connection we've already established should be kept and is
×
3601
                // not of the same type of the new connection (inbound), then
×
3602
                // we'll close out the new connection s.t there's only a single
×
3603
                // connection between us.
×
3604
                localPub := s.identityECDH.PubKey()
×
3605
                if !connectedPeer.Inbound() &&
×
3606
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3607

×
3608
                        srvrLog.Warnf("Received inbound connection from "+
×
3609
                                "peer %v, but already have outbound "+
×
3610
                                "connection, dropping conn", connectedPeer)
×
3611
                        conn.Close()
×
3612
                        return
×
3613
                }
×
3614

3615
                // Otherwise, if we should drop the connection, then we'll
3616
                // disconnect our already connected peer.
3617
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3618
                        connectedPeer)
×
3619

×
3620
                s.cancelConnReqs(pubStr, nil)
×
3621

×
3622
                // Remove the current peer from the server's internal state and
×
3623
                // signal that the peer termination watcher does not need to
×
3624
                // execute for this peer.
×
3625
                s.removePeer(connectedPeer)
×
3626
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3627
                s.scheduledPeerConnection[pubStr] = func() {
×
3628
                        s.peerConnected(conn, nil, true)
×
3629
                }
×
3630
        }
3631
}
3632

3633
// OutboundPeerConnected initializes a new peer in response to a new outbound
3634
// connection.
3635
// NOTE: This function is safe for concurrent access.
3636
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
3637
        // Exit early if we have already been instructed to shutdown, this
3✔
3638
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3639
        if s.Stopped() {
3✔
3640
                return
×
3641
        }
×
3642

3643
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3644
        pubStr := string(nodePub.SerializeCompressed())
3✔
3645

3✔
3646
        s.mu.Lock()
3✔
3647
        defer s.mu.Unlock()
3✔
3648

3✔
3649
        // If we already have an inbound connection to this peer, then ignore
3✔
3650
        // this new connection.
3✔
3651
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
3652
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
3653
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
3654
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3655

3✔
3656
                if connReq != nil {
6✔
3657
                        s.connMgr.Remove(connReq.ID())
3✔
3658
                }
3✔
3659
                conn.Close()
3✔
3660
                return
3✔
3661
        }
3662
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
3663
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3664
                s.connMgr.Remove(connReq.ID())
×
3665
                conn.Close()
×
3666
                return
×
3667
        }
×
3668

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

×
3675
                if connReq != nil {
×
3676
                        s.connMgr.Remove(connReq.ID())
×
3677
                }
×
3678

3679
                conn.Close()
×
3680
                return
×
3681
        }
3682

3683
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
3684
                conn.RemoteAddr())
3✔
3685

3✔
3686
        if connReq != nil {
6✔
3687
                // A successful connection was returned by the connmgr.
3✔
3688
                // Immediately cancel all pending requests, excluding the
3✔
3689
                // outbound connection we just established.
3✔
3690
                ignore := connReq.ID()
3✔
3691
                s.cancelConnReqs(pubStr, &ignore)
3✔
3692
        } else {
6✔
3693
                // This was a successful connection made by some other
3✔
3694
                // subsystem. Remove all requests being managed by the connmgr.
3✔
3695
                s.cancelConnReqs(pubStr, nil)
3✔
3696
        }
3✔
3697

3698
        // If we already have a connection with this peer, decide whether or not
3699
        // we need to drop the stale connection. We forgo adding a default case
3700
        // as we expect these to be the only error values returned from
3701
        // findPeerByPubStr.
3702
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3703
        switch err {
3✔
3704
        case ErrPeerNotConnected:
3✔
3705
                // We were unable to locate an existing connection with the
3✔
3706
                // target peer, proceed to connect.
3✔
3707
                s.peerConnected(conn, connReq, false)
3✔
3708

3709
        case nil:
×
3710
                // We already have a connection with the incoming peer. If the
×
3711
                // connection we've already established should be kept and is
×
3712
                // not of the same type of the new connection (outbound), then
×
3713
                // we'll close out the new connection s.t there's only a single
×
3714
                // connection between us.
×
3715
                localPub := s.identityECDH.PubKey()
×
3716
                if connectedPeer.Inbound() &&
×
3717
                        shouldDropLocalConnection(localPub, nodePub) {
×
3718

×
3719
                        srvrLog.Warnf("Established outbound connection to "+
×
3720
                                "peer %v, but already have inbound "+
×
3721
                                "connection, dropping conn", connectedPeer)
×
3722
                        if connReq != nil {
×
3723
                                s.connMgr.Remove(connReq.ID())
×
3724
                        }
×
3725
                        conn.Close()
×
3726
                        return
×
3727
                }
3728

3729
                // Otherwise, _their_ connection should be dropped. So we'll
3730
                // disconnect the peer and send the now obsolete peer to the
3731
                // server for garbage collection.
3732
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3733
                        connectedPeer)
×
3734

×
3735
                // Remove the current peer from the server's internal state and
×
3736
                // signal that the peer termination watcher does not need to
×
3737
                // execute for this peer.
×
3738
                s.removePeer(connectedPeer)
×
3739
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3740
                s.scheduledPeerConnection[pubStr] = func() {
×
3741
                        s.peerConnected(conn, connReq, false)
×
3742
                }
×
3743
        }
3744
}
3745

3746
// UnassignedConnID is the default connection ID that a request can have before
3747
// it actually is submitted to the connmgr.
3748
// TODO(conner): move into connmgr package, or better, add connmgr method for
3749
// generating atomic IDs
3750
const UnassignedConnID uint64 = 0
3751

3752
// cancelConnReqs stops all persistent connection requests for a given pubkey.
3753
// Any attempts initiated by the peerTerminationWatcher are canceled first.
3754
// Afterwards, each connection request removed from the connmgr. The caller can
3755
// optionally specify a connection ID to ignore, which prevents us from
3756
// canceling a successful request. All persistent connreqs for the provided
3757
// pubkey are discarded after the operationjw.
3758
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
3759
        // First, cancel any lingering persistent retry attempts, which will
3✔
3760
        // prevent retries for any with backoffs that are still maturing.
3✔
3761
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
3762
                close(cancelChan)
3✔
3763
                delete(s.persistentRetryCancels, pubStr)
3✔
3764
        }
3✔
3765

3766
        // Next, check to see if we have any outstanding persistent connection
3767
        // requests to this peer. If so, then we'll remove all of these
3768
        // connection requests, and also delete the entry from the map.
3769
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
3770
        if !ok {
6✔
3771
                return
3✔
3772
        }
3✔
3773

3774
        for _, connReq := range connReqs {
6✔
3775
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
3776

3✔
3777
                // Atomically capture the current request identifier.
3✔
3778
                connID := connReq.ID()
3✔
3779

3✔
3780
                // Skip any zero IDs, this indicates the request has not
3✔
3781
                // yet been schedule.
3✔
3782
                if connID == UnassignedConnID {
3✔
UNCOV
3783
                        continue
×
3784
                }
3785

3786
                // Skip a particular connection ID if instructed.
3787
                if skip != nil && connID == *skip {
6✔
3788
                        continue
3✔
3789
                }
3790

3791
                s.connMgr.Remove(connID)
3✔
3792
        }
3793

3794
        delete(s.persistentConnReqs, pubStr)
3✔
3795
}
3796

3797
// handleCustomMessage dispatches an incoming custom peers message to
3798
// subscribers.
3799
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
3800
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
3801
                peer, msg.Type)
3✔
3802

3✔
3803
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
3804
                Peer: peer,
3✔
3805
                Msg:  msg,
3✔
3806
        })
3✔
3807
}
3✔
3808

3809
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
3810
// messages.
3811
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
3812
        return s.customMessageServer.Subscribe()
3✔
3813
}
3✔
3814

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

3✔
3822
        brontideConn := conn.(*brontide.Conn)
3✔
3823
        addr := conn.RemoteAddr()
3✔
3824
        pubKey := brontideConn.RemotePub()
3✔
3825

3✔
3826
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
3827
                pubKey.SerializeCompressed(), addr, inbound)
3✔
3828

3✔
3829
        peerAddr := &lnwire.NetAddress{
3✔
3830
                IdentityKey: pubKey,
3✔
3831
                Address:     addr,
3✔
3832
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
3833
        }
3✔
3834

3✔
3835
        // With the brontide connection established, we'll now craft the feature
3✔
3836
        // vectors to advertise to the remote node.
3✔
3837
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
3838
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
3839

3✔
3840
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
3841
        // found, create a fresh buffer.
3✔
3842
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
3843
        errBuffer, ok := s.peerErrors[pkStr]
3✔
3844
        if !ok {
6✔
3845
                var err error
3✔
3846
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
3847
                if err != nil {
3✔
3848
                        srvrLog.Errorf("unable to create peer %v", err)
×
3849
                        return
×
3850
                }
×
3851
        }
3852

3853
        // If we directly set the peer.Config TowerClient member to the
3854
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
3855
        // the peer.Config's TowerClient member will not evaluate to nil even
3856
        // though the underlying value is nil. To avoid this gotcha which can
3857
        // cause a panic, we need to explicitly pass nil to the peer.Config's
3858
        // TowerClient if needed.
3859
        var towerClient wtclient.ClientManager
3✔
3860
        if s.towerClientMgr != nil {
6✔
3861
                towerClient = s.towerClientMgr
3✔
3862
        }
3✔
3863

3864
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
3865
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
3866

3✔
3867
        // Now that we've established a connection, create a peer, and it to the
3✔
3868
        // set of currently active peers. Configure the peer with the incoming
3✔
3869
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
3870
        // offered that would trigger channel closure. In case of outgoing
3✔
3871
        // htlcs, an extra block is added to prevent the channel from being
3✔
3872
        // closed when the htlc is outstanding and a new block comes in.
3✔
3873
        pCfg := peer.Config{
3✔
3874
                Conn:                    brontideConn,
3✔
3875
                ConnReq:                 connReq,
3✔
3876
                Addr:                    peerAddr,
3✔
3877
                Inbound:                 inbound,
3✔
3878
                Features:                initFeatures,
3✔
3879
                LegacyFeatures:          legacyFeatures,
3✔
3880
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
3881
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
3882
                ErrorBuffer:             errBuffer,
3✔
3883
                WritePool:               s.writePool,
3✔
3884
                ReadPool:                s.readPool,
3✔
3885
                Switch:                  s.htlcSwitch,
3✔
3886
                InterceptSwitch:         s.interceptableSwitch,
3✔
3887
                ChannelDB:               s.chanStateDB,
3✔
3888
                ChannelGraph:            s.graphDB,
3✔
3889
                ChainArb:                s.chainArb,
3✔
3890
                AuthGossiper:            s.authGossiper,
3✔
3891
                ChanStatusMgr:           s.chanStatusMgr,
3✔
3892
                ChainIO:                 s.cc.ChainIO,
3✔
3893
                FeeEstimator:            s.cc.FeeEstimator,
3✔
3894
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
3895
                SigPool:                 s.sigPool,
3✔
3896
                Wallet:                  s.cc.Wallet,
3✔
3897
                ChainNotifier:           s.cc.ChainNotifier,
3✔
3898
                BestBlockView:           s.cc.BestBlockTracker,
3✔
3899
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
3900
                Sphinx:                  s.sphinx,
3✔
3901
                WitnessBeacon:           s.witnessBeacon,
3✔
3902
                Invoices:                s.invoices,
3✔
3903
                ChannelNotifier:         s.channelNotifier,
3✔
3904
                HtlcNotifier:            s.htlcNotifier,
3✔
3905
                TowerClient:             towerClient,
3✔
3906
                DisconnectPeer:          s.DisconnectPeer,
3✔
3907
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
3908
                        lnwire.NodeAnnouncement, error) {
6✔
3909

3✔
3910
                        return s.genNodeAnnouncement(nil)
3✔
3911
                },
3✔
3912

3913
                PongBuf: s.pongBuf,
3914

3915
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
3916

3917
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
3918

3919
                FundingManager: s.fundingMgr,
3920

3921
                Hodl:                    s.cfg.Hodl,
3922
                UnsafeReplay:            s.cfg.UnsafeReplay,
3923
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
3924
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
3925
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
3926
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
3927
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
3928
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
3929
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
3930
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
3931
                HandleCustomMessage:    s.handleCustomMessage,
3932
                GetAliases:             s.aliasMgr.GetAliases,
3933
                RequestAlias:           s.aliasMgr.RequestAlias,
3934
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
3935
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
3936
                MaxFeeExposure:         thresholdMSats,
3937
                Quit:                   s.quit,
3938
        }
3939

3940
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
3941
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
3942

3✔
3943
        p := peer.NewBrontide(pCfg)
3✔
3944

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

3✔
3948
        s.addPeer(p)
3✔
3949

3✔
3950
        // Once we have successfully added the peer to the server, we can
3✔
3951
        // delete the previous error buffer from the server's map of error
3✔
3952
        // buffers.
3✔
3953
        delete(s.peerErrors, pkStr)
3✔
3954

3✔
3955
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
3956
        // includes sending and receiving Init messages, which would be a DOS
3✔
3957
        // vector if we held the server's mutex throughout the procedure.
3✔
3958
        s.wg.Add(1)
3✔
3959
        go s.peerInitializer(p)
3✔
3960
}
3961

3962
// addPeer adds the passed peer to the server's global state of all active
3963
// peers.
3964
func (s *server) addPeer(p *peer.Brontide) {
3✔
3965
        if p == nil {
3✔
3966
                return
×
3967
        }
×
3968

3969
        // Ignore new peers if we're shutting down.
3970
        if s.Stopped() {
3✔
3971
                p.Disconnect(ErrServerShuttingDown)
×
3972
                return
×
3973
        }
×
3974

3975
        // Track the new peer in our indexes so we can quickly look it up either
3976
        // according to its public key, or its peer ID.
3977
        // TODO(roasbeef): pipe all requests through to the
3978
        // queryHandler/peerManager
3979

3980
        pubSer := p.IdentityKey().SerializeCompressed()
3✔
3981
        pubStr := string(pubSer)
3✔
3982

3✔
3983
        s.peersByPub[pubStr] = p
3✔
3984

3✔
3985
        if p.Inbound() {
6✔
3986
                s.inboundPeers[pubStr] = p
3✔
3987
        } else {
6✔
3988
                s.outboundPeers[pubStr] = p
3✔
3989
        }
3✔
3990

3991
        // Inform the peer notifier of a peer online event so that it can be reported
3992
        // to clients listening for peer events.
3993
        var pubKey [33]byte
3✔
3994
        copy(pubKey[:], pubSer)
3✔
3995

3✔
3996
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
3997
}
3998

3999
// peerInitializer asynchronously starts a newly connected peer after it has
4000
// been added to the server's peer map. This method sets up a
4001
// peerTerminationWatcher for the given peer, and ensures that it executes even
4002
// if the peer failed to start. In the event of a successful connection, this
4003
// method reads the negotiated, local feature-bits and spawns the appropriate
4004
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4005
// be signaled of the new peer once the method returns.
4006
//
4007
// NOTE: This MUST be launched as a goroutine.
4008
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4009
        defer s.wg.Done()
3✔
4010

3✔
4011
        // Avoid initializing peers while the server is exiting.
3✔
4012
        if s.Stopped() {
3✔
4013
                return
×
4014
        }
×
4015

4016
        // Create a channel that will be used to signal a successful start of
4017
        // the link. This prevents the peer termination watcher from beginning
4018
        // its duty too early.
4019
        ready := make(chan struct{})
3✔
4020

3✔
4021
        // Before starting the peer, launch a goroutine to watch for the
3✔
4022
        // unexpected termination of this peer, which will ensure all resources
3✔
4023
        // are properly cleaned up, and re-establish persistent connections when
3✔
4024
        // necessary. The peer termination watcher will be short circuited if
3✔
4025
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4026
        // that the server has already handled the removal of this peer.
3✔
4027
        s.wg.Add(1)
3✔
4028
        go s.peerTerminationWatcher(p, ready)
3✔
4029

3✔
4030
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4031
        // will unblock the peerTerminationWatcher.
3✔
4032
        if err := p.Start(); err != nil {
3✔
UNCOV
4033
                srvrLog.Warnf("Starting peer=%v got error: %v",
×
UNCOV
4034
                        p.IdentityKey(), err)
×
UNCOV
4035

×
UNCOV
4036
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4037
                return
×
UNCOV
4038
        }
×
4039

4040
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4041
        // was successful, and to begin watching the peer's wait group.
4042
        close(ready)
3✔
4043

3✔
4044
        pubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4045

3✔
4046
        s.mu.Lock()
3✔
4047
        defer s.mu.Unlock()
3✔
4048

3✔
4049
        // Check if there are listeners waiting for this peer to come online.
3✔
4050
        srvrLog.Debugf("Notifying that peer %v is online", p)
3✔
4051
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4052
                select {
3✔
4053
                case peerChan <- p:
3✔
UNCOV
4054
                case <-s.quit:
×
UNCOV
4055
                        return
×
4056
                }
4057
        }
4058
        delete(s.peerConnectedListeners, pubStr)
3✔
4059
}
4060

4061
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4062
// and then cleans up all resources allocated to the peer, notifies relevant
4063
// sub-systems of its demise, and finally handles re-connecting to the peer if
4064
// it's persistent. If the server intentionally disconnects a peer, it should
4065
// have a corresponding entry in the ignorePeerTermination map which will cause
4066
// the cleanup routine to exit early. The passed `ready` chan is used to
4067
// synchronize when WaitForDisconnect should begin watching on the peer's
4068
// waitgroup. The ready chan should only be signaled if the peer starts
4069
// successfully, otherwise the peer should be disconnected instead.
4070
//
4071
// NOTE: This MUST be launched as a goroutine.
4072
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4073
        defer s.wg.Done()
3✔
4074

3✔
4075
        p.WaitForDisconnect(ready)
3✔
4076

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

3✔
4079
        // If the server is exiting then we can bail out early ourselves as all
3✔
4080
        // the other sub-systems will already be shutting down.
3✔
4081
        if s.Stopped() {
6✔
4082
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4083
                return
3✔
4084
        }
3✔
4085

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

3✔
4092
        pubKey := p.IdentityKey()
3✔
4093

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

3✔
4098
        // Tell the switch to remove all links associated with this peer.
3✔
4099
        // Passing nil as the target link indicates that all links associated
3✔
4100
        // with this interface should be closed.
3✔
4101
        //
3✔
4102
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4103
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4104
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4105
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4106
        }
×
4107

4108
        for _, link := range links {
6✔
4109
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4110
        }
3✔
4111

4112
        s.mu.Lock()
3✔
4113
        defer s.mu.Unlock()
3✔
4114

3✔
4115
        // If there were any notification requests for when this peer
3✔
4116
        // disconnected, we can trigger them now.
3✔
4117
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4118
        pubStr := string(pubKey.SerializeCompressed())
3✔
4119
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4120
                close(offlineChan)
3✔
4121
        }
3✔
4122
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4123

3✔
4124
        // If the server has already removed this peer, we can short circuit the
3✔
4125
        // peer termination watcher and skip cleanup.
3✔
4126
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4127
                delete(s.ignorePeerTermination, p)
×
4128

×
4129
                pubKey := p.PubKey()
×
4130
                pubStr := string(pubKey[:])
×
4131

×
4132
                // If a connection callback is present, we'll go ahead and
×
4133
                // execute it now that previous peer has fully disconnected. If
×
4134
                // the callback is not present, this likely implies the peer was
×
4135
                // purposefully disconnected via RPC, and that no reconnect
×
4136
                // should be attempted.
×
4137
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4138
                if ok {
×
4139
                        delete(s.scheduledPeerConnection, pubStr)
×
4140
                        connCallback()
×
4141
                }
×
4142
                return
×
4143
        }
4144

4145
        // First, cleanup any remaining state the server has regarding the peer
4146
        // in question.
4147
        s.removePeer(p)
3✔
4148

3✔
4149
        // Next, check to see if this is a persistent peer or not.
3✔
4150
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4151
                return
3✔
4152
        }
3✔
4153

4154
        // Get the last address that we used to connect to the peer.
4155
        addrs := []net.Addr{
3✔
4156
                p.NetAddress().Address,
3✔
4157
        }
3✔
4158

3✔
4159
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4160
        // reconnection purposes.
3✔
4161
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4162
        switch {
3✔
4163
        // We found advertised addresses, so use them.
4164
        case err == nil:
3✔
4165
                addrs = advertisedAddrs
3✔
4166

4167
        // The peer doesn't have an advertised address.
4168
        case err == errNoAdvertisedAddr:
3✔
4169
                // If it is an outbound peer then we fall back to the existing
3✔
4170
                // peer address.
3✔
4171
                if !p.Inbound() {
6✔
4172
                        break
3✔
4173
                }
4174

4175
                // Fall back to the existing peer address if
4176
                // we're not accepting connections over Tor.
4177
                if s.torController == nil {
6✔
4178
                        break
3✔
4179
                }
4180

4181
                // If we are, the peer's address won't be known
4182
                // to us (we'll see a private address, which is
4183
                // the address used by our onion service to dial
4184
                // to lnd), so we don't have enough information
4185
                // to attempt a reconnect.
4186
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4187
                        "to inbound peer %v without "+
×
4188
                        "advertised address", p)
×
4189
                return
×
4190

4191
        // We came across an error retrieving an advertised
4192
        // address, log it, and fall back to the existing peer
4193
        // address.
4194
        default:
3✔
4195
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4196
                        "address for node %x: %v", p.PubKey(),
3✔
4197
                        err)
3✔
4198
        }
4199

4200
        // Make an easy lookup map so that we can check if an address
4201
        // is already in the address list that we have stored for this peer.
4202
        existingAddrs := make(map[string]bool)
3✔
4203
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4204
                existingAddrs[addr.String()] = true
3✔
4205
        }
3✔
4206

4207
        // Add any missing addresses for this peer to persistentPeerAddr.
4208
        for _, addr := range addrs {
6✔
4209
                if existingAddrs[addr.String()] {
3✔
4210
                        continue
×
4211
                }
4212

4213
                s.persistentPeerAddrs[pubStr] = append(
3✔
4214
                        s.persistentPeerAddrs[pubStr],
3✔
4215
                        &lnwire.NetAddress{
3✔
4216
                                IdentityKey: p.IdentityKey(),
3✔
4217
                                Address:     addr,
3✔
4218
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4219
                        },
3✔
4220
                )
3✔
4221
        }
4222

4223
        // Record the computed backoff in the backoff map.
4224
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4225
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4226

3✔
4227
        // Initialize a retry canceller for this peer if one does not
3✔
4228
        // exist.
3✔
4229
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4230
        if !ok {
6✔
4231
                cancelChan = make(chan struct{})
3✔
4232
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4233
        }
3✔
4234

4235
        // We choose not to wait group this go routine since the Connect
4236
        // call can stall for arbitrarily long if we shutdown while an
4237
        // outbound connection attempt is being made.
4238
        go func() {
6✔
4239
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4240
                        "persistent peer %x in %s",
3✔
4241
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4242

3✔
4243
                select {
3✔
4244
                case <-time.After(backoff):
3✔
4245
                case <-cancelChan:
3✔
4246
                        return
3✔
4247
                case <-s.quit:
3✔
4248
                        return
3✔
4249
                }
4250

4251
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4252
                        "connection to peer %x",
3✔
4253
                        p.IdentityKey().SerializeCompressed())
3✔
4254

3✔
4255
                s.connectToPersistentPeer(pubStr)
3✔
4256
        }()
4257
}
4258

4259
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4260
// to connect to the peer. It creates connection requests if there are
4261
// currently none for a given address and it removes old connection requests
4262
// if the associated address is no longer in the latest address list for the
4263
// peer.
4264
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4265
        s.mu.Lock()
3✔
4266
        defer s.mu.Unlock()
3✔
4267

3✔
4268
        // Create an easy lookup map of the addresses we have stored for the
3✔
4269
        // peer. We will remove entries from this map if we have existing
3✔
4270
        // connection requests for the associated address and then any leftover
3✔
4271
        // entries will indicate which addresses we should create new
3✔
4272
        // connection requests for.
3✔
4273
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4274
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4275
                addrMap[addr.String()] = addr
3✔
4276
        }
3✔
4277

4278
        // Go through each of the existing connection requests and
4279
        // check if they correspond to the latest set of addresses. If
4280
        // there is a connection requests that does not use one of the latest
4281
        // advertised addresses then remove that connection request.
4282
        var updatedConnReqs []*connmgr.ConnReq
3✔
4283
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4284
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4285

3✔
4286
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4287
                // If the existing connection request is using one of the
4288
                // latest advertised addresses for the peer then we add it to
4289
                // updatedConnReqs and remove the associated address from
4290
                // addrMap so that we don't recreate this connReq later on.
4291
                case true:
×
4292
                        updatedConnReqs = append(
×
4293
                                updatedConnReqs, connReq,
×
4294
                        )
×
4295
                        delete(addrMap, lnAddr)
×
4296

4297
                // If the existing connection request is using an address that
4298
                // is not one of the latest advertised addresses for the peer
4299
                // then we remove the connecting request from the connection
4300
                // manager.
4301
                case false:
3✔
4302
                        srvrLog.Info(
3✔
4303
                                "Removing conn req:", connReq.Addr.String(),
3✔
4304
                        )
3✔
4305
                        s.connMgr.Remove(connReq.ID())
3✔
4306
                }
4307
        }
4308

4309
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4310

3✔
4311
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4312
        if !ok {
6✔
4313
                cancelChan = make(chan struct{})
3✔
4314
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4315
        }
3✔
4316

4317
        // Any addresses left in addrMap are new ones that we have not made
4318
        // connection requests for. So create new connection requests for those.
4319
        // If there is more than one address in the address map, stagger the
4320
        // creation of the connection requests for those.
4321
        go func() {
6✔
4322
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4323
                defer ticker.Stop()
3✔
4324

3✔
4325
                for _, addr := range addrMap {
6✔
4326
                        // Send the persistent connection request to the
3✔
4327
                        // connection manager, saving the request itself so we
3✔
4328
                        // can cancel/restart the process as needed.
3✔
4329
                        connReq := &connmgr.ConnReq{
3✔
4330
                                Addr:      addr,
3✔
4331
                                Permanent: true,
3✔
4332
                        }
3✔
4333

3✔
4334
                        s.mu.Lock()
3✔
4335
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4336
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4337
                        )
3✔
4338
                        s.mu.Unlock()
3✔
4339

3✔
4340
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4341
                                "channel peer %v", addr)
3✔
4342

3✔
4343
                        go s.connMgr.Connect(connReq)
3✔
4344

3✔
4345
                        select {
3✔
4346
                        case <-s.quit:
3✔
4347
                                return
3✔
4348
                        case <-cancelChan:
3✔
4349
                                return
3✔
4350
                        case <-ticker.C:
3✔
4351
                        }
4352
                }
4353
        }()
4354
}
4355

4356
// removePeer removes the passed peer from the server's state of all active
4357
// peers.
4358
func (s *server) removePeer(p *peer.Brontide) {
3✔
4359
        if p == nil {
3✔
4360
                return
×
4361
        }
×
4362

4363
        srvrLog.Debugf("removing peer %v", p)
3✔
4364

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

3✔
4369
        // If this peer had an active persistent connection request, remove it.
3✔
4370
        if p.ConnReq() != nil {
6✔
4371
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4372
        }
3✔
4373

4374
        // Ignore deleting peers if we're shutting down.
4375
        if s.Stopped() {
3✔
4376
                return
×
4377
        }
×
4378

4379
        pKey := p.PubKey()
3✔
4380
        pubSer := pKey[:]
3✔
4381
        pubStr := string(pubSer)
3✔
4382

3✔
4383
        delete(s.peersByPub, pubStr)
3✔
4384

3✔
4385
        if p.Inbound() {
6✔
4386
                delete(s.inboundPeers, pubStr)
3✔
4387
        } else {
6✔
4388
                delete(s.outboundPeers, pubStr)
3✔
4389
        }
3✔
4390

4391
        // Copy the peer's error buffer across to the server if it has any items
4392
        // in it so that we can restore peer errors across connections.
4393
        if p.ErrorBuffer().Total() > 0 {
6✔
4394
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4395
        }
3✔
4396

4397
        // Inform the peer notifier of a peer offline event so that it can be
4398
        // reported to clients listening for peer events.
4399
        var pubKey [33]byte
3✔
4400
        copy(pubKey[:], pubSer)
3✔
4401

3✔
4402
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4403
}
4404

4405
// ConnectToPeer requests that the server connect to a Lightning Network peer
4406
// at the specified address. This function will *block* until either a
4407
// connection is established, or the initial handshake process fails.
4408
//
4409
// NOTE: This function is safe for concurrent access.
4410
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4411
        perm bool, timeout time.Duration) error {
3✔
4412

3✔
4413
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4414

3✔
4415
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4416
        // better granularity.  In certain conditions, this method requires
3✔
4417
        // making an outbound connection to a remote peer, which requires the
3✔
4418
        // lock to be released, and subsequently reacquired.
3✔
4419
        s.mu.Lock()
3✔
4420

3✔
4421
        // Ensure we're not already connected to this peer.
3✔
4422
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4423
        if err == nil {
6✔
4424
                s.mu.Unlock()
3✔
4425
                return &errPeerAlreadyConnected{peer: peer}
3✔
4426
        }
3✔
4427

4428
        // Peer was not found, continue to pursue connection with peer.
4429

4430
        // If there's already a pending connection request for this pubkey,
4431
        // then we ignore this request to ensure we don't create a redundant
4432
        // connection.
4433
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4434
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4435
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4436
        }
3✔
4437

4438
        // If there's not already a pending or active connection to this node,
4439
        // then instruct the connection manager to attempt to establish a
4440
        // persistent connection to the peer.
4441
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4442
        if perm {
6✔
4443
                connReq := &connmgr.ConnReq{
3✔
4444
                        Addr:      addr,
3✔
4445
                        Permanent: true,
3✔
4446
                }
3✔
4447

3✔
4448
                // Since the user requested a permanent connection, we'll set
3✔
4449
                // the entry to true which will tell the server to continue
3✔
4450
                // reconnecting even if the number of channels with this peer is
3✔
4451
                // zero.
3✔
4452
                s.persistentPeers[targetPub] = true
3✔
4453
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
4454
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
4455
                }
3✔
4456
                s.persistentConnReqs[targetPub] = append(
3✔
4457
                        s.persistentConnReqs[targetPub], connReq,
3✔
4458
                )
3✔
4459
                s.mu.Unlock()
3✔
4460

3✔
4461
                go s.connMgr.Connect(connReq)
3✔
4462

3✔
4463
                return nil
3✔
4464
        }
4465
        s.mu.Unlock()
3✔
4466

3✔
4467
        // If we're not making a persistent connection, then we'll attempt to
3✔
4468
        // connect to the target peer. If the we can't make the connection, or
3✔
4469
        // the crypto negotiation breaks down, then return an error to the
3✔
4470
        // caller.
3✔
4471
        errChan := make(chan error, 1)
3✔
4472
        s.connectToPeer(addr, errChan, timeout)
3✔
4473

3✔
4474
        select {
3✔
4475
        case err := <-errChan:
3✔
4476
                return err
3✔
4477
        case <-s.quit:
×
4478
                return ErrServerShuttingDown
×
4479
        }
4480
}
4481

4482
// connectToPeer establishes a connection to a remote peer. errChan is used to
4483
// notify the caller if the connection attempt has failed. Otherwise, it will be
4484
// closed.
4485
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4486
        errChan chan<- error, timeout time.Duration) {
3✔
4487

3✔
4488
        conn, err := brontide.Dial(
3✔
4489
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
4490
        )
3✔
4491
        if err != nil {
6✔
4492
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
4493
                select {
3✔
4494
                case errChan <- err:
3✔
4495
                case <-s.quit:
×
4496
                }
4497
                return
3✔
4498
        }
4499

4500
        close(errChan)
3✔
4501

3✔
4502
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
4503
                conn.LocalAddr(), conn.RemoteAddr())
3✔
4504

3✔
4505
        s.OutboundPeerConnected(nil, conn)
3✔
4506
}
4507

4508
// DisconnectPeer sends the request to server to close the connection with peer
4509
// identified by public key.
4510
//
4511
// NOTE: This function is safe for concurrent access.
4512
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
4513
        pubBytes := pubKey.SerializeCompressed()
3✔
4514
        pubStr := string(pubBytes)
3✔
4515

3✔
4516
        s.mu.Lock()
3✔
4517
        defer s.mu.Unlock()
3✔
4518

3✔
4519
        // Check that were actually connected to this peer. If not, then we'll
3✔
4520
        // exit in an error as we can't disconnect from a peer that we're not
3✔
4521
        // currently connected to.
3✔
4522
        peer, err := s.findPeerByPubStr(pubStr)
3✔
4523
        if err == ErrPeerNotConnected {
6✔
4524
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
4525
        }
3✔
4526

4527
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
4528

3✔
4529
        s.cancelConnReqs(pubStr, nil)
3✔
4530

3✔
4531
        // If this peer was formerly a persistent connection, then we'll remove
3✔
4532
        // them from this map so we don't attempt to re-connect after we
3✔
4533
        // disconnect.
3✔
4534
        delete(s.persistentPeers, pubStr)
3✔
4535
        delete(s.persistentPeersBackoff, pubStr)
3✔
4536

3✔
4537
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
4538
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
4539
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
4540

3✔
4541
        return nil
3✔
4542
}
4543

4544
// OpenChannel sends a request to the server to open a channel to the specified
4545
// peer identified by nodeKey with the passed channel funding parameters.
4546
//
4547
// NOTE: This function is safe for concurrent access.
4548
func (s *server) OpenChannel(
4549
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
4550

3✔
4551
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
4552
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
4553
        // not blocked if the caller is not reading the updates.
3✔
4554
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
4555
        req.Err = make(chan error, 1)
3✔
4556

3✔
4557
        // First attempt to locate the target peer to open a channel with, if
3✔
4558
        // we're unable to locate the peer then this request will fail.
3✔
4559
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
4560
        s.mu.RLock()
3✔
4561
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
4562
        if !ok {
3✔
4563
                s.mu.RUnlock()
×
4564

×
4565
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4566
                return req.Updates, req.Err
×
4567
        }
×
4568
        req.Peer = peer
3✔
4569
        s.mu.RUnlock()
3✔
4570

3✔
4571
        // We'll wait until the peer is active before beginning the channel
3✔
4572
        // opening process.
3✔
4573
        select {
3✔
4574
        case <-peer.ActiveSignal():
3✔
4575
        case <-peer.QuitSignal():
×
4576
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4577
                return req.Updates, req.Err
×
4578
        case <-s.quit:
×
4579
                req.Err <- ErrServerShuttingDown
×
4580
                return req.Updates, req.Err
×
4581
        }
4582

4583
        // If the fee rate wasn't specified at this point we fail the funding
4584
        // because of the missing fee rate information. The caller of the
4585
        // `OpenChannel` method needs to make sure that default values for the
4586
        // fee rate are set beforehand.
4587
        if req.FundingFeePerKw == 0 {
3✔
4588
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4589
                        "the channel opening transaction")
×
4590

×
4591
                return req.Updates, req.Err
×
4592
        }
×
4593

4594
        // Spawn a goroutine to send the funding workflow request to the funding
4595
        // manager. This allows the server to continue handling queries instead
4596
        // of blocking on this request which is exported as a synchronous
4597
        // request to the outside world.
4598
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
4599

3✔
4600
        return req.Updates, req.Err
3✔
4601
}
4602

4603
// Peers returns a slice of all active peers.
4604
//
4605
// NOTE: This function is safe for concurrent access.
4606
func (s *server) Peers() []*peer.Brontide {
3✔
4607
        s.mu.RLock()
3✔
4608
        defer s.mu.RUnlock()
3✔
4609

3✔
4610
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
4611
        for _, peer := range s.peersByPub {
6✔
4612
                peers = append(peers, peer)
3✔
4613
        }
3✔
4614

4615
        return peers
3✔
4616
}
4617

4618
// computeNextBackoff uses a truncated exponential backoff to compute the next
4619
// backoff using the value of the exiting backoff. The returned duration is
4620
// randomized in either direction by 1/20 to prevent tight loops from
4621
// stabilizing.
4622
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
4623
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
4624
        nextBackoff := 2 * currBackoff
3✔
4625
        if nextBackoff > maxBackoff {
6✔
4626
                nextBackoff = maxBackoff
3✔
4627
        }
3✔
4628

4629
        // Using 1/10 of our duration as a margin, compute a random offset to
4630
        // avoid the nodes entering connection cycles.
4631
        margin := nextBackoff / 10
3✔
4632

3✔
4633
        var wiggle big.Int
3✔
4634
        wiggle.SetUint64(uint64(margin))
3✔
4635
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
4636
                // Randomizing is not mission critical, so we'll just return the
×
4637
                // current backoff.
×
4638
                return nextBackoff
×
4639
        }
×
4640

4641
        // Otherwise add in our wiggle, but subtract out half of the margin so
4642
        // that the backoff can tweaked by 1/20 in either direction.
4643
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
4644
}
4645

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

4650
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4651
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
4652
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
4653
        if err != nil {
3✔
4654
                return nil, err
×
4655
        }
×
4656

4657
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
4658
        if err != nil {
6✔
4659
                return nil, err
3✔
4660
        }
3✔
4661

4662
        if len(node.Addresses) == 0 {
6✔
4663
                return nil, errNoAdvertisedAddr
3✔
4664
        }
3✔
4665

4666
        return node.Addresses, nil
3✔
4667
}
4668

4669
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4670
// channel update for a target channel.
4671
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4672
        *lnwire.ChannelUpdate, error) {
3✔
4673

3✔
4674
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
4675
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate, error) {
6✔
4676
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
4677
                if err != nil {
6✔
4678
                        return nil, err
3✔
4679
                }
3✔
4680

4681
                return netann.ExtractChannelUpdate(
3✔
4682
                        ourPubKey[:], info, edge1, edge2,
3✔
4683
                )
3✔
4684
        }
4685
}
4686

4687
// applyChannelUpdate applies the channel update to the different sub-systems of
4688
// the server. The useAlias boolean denotes whether or not to send an alias in
4689
// place of the real SCID.
4690
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate,
4691
        op *wire.OutPoint, useAlias bool) error {
3✔
4692

3✔
4693
        var (
3✔
4694
                peerAlias    *lnwire.ShortChannelID
3✔
4695
                defaultAlias lnwire.ShortChannelID
3✔
4696
        )
3✔
4697

3✔
4698
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
4699

3✔
4700
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
4701
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
4702
        if useAlias {
6✔
4703
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
4704
                if foundAlias != defaultAlias {
6✔
4705
                        peerAlias = &foundAlias
3✔
4706
                }
3✔
4707
        }
4708

4709
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
4710
                update, discovery.RemoteAlias(peerAlias),
3✔
4711
        )
3✔
4712
        select {
3✔
4713
        case err := <-errChan:
3✔
4714
                return err
3✔
4715
        case <-s.quit:
×
4716
                return ErrServerShuttingDown
×
4717
        }
4718
}
4719

4720
// SendCustomMessage sends a custom message to the peer with the specified
4721
// pubkey.
4722
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
4723
        data []byte) error {
3✔
4724

3✔
4725
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
4726
        if err != nil {
3✔
4727
                return err
×
4728
        }
×
4729

4730
        // We'll wait until the peer is active.
4731
        select {
3✔
4732
        case <-peer.ActiveSignal():
3✔
4733
        case <-peer.QuitSignal():
×
4734
                return fmt.Errorf("peer %x disconnected", peerPub)
×
4735
        case <-s.quit:
×
4736
                return ErrServerShuttingDown
×
4737
        }
4738

4739
        msg, err := lnwire.NewCustom(msgType, data)
3✔
4740
        if err != nil {
6✔
4741
                return err
3✔
4742
        }
3✔
4743

4744
        // Send the message as low-priority. For now we assume that all
4745
        // application-defined message are low priority.
4746
        return peer.SendMessageLazy(true, msg)
3✔
4747
}
4748

4749
// newSweepPkScriptGen creates closure that generates a new public key script
4750
// which should be used to sweep any funds into the on-chain wallet.
4751
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
4752
// (p2wkh) output.
4753
func newSweepPkScriptGen(
4754
        wallet lnwallet.WalletController) func() ([]byte, error) {
3✔
4755

3✔
4756
        return func() ([]byte, error) {
6✔
4757
                sweepAddr, err := wallet.NewAddress(
3✔
4758
                        lnwallet.TaprootPubkey, false,
3✔
4759
                        lnwallet.DefaultAccountName,
3✔
4760
                )
3✔
4761
                if err != nil {
3✔
4762
                        return nil, err
×
4763
                }
×
4764

4765
                return txscript.PayToAddrScript(sweepAddr)
3✔
4766
        }
4767
}
4768

4769
// shouldPeerBootstrap returns true if we should attempt to perform peer
4770
// bootstrapping to actively seek our peers using the set of active network
4771
// bootstrappers.
4772
func shouldPeerBootstrap(cfg *Config) bool {
9✔
4773
        isSimnet := cfg.Bitcoin.SimNet
9✔
4774
        isSignet := cfg.Bitcoin.SigNet
9✔
4775
        isRegtest := cfg.Bitcoin.RegTest
9✔
4776
        isDevNetwork := isSimnet || isSignet || isRegtest
9✔
4777

9✔
4778
        // TODO(yy): remove the check on simnet/regtest such that the itest is
9✔
4779
        // covering the bootstrapping process.
9✔
4780
        return !cfg.NoNetBootstrap && !isDevNetwork
9✔
4781
}
9✔
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