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

lightningnetwork / lnd / 10244606158

05 Aug 2024 07:33AM UTC coverage: 58.686% (+0.007%) from 58.679%
10244606158

Pull #8959

github

guggero
mod: bump kvdb to v1.4.10

To support the new comma-separated list of etcd hosts in db.etcd.host,
we need to bump the `kvdb` submodule version.
This also fixes a leader election bug in the etcd code.
Pull Request #8959: mod: bump kvdb to v1.4.10

125469 of 213798 relevant lines covered (58.69%)

28246.55 hits per line

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

63.74
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

158
        start sync.Once
159
        stop  sync.Once
160

161
        cfg *Config
162

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

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

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

174
        chanStatusMgr *netann.ChanStatusManager
175

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

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

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

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

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

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

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

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

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

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

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

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

240
        cc *chainreg.ChainControl
241

242
        fundingMgr *funding.Manager
243

244
        graphDB *channeldb.ChannelGraph
245

246
        chanStateDB *channeldb.ChannelStateDB
247

248
        addrSource chanbackup.AddressSource
249

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

254
        invoicesDB invoices.InvoiceDB
255

256
        aliasMgr *aliasmgr.Manager
257

258
        htlcSwitch *htlcswitch.Switch
259

260
        interceptableSwitch *htlcswitch.InterceptableSwitch
261

262
        invoices *invoices.InvoiceRegistry
263

264
        channelNotifier *channelnotifier.ChannelNotifier
265

266
        peerNotifier *peernotifier.PeerNotifier
267

268
        htlcNotifier *htlcswitch.HtlcNotifier
269

270
        witnessBeacon contractcourt.WitnessBeacon
271

272
        breachArbitrator *contractcourt.BreachArbitrator
273

274
        missionControl *routing.MissionControl
275

276
        graphBuilder *graph.Builder
277

278
        chanRouter *routing.ChannelRouter
279

280
        controlTower routing.ControlTower
281

282
        authGossiper *discovery.AuthenticatedGossiper
283

284
        localChanMgr *localchans.Manager
285

286
        utxoNursery *contractcourt.UtxoNursery
287

288
        sweeper *sweep.UtxoSweeper
289

290
        chainArb *contractcourt.ChainArbitrator
291

292
        sphinx *hop.OnionProcessor
293

294
        towerClientMgr *wtclient.Manager
295

296
        connMgr *connmgr.ConnManager
297

298
        sigPool *lnwallet.SigPool
299

300
        writePool *pool.Write
301

302
        readPool *pool.Read
303

304
        tlsManager *TLSManager
305

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

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

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

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

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

328
        hostAnn *netann.HostAnnouncer
329

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

333
        customMessageServer *subscribe.Server
334

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

338
        quit chan struct{}
339

340
        wg sync.WaitGroup
341
}
342

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

351
        s.wg.Add(1)
4✔
352
        go func() {
8✔
353
                defer func() {
8✔
354
                        graphSub.Cancel()
4✔
355
                        s.wg.Done()
4✔
356
                }()
4✔
357

358
                for {
8✔
359
                        select {
4✔
360
                        case <-s.quit:
4✔
361
                                return
4✔
362

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

370
                                for _, update := range topChange.NodeUpdates {
8✔
371
                                        pubKeyStr := string(
4✔
372
                                                update.IdentityKey.
4✔
373
                                                        SerializeCompressed(),
4✔
374
                                        )
4✔
375

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

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

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

398
                                        s.mu.Lock()
4✔
399

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

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

414
                                        s.mu.Unlock()
4✔
415

4✔
416
                                        s.connectToPersistentPeer(pubKeyStr)
4✔
417
                                }
418
                        }
419
                }
420
        }()
421

422
        return nil
4✔
423
}
424

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
585
                channelNotifier: channelnotifier.New(
4✔
586
                        dbs.ChanStateDB.ChannelStateDB(),
4✔
587
                ),
4✔
588

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

4✔
593
                listenAddrs: listenAddrs,
4✔
594

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

4✔
599
                torController: torController,
4✔
600

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

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

4✔
617
                customMessageServer: subscribe.NewServer(),
4✔
618

4✔
619
                tlsManager: tlsManager,
4✔
620

4✔
621
                featureMgr: featureMgr,
4✔
622
                quit:       make(chan struct{}),
4✔
623
        }
4✔
624

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

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

4✔
638
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
4✔
639

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
971
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
4✔
972

4✔
973
        s.controlTower = routing.NewControlTower(paymentControl)
4✔
974

4✔
975
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
4✔
976
                cfg.Routing.StrictZombiePruning
4✔
977

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1265
                        return &pc.Incoming
4✔
1266
                },
1267
        }, dbs.ChanStateDB)
1268

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

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

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

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

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

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

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

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

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

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

4✔
1333
                reservationTimeout = cfg.Dev.GetReservationTimeout()
4✔
1334
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
4✔
1335

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1558
        if cfg.WtClient.Active {
8✔
1559
                policy := wtpolicy.DefaultPolicy()
4✔
1560
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
4✔
1561

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

4✔
1568
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
4✔
1569

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

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

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

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

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

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

1606
                        return br, channel.ChanType, nil
4✔
1607
                }
1608

1609
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
4✔
1610

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

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

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

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

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

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

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

1677
        // Create liveness monitor.
1678
        s.createLivenessMonitor(cfg, cc, leaderElector)
4✔
1679

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

4✔
1698
        return s, nil
4✔
1699
}
1700

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

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

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

1715
// createLivenessMonitor creates a set of health checks using our configured
1716
// values and uses these checks to create a liveness monitor. Available
1717
// health checks,
1718
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1719
//   - diskCheck
1720
//   - tlsHealthCheck
1721
//   - torController, only created when tor is enabled.
1722
//
1723
// If a health check has been disabled by setting attempts to 0, our monitor
1724
// will not run it.
1725
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1726
        leaderElector cluster.LeaderElector) {
4✔
1727

4✔
1728
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
4✔
1729
        if cfg.Bitcoin.Node == "nochainbackend" {
4✔
1730
                srvrLog.Info("Disabling chain backend checks for " +
×
1731
                        "nochainbackend mode")
×
1732

×
1733
                chainBackendAttempts = 0
×
1734
        }
×
1735

1736
        chainHealthCheck := healthcheck.NewObservation(
4✔
1737
                "chain backend",
4✔
1738
                cc.HealthCheck,
4✔
1739
                cfg.HealthChecks.ChainCheck.Interval,
4✔
1740
                cfg.HealthChecks.ChainCheck.Timeout,
4✔
1741
                cfg.HealthChecks.ChainCheck.Backoff,
4✔
1742
                chainBackendAttempts,
4✔
1743
        )
4✔
1744

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

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

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

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

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

1795
        checks := []*healthcheck.Observation{
4✔
1796
                chainHealthCheck, diskCheck, tlsHealthCheck,
4✔
1797
        }
4✔
1798

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

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

4✔
1825
                remoteSignerConnectionCheck := healthcheck.NewObservation(
4✔
1826
                        "remote signer connection",
4✔
1827
                        rpcwallet.HealthCheck(
4✔
1828
                                s.cfg.RemoteSigner,
4✔
1829

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

1843
        // If we have a leader elector, we add a health check to ensure we are
1844
        // still the leader. During normal operation, we should always be the
1845
        // leader, but there are circumstances where this may change, such as
1846
        // when we lose network connectivity for long enough expiring out lease.
1847
        if leaderElector != nil {
4✔
1848
                leaderCheck := healthcheck.NewObservation(
×
1849
                        "leader status",
×
1850
                        func() error {
×
1851
                                // Check if we are still the leader. Note that
×
1852
                                // we don't need to use a timeout context here
×
1853
                                // as the healthcheck observer will handle the
×
1854
                                // timeout case for us.
×
1855
                                timeoutCtx, cancel := context.WithTimeout(
×
1856
                                        context.Background(),
×
1857
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
1858
                                )
×
1859
                                defer cancel()
×
1860

×
1861
                                leader, err := leaderElector.IsLeader(
×
1862
                                        timeoutCtx,
×
1863
                                )
×
1864
                                if err != nil {
×
1865
                                        return fmt.Errorf("unable to check if "+
×
1866
                                                "still leader: %v", err)
×
1867
                                }
×
1868

1869
                                if !leader {
×
1870
                                        srvrLog.Debug("Not the current leader")
×
1871
                                        return fmt.Errorf("not the current " +
×
1872
                                                "leader")
×
1873
                                }
×
1874

1875
                                return nil
×
1876
                        },
1877
                        cfg.HealthChecks.LeaderCheck.Interval,
1878
                        cfg.HealthChecks.LeaderCheck.Timeout,
1879
                        cfg.HealthChecks.LeaderCheck.Backoff,
1880
                        cfg.HealthChecks.LeaderCheck.Attempts,
1881
                )
1882

1883
                checks = append(checks, leaderCheck)
×
1884
        }
1885

1886
        // If we have not disabled all of our health checks, we create a
1887
        // liveness monitor with our configured checks.
1888
        s.livenessMonitor = healthcheck.NewMonitor(
4✔
1889
                &healthcheck.Config{
4✔
1890
                        Checks:   checks,
4✔
1891
                        Shutdown: srvrLog.Criticalf,
4✔
1892
                },
4✔
1893
        )
4✔
1894
}
1895

1896
// Started returns true if the server has been started, and false otherwise.
1897
// NOTE: This function is safe for concurrent access.
1898
func (s *server) Started() bool {
4✔
1899
        return atomic.LoadInt32(&s.active) != 0
4✔
1900
}
4✔
1901

1902
// cleaner is used to aggregate "cleanup" functions during an operation that
1903
// starts several subsystems. In case one of the subsystem fails to start
1904
// and a proper resource cleanup is required, the "run" method achieves this
1905
// by running all these added "cleanup" functions.
1906
type cleaner []func() error
1907

1908
// add is used to add a cleanup function to be called when
1909
// the run function is executed.
1910
func (c cleaner) add(cleanup func() error) cleaner {
4✔
1911
        return append(c, cleanup)
4✔
1912
}
4✔
1913

1914
// run is used to run all the previousely added cleanup functions.
1915
func (c cleaner) run() {
×
1916
        for i := len(c) - 1; i >= 0; i-- {
×
1917
                if err := c[i](); err != nil {
×
1918
                        srvrLog.Infof("Cleanup failed: %v", err)
×
1919
                }
×
1920
        }
1921
}
1922

1923
// Start starts the main daemon server, all requested listeners, and any helper
1924
// goroutines.
1925
// NOTE: This function is safe for concurrent access.
1926
//
1927
//nolint:funlen
1928
func (s *server) Start() error {
4✔
1929
        var startErr error
4✔
1930

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

4✔
1936
        s.start.Do(func() {
8✔
1937
                cleanup = cleanup.add(s.customMessageServer.Stop)
4✔
1938
                if err := s.customMessageServer.Start(); err != nil {
4✔
1939
                        startErr = err
×
1940
                        return
×
1941
                }
×
1942

1943
                if s.hostAnn != nil {
4✔
1944
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
1945
                        if err := s.hostAnn.Start(); err != nil {
×
1946
                                startErr = err
×
1947
                                return
×
1948
                        }
×
1949
                }
1950

1951
                if s.livenessMonitor != nil {
8✔
1952
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
4✔
1953
                        if err := s.livenessMonitor.Start(); err != nil {
4✔
1954
                                startErr = err
×
1955
                                return
×
1956
                        }
×
1957
                }
1958

1959
                // Start the notification server. This is used so channel
1960
                // management goroutines can be notified when a funding
1961
                // transaction reaches a sufficient number of confirmations, or
1962
                // when the input for the funding transaction is spent in an
1963
                // attempt at an uncooperative close by the counterparty.
1964
                cleanup = cleanup.add(s.sigPool.Stop)
4✔
1965
                if err := s.sigPool.Start(); err != nil {
4✔
1966
                        startErr = err
×
1967
                        return
×
1968
                }
×
1969

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

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

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

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

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

2000
                cleanup = cleanup.add(func() error {
4✔
2001
                        return s.peerNotifier.Stop()
×
2002
                })
×
2003
                if err := s.peerNotifier.Start(); err != nil {
4✔
2004
                        startErr = err
×
2005
                        return
×
2006
                }
×
2007

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

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

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

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

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

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

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

2052
                // htlcSwitch must be started before chainArb since the latter
2053
                // relies on htlcSwitch to deliver resolution message upon
2054
                // start.
2055
                cleanup = cleanup.add(s.htlcSwitch.Stop)
4✔
2056
                if err := s.htlcSwitch.Start(); err != nil {
4✔
2057
                        startErr = err
×
2058
                        return
×
2059
                }
×
2060

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

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

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

2079
                cleanup = cleanup.add(s.chanRouter.Stop)
4✔
2080
                if err := s.chanRouter.Start(); err != nil {
4✔
2081
                        startErr = err
×
2082
                        return
×
2083
                }
×
2084
                // The authGossiper depends on the chanRouter and therefore
2085
                // should be started after it.
2086
                cleanup = cleanup.add(s.authGossiper.Stop)
4✔
2087
                if err := s.authGossiper.Start(); err != nil {
4✔
2088
                        startErr = err
×
2089
                        return
×
2090
                }
×
2091

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

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

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

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

2116
                cleanup.add(func() error {
4✔
2117
                        s.missionControl.StopStoreTicker()
×
2118
                        return nil
×
2119
                })
×
2120
                s.missionControl.RunStoreTicker()
4✔
2121

4✔
2122
                // Before we start the connMgr, we'll check to see if we have
4✔
2123
                // any backups to recover. We do this now as we want to ensure
4✔
2124
                // that have all the information we need to handle channel
4✔
2125
                // recovery _before_ we even accept connections from any peers.
4✔
2126
                chanRestorer := &chanDBRestorer{
4✔
2127
                        db:         s.chanStateDB,
4✔
2128
                        secretKeys: s.cc.KeyRing,
4✔
2129
                        chainArb:   s.chainArb,
4✔
2130
                }
4✔
2131
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
4✔
2132
                        err := chanbackup.UnpackAndRecoverSingles(
×
2133
                                s.chansToRestore.PackedSingleChanBackups,
×
2134
                                s.cc.KeyRing, chanRestorer, s,
×
2135
                        )
×
2136
                        if err != nil {
×
2137
                                startErr = fmt.Errorf("unable to unpack single "+
×
2138
                                        "backups: %v", err)
×
2139
                                return
×
2140
                        }
×
2141
                }
2142
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
8✔
2143
                        err := chanbackup.UnpackAndRecoverMulti(
4✔
2144
                                s.chansToRestore.PackedMultiChanBackup,
4✔
2145
                                s.cc.KeyRing, chanRestorer, s,
4✔
2146
                        )
4✔
2147
                        if err != nil {
4✔
2148
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2149
                                        "backup: %v", err)
×
2150
                                return
×
2151
                        }
×
2152
                }
2153

2154
                // chanSubSwapper must be started after the `channelNotifier`
2155
                // because it depends on channel events as a synchronization
2156
                // point.
2157
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
4✔
2158
                if err := s.chanSubSwapper.Start(); err != nil {
4✔
2159
                        startErr = err
×
2160
                        return
×
2161
                }
×
2162

2163
                if s.torController != nil {
4✔
2164
                        cleanup = cleanup.add(s.torController.Stop)
×
2165
                        if err := s.createNewHiddenService(); err != nil {
×
2166
                                startErr = err
×
2167
                                return
×
2168
                        }
×
2169
                }
2170

2171
                if s.natTraversal != nil {
4✔
2172
                        s.wg.Add(1)
×
2173
                        go s.watchExternalIP()
×
2174
                }
×
2175

2176
                // Start connmgr last to prevent connections before init.
2177
                cleanup = cleanup.add(func() error {
4✔
2178
                        s.connMgr.Stop()
×
2179
                        return nil
×
2180
                })
×
2181
                s.connMgr.Start()
4✔
2182

4✔
2183
                // If peers are specified as a config option, we'll add those
4✔
2184
                // peers first.
4✔
2185
                for _, peerAddrCfg := range s.cfg.AddPeers {
8✔
2186
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
4✔
2187
                                peerAddrCfg,
4✔
2188
                        )
4✔
2189
                        if err != nil {
4✔
2190
                                startErr = fmt.Errorf("unable to parse peer "+
×
2191
                                        "pubkey from config: %v", err)
×
2192
                                return
×
2193
                        }
×
2194
                        addr, err := parseAddr(parsedHost, s.cfg.net)
4✔
2195
                        if err != nil {
4✔
2196
                                startErr = fmt.Errorf("unable to parse peer "+
×
2197
                                        "address provided as a config option: "+
×
2198
                                        "%v", err)
×
2199
                                return
×
2200
                        }
×
2201

2202
                        peerAddr := &lnwire.NetAddress{
4✔
2203
                                IdentityKey: parsedPubkey,
4✔
2204
                                Address:     addr,
4✔
2205
                                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
2206
                        }
4✔
2207

4✔
2208
                        err = s.ConnectToPeer(
4✔
2209
                                peerAddr, true,
4✔
2210
                                s.cfg.ConnectionTimeout,
4✔
2211
                        )
4✔
2212
                        if err != nil {
4✔
2213
                                startErr = fmt.Errorf("unable to connect to "+
×
2214
                                        "peer address provided as a config "+
×
2215
                                        "option: %v", err)
×
2216
                                return
×
2217
                        }
×
2218
                }
2219

2220
                // Subscribe to NodeAnnouncements that advertise new addresses
2221
                // our persistent peers.
2222
                if err := s.updatePersistentPeerAddrs(); err != nil {
4✔
2223
                        startErr = err
×
2224
                        return
×
2225
                }
×
2226

2227
                // With all the relevant sub-systems started, we'll now attempt
2228
                // to establish persistent connections to our direct channel
2229
                // collaborators within the network. Before doing so however,
2230
                // we'll prune our set of link nodes found within the database
2231
                // to ensure we don't reconnect to any nodes we no longer have
2232
                // open channels with.
2233
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
4✔
2234
                        startErr = err
×
2235
                        return
×
2236
                }
×
2237
                if err := s.establishPersistentConnections(); err != nil {
4✔
2238
                        startErr = err
×
2239
                        return
×
2240
                }
×
2241

2242
                // setSeedList is a helper function that turns multiple DNS seed
2243
                // server tuples from the command line or config file into the
2244
                // data structure we need and does a basic formal sanity check
2245
                // in the process.
2246
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
4✔
2247
                        if len(tuples) == 0 {
×
2248
                                return
×
2249
                        }
×
2250

2251
                        result := make([][2]string, len(tuples))
×
2252
                        for idx, tuple := range tuples {
×
2253
                                tuple = strings.TrimSpace(tuple)
×
2254
                                if len(tuple) == 0 {
×
2255
                                        return
×
2256
                                }
×
2257

2258
                                servers := strings.Split(tuple, ",")
×
2259
                                if len(servers) > 2 || len(servers) == 0 {
×
2260
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2261
                                                "seed tuple: %v", servers)
×
2262
                                        return
×
2263
                                }
×
2264

2265
                                copy(result[idx][:], servers)
×
2266
                        }
2267

2268
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2269
                }
2270

2271
                // Let users overwrite the DNS seed nodes. We only allow them
2272
                // for bitcoin mainnet/testnet/signet.
2273
                if s.cfg.Bitcoin.MainNet {
4✔
2274
                        setSeedList(
×
2275
                                s.cfg.Bitcoin.DNSSeeds,
×
2276
                                chainreg.BitcoinMainnetGenesis,
×
2277
                        )
×
2278
                }
×
2279
                if s.cfg.Bitcoin.TestNet3 {
4✔
2280
                        setSeedList(
×
2281
                                s.cfg.Bitcoin.DNSSeeds,
×
2282
                                chainreg.BitcoinTestnetGenesis,
×
2283
                        )
×
2284
                }
×
2285
                if s.cfg.Bitcoin.SigNet {
4✔
2286
                        setSeedList(
×
2287
                                s.cfg.Bitcoin.DNSSeeds,
×
2288
                                chainreg.BitcoinSignetGenesis,
×
2289
                        )
×
2290
                }
×
2291

2292
                // If network bootstrapping hasn't been disabled, then we'll
2293
                // configure the set of active bootstrappers, and launch a
2294
                // dedicated goroutine to maintain a set of persistent
2295
                // connections.
2296
                if shouldPeerBootstrap(s.cfg) {
4✔
2297
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2298
                        if err != nil {
×
2299
                                startErr = err
×
2300
                                return
×
2301
                        }
×
2302

2303
                        s.wg.Add(1)
×
2304
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2305
                } else {
4✔
2306
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
4✔
2307
                }
4✔
2308

2309
                // Set the active flag now that we've completed the full
2310
                // startup.
2311
                atomic.StoreInt32(&s.active, 1)
4✔
2312
        })
2313

2314
        if startErr != nil {
4✔
2315
                cleanup.run()
×
2316
        }
×
2317
        return startErr
4✔
2318
}
2319

2320
// Stop gracefully shutsdown the main daemon server. This function will signal
2321
// any active goroutines, or helper objects to exit, then blocks until they've
2322
// all successfully exited. Additionally, any/all listeners are closed.
2323
// NOTE: This function is safe for concurrent access.
2324
func (s *server) Stop() error {
4✔
2325
        s.stop.Do(func() {
8✔
2326
                atomic.StoreInt32(&s.stopping, 1)
4✔
2327

4✔
2328
                close(s.quit)
4✔
2329

4✔
2330
                // Shutdown connMgr first to prevent conns during shutdown.
4✔
2331
                s.connMgr.Stop()
4✔
2332

4✔
2333
                // Shutdown the wallet, funding manager, and the rpc server.
4✔
2334
                if err := s.chanStatusMgr.Stop(); err != nil {
4✔
2335
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2336
                }
×
2337
                if err := s.htlcSwitch.Stop(); err != nil {
4✔
2338
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2339
                }
×
2340
                if err := s.sphinx.Stop(); err != nil {
4✔
2341
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2342
                }
×
2343
                if err := s.invoices.Stop(); err != nil {
4✔
2344
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2345
                }
×
2346
                if err := s.chanRouter.Stop(); err != nil {
4✔
2347
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2348
                }
×
2349
                if err := s.chainArb.Stop(); err != nil {
4✔
2350
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2351
                }
×
2352
                if err := s.fundingMgr.Stop(); err != nil {
4✔
2353
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2354
                }
×
2355
                if err := s.breachArbitrator.Stop(); err != nil {
4✔
2356
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2357
                                err)
×
2358
                }
×
2359
                if err := s.utxoNursery.Stop(); err != nil {
4✔
2360
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2361
                }
×
2362
                if err := s.authGossiper.Stop(); err != nil {
4✔
2363
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2364
                }
×
2365
                if err := s.sweeper.Stop(); err != nil {
4✔
2366
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2367
                }
×
2368
                if err := s.txPublisher.Stop(); err != nil {
4✔
2369
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2370
                }
×
2371
                if err := s.channelNotifier.Stop(); err != nil {
4✔
2372
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2373
                }
×
2374
                if err := s.peerNotifier.Stop(); err != nil {
4✔
2375
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2376
                }
×
2377
                if err := s.htlcNotifier.Stop(); err != nil {
4✔
2378
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2379
                }
×
2380
                if err := s.chanSubSwapper.Stop(); err != nil {
4✔
2381
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2382
                }
×
2383
                if err := s.cc.ChainNotifier.Stop(); err != nil {
4✔
2384
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2385
                }
×
2386
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
4✔
2387
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2388
                                err)
×
2389
                }
×
2390
                if err := s.chanEventStore.Stop(); err != nil {
4✔
2391
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2392
                                err)
×
2393
                }
×
2394
                s.missionControl.StopStoreTicker()
4✔
2395

4✔
2396
                // Disconnect from each active peers to ensure that
4✔
2397
                // peerTerminationWatchers signal completion to each peer.
4✔
2398
                for _, peer := range s.Peers() {
8✔
2399
                        err := s.DisconnectPeer(peer.IdentityKey())
4✔
2400
                        if err != nil {
4✔
2401
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2402
                                        "received error: %v", peer.IdentityKey(),
×
2403
                                        err,
×
2404
                                )
×
2405
                        }
×
2406
                }
2407

2408
                // Now that all connections have been torn down, stop the tower
2409
                // client which will reliably flush all queued states to the
2410
                // tower. If this is halted for any reason, the force quit timer
2411
                // will kick in and abort to allow this method to return.
2412
                if s.towerClientMgr != nil {
8✔
2413
                        if err := s.towerClientMgr.Stop(); err != nil {
4✔
2414
                                srvrLog.Warnf("Unable to shut down tower "+
×
2415
                                        "client manager: %v", err)
×
2416
                        }
×
2417
                }
2418

2419
                if s.hostAnn != nil {
4✔
2420
                        if err := s.hostAnn.Stop(); err != nil {
×
2421
                                srvrLog.Warnf("unable to shut down host "+
×
2422
                                        "annoucner: %v", err)
×
2423
                        }
×
2424
                }
2425

2426
                if s.livenessMonitor != nil {
8✔
2427
                        if err := s.livenessMonitor.Stop(); err != nil {
4✔
2428
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2429
                                        "monitor: %v", err)
×
2430
                        }
×
2431
                }
2432

2433
                // Wait for all lingering goroutines to quit.
2434
                srvrLog.Debug("Waiting for server to shutdown...")
4✔
2435
                s.wg.Wait()
4✔
2436

4✔
2437
                srvrLog.Debug("Stopping buffer pools...")
4✔
2438
                s.sigPool.Stop()
4✔
2439
                s.writePool.Stop()
4✔
2440
                s.readPool.Stop()
4✔
2441
        })
2442

2443
        return nil
4✔
2444
}
2445

2446
// Stopped returns true if the server has been instructed to shutdown.
2447
// NOTE: This function is safe for concurrent access.
2448
func (s *server) Stopped() bool {
4✔
2449
        return atomic.LoadInt32(&s.stopping) != 0
4✔
2450
}
4✔
2451

2452
// configurePortForwarding attempts to set up port forwarding for the different
2453
// ports that the server will be listening on.
2454
//
2455
// NOTE: This should only be used when using some kind of NAT traversal to
2456
// automatically set up forwarding rules.
2457
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2458
        ip, err := s.natTraversal.ExternalIP()
×
2459
        if err != nil {
×
2460
                return nil, err
×
2461
        }
×
2462
        s.lastDetectedIP = ip
×
2463

×
2464
        externalIPs := make([]string, 0, len(ports))
×
2465
        for _, port := range ports {
×
2466
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2467
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2468
                        continue
×
2469
                }
2470

2471
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2472
                externalIPs = append(externalIPs, hostIP)
×
2473
        }
2474

2475
        return externalIPs, nil
×
2476
}
2477

2478
// removePortForwarding attempts to clear the forwarding rules for the different
2479
// ports the server is currently listening on.
2480
//
2481
// NOTE: This should only be used when using some kind of NAT traversal to
2482
// automatically set up forwarding rules.
2483
func (s *server) removePortForwarding() {
×
2484
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2485
        for _, port := range forwardedPorts {
×
2486
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2487
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2488
                                "port %d: %v", port, err)
×
2489
                }
×
2490
        }
2491
}
2492

2493
// watchExternalIP continuously checks for an updated external IP address every
2494
// 15 minutes. Once a new IP address has been detected, it will automatically
2495
// handle port forwarding rules and send updated node announcements to the
2496
// currently connected peers.
2497
//
2498
// NOTE: This MUST be run as a goroutine.
2499
func (s *server) watchExternalIP() {
×
2500
        defer s.wg.Done()
×
2501

×
2502
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2503
        // up by the server.
×
2504
        defer s.removePortForwarding()
×
2505

×
2506
        // Keep track of the external IPs set by the user to avoid replacing
×
2507
        // them when detecting a new IP.
×
2508
        ipsSetByUser := make(map[string]struct{})
×
2509
        for _, ip := range s.cfg.ExternalIPs {
×
2510
                ipsSetByUser[ip.String()] = struct{}{}
×
2511
        }
×
2512

2513
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2514

×
2515
        ticker := time.NewTicker(15 * time.Minute)
×
2516
        defer ticker.Stop()
×
2517
out:
×
2518
        for {
×
2519
                select {
×
2520
                case <-ticker.C:
×
2521
                        // We'll start off by making sure a new IP address has
×
2522
                        // been detected.
×
2523
                        ip, err := s.natTraversal.ExternalIP()
×
2524
                        if err != nil {
×
2525
                                srvrLog.Debugf("Unable to retrieve the "+
×
2526
                                        "external IP address: %v", err)
×
2527
                                continue
×
2528
                        }
2529

2530
                        // Periodically renew the NAT port forwarding.
2531
                        for _, port := range forwardedPorts {
×
2532
                                err := s.natTraversal.AddPortMapping(port)
×
2533
                                if err != nil {
×
2534
                                        srvrLog.Warnf("Unable to automatically "+
×
2535
                                                "re-create port forwarding using %s: %v",
×
2536
                                                s.natTraversal.Name(), err)
×
2537
                                } else {
×
2538
                                        srvrLog.Debugf("Automatically re-created "+
×
2539
                                                "forwarding for port %d using %s to "+
×
2540
                                                "advertise external IP",
×
2541
                                                port, s.natTraversal.Name())
×
2542
                                }
×
2543
                        }
2544

2545
                        if ip.Equal(s.lastDetectedIP) {
×
2546
                                continue
×
2547
                        }
2548

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

×
2551
                        // Next, we'll craft the new addresses that will be
×
2552
                        // included in the new node announcement and advertised
×
2553
                        // to the network. Each address will consist of the new
×
2554
                        // IP detected and one of the currently advertised
×
2555
                        // ports.
×
2556
                        var newAddrs []net.Addr
×
2557
                        for _, port := range forwardedPorts {
×
2558
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2559
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2560
                                if err != nil {
×
2561
                                        srvrLog.Debugf("Unable to resolve "+
×
2562
                                                "host %v: %v", addr, err)
×
2563
                                        continue
×
2564
                                }
2565

2566
                                newAddrs = append(newAddrs, addr)
×
2567
                        }
2568

2569
                        // Skip the update if we weren't able to resolve any of
2570
                        // the new addresses.
2571
                        if len(newAddrs) == 0 {
×
2572
                                srvrLog.Debug("Skipping node announcement " +
×
2573
                                        "update due to not being able to " +
×
2574
                                        "resolve any new addresses")
×
2575
                                continue
×
2576
                        }
2577

2578
                        // Now, we'll need to update the addresses in our node's
2579
                        // announcement in order to propagate the update
2580
                        // throughout the network. We'll only include addresses
2581
                        // that have a different IP from the previous one, as
2582
                        // the previous IP is no longer valid.
2583
                        currentNodeAnn := s.getNodeAnnouncement()
×
2584

×
2585
                        for _, addr := range currentNodeAnn.Addresses {
×
2586
                                host, _, err := net.SplitHostPort(addr.String())
×
2587
                                if err != nil {
×
2588
                                        srvrLog.Debugf("Unable to determine "+
×
2589
                                                "host from address %v: %v",
×
2590
                                                addr, err)
×
2591
                                        continue
×
2592
                                }
2593

2594
                                // We'll also make sure to include external IPs
2595
                                // set manually by the user.
2596
                                _, setByUser := ipsSetByUser[addr.String()]
×
2597
                                if setByUser || host != s.lastDetectedIP.String() {
×
2598
                                        newAddrs = append(newAddrs, addr)
×
2599
                                }
×
2600
                        }
2601

2602
                        // Then, we'll generate a new timestamped node
2603
                        // announcement with the updated addresses and broadcast
2604
                        // it to our peers.
2605
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2606
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2607
                        )
×
2608
                        if err != nil {
×
2609
                                srvrLog.Debugf("Unable to generate new node "+
×
2610
                                        "announcement: %v", err)
×
2611
                                continue
×
2612
                        }
2613

2614
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2615
                        if err != nil {
×
2616
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2617
                                        "announcement to peers: %v", err)
×
2618
                                continue
×
2619
                        }
2620

2621
                        // Finally, update the last IP seen to the current one.
2622
                        s.lastDetectedIP = ip
×
2623
                case <-s.quit:
×
2624
                        break out
×
2625
                }
2626
        }
2627
}
2628

2629
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2630
// based on the server, and currently active bootstrap mechanisms as defined
2631
// within the current configuration.
2632
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2633
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2634

×
2635
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2636

×
2637
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2638
        // this can be used by default if we've already partially seeded the
×
2639
        // network.
×
2640
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2641
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2642
        if err != nil {
×
2643
                return nil, err
×
2644
        }
×
2645
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2646

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

×
2652
                // If we have a set of DNS seeds for this chain, then we'll add
×
2653
                // it as an additional bootstrapping source.
×
2654
                if ok {
×
2655
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2656
                                "seeds: %v", dnsSeeds)
×
2657

×
2658
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2659
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2660
                        )
×
2661
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2662
                }
×
2663
        }
2664

2665
        return bootStrappers, nil
×
2666
}
2667

2668
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2669
// needs to ignore, which is made of three parts,
2670
//   - the node itself needs to be skipped as it doesn't make sense to connect
2671
//     to itself.
2672
//   - the peers that already have connections with, as in s.peersByPub.
2673
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2674
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2675
        s.mu.RLock()
×
2676
        defer s.mu.RUnlock()
×
2677

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

×
2680
        // We should ignore ourselves from bootstrapping.
×
2681
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2682
        ignore[selfKey] = struct{}{}
×
2683

×
2684
        // Ignore all connected peers.
×
2685
        for _, peer := range s.peersByPub {
×
2686
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2687
                ignore[nID] = struct{}{}
×
2688
        }
×
2689

2690
        // Ignore all persistent peers as they have a dedicated reconnecting
2691
        // process.
2692
        for pubKeyStr := range s.persistentPeers {
×
2693
                var nID autopilot.NodeID
×
2694
                copy(nID[:], []byte(pubKeyStr))
×
2695
                ignore[nID] = struct{}{}
×
2696
        }
×
2697

2698
        return ignore
×
2699
}
2700

2701
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2702
// and maintain a target minimum number of outbound connections. With this
2703
// invariant, we ensure that our node is connected to a diverse set of peers
2704
// and that nodes newly joining the network receive an up to date network view
2705
// as soon as possible.
2706
func (s *server) peerBootstrapper(numTargetPeers uint32,
2707
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2708

×
2709
        defer s.wg.Done()
×
2710

×
2711
        // Before we continue, init the ignore peers map.
×
2712
        ignoreList := s.createBootstrapIgnorePeers()
×
2713

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

×
2718
        // Once done, we'll attempt to maintain our target minimum number of
×
2719
        // peers.
×
2720
        //
×
2721
        // We'll use a 15 second backoff, and double the time every time an
×
2722
        // epoch fails up to a ceiling.
×
2723
        backOff := time.Second * 15
×
2724

×
2725
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2726
        // see if we've reached our minimum number of peers.
×
2727
        sampleTicker := time.NewTicker(backOff)
×
2728
        defer sampleTicker.Stop()
×
2729

×
2730
        // We'll use the number of attempts and errors to determine if we need
×
2731
        // to increase the time between discovery epochs.
×
2732
        var epochErrors uint32 // To be used atomically.
×
2733
        var epochAttempts uint32
×
2734

×
2735
        for {
×
2736
                select {
×
2737
                // The ticker has just woken us up, so we'll need to check if
2738
                // we need to attempt to connect our to any more peers.
2739
                case <-sampleTicker.C:
×
2740
                        // Obtain the current number of peers, so we can gauge
×
2741
                        // if we need to sample more peers or not.
×
2742
                        s.mu.RLock()
×
2743
                        numActivePeers := uint32(len(s.peersByPub))
×
2744
                        s.mu.RUnlock()
×
2745

×
2746
                        // If we have enough peers, then we can loop back
×
2747
                        // around to the next round as we're done here.
×
2748
                        if numActivePeers >= numTargetPeers {
×
2749
                                continue
×
2750
                        }
2751

2752
                        // If all of our attempts failed during this last back
2753
                        // off period, then will increase our backoff to 5
2754
                        // minute ceiling to avoid an excessive number of
2755
                        // queries
2756
                        //
2757
                        // TODO(roasbeef): add reverse policy too?
2758

2759
                        if epochAttempts > 0 &&
×
2760
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2761

×
2762
                                sampleTicker.Stop()
×
2763

×
2764
                                backOff *= 2
×
2765
                                if backOff > bootstrapBackOffCeiling {
×
2766
                                        backOff = bootstrapBackOffCeiling
×
2767
                                }
×
2768

2769
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2770
                                        "%v", backOff)
×
2771
                                sampleTicker = time.NewTicker(backOff)
×
2772
                                continue
×
2773
                        }
2774

2775
                        atomic.StoreUint32(&epochErrors, 0)
×
2776
                        epochAttempts = 0
×
2777

×
2778
                        // Since we know need more peers, we'll compute the
×
2779
                        // exact number we need to reach our threshold.
×
2780
                        numNeeded := numTargetPeers - numActivePeers
×
2781

×
2782
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2783
                                "peers", numNeeded)
×
2784

×
2785
                        // With the number of peers we need calculated, we'll
×
2786
                        // query the network bootstrappers to sample a set of
×
2787
                        // random addrs for us.
×
2788
                        //
×
2789
                        // Before we continue, get a copy of the ignore peers
×
2790
                        // map.
×
2791
                        ignoreList = s.createBootstrapIgnorePeers()
×
2792

×
2793
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2794
                                ignoreList, numNeeded*2, bootstrappers...,
×
2795
                        )
×
2796
                        if err != nil {
×
2797
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2798
                                        "peers: %v", err)
×
2799
                                continue
×
2800
                        }
2801

2802
                        // Finally, we'll launch a new goroutine for each
2803
                        // prospective peer candidates.
2804
                        for _, addr := range peerAddrs {
×
2805
                                epochAttempts++
×
2806

×
2807
                                go func(a *lnwire.NetAddress) {
×
2808
                                        // TODO(roasbeef): can do AS, subnet,
×
2809
                                        // country diversity, etc
×
2810
                                        errChan := make(chan error, 1)
×
2811
                                        s.connectToPeer(
×
2812
                                                a, errChan,
×
2813
                                                s.cfg.ConnectionTimeout,
×
2814
                                        )
×
2815
                                        select {
×
2816
                                        case err := <-errChan:
×
2817
                                                if err == nil {
×
2818
                                                        return
×
2819
                                                }
×
2820

2821
                                                srvrLog.Errorf("Unable to "+
×
2822
                                                        "connect to %v: %v",
×
2823
                                                        a, err)
×
2824
                                                atomic.AddUint32(&epochErrors, 1)
×
2825
                                        case <-s.quit:
×
2826
                                        }
2827
                                }(addr)
2828
                        }
2829
                case <-s.quit:
×
2830
                        return
×
2831
                }
2832
        }
2833
}
2834

2835
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
2836
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
2837
// query back off each time we encounter a failure.
2838
const bootstrapBackOffCeiling = time.Minute * 5
2839

2840
// initialPeerBootstrap attempts to continuously connect to peers on startup
2841
// until the target number of peers has been reached. This ensures that nodes
2842
// receive an up to date network view as soon as possible.
2843
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2844
        numTargetPeers uint32,
2845
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2846

×
2847
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
2848
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
2849

×
2850
        // We'll start off by waiting 2 seconds between failed attempts, then
×
2851
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
2852
        var delaySignal <-chan time.Time
×
2853
        delayTime := time.Second * 2
×
2854

×
2855
        // As want to be more aggressive, we'll use a lower back off celling
×
2856
        // then the main peer bootstrap logic.
×
2857
        backOffCeiling := bootstrapBackOffCeiling / 5
×
2858

×
2859
        for attempts := 0; ; attempts++ {
×
2860
                // Check if the server has been requested to shut down in order
×
2861
                // to prevent blocking.
×
2862
                if s.Stopped() {
×
2863
                        return
×
2864
                }
×
2865

2866
                // We can exit our aggressive initial peer bootstrapping stage
2867
                // if we've reached out target number of peers.
2868
                s.mu.RLock()
×
2869
                numActivePeers := uint32(len(s.peersByPub))
×
2870
                s.mu.RUnlock()
×
2871

×
2872
                if numActivePeers >= numTargetPeers {
×
2873
                        return
×
2874
                }
×
2875

2876
                if attempts > 0 {
×
2877
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
2878
                                "bootstrap peers (attempt #%v)", delayTime,
×
2879
                                attempts)
×
2880

×
2881
                        // We've completed at least one iterating and haven't
×
2882
                        // finished, so we'll start to insert a delay period
×
2883
                        // between each attempt.
×
2884
                        delaySignal = time.After(delayTime)
×
2885
                        select {
×
2886
                        case <-delaySignal:
×
2887
                        case <-s.quit:
×
2888
                                return
×
2889
                        }
2890

2891
                        // After our delay, we'll double the time we wait up to
2892
                        // the max back off period.
2893
                        delayTime *= 2
×
2894
                        if delayTime > backOffCeiling {
×
2895
                                delayTime = backOffCeiling
×
2896
                        }
×
2897
                }
2898

2899
                // Otherwise, we'll request for the remaining number of peers
2900
                // in order to reach our target.
2901
                peersNeeded := numTargetPeers - numActivePeers
×
2902
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
2903
                        ignore, peersNeeded, bootstrappers...,
×
2904
                )
×
2905
                if err != nil {
×
2906
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
2907
                                "peers: %v", err)
×
2908
                        continue
×
2909
                }
2910

2911
                // Then, we'll attempt to establish a connection to the
2912
                // different peer addresses retrieved by our bootstrappers.
2913
                var wg sync.WaitGroup
×
2914
                for _, bootstrapAddr := range bootstrapAddrs {
×
2915
                        wg.Add(1)
×
2916
                        go func(addr *lnwire.NetAddress) {
×
2917
                                defer wg.Done()
×
2918

×
2919
                                errChan := make(chan error, 1)
×
2920
                                go s.connectToPeer(
×
2921
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
2922
                                )
×
2923

×
2924
                                // We'll only allow this connection attempt to
×
2925
                                // take up to 3 seconds. This allows us to move
×
2926
                                // quickly by discarding peers that are slowing
×
2927
                                // us down.
×
2928
                                select {
×
2929
                                case err := <-errChan:
×
2930
                                        if err == nil {
×
2931
                                                return
×
2932
                                        }
×
2933
                                        srvrLog.Errorf("Unable to connect to "+
×
2934
                                                "%v: %v", addr, err)
×
2935
                                // TODO: tune timeout? 3 seconds might be *too*
2936
                                // aggressive but works well.
2937
                                case <-time.After(3 * time.Second):
×
2938
                                        srvrLog.Tracef("Skipping peer %v due "+
×
2939
                                                "to not establishing a "+
×
2940
                                                "connection within 3 seconds",
×
2941
                                                addr)
×
2942
                                case <-s.quit:
×
2943
                                }
2944
                        }(bootstrapAddr)
2945
                }
2946

2947
                wg.Wait()
×
2948
        }
2949
}
2950

2951
// createNewHiddenService automatically sets up a v2 or v3 onion service in
2952
// order to listen for inbound connections over Tor.
2953
func (s *server) createNewHiddenService() error {
×
2954
        // Determine the different ports the server is listening on. The onion
×
2955
        // service's virtual port will map to these ports and one will be picked
×
2956
        // at random when the onion service is being accessed.
×
2957
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
2958
        for _, listenAddr := range s.listenAddrs {
×
2959
                port := listenAddr.(*net.TCPAddr).Port
×
2960
                listenPorts = append(listenPorts, port)
×
2961
        }
×
2962

2963
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
2964
        if err != nil {
×
2965
                return err
×
2966
        }
×
2967

2968
        // Once the port mapping has been set, we can go ahead and automatically
2969
        // create our onion service. The service's private key will be saved to
2970
        // disk in order to regain access to this service when restarting `lnd`.
2971
        onionCfg := tor.AddOnionConfig{
×
2972
                VirtualPort: defaultPeerPort,
×
2973
                TargetPorts: listenPorts,
×
2974
                Store: tor.NewOnionFile(
×
2975
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
2976
                        encrypter,
×
2977
                ),
×
2978
        }
×
2979

×
2980
        switch {
×
2981
        case s.cfg.Tor.V2:
×
2982
                onionCfg.Type = tor.V2
×
2983
        case s.cfg.Tor.V3:
×
2984
                onionCfg.Type = tor.V3
×
2985
        }
2986

2987
        addr, err := s.torController.AddOnion(onionCfg)
×
2988
        if err != nil {
×
2989
                return err
×
2990
        }
×
2991

2992
        // Now that the onion service has been created, we'll add the onion
2993
        // address it can be reached at to our list of advertised addresses.
2994
        newNodeAnn, err := s.genNodeAnnouncement(
×
2995
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
2996
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
2997
                },
×
2998
        )
2999
        if err != nil {
×
3000
                return fmt.Errorf("unable to generate new node "+
×
3001
                        "announcement: %v", err)
×
3002
        }
×
3003

3004
        // Finally, we'll update the on-disk version of our announcement so it
3005
        // will eventually propagate to nodes in the network.
3006
        selfNode := &channeldb.LightningNode{
×
3007
                HaveNodeAnnouncement: true,
×
3008
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3009
                Addresses:            newNodeAnn.Addresses,
×
3010
                Alias:                newNodeAnn.Alias.String(),
×
3011
                Features: lnwire.NewFeatureVector(
×
3012
                        newNodeAnn.Features, lnwire.Features,
×
3013
                ),
×
3014
                Color:        newNodeAnn.RGBColor,
×
3015
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3016
        }
×
3017
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3018
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3019
                return fmt.Errorf("can't set self node: %w", err)
×
3020
        }
×
3021

3022
        return nil
×
3023
}
3024

3025
// findChannel finds a channel given a public key and ChannelID. It is an
3026
// optimization that is quicker than seeking for a channel given only the
3027
// ChannelID.
3028
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3029
        *channeldb.OpenChannel, error) {
4✔
3030

4✔
3031
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
4✔
3032
        if err != nil {
4✔
3033
                return nil, err
×
3034
        }
×
3035

3036
        for _, channel := range nodeChans {
8✔
3037
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
8✔
3038
                        return channel, nil
4✔
3039
                }
4✔
3040
        }
3041

3042
        return nil, fmt.Errorf("unable to find channel")
4✔
3043
}
3044

3045
// getNodeAnnouncement fetches the current, fully signed node announcement.
3046
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
4✔
3047
        s.mu.Lock()
4✔
3048
        defer s.mu.Unlock()
4✔
3049

4✔
3050
        return *s.currentNodeAnn
4✔
3051
}
4✔
3052

3053
// genNodeAnnouncement generates and returns the current fully signed node
3054
// announcement. The time stamp of the announcement will be updated in order
3055
// to ensure it propagates through the network.
3056
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3057
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
4✔
3058

4✔
3059
        s.mu.Lock()
4✔
3060
        defer s.mu.Unlock()
4✔
3061

4✔
3062
        // First, try to update our feature manager with the updated set of
4✔
3063
        // features.
4✔
3064
        if features != nil {
8✔
3065
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
4✔
3066
                        feature.SetNodeAnn: features,
4✔
3067
                }
4✔
3068
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
4✔
3069
                if err != nil {
8✔
3070
                        return lnwire.NodeAnnouncement{}, err
4✔
3071
                }
4✔
3072

3073
                // If we could successfully update our feature manager, add
3074
                // an update modifier to include these new features to our
3075
                // set.
3076
                modifiers = append(
4✔
3077
                        modifiers, netann.NodeAnnSetFeatures(features),
4✔
3078
                )
4✔
3079
        }
3080

3081
        // Always update the timestamp when refreshing to ensure the update
3082
        // propagates.
3083
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
4✔
3084

4✔
3085
        // Apply the requested changes to the node announcement.
4✔
3086
        for _, modifier := range modifiers {
8✔
3087
                modifier(s.currentNodeAnn)
4✔
3088
        }
4✔
3089

3090
        // Sign a new update after applying all of the passed modifiers.
3091
        err := netann.SignNodeAnnouncement(
4✔
3092
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
4✔
3093
        )
4✔
3094
        if err != nil {
4✔
3095
                return lnwire.NodeAnnouncement{}, err
×
3096
        }
×
3097

3098
        return *s.currentNodeAnn, nil
4✔
3099
}
3100

3101
// updateAndBrodcastSelfNode generates a new node announcement
3102
// applying the giving modifiers and updating the time stamp
3103
// to ensure it propagates through the network. Then it brodcasts
3104
// it to the network.
3105
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
3106
        modifiers ...netann.NodeAnnModifier) error {
4✔
3107

4✔
3108
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
4✔
3109
        if err != nil {
8✔
3110
                return fmt.Errorf("unable to generate new node "+
4✔
3111
                        "announcement: %v", err)
4✔
3112
        }
4✔
3113

3114
        // Update the on-disk version of our announcement.
3115
        // Load and modify self node istead of creating anew instance so we
3116
        // don't risk overwriting any existing values.
3117
        selfNode, err := s.graphDB.SourceNode()
4✔
3118
        if err != nil {
4✔
3119
                return fmt.Errorf("unable to get current source node: %w", err)
×
3120
        }
×
3121

3122
        selfNode.HaveNodeAnnouncement = true
4✔
3123
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
4✔
3124
        selfNode.Addresses = newNodeAnn.Addresses
4✔
3125
        selfNode.Alias = newNodeAnn.Alias.String()
4✔
3126
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
4✔
3127
        selfNode.Color = newNodeAnn.RGBColor
4✔
3128
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
4✔
3129

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

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

3136
        // Finally, propagate it to the nodes in the network.
3137
        err = s.BroadcastMessage(nil, &newNodeAnn)
4✔
3138
        if err != nil {
4✔
3139
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3140
                        "announcement to peers: %v", err)
×
3141
                return err
×
3142
        }
×
3143

3144
        return nil
4✔
3145
}
3146

3147
type nodeAddresses struct {
3148
        pubKey    *btcec.PublicKey
3149
        addresses []net.Addr
3150
}
3151

3152
// establishPersistentConnections attempts to establish persistent connections
3153
// to all our direct channel collaborators. In order to promote liveness of our
3154
// active channels, we instruct the connection manager to attempt to establish
3155
// and maintain persistent connections to all our direct channel counterparties.
3156
func (s *server) establishPersistentConnections() error {
4✔
3157
        // nodeAddrsMap stores the combination of node public keys and addresses
4✔
3158
        // that we'll attempt to reconnect to. PubKey strings are used as keys
4✔
3159
        // since other PubKey forms can't be compared.
4✔
3160
        nodeAddrsMap := map[string]*nodeAddresses{}
4✔
3161

4✔
3162
        // Iterate through the list of LinkNodes to find addresses we should
4✔
3163
        // attempt to connect to based on our set of previous connections. Set
4✔
3164
        // the reconnection port to the default peer port.
4✔
3165
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
4✔
3166
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
4✔
3167
                return err
×
3168
        }
×
3169
        for _, node := range linkNodes {
8✔
3170
                pubStr := string(node.IdentityPub.SerializeCompressed())
4✔
3171
                nodeAddrs := &nodeAddresses{
4✔
3172
                        pubKey:    node.IdentityPub,
4✔
3173
                        addresses: node.Addresses,
4✔
3174
                }
4✔
3175
                nodeAddrsMap[pubStr] = nodeAddrs
4✔
3176
        }
4✔
3177

3178
        // After checking our previous connections for addresses to connect to,
3179
        // iterate through the nodes in our channel graph to find addresses
3180
        // that have been added via NodeAnnouncement messages.
3181
        sourceNode, err := s.graphDB.SourceNode()
4✔
3182
        if err != nil {
4✔
3183
                return err
×
3184
        }
×
3185

3186
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3187
        // each of the nodes.
3188
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
4✔
3189
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
4✔
3190
                tx kvdb.RTx,
4✔
3191
                chanInfo *models.ChannelEdgeInfo,
4✔
3192
                policy, _ *models.ChannelEdgePolicy) error {
8✔
3193

4✔
3194
                // If the remote party has announced the channel to us, but we
4✔
3195
                // haven't yet, then we won't have a policy. However, we don't
4✔
3196
                // need this to connect to the peer, so we'll log it and move on.
4✔
3197
                if policy == nil {
4✔
3198
                        srvrLog.Warnf("No channel policy found for "+
×
3199
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3200
                }
×
3201

3202
                // We'll now fetch the peer opposite from us within this
3203
                // channel so we can queue up a direct connection to them.
3204
                channelPeer, err := s.graphDB.FetchOtherNode(
4✔
3205
                        tx, chanInfo, selfPub,
4✔
3206
                )
4✔
3207
                if err != nil {
4✔
3208
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3209
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3210
                                err)
×
3211
                }
×
3212

3213
                pubStr := string(channelPeer.PubKeyBytes[:])
4✔
3214

4✔
3215
                // Add all unique addresses from channel
4✔
3216
                // graph/NodeAnnouncements to the list of addresses we'll
4✔
3217
                // connect to for this peer.
4✔
3218
                addrSet := make(map[string]net.Addr)
4✔
3219
                for _, addr := range channelPeer.Addresses {
8✔
3220
                        switch addr.(type) {
4✔
3221
                        case *net.TCPAddr:
4✔
3222
                                addrSet[addr.String()] = addr
4✔
3223

3224
                        // We'll only attempt to connect to Tor addresses if Tor
3225
                        // outbound support is enabled.
3226
                        case *tor.OnionAddr:
×
3227
                                if s.cfg.Tor.Active {
×
3228
                                        addrSet[addr.String()] = addr
×
3229
                                }
×
3230
                        }
3231
                }
3232

3233
                // If this peer is also recorded as a link node, we'll add any
3234
                // additional addresses that have not already been selected.
3235
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
4✔
3236
                if ok {
8✔
3237
                        for _, lnAddress := range linkNodeAddrs.addresses {
8✔
3238
                                switch lnAddress.(type) {
4✔
3239
                                case *net.TCPAddr:
4✔
3240
                                        addrSet[lnAddress.String()] = lnAddress
4✔
3241

3242
                                // We'll only attempt to connect to Tor
3243
                                // addresses if Tor outbound support is enabled.
3244
                                case *tor.OnionAddr:
×
3245
                                        if s.cfg.Tor.Active {
×
3246
                                                addrSet[lnAddress.String()] = lnAddress
×
3247
                                        }
×
3248
                                }
3249
                        }
3250
                }
3251

3252
                // Construct a slice of the deduped addresses.
3253
                var addrs []net.Addr
4✔
3254
                for _, addr := range addrSet {
8✔
3255
                        addrs = append(addrs, addr)
4✔
3256
                }
4✔
3257

3258
                n := &nodeAddresses{
4✔
3259
                        addresses: addrs,
4✔
3260
                }
4✔
3261
                n.pubKey, err = channelPeer.PubKey()
4✔
3262
                if err != nil {
4✔
3263
                        return err
×
3264
                }
×
3265

3266
                nodeAddrsMap[pubStr] = n
4✔
3267
                return nil
4✔
3268
        })
3269
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
4✔
3270
                return err
×
3271
        }
×
3272

3273
        srvrLog.Debugf("Establishing %v persistent connections on start",
4✔
3274
                len(nodeAddrsMap))
4✔
3275

4✔
3276
        // Acquire and hold server lock until all persistent connection requests
4✔
3277
        // have been recorded and sent to the connection manager.
4✔
3278
        s.mu.Lock()
4✔
3279
        defer s.mu.Unlock()
4✔
3280

4✔
3281
        // Iterate through the combined list of addresses from prior links and
4✔
3282
        // node announcements and attempt to reconnect to each node.
4✔
3283
        var numOutboundConns int
4✔
3284
        for pubStr, nodeAddr := range nodeAddrsMap {
8✔
3285
                // Add this peer to the set of peers we should maintain a
4✔
3286
                // persistent connection with. We set the value to false to
4✔
3287
                // indicate that we should not continue to reconnect if the
4✔
3288
                // number of channels returns to zero, since this peer has not
4✔
3289
                // been requested as perm by the user.
4✔
3290
                s.persistentPeers[pubStr] = false
4✔
3291
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
8✔
3292
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
4✔
3293
                }
4✔
3294

3295
                for _, address := range nodeAddr.addresses {
8✔
3296
                        // Create a wrapper address which couples the IP and
4✔
3297
                        // the pubkey so the brontide authenticated connection
4✔
3298
                        // can be established.
4✔
3299
                        lnAddr := &lnwire.NetAddress{
4✔
3300
                                IdentityKey: nodeAddr.pubKey,
4✔
3301
                                Address:     address,
4✔
3302
                        }
4✔
3303

4✔
3304
                        s.persistentPeerAddrs[pubStr] = append(
4✔
3305
                                s.persistentPeerAddrs[pubStr], lnAddr)
4✔
3306
                }
4✔
3307

3308
                // We'll connect to the first 10 peers immediately, then
3309
                // randomly stagger any remaining connections if the
3310
                // stagger initial reconnect flag is set. This ensures
3311
                // that mobile nodes or nodes with a small number of
3312
                // channels obtain connectivity quickly, but larger
3313
                // nodes are able to disperse the costs of connecting to
3314
                // all peers at once.
3315
                if numOutboundConns < numInstantInitReconnect ||
4✔
3316
                        !s.cfg.StaggerInitialReconnect {
8✔
3317

4✔
3318
                        go s.connectToPersistentPeer(pubStr)
4✔
3319
                } else {
4✔
3320
                        go s.delayInitialReconnect(pubStr)
×
3321
                }
×
3322

3323
                numOutboundConns++
4✔
3324
        }
3325

3326
        return nil
4✔
3327
}
3328

3329
// delayInitialReconnect will attempt a reconnection to the given peer after
3330
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3331
//
3332
// NOTE: This method MUST be run as a goroutine.
3333
func (s *server) delayInitialReconnect(pubStr string) {
×
3334
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3335
        select {
×
3336
        case <-time.After(delay):
×
3337
                s.connectToPersistentPeer(pubStr)
×
3338
        case <-s.quit:
×
3339
        }
3340
}
3341

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

4✔
3348
        s.mu.Lock()
4✔
3349
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
8✔
3350
                delete(s.persistentPeers, pubKeyStr)
4✔
3351
                delete(s.persistentPeersBackoff, pubKeyStr)
4✔
3352
                delete(s.persistentPeerAddrs, pubKeyStr)
4✔
3353
                s.cancelConnReqs(pubKeyStr, nil)
4✔
3354
                s.mu.Unlock()
4✔
3355

4✔
3356
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
4✔
3357
                        "peer has no open channels", compressedPubKey)
4✔
3358

4✔
3359
                return
4✔
3360
        }
4✔
3361
        s.mu.Unlock()
4✔
3362
}
3363

3364
// BroadcastMessage sends a request to the server to broadcast a set of
3365
// messages to all peers other than the one specified by the `skips` parameter.
3366
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3367
// the target peers.
3368
//
3369
// NOTE: This function is safe for concurrent access.
3370
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3371
        msgs ...lnwire.Message) error {
4✔
3372

4✔
3373
        // Filter out peers found in the skips map. We synchronize access to
4✔
3374
        // peersByPub throughout this process to ensure we deliver messages to
4✔
3375
        // exact set of peers present at the time of invocation.
4✔
3376
        s.mu.RLock()
4✔
3377
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
3378
        for pubStr, sPeer := range s.peersByPub {
8✔
3379
                if skips != nil {
8✔
3380
                        if _, ok := skips[sPeer.PubKey()]; ok {
8✔
3381
                                srvrLog.Tracef("Skipping %x in broadcast with "+
4✔
3382
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
4✔
3383
                                continue
4✔
3384
                        }
3385
                }
3386

3387
                peers = append(peers, sPeer)
4✔
3388
        }
3389
        s.mu.RUnlock()
4✔
3390

4✔
3391
        // Iterate over all known peers, dispatching a go routine to enqueue
4✔
3392
        // all messages to each of peers.
4✔
3393
        var wg sync.WaitGroup
4✔
3394
        for _, sPeer := range peers {
8✔
3395
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
4✔
3396
                        sPeer.PubKey())
4✔
3397

4✔
3398
                // Dispatch a go routine to enqueue all messages to this peer.
4✔
3399
                wg.Add(1)
4✔
3400
                s.wg.Add(1)
4✔
3401
                go func(p lnpeer.Peer) {
8✔
3402
                        defer s.wg.Done()
4✔
3403
                        defer wg.Done()
4✔
3404

4✔
3405
                        p.SendMessageLazy(false, msgs...)
4✔
3406
                }(sPeer)
4✔
3407
        }
3408

3409
        // Wait for all messages to have been dispatched before returning to
3410
        // caller.
3411
        wg.Wait()
4✔
3412

4✔
3413
        return nil
4✔
3414
}
3415

3416
// NotifyWhenOnline can be called by other subsystems to get notified when a
3417
// particular peer comes online. The peer itself is sent across the peerChan.
3418
//
3419
// NOTE: This function is safe for concurrent access.
3420
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3421
        peerChan chan<- lnpeer.Peer) {
4✔
3422

4✔
3423
        s.mu.Lock()
4✔
3424

4✔
3425
        // Compute the target peer's identifier.
4✔
3426
        pubStr := string(peerKey[:])
4✔
3427

4✔
3428
        // Check if peer is connected.
4✔
3429
        peer, ok := s.peersByPub[pubStr]
4✔
3430
        if ok {
8✔
3431
                // Unlock here so that the mutex isn't held while we are
4✔
3432
                // waiting for the peer to become active.
4✔
3433
                s.mu.Unlock()
4✔
3434

4✔
3435
                // Wait until the peer signals that it is actually active
4✔
3436
                // rather than only in the server's maps.
4✔
3437
                select {
4✔
3438
                case <-peer.ActiveSignal():
4✔
3439
                case <-peer.QuitSignal():
×
3440
                        // The peer quit, so we'll add the channel to the slice
×
3441
                        // and return.
×
3442
                        s.mu.Lock()
×
3443
                        s.peerConnectedListeners[pubStr] = append(
×
3444
                                s.peerConnectedListeners[pubStr], peerChan,
×
3445
                        )
×
3446
                        s.mu.Unlock()
×
3447
                        return
×
3448
                }
3449

3450
                // Connected, can return early.
3451
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
4✔
3452

4✔
3453
                select {
4✔
3454
                case peerChan <- peer:
4✔
3455
                case <-s.quit:
×
3456
                }
3457

3458
                return
4✔
3459
        }
3460

3461
        // Not connected, store this listener such that it can be notified when
3462
        // the peer comes online.
3463
        s.peerConnectedListeners[pubStr] = append(
4✔
3464
                s.peerConnectedListeners[pubStr], peerChan,
4✔
3465
        )
4✔
3466
        s.mu.Unlock()
4✔
3467
}
3468

3469
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3470
// the given public key has been disconnected. The notification is signaled by
3471
// closing the channel returned.
3472
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
4✔
3473
        s.mu.Lock()
4✔
3474
        defer s.mu.Unlock()
4✔
3475

4✔
3476
        c := make(chan struct{})
4✔
3477

4✔
3478
        // If the peer is already offline, we can immediately trigger the
4✔
3479
        // notification.
4✔
3480
        peerPubKeyStr := string(peerPubKey[:])
4✔
3481
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
4✔
3482
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3483
                close(c)
×
3484
                return c
×
3485
        }
×
3486

3487
        // Otherwise, the peer is online, so we'll keep track of the channel to
3488
        // trigger the notification once the server detects the peer
3489
        // disconnects.
3490
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
4✔
3491
                s.peerDisconnectedListeners[peerPubKeyStr], c,
4✔
3492
        )
4✔
3493

4✔
3494
        return c
4✔
3495
}
3496

3497
// FindPeer will return the peer that corresponds to the passed in public key.
3498
// This function is used by the funding manager, allowing it to update the
3499
// daemon's local representation of the remote peer.
3500
//
3501
// NOTE: This function is safe for concurrent access.
3502
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
4✔
3503
        s.mu.RLock()
4✔
3504
        defer s.mu.RUnlock()
4✔
3505

4✔
3506
        pubStr := string(peerKey.SerializeCompressed())
4✔
3507

4✔
3508
        return s.findPeerByPubStr(pubStr)
4✔
3509
}
4✔
3510

3511
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3512
// which should be a string representation of the peer's serialized, compressed
3513
// public key.
3514
//
3515
// NOTE: This function is safe for concurrent access.
3516
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3517
        s.mu.RLock()
4✔
3518
        defer s.mu.RUnlock()
4✔
3519

4✔
3520
        return s.findPeerByPubStr(pubStr)
4✔
3521
}
4✔
3522

3523
// findPeerByPubStr is an internal method that retrieves the specified peer from
3524
// the server's internal state using.
3525
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3526
        peer, ok := s.peersByPub[pubStr]
4✔
3527
        if !ok {
8✔
3528
                return nil, ErrPeerNotConnected
4✔
3529
        }
4✔
3530

3531
        return peer, nil
4✔
3532
}
3533

3534
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3535
// exponential backoff. If no previous backoff was known, the default is
3536
// returned.
3537
func (s *server) nextPeerBackoff(pubStr string,
3538
        startTime time.Time) time.Duration {
4✔
3539

4✔
3540
        // Now, determine the appropriate backoff to use for the retry.
4✔
3541
        backoff, ok := s.persistentPeersBackoff[pubStr]
4✔
3542
        if !ok {
8✔
3543
                // If an existing backoff was unknown, use the default.
4✔
3544
                return s.cfg.MinBackoff
4✔
3545
        }
4✔
3546

3547
        // If the peer failed to start properly, we'll just use the previous
3548
        // backoff to compute the subsequent randomized exponential backoff
3549
        // duration. This will roughly double on average.
3550
        if startTime.IsZero() {
4✔
3551
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3552
        }
×
3553

3554
        // The peer succeeded in starting. If the connection didn't last long
3555
        // enough to be considered stable, we'll continue to back off retries
3556
        // with this peer.
3557
        connDuration := time.Since(startTime)
4✔
3558
        if connDuration < defaultStableConnDuration {
8✔
3559
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
4✔
3560
        }
4✔
3561

3562
        // The peer succeed in starting and this was stable peer, so we'll
3563
        // reduce the timeout duration by the length of the connection after
3564
        // applying randomized exponential backoff. We'll only apply this in the
3565
        // case that:
3566
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3567
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3568
        if relaxedBackoff > s.cfg.MinBackoff {
×
3569
                return relaxedBackoff
×
3570
        }
×
3571

3572
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3573
        // the stable connection lasted much longer than our previous backoff.
3574
        // To reward such good behavior, we'll reconnect after the default
3575
        // timeout.
3576
        return s.cfg.MinBackoff
×
3577
}
3578

3579
// shouldDropLocalConnection determines if our local connection to a remote peer
3580
// should be dropped in the case of concurrent connection establishment. In
3581
// order to deterministically decide which connection should be dropped, we'll
3582
// utilize the ordering of the local and remote public key. If we didn't use
3583
// such a tie breaker, then we risk _both_ connections erroneously being
3584
// dropped.
3585
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3586
        localPubBytes := local.SerializeCompressed()
×
3587
        remotePubPbytes := remote.SerializeCompressed()
×
3588

×
3589
        // The connection that comes from the node with a "smaller" pubkey
×
3590
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3591
        // should drop our established connection.
×
3592
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3593
}
×
3594

3595
// InboundPeerConnected initializes a new peer in response to a new inbound
3596
// connection.
3597
//
3598
// NOTE: This function is safe for concurrent access.
3599
func (s *server) InboundPeerConnected(conn net.Conn) {
4✔
3600
        // Exit early if we have already been instructed to shutdown, this
4✔
3601
        // prevents any delayed callbacks from accidentally registering peers.
4✔
3602
        if s.Stopped() {
4✔
3603
                return
×
3604
        }
×
3605

3606
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3607
        pubStr := string(nodePub.SerializeCompressed())
4✔
3608

4✔
3609
        s.mu.Lock()
4✔
3610
        defer s.mu.Unlock()
4✔
3611

4✔
3612
        // If we already have an outbound connection to this peer, then ignore
4✔
3613
        // this new connection.
4✔
3614
        if p, ok := s.outboundPeers[pubStr]; ok {
8✔
3615
                srvrLog.Debugf("Already have outbound connection for %v, "+
4✔
3616
                        "ignoring inbound connection from local=%v, remote=%v",
4✔
3617
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
3618

4✔
3619
                conn.Close()
4✔
3620
                return
4✔
3621
        }
4✔
3622

3623
        // If we already have a valid connection that is scheduled to take
3624
        // precedence once the prior peer has finished disconnecting, we'll
3625
        // ignore this connection.
3626
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
4✔
3627
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3628
                        "scheduled", conn.RemoteAddr(), p)
×
3629
                conn.Close()
×
3630
                return
×
3631
        }
×
3632

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

4✔
3635
        // Check to see if we already have a connection with this peer. If so,
4✔
3636
        // we may need to drop our existing connection. This prevents us from
4✔
3637
        // having duplicate connections to the same peer. We forgo adding a
4✔
3638
        // default case as we expect these to be the only error values returned
4✔
3639
        // from findPeerByPubStr.
4✔
3640
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
3641
        switch err {
4✔
3642
        case ErrPeerNotConnected:
4✔
3643
                // We were unable to locate an existing connection with the
4✔
3644
                // target peer, proceed to connect.
4✔
3645
                s.cancelConnReqs(pubStr, nil)
4✔
3646
                s.peerConnected(conn, nil, true)
4✔
3647

3648
        case nil:
×
3649
                // We already have a connection with the incoming peer. If the
×
3650
                // connection we've already established should be kept and is
×
3651
                // not of the same type of the new connection (inbound), then
×
3652
                // we'll close out the new connection s.t there's only a single
×
3653
                // connection between us.
×
3654
                localPub := s.identityECDH.PubKey()
×
3655
                if !connectedPeer.Inbound() &&
×
3656
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3657

×
3658
                        srvrLog.Warnf("Received inbound connection from "+
×
3659
                                "peer %v, but already have outbound "+
×
3660
                                "connection, dropping conn", connectedPeer)
×
3661
                        conn.Close()
×
3662
                        return
×
3663
                }
×
3664

3665
                // Otherwise, if we should drop the connection, then we'll
3666
                // disconnect our already connected peer.
3667
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3668
                        connectedPeer)
×
3669

×
3670
                s.cancelConnReqs(pubStr, nil)
×
3671

×
3672
                // Remove the current peer from the server's internal state and
×
3673
                // signal that the peer termination watcher does not need to
×
3674
                // execute for this peer.
×
3675
                s.removePeer(connectedPeer)
×
3676
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3677
                s.scheduledPeerConnection[pubStr] = func() {
×
3678
                        s.peerConnected(conn, nil, true)
×
3679
                }
×
3680
        }
3681
}
3682

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

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

4✔
3696
        s.mu.Lock()
4✔
3697
        defer s.mu.Unlock()
4✔
3698

4✔
3699
        // If we already have an inbound connection to this peer, then ignore
4✔
3700
        // this new connection.
4✔
3701
        if p, ok := s.inboundPeers[pubStr]; ok {
8✔
3702
                srvrLog.Debugf("Already have inbound connection for %v, "+
4✔
3703
                        "ignoring outbound connection from local=%v, remote=%v",
4✔
3704
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
3705

4✔
3706
                if connReq != nil {
8✔
3707
                        s.connMgr.Remove(connReq.ID())
4✔
3708
                }
4✔
3709
                conn.Close()
4✔
3710
                return
4✔
3711
        }
3712
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
4✔
3713
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3714
                s.connMgr.Remove(connReq.ID())
×
3715
                conn.Close()
×
3716
                return
×
3717
        }
×
3718

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

×
3725
                if connReq != nil {
×
3726
                        s.connMgr.Remove(connReq.ID())
×
3727
                }
×
3728

3729
                conn.Close()
×
3730
                return
×
3731
        }
3732

3733
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
4✔
3734
                conn.RemoteAddr())
4✔
3735

4✔
3736
        if connReq != nil {
8✔
3737
                // A successful connection was returned by the connmgr.
4✔
3738
                // Immediately cancel all pending requests, excluding the
4✔
3739
                // outbound connection we just established.
4✔
3740
                ignore := connReq.ID()
4✔
3741
                s.cancelConnReqs(pubStr, &ignore)
4✔
3742
        } else {
8✔
3743
                // This was a successful connection made by some other
4✔
3744
                // subsystem. Remove all requests being managed by the connmgr.
4✔
3745
                s.cancelConnReqs(pubStr, nil)
4✔
3746
        }
4✔
3747

3748
        // If we already have a connection with this peer, decide whether or not
3749
        // we need to drop the stale connection. We forgo adding a default case
3750
        // as we expect these to be the only error values returned from
3751
        // findPeerByPubStr.
3752
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
3753
        switch err {
4✔
3754
        case ErrPeerNotConnected:
4✔
3755
                // We were unable to locate an existing connection with the
4✔
3756
                // target peer, proceed to connect.
4✔
3757
                s.peerConnected(conn, connReq, false)
4✔
3758

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

×
3769
                        srvrLog.Warnf("Established outbound connection to "+
×
3770
                                "peer %v, but already have inbound "+
×
3771
                                "connection, dropping conn", connectedPeer)
×
3772
                        if connReq != nil {
×
3773
                                s.connMgr.Remove(connReq.ID())
×
3774
                        }
×
3775
                        conn.Close()
×
3776
                        return
×
3777
                }
3778

3779
                // Otherwise, _their_ connection should be dropped. So we'll
3780
                // disconnect the peer and send the now obsolete peer to the
3781
                // server for garbage collection.
3782
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3783
                        connectedPeer)
×
3784

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

3796
// UnassignedConnID is the default connection ID that a request can have before
3797
// it actually is submitted to the connmgr.
3798
// TODO(conner): move into connmgr package, or better, add connmgr method for
3799
// generating atomic IDs
3800
const UnassignedConnID uint64 = 0
3801

3802
// cancelConnReqs stops all persistent connection requests for a given pubkey.
3803
// Any attempts initiated by the peerTerminationWatcher are canceled first.
3804
// Afterwards, each connection request removed from the connmgr. The caller can
3805
// optionally specify a connection ID to ignore, which prevents us from
3806
// canceling a successful request. All persistent connreqs for the provided
3807
// pubkey are discarded after the operationjw.
3808
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
4✔
3809
        // First, cancel any lingering persistent retry attempts, which will
4✔
3810
        // prevent retries for any with backoffs that are still maturing.
4✔
3811
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
8✔
3812
                close(cancelChan)
4✔
3813
                delete(s.persistentRetryCancels, pubStr)
4✔
3814
        }
4✔
3815

3816
        // Next, check to see if we have any outstanding persistent connection
3817
        // requests to this peer. If so, then we'll remove all of these
3818
        // connection requests, and also delete the entry from the map.
3819
        connReqs, ok := s.persistentConnReqs[pubStr]
4✔
3820
        if !ok {
8✔
3821
                return
4✔
3822
        }
4✔
3823

3824
        for _, connReq := range connReqs {
8✔
3825
                srvrLog.Tracef("Canceling %s:", connReqs)
4✔
3826

4✔
3827
                // Atomically capture the current request identifier.
4✔
3828
                connID := connReq.ID()
4✔
3829

4✔
3830
                // Skip any zero IDs, this indicates the request has not
4✔
3831
                // yet been schedule.
4✔
3832
                if connID == UnassignedConnID {
4✔
3833
                        continue
×
3834
                }
3835

3836
                // Skip a particular connection ID if instructed.
3837
                if skip != nil && connID == *skip {
8✔
3838
                        continue
4✔
3839
                }
3840

3841
                s.connMgr.Remove(connID)
4✔
3842
        }
3843

3844
        delete(s.persistentConnReqs, pubStr)
4✔
3845
}
3846

3847
// handleCustomMessage dispatches an incoming custom peers message to
3848
// subscribers.
3849
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
4✔
3850
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
4✔
3851
                peer, msg.Type)
4✔
3852

4✔
3853
        return s.customMessageServer.SendUpdate(&CustomMessage{
4✔
3854
                Peer: peer,
4✔
3855
                Msg:  msg,
4✔
3856
        })
4✔
3857
}
4✔
3858

3859
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
3860
// messages.
3861
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
4✔
3862
        return s.customMessageServer.Subscribe()
4✔
3863
}
4✔
3864

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

4✔
3872
        brontideConn := conn.(*brontide.Conn)
4✔
3873
        addr := conn.RemoteAddr()
4✔
3874
        pubKey := brontideConn.RemotePub()
4✔
3875

4✔
3876
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
4✔
3877
                pubKey.SerializeCompressed(), addr, inbound)
4✔
3878

4✔
3879
        peerAddr := &lnwire.NetAddress{
4✔
3880
                IdentityKey: pubKey,
4✔
3881
                Address:     addr,
4✔
3882
                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
3883
        }
4✔
3884

4✔
3885
        // With the brontide connection established, we'll now craft the feature
4✔
3886
        // vectors to advertise to the remote node.
4✔
3887
        initFeatures := s.featureMgr.Get(feature.SetInit)
4✔
3888
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
4✔
3889

4✔
3890
        // Lookup past error caches for the peer in the server. If no buffer is
4✔
3891
        // found, create a fresh buffer.
4✔
3892
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
4✔
3893
        errBuffer, ok := s.peerErrors[pkStr]
4✔
3894
        if !ok {
8✔
3895
                var err error
4✔
3896
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
4✔
3897
                if err != nil {
4✔
3898
                        srvrLog.Errorf("unable to create peer %v", err)
×
3899
                        return
×
3900
                }
×
3901
        }
3902

3903
        // If we directly set the peer.Config TowerClient member to the
3904
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
3905
        // the peer.Config's TowerClient member will not evaluate to nil even
3906
        // though the underlying value is nil. To avoid this gotcha which can
3907
        // cause a panic, we need to explicitly pass nil to the peer.Config's
3908
        // TowerClient if needed.
3909
        var towerClient wtclient.ClientManager
4✔
3910
        if s.towerClientMgr != nil {
8✔
3911
                towerClient = s.towerClientMgr
4✔
3912
        }
4✔
3913

3914
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
4✔
3915
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
3916

4✔
3917
        // Now that we've established a connection, create a peer, and it to the
4✔
3918
        // set of currently active peers. Configure the peer with the incoming
4✔
3919
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
4✔
3920
        // offered that would trigger channel closure. In case of outgoing
4✔
3921
        // htlcs, an extra block is added to prevent the channel from being
4✔
3922
        // closed when the htlc is outstanding and a new block comes in.
4✔
3923
        pCfg := peer.Config{
4✔
3924
                Conn:                    brontideConn,
4✔
3925
                ConnReq:                 connReq,
4✔
3926
                Addr:                    peerAddr,
4✔
3927
                Inbound:                 inbound,
4✔
3928
                Features:                initFeatures,
4✔
3929
                LegacyFeatures:          legacyFeatures,
4✔
3930
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
4✔
3931
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
4✔
3932
                ErrorBuffer:             errBuffer,
4✔
3933
                WritePool:               s.writePool,
4✔
3934
                ReadPool:                s.readPool,
4✔
3935
                Switch:                  s.htlcSwitch,
4✔
3936
                InterceptSwitch:         s.interceptableSwitch,
4✔
3937
                ChannelDB:               s.chanStateDB,
4✔
3938
                ChannelGraph:            s.graphDB,
4✔
3939
                ChainArb:                s.chainArb,
4✔
3940
                AuthGossiper:            s.authGossiper,
4✔
3941
                ChanStatusMgr:           s.chanStatusMgr,
4✔
3942
                ChainIO:                 s.cc.ChainIO,
4✔
3943
                FeeEstimator:            s.cc.FeeEstimator,
4✔
3944
                Signer:                  s.cc.Wallet.Cfg.Signer,
4✔
3945
                SigPool:                 s.sigPool,
4✔
3946
                Wallet:                  s.cc.Wallet,
4✔
3947
                ChainNotifier:           s.cc.ChainNotifier,
4✔
3948
                BestBlockView:           s.cc.BestBlockTracker,
4✔
3949
                RoutingPolicy:           s.cc.RoutingPolicy,
4✔
3950
                Sphinx:                  s.sphinx,
4✔
3951
                WitnessBeacon:           s.witnessBeacon,
4✔
3952
                Invoices:                s.invoices,
4✔
3953
                ChannelNotifier:         s.channelNotifier,
4✔
3954
                HtlcNotifier:            s.htlcNotifier,
4✔
3955
                TowerClient:             towerClient,
4✔
3956
                DisconnectPeer:          s.DisconnectPeer,
4✔
3957
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
4✔
3958
                        lnwire.NodeAnnouncement, error) {
8✔
3959

4✔
3960
                        return s.genNodeAnnouncement(nil)
4✔
3961
                },
4✔
3962

3963
                PongBuf: s.pongBuf,
3964

3965
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
3966

3967
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
3968

3969
                FundingManager: s.fundingMgr,
3970

3971
                Hodl:                    s.cfg.Hodl,
3972
                UnsafeReplay:            s.cfg.UnsafeReplay,
3973
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
3974
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
3975
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
3976
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
3977
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
3978
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
3979
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
3980
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
3981
                HandleCustomMessage:    s.handleCustomMessage,
3982
                GetAliases:             s.aliasMgr.GetAliases,
3983
                RequestAlias:           s.aliasMgr.RequestAlias,
3984
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
3985
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
3986
                MaxFeeExposure:         thresholdMSats,
3987
                Quit:                   s.quit,
3988
        }
3989

3990
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
4✔
3991
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
4✔
3992

4✔
3993
        p := peer.NewBrontide(pCfg)
4✔
3994

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

4✔
3998
        s.addPeer(p)
4✔
3999

4✔
4000
        // Once we have successfully added the peer to the server, we can
4✔
4001
        // delete the previous error buffer from the server's map of error
4✔
4002
        // buffers.
4✔
4003
        delete(s.peerErrors, pkStr)
4✔
4004

4✔
4005
        // Dispatch a goroutine to asynchronously start the peer. This process
4✔
4006
        // includes sending and receiving Init messages, which would be a DOS
4✔
4007
        // vector if we held the server's mutex throughout the procedure.
4✔
4008
        s.wg.Add(1)
4✔
4009
        go s.peerInitializer(p)
4✔
4010
}
4011

4012
// addPeer adds the passed peer to the server's global state of all active
4013
// peers.
4014
func (s *server) addPeer(p *peer.Brontide) {
4✔
4015
        if p == nil {
4✔
4016
                return
×
4017
        }
×
4018

4019
        // Ignore new peers if we're shutting down.
4020
        if s.Stopped() {
4✔
4021
                p.Disconnect(ErrServerShuttingDown)
×
4022
                return
×
4023
        }
×
4024

4025
        // Track the new peer in our indexes so we can quickly look it up either
4026
        // according to its public key, or its peer ID.
4027
        // TODO(roasbeef): pipe all requests through to the
4028
        // queryHandler/peerManager
4029

4030
        pubSer := p.IdentityKey().SerializeCompressed()
4✔
4031
        pubStr := string(pubSer)
4✔
4032

4✔
4033
        s.peersByPub[pubStr] = p
4✔
4034

4✔
4035
        if p.Inbound() {
8✔
4036
                s.inboundPeers[pubStr] = p
4✔
4037
        } else {
8✔
4038
                s.outboundPeers[pubStr] = p
4✔
4039
        }
4✔
4040

4041
        // Inform the peer notifier of a peer online event so that it can be reported
4042
        // to clients listening for peer events.
4043
        var pubKey [33]byte
4✔
4044
        copy(pubKey[:], pubSer)
4✔
4045

4✔
4046
        s.peerNotifier.NotifyPeerOnline(pubKey)
4✔
4047
}
4048

4049
// peerInitializer asynchronously starts a newly connected peer after it has
4050
// been added to the server's peer map. This method sets up a
4051
// peerTerminationWatcher for the given peer, and ensures that it executes even
4052
// if the peer failed to start. In the event of a successful connection, this
4053
// method reads the negotiated, local feature-bits and spawns the appropriate
4054
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4055
// be signaled of the new peer once the method returns.
4056
//
4057
// NOTE: This MUST be launched as a goroutine.
4058
func (s *server) peerInitializer(p *peer.Brontide) {
4✔
4059
        defer s.wg.Done()
4✔
4060

4✔
4061
        // Avoid initializing peers while the server is exiting.
4✔
4062
        if s.Stopped() {
4✔
4063
                return
×
4064
        }
×
4065

4066
        // Create a channel that will be used to signal a successful start of
4067
        // the link. This prevents the peer termination watcher from beginning
4068
        // its duty too early.
4069
        ready := make(chan struct{})
4✔
4070

4✔
4071
        // Before starting the peer, launch a goroutine to watch for the
4✔
4072
        // unexpected termination of this peer, which will ensure all resources
4✔
4073
        // are properly cleaned up, and re-establish persistent connections when
4✔
4074
        // necessary. The peer termination watcher will be short circuited if
4✔
4075
        // the peer is ever added to the ignorePeerTermination map, indicating
4✔
4076
        // that the server has already handled the removal of this peer.
4✔
4077
        s.wg.Add(1)
4✔
4078
        go s.peerTerminationWatcher(p, ready)
4✔
4079

4✔
4080
        // Start the peer! If an error occurs, we Disconnect the peer, which
4✔
4081
        // will unblock the peerTerminationWatcher.
4✔
4082
        if err := p.Start(); err != nil {
6✔
4083
                srvrLog.Warnf("Starting peer=%v got error: %v",
2✔
4084
                        p.IdentityKey(), err)
2✔
4085

2✔
4086
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
2✔
4087
                return
2✔
4088
        }
2✔
4089

4090
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4091
        // was successful, and to begin watching the peer's wait group.
4092
        close(ready)
4✔
4093

4✔
4094
        pubStr := string(p.IdentityKey().SerializeCompressed())
4✔
4095

4✔
4096
        s.mu.Lock()
4✔
4097
        defer s.mu.Unlock()
4✔
4098

4✔
4099
        // Check if there are listeners waiting for this peer to come online.
4✔
4100
        srvrLog.Debugf("Notifying that peer %v is online", p)
4✔
4101
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
8✔
4102
                select {
4✔
4103
                case peerChan <- p:
4✔
4104
                case <-s.quit:
×
4105
                        return
×
4106
                }
4107
        }
4108
        delete(s.peerConnectedListeners, pubStr)
4✔
4109
}
4110

4111
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4112
// and then cleans up all resources allocated to the peer, notifies relevant
4113
// sub-systems of its demise, and finally handles re-connecting to the peer if
4114
// it's persistent. If the server intentionally disconnects a peer, it should
4115
// have a corresponding entry in the ignorePeerTermination map which will cause
4116
// the cleanup routine to exit early. The passed `ready` chan is used to
4117
// synchronize when WaitForDisconnect should begin watching on the peer's
4118
// waitgroup. The ready chan should only be signaled if the peer starts
4119
// successfully, otherwise the peer should be disconnected instead.
4120
//
4121
// NOTE: This MUST be launched as a goroutine.
4122
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
4✔
4123
        defer s.wg.Done()
4✔
4124

4✔
4125
        p.WaitForDisconnect(ready)
4✔
4126

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

4✔
4129
        // If the server is exiting then we can bail out early ourselves as all
4✔
4130
        // the other sub-systems will already be shutting down.
4✔
4131
        if s.Stopped() {
8✔
4132
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
4✔
4133
                return
4✔
4134
        }
4✔
4135

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

4✔
4142
        pubKey := p.IdentityKey()
4✔
4143

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

4✔
4148
        // Tell the switch to remove all links associated with this peer.
4✔
4149
        // Passing nil as the target link indicates that all links associated
4✔
4150
        // with this interface should be closed.
4✔
4151
        //
4✔
4152
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
4✔
4153
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
4✔
4154
        if err != nil && err != htlcswitch.ErrNoLinksFound {
4✔
4155
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4156
        }
×
4157

4158
        for _, link := range links {
8✔
4159
                s.htlcSwitch.RemoveLink(link.ChanID())
4✔
4160
        }
4✔
4161

4162
        s.mu.Lock()
4✔
4163
        defer s.mu.Unlock()
4✔
4164

4✔
4165
        // If there were any notification requests for when this peer
4✔
4166
        // disconnected, we can trigger them now.
4✔
4167
        srvrLog.Debugf("Notifying that peer %v is offline", p)
4✔
4168
        pubStr := string(pubKey.SerializeCompressed())
4✔
4169
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
8✔
4170
                close(offlineChan)
4✔
4171
        }
4✔
4172
        delete(s.peerDisconnectedListeners, pubStr)
4✔
4173

4✔
4174
        // If the server has already removed this peer, we can short circuit the
4✔
4175
        // peer termination watcher and skip cleanup.
4✔
4176
        if _, ok := s.ignorePeerTermination[p]; ok {
4✔
4177
                delete(s.ignorePeerTermination, p)
×
4178

×
4179
                pubKey := p.PubKey()
×
4180
                pubStr := string(pubKey[:])
×
4181

×
4182
                // If a connection callback is present, we'll go ahead and
×
4183
                // execute it now that previous peer has fully disconnected. If
×
4184
                // the callback is not present, this likely implies the peer was
×
4185
                // purposefully disconnected via RPC, and that no reconnect
×
4186
                // should be attempted.
×
4187
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4188
                if ok {
×
4189
                        delete(s.scheduledPeerConnection, pubStr)
×
4190
                        connCallback()
×
4191
                }
×
4192
                return
×
4193
        }
4194

4195
        // First, cleanup any remaining state the server has regarding the peer
4196
        // in question.
4197
        s.removePeer(p)
4✔
4198

4✔
4199
        // Next, check to see if this is a persistent peer or not.
4✔
4200
        if _, ok := s.persistentPeers[pubStr]; !ok {
8✔
4201
                return
4✔
4202
        }
4✔
4203

4204
        // Get the last address that we used to connect to the peer.
4205
        addrs := []net.Addr{
4✔
4206
                p.NetAddress().Address,
4✔
4207
        }
4✔
4208

4✔
4209
        // We'll ensure that we locate all the peers advertised addresses for
4✔
4210
        // reconnection purposes.
4✔
4211
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
4✔
4212
        switch {
4✔
4213
        // We found advertised addresses, so use them.
4214
        case err == nil:
4✔
4215
                addrs = advertisedAddrs
4✔
4216

4217
        // The peer doesn't have an advertised address.
4218
        case err == errNoAdvertisedAddr:
4✔
4219
                // If it is an outbound peer then we fall back to the existing
4✔
4220
                // peer address.
4✔
4221
                if !p.Inbound() {
8✔
4222
                        break
4✔
4223
                }
4224

4225
                // Fall back to the existing peer address if
4226
                // we're not accepting connections over Tor.
4227
                if s.torController == nil {
8✔
4228
                        break
4✔
4229
                }
4230

4231
                // If we are, the peer's address won't be known
4232
                // to us (we'll see a private address, which is
4233
                // the address used by our onion service to dial
4234
                // to lnd), so we don't have enough information
4235
                // to attempt a reconnect.
4236
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4237
                        "to inbound peer %v without "+
×
4238
                        "advertised address", p)
×
4239
                return
×
4240

4241
        // We came across an error retrieving an advertised
4242
        // address, log it, and fall back to the existing peer
4243
        // address.
4244
        default:
4✔
4245
                srvrLog.Errorf("Unable to retrieve advertised "+
4✔
4246
                        "address for node %x: %v", p.PubKey(),
4✔
4247
                        err)
4✔
4248
        }
4249

4250
        // Make an easy lookup map so that we can check if an address
4251
        // is already in the address list that we have stored for this peer.
4252
        existingAddrs := make(map[string]bool)
4✔
4253
        for _, addr := range s.persistentPeerAddrs[pubStr] {
8✔
4254
                existingAddrs[addr.String()] = true
4✔
4255
        }
4✔
4256

4257
        // Add any missing addresses for this peer to persistentPeerAddr.
4258
        for _, addr := range addrs {
8✔
4259
                if existingAddrs[addr.String()] {
4✔
4260
                        continue
×
4261
                }
4262

4263
                s.persistentPeerAddrs[pubStr] = append(
4✔
4264
                        s.persistentPeerAddrs[pubStr],
4✔
4265
                        &lnwire.NetAddress{
4✔
4266
                                IdentityKey: p.IdentityKey(),
4✔
4267
                                Address:     addr,
4✔
4268
                                ChainNet:    p.NetAddress().ChainNet,
4✔
4269
                        },
4✔
4270
                )
4✔
4271
        }
4272

4273
        // Record the computed backoff in the backoff map.
4274
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
4✔
4275
        s.persistentPeersBackoff[pubStr] = backoff
4✔
4276

4✔
4277
        // Initialize a retry canceller for this peer if one does not
4✔
4278
        // exist.
4✔
4279
        cancelChan, ok := s.persistentRetryCancels[pubStr]
4✔
4280
        if !ok {
8✔
4281
                cancelChan = make(chan struct{})
4✔
4282
                s.persistentRetryCancels[pubStr] = cancelChan
4✔
4283
        }
4✔
4284

4285
        // We choose not to wait group this go routine since the Connect
4286
        // call can stall for arbitrarily long if we shutdown while an
4287
        // outbound connection attempt is being made.
4288
        go func() {
8✔
4289
                srvrLog.Debugf("Scheduling connection re-establishment to "+
4✔
4290
                        "persistent peer %x in %s",
4✔
4291
                        p.IdentityKey().SerializeCompressed(), backoff)
4✔
4292

4✔
4293
                select {
4✔
4294
                case <-time.After(backoff):
4✔
4295
                case <-cancelChan:
4✔
4296
                        return
4✔
4297
                case <-s.quit:
4✔
4298
                        return
4✔
4299
                }
4300

4301
                srvrLog.Debugf("Attempting to re-establish persistent "+
4✔
4302
                        "connection to peer %x",
4✔
4303
                        p.IdentityKey().SerializeCompressed())
4✔
4304

4✔
4305
                s.connectToPersistentPeer(pubStr)
4✔
4306
        }()
4307
}
4308

4309
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4310
// to connect to the peer. It creates connection requests if there are
4311
// currently none for a given address and it removes old connection requests
4312
// if the associated address is no longer in the latest address list for the
4313
// peer.
4314
func (s *server) connectToPersistentPeer(pubKeyStr string) {
4✔
4315
        s.mu.Lock()
4✔
4316
        defer s.mu.Unlock()
4✔
4317

4✔
4318
        // Create an easy lookup map of the addresses we have stored for the
4✔
4319
        // peer. We will remove entries from this map if we have existing
4✔
4320
        // connection requests for the associated address and then any leftover
4✔
4321
        // entries will indicate which addresses we should create new
4✔
4322
        // connection requests for.
4✔
4323
        addrMap := make(map[string]*lnwire.NetAddress)
4✔
4324
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
8✔
4325
                addrMap[addr.String()] = addr
4✔
4326
        }
4✔
4327

4328
        // Go through each of the existing connection requests and
4329
        // check if they correspond to the latest set of addresses. If
4330
        // there is a connection requests that does not use one of the latest
4331
        // advertised addresses then remove that connection request.
4332
        var updatedConnReqs []*connmgr.ConnReq
4✔
4333
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
8✔
4334
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
4✔
4335

4✔
4336
                switch _, ok := addrMap[lnAddr]; ok {
4✔
4337
                // If the existing connection request is using one of the
4338
                // latest advertised addresses for the peer then we add it to
4339
                // updatedConnReqs and remove the associated address from
4340
                // addrMap so that we don't recreate this connReq later on.
4341
                case true:
×
4342
                        updatedConnReqs = append(
×
4343
                                updatedConnReqs, connReq,
×
4344
                        )
×
4345
                        delete(addrMap, lnAddr)
×
4346

4347
                // If the existing connection request is using an address that
4348
                // is not one of the latest advertised addresses for the peer
4349
                // then we remove the connecting request from the connection
4350
                // manager.
4351
                case false:
4✔
4352
                        srvrLog.Info(
4✔
4353
                                "Removing conn req:", connReq.Addr.String(),
4✔
4354
                        )
4✔
4355
                        s.connMgr.Remove(connReq.ID())
4✔
4356
                }
4357
        }
4358

4359
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
4✔
4360

4✔
4361
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
4✔
4362
        if !ok {
8✔
4363
                cancelChan = make(chan struct{})
4✔
4364
                s.persistentRetryCancels[pubKeyStr] = cancelChan
4✔
4365
        }
4✔
4366

4367
        // Any addresses left in addrMap are new ones that we have not made
4368
        // connection requests for. So create new connection requests for those.
4369
        // If there is more than one address in the address map, stagger the
4370
        // creation of the connection requests for those.
4371
        go func() {
8✔
4372
                ticker := time.NewTicker(multiAddrConnectionStagger)
4✔
4373
                defer ticker.Stop()
4✔
4374

4✔
4375
                for _, addr := range addrMap {
8✔
4376
                        // Send the persistent connection request to the
4✔
4377
                        // connection manager, saving the request itself so we
4✔
4378
                        // can cancel/restart the process as needed.
4✔
4379
                        connReq := &connmgr.ConnReq{
4✔
4380
                                Addr:      addr,
4✔
4381
                                Permanent: true,
4✔
4382
                        }
4✔
4383

4✔
4384
                        s.mu.Lock()
4✔
4385
                        s.persistentConnReqs[pubKeyStr] = append(
4✔
4386
                                s.persistentConnReqs[pubKeyStr], connReq,
4✔
4387
                        )
4✔
4388
                        s.mu.Unlock()
4✔
4389

4✔
4390
                        srvrLog.Debugf("Attempting persistent connection to "+
4✔
4391
                                "channel peer %v", addr)
4✔
4392

4✔
4393
                        go s.connMgr.Connect(connReq)
4✔
4394

4✔
4395
                        select {
4✔
4396
                        case <-s.quit:
4✔
4397
                                return
4✔
4398
                        case <-cancelChan:
4✔
4399
                                return
4✔
4400
                        case <-ticker.C:
4✔
4401
                        }
4402
                }
4403
        }()
4404
}
4405

4406
// removePeer removes the passed peer from the server's state of all active
4407
// peers.
4408
func (s *server) removePeer(p *peer.Brontide) {
4✔
4409
        if p == nil {
4✔
4410
                return
×
4411
        }
×
4412

4413
        srvrLog.Debugf("removing peer %v", p)
4✔
4414

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

4✔
4419
        // If this peer had an active persistent connection request, remove it.
4✔
4420
        if p.ConnReq() != nil {
8✔
4421
                s.connMgr.Remove(p.ConnReq().ID())
4✔
4422
        }
4✔
4423

4424
        // Ignore deleting peers if we're shutting down.
4425
        if s.Stopped() {
4✔
4426
                return
×
4427
        }
×
4428

4429
        pKey := p.PubKey()
4✔
4430
        pubSer := pKey[:]
4✔
4431
        pubStr := string(pubSer)
4✔
4432

4✔
4433
        delete(s.peersByPub, pubStr)
4✔
4434

4✔
4435
        if p.Inbound() {
8✔
4436
                delete(s.inboundPeers, pubStr)
4✔
4437
        } else {
8✔
4438
                delete(s.outboundPeers, pubStr)
4✔
4439
        }
4✔
4440

4441
        // Copy the peer's error buffer across to the server if it has any items
4442
        // in it so that we can restore peer errors across connections.
4443
        if p.ErrorBuffer().Total() > 0 {
8✔
4444
                s.peerErrors[pubStr] = p.ErrorBuffer()
4✔
4445
        }
4✔
4446

4447
        // Inform the peer notifier of a peer offline event so that it can be
4448
        // reported to clients listening for peer events.
4449
        var pubKey [33]byte
4✔
4450
        copy(pubKey[:], pubSer)
4✔
4451

4✔
4452
        s.peerNotifier.NotifyPeerOffline(pubKey)
4✔
4453
}
4454

4455
// ConnectToPeer requests that the server connect to a Lightning Network peer
4456
// at the specified address. This function will *block* until either a
4457
// connection is established, or the initial handshake process fails.
4458
//
4459
// NOTE: This function is safe for concurrent access.
4460
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4461
        perm bool, timeout time.Duration) error {
4✔
4462

4✔
4463
        targetPub := string(addr.IdentityKey.SerializeCompressed())
4✔
4464

4✔
4465
        // Acquire mutex, but use explicit unlocking instead of defer for
4✔
4466
        // better granularity.  In certain conditions, this method requires
4✔
4467
        // making an outbound connection to a remote peer, which requires the
4✔
4468
        // lock to be released, and subsequently reacquired.
4✔
4469
        s.mu.Lock()
4✔
4470

4✔
4471
        // Ensure we're not already connected to this peer.
4✔
4472
        peer, err := s.findPeerByPubStr(targetPub)
4✔
4473
        if err == nil {
8✔
4474
                s.mu.Unlock()
4✔
4475
                return &errPeerAlreadyConnected{peer: peer}
4✔
4476
        }
4✔
4477

4478
        // Peer was not found, continue to pursue connection with peer.
4479

4480
        // If there's already a pending connection request for this pubkey,
4481
        // then we ignore this request to ensure we don't create a redundant
4482
        // connection.
4483
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
8✔
4484
                srvrLog.Warnf("Already have %d persistent connection "+
4✔
4485
                        "requests for %v, connecting anyway.", len(reqs), addr)
4✔
4486
        }
4✔
4487

4488
        // If there's not already a pending or active connection to this node,
4489
        // then instruct the connection manager to attempt to establish a
4490
        // persistent connection to the peer.
4491
        srvrLog.Debugf("Connecting to %v", addr)
4✔
4492
        if perm {
8✔
4493
                connReq := &connmgr.ConnReq{
4✔
4494
                        Addr:      addr,
4✔
4495
                        Permanent: true,
4✔
4496
                }
4✔
4497

4✔
4498
                // Since the user requested a permanent connection, we'll set
4✔
4499
                // the entry to true which will tell the server to continue
4✔
4500
                // reconnecting even if the number of channels with this peer is
4✔
4501
                // zero.
4✔
4502
                s.persistentPeers[targetPub] = true
4✔
4503
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
8✔
4504
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
4✔
4505
                }
4✔
4506
                s.persistentConnReqs[targetPub] = append(
4✔
4507
                        s.persistentConnReqs[targetPub], connReq,
4✔
4508
                )
4✔
4509
                s.mu.Unlock()
4✔
4510

4✔
4511
                go s.connMgr.Connect(connReq)
4✔
4512

4✔
4513
                return nil
4✔
4514
        }
4515
        s.mu.Unlock()
4✔
4516

4✔
4517
        // If we're not making a persistent connection, then we'll attempt to
4✔
4518
        // connect to the target peer. If the we can't make the connection, or
4✔
4519
        // the crypto negotiation breaks down, then return an error to the
4✔
4520
        // caller.
4✔
4521
        errChan := make(chan error, 1)
4✔
4522
        s.connectToPeer(addr, errChan, timeout)
4✔
4523

4✔
4524
        select {
4✔
4525
        case err := <-errChan:
4✔
4526
                return err
4✔
4527
        case <-s.quit:
×
4528
                return ErrServerShuttingDown
×
4529
        }
4530
}
4531

4532
// connectToPeer establishes a connection to a remote peer. errChan is used to
4533
// notify the caller if the connection attempt has failed. Otherwise, it will be
4534
// closed.
4535
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4536
        errChan chan<- error, timeout time.Duration) {
4✔
4537

4✔
4538
        conn, err := brontide.Dial(
4✔
4539
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
4✔
4540
        )
4✔
4541
        if err != nil {
8✔
4542
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
4✔
4543
                select {
4✔
4544
                case errChan <- err:
4✔
4545
                case <-s.quit:
×
4546
                }
4547
                return
4✔
4548
        }
4549

4550
        close(errChan)
4✔
4551

4✔
4552
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
4✔
4553
                conn.LocalAddr(), conn.RemoteAddr())
4✔
4554

4✔
4555
        s.OutboundPeerConnected(nil, conn)
4✔
4556
}
4557

4558
// DisconnectPeer sends the request to server to close the connection with peer
4559
// identified by public key.
4560
//
4561
// NOTE: This function is safe for concurrent access.
4562
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
4✔
4563
        pubBytes := pubKey.SerializeCompressed()
4✔
4564
        pubStr := string(pubBytes)
4✔
4565

4✔
4566
        s.mu.Lock()
4✔
4567
        defer s.mu.Unlock()
4✔
4568

4✔
4569
        // Check that were actually connected to this peer. If not, then we'll
4✔
4570
        // exit in an error as we can't disconnect from a peer that we're not
4✔
4571
        // currently connected to.
4✔
4572
        peer, err := s.findPeerByPubStr(pubStr)
4✔
4573
        if err == ErrPeerNotConnected {
8✔
4574
                return fmt.Errorf("peer %x is not connected", pubBytes)
4✔
4575
        }
4✔
4576

4577
        srvrLog.Infof("Disconnecting from %v", peer)
4✔
4578

4✔
4579
        s.cancelConnReqs(pubStr, nil)
4✔
4580

4✔
4581
        // If this peer was formerly a persistent connection, then we'll remove
4✔
4582
        // them from this map so we don't attempt to re-connect after we
4✔
4583
        // disconnect.
4✔
4584
        delete(s.persistentPeers, pubStr)
4✔
4585
        delete(s.persistentPeersBackoff, pubStr)
4✔
4586

4✔
4587
        // Remove the peer by calling Disconnect. Previously this was done with
4✔
4588
        // removePeer, which bypassed the peerTerminationWatcher.
4✔
4589
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
4✔
4590

4✔
4591
        return nil
4✔
4592
}
4593

4594
// OpenChannel sends a request to the server to open a channel to the specified
4595
// peer identified by nodeKey with the passed channel funding parameters.
4596
//
4597
// NOTE: This function is safe for concurrent access.
4598
func (s *server) OpenChannel(
4599
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
4✔
4600

4✔
4601
        // The updateChan will have a buffer of 2, since we expect a ChanPending
4✔
4602
        // + a ChanOpen update, and we want to make sure the funding process is
4✔
4603
        // not blocked if the caller is not reading the updates.
4✔
4604
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
4✔
4605
        req.Err = make(chan error, 1)
4✔
4606

4✔
4607
        // First attempt to locate the target peer to open a channel with, if
4✔
4608
        // we're unable to locate the peer then this request will fail.
4✔
4609
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
4✔
4610
        s.mu.RLock()
4✔
4611
        peer, ok := s.peersByPub[string(pubKeyBytes)]
4✔
4612
        if !ok {
4✔
4613
                s.mu.RUnlock()
×
4614

×
4615
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4616
                return req.Updates, req.Err
×
4617
        }
×
4618
        req.Peer = peer
4✔
4619
        s.mu.RUnlock()
4✔
4620

4✔
4621
        // We'll wait until the peer is active before beginning the channel
4✔
4622
        // opening process.
4✔
4623
        select {
4✔
4624
        case <-peer.ActiveSignal():
4✔
4625
        case <-peer.QuitSignal():
×
4626
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4627
                return req.Updates, req.Err
×
4628
        case <-s.quit:
×
4629
                req.Err <- ErrServerShuttingDown
×
4630
                return req.Updates, req.Err
×
4631
        }
4632

4633
        // If the fee rate wasn't specified at this point we fail the funding
4634
        // because of the missing fee rate information. The caller of the
4635
        // `OpenChannel` method needs to make sure that default values for the
4636
        // fee rate are set beforehand.
4637
        if req.FundingFeePerKw == 0 {
4✔
4638
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4639
                        "the channel opening transaction")
×
4640

×
4641
                return req.Updates, req.Err
×
4642
        }
×
4643

4644
        // Spawn a goroutine to send the funding workflow request to the funding
4645
        // manager. This allows the server to continue handling queries instead
4646
        // of blocking on this request which is exported as a synchronous
4647
        // request to the outside world.
4648
        go s.fundingMgr.InitFundingWorkflow(req)
4✔
4649

4✔
4650
        return req.Updates, req.Err
4✔
4651
}
4652

4653
// Peers returns a slice of all active peers.
4654
//
4655
// NOTE: This function is safe for concurrent access.
4656
func (s *server) Peers() []*peer.Brontide {
4✔
4657
        s.mu.RLock()
4✔
4658
        defer s.mu.RUnlock()
4✔
4659

4✔
4660
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
4661
        for _, peer := range s.peersByPub {
8✔
4662
                peers = append(peers, peer)
4✔
4663
        }
4✔
4664

4665
        return peers
4✔
4666
}
4667

4668
// computeNextBackoff uses a truncated exponential backoff to compute the next
4669
// backoff using the value of the exiting backoff. The returned duration is
4670
// randomized in either direction by 1/20 to prevent tight loops from
4671
// stabilizing.
4672
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
4✔
4673
        // Double the current backoff, truncating if it exceeds our maximum.
4✔
4674
        nextBackoff := 2 * currBackoff
4✔
4675
        if nextBackoff > maxBackoff {
8✔
4676
                nextBackoff = maxBackoff
4✔
4677
        }
4✔
4678

4679
        // Using 1/10 of our duration as a margin, compute a random offset to
4680
        // avoid the nodes entering connection cycles.
4681
        margin := nextBackoff / 10
4✔
4682

4✔
4683
        var wiggle big.Int
4✔
4684
        wiggle.SetUint64(uint64(margin))
4✔
4685
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
4✔
4686
                // Randomizing is not mission critical, so we'll just return the
×
4687
                // current backoff.
×
4688
                return nextBackoff
×
4689
        }
×
4690

4691
        // Otherwise add in our wiggle, but subtract out half of the margin so
4692
        // that the backoff can tweaked by 1/20 in either direction.
4693
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
4✔
4694
}
4695

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

4700
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4701
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
4✔
4702
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
4✔
4703
        if err != nil {
4✔
4704
                return nil, err
×
4705
        }
×
4706

4707
        node, err := s.graphDB.FetchLightningNode(vertex)
4✔
4708
        if err != nil {
8✔
4709
                return nil, err
4✔
4710
        }
4✔
4711

4712
        if len(node.Addresses) == 0 {
8✔
4713
                return nil, errNoAdvertisedAddr
4✔
4714
        }
4✔
4715

4716
        return node.Addresses, nil
4✔
4717
}
4718

4719
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4720
// channel update for a target channel.
4721
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4722
        *lnwire.ChannelUpdate, error) {
4✔
4723

4✔
4724
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
4✔
4725
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate, error) {
8✔
4726
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
4✔
4727
                if err != nil {
8✔
4728
                        return nil, err
4✔
4729
                }
4✔
4730

4731
                return netann.ExtractChannelUpdate(
4✔
4732
                        ourPubKey[:], info, edge1, edge2,
4✔
4733
                )
4✔
4734
        }
4735
}
4736

4737
// applyChannelUpdate applies the channel update to the different sub-systems of
4738
// the server. The useAlias boolean denotes whether or not to send an alias in
4739
// place of the real SCID.
4740
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate,
4741
        op *wire.OutPoint, useAlias bool) error {
4✔
4742

4✔
4743
        var (
4✔
4744
                peerAlias    *lnwire.ShortChannelID
4✔
4745
                defaultAlias lnwire.ShortChannelID
4✔
4746
        )
4✔
4747

4✔
4748
        chanID := lnwire.NewChanIDFromOutPoint(*op)
4✔
4749

4✔
4750
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
4✔
4751
        // in the ChannelUpdate if it hasn't been announced yet.
4✔
4752
        if useAlias {
8✔
4753
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
4✔
4754
                if foundAlias != defaultAlias {
8✔
4755
                        peerAlias = &foundAlias
4✔
4756
                }
4✔
4757
        }
4758

4759
        errChan := s.authGossiper.ProcessLocalAnnouncement(
4✔
4760
                update, discovery.RemoteAlias(peerAlias),
4✔
4761
        )
4✔
4762
        select {
4✔
4763
        case err := <-errChan:
4✔
4764
                return err
4✔
4765
        case <-s.quit:
×
4766
                return ErrServerShuttingDown
×
4767
        }
4768
}
4769

4770
// SendCustomMessage sends a custom message to the peer with the specified
4771
// pubkey.
4772
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
4773
        data []byte) error {
4✔
4774

4✔
4775
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
4✔
4776
        if err != nil {
4✔
4777
                return err
×
4778
        }
×
4779

4780
        // We'll wait until the peer is active.
4781
        select {
4✔
4782
        case <-peer.ActiveSignal():
4✔
4783
        case <-peer.QuitSignal():
×
4784
                return fmt.Errorf("peer %x disconnected", peerPub)
×
4785
        case <-s.quit:
×
4786
                return ErrServerShuttingDown
×
4787
        }
4788

4789
        msg, err := lnwire.NewCustom(msgType, data)
4✔
4790
        if err != nil {
8✔
4791
                return err
4✔
4792
        }
4✔
4793

4794
        // Send the message as low-priority. For now we assume that all
4795
        // application-defined message are low priority.
4796
        return peer.SendMessageLazy(true, msg)
4✔
4797
}
4798

4799
// newSweepPkScriptGen creates closure that generates a new public key script
4800
// which should be used to sweep any funds into the on-chain wallet.
4801
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
4802
// (p2wkh) output.
4803
func newSweepPkScriptGen(
4804
        wallet lnwallet.WalletController) func() ([]byte, error) {
4✔
4805

4✔
4806
        return func() ([]byte, error) {
8✔
4807
                sweepAddr, err := wallet.NewAddress(
4✔
4808
                        lnwallet.TaprootPubkey, false,
4✔
4809
                        lnwallet.DefaultAccountName,
4✔
4810
                )
4✔
4811
                if err != nil {
4✔
4812
                        return nil, err
×
4813
                }
×
4814

4815
                return txscript.PayToAddrScript(sweepAddr)
4✔
4816
        }
4817
}
4818

4819
// shouldPeerBootstrap returns true if we should attempt to perform peer
4820
// bootstrapping to actively seek our peers using the set of active network
4821
// bootstrappers.
4822
func shouldPeerBootstrap(cfg *Config) bool {
10✔
4823
        isSimnet := cfg.Bitcoin.SimNet
10✔
4824
        isSignet := cfg.Bitcoin.SigNet
10✔
4825
        isRegtest := cfg.Bitcoin.RegTest
10✔
4826
        isDevNetwork := isSimnet || isSignet || isRegtest
10✔
4827

10✔
4828
        // TODO(yy): remove the check on simnet/regtest such that the itest is
10✔
4829
        // covering the bootstrapping process.
10✔
4830
        return !cfg.NoNetBootstrap && !isDevNetwork
10✔
4831
}
10✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc